[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71DAMV3PAAPBADP5EY1N61S":3,"skill-same:01M71DAMV3PAAPBADP5EY1N61S":111},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":22,"publishedAt":43,"linkOnly":44,"markdownContent":45,"markdownBody":46,"frontMatter":47,"refName":90,"commitSha":91,"skillDirectory":92,"forksCount":93,"repositoryHtmlUrl":94,"repositoryHomepageUrl":6,"ownerHtmlUrl":95,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":96,"install":97,"resources":110},"01M71DAMV3PAAPBADP5EY1N61S","best-practices-rust",null,"Repo-specific Rust best practices for agentic coding: thiserror + anyhow error handling, tokio async runtime, tracing for observability, clap for CLI, axum for HTTP, serde patterns, cargo workspace conventions, ownership and lifetimes, and idiomatic Rust 2024 edition patterns.","cateyephotos\u002Fagent-skills","cateyephotos","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F110843613?v=4","01M71CCSDD8VJ7CZ4V1QQGBMA7","01M71CCSE1VRT329KB810CRC0V",0,"MIT","https:\u002F\u002Fgithub.com\u002Fcateyephotos\u002Fagent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fbest-practices-rust\u002FSKILL.md",[17],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000007","代码审查","SCENARIO","使用场景",[23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42],"best practices rust","best practices","rust","tracing","rust best practices","polars","rust error handling","axum","cli","server","resilience","review","code","agentic","2024","code review","performance","tokio","async runtime","error","2026-11-10 10:12:30",false,"---\nname: best-practices-rust\ndescription: >\n  Repo-specific Rust best practices for agentic coding: thiserror + anyhow error handling,\n  tokio async runtime, tracing for observability, clap for CLI, axum for HTTP, serde patterns,\n  cargo workspace conventions, ownership and lifetimes, and idiomatic Rust 2024 edition patterns.\ntriggers:\n  - best practices rust\n  - rust conventions\n  - rust code review\n  - cargo workspace\n  - thiserror anyhow\n  - tokio async\n  - rust error handling\n  - axum server\n  - clap cli\n  - rust performance\n  - rust ownership lifetimes\n  - rust edition 2024\nlicense: MIT\nmetadata:\n  language: rust\n  edition: \"2024\"\n  rust_versions: [\"1.85+\"]\n  defaults:\n    error_handling:\n      libraries: thiserror\n      applications: anyhow\n    async_runtime: tokio\n    http_server: axum\n    http_client: reqwest\n    cli: clap (derive)\n    serialization: serde + serde_json\n    logging: tracing + tracing-subscriber\n    tui: ratatui + crossterm\n    data_processing: polars\n    parallelism: rayon\n    progress: indicatif\n    packaging: cargo\n    style:\n      max_line_length: 100\n      indentation: 4 spaces\n      naming:\n        functions: snake_case\n        types: PascalCase\n        constants: SCREAMING_SNAKE_CASE\n    testing:\n      framework: built-in (#[test])\n      runner: cargo test\n\nprovides:\n  - best-practices-rust\ncomposes: []\n\ntaxonomy:\n  - validation\n  - precision\n  - resilience\n---\n\n# Rust Best Practices (Project Skill)\n\nThis skill is a curated set of atomic rules for writing and refactoring Rust in *this* repo.\nAssume the reader is a Python expert but a Rust novice. Include additional code comments\naround Rust-specific nuances that a Python developer may not recognize.\n\n## Advanced Patterns Reference\n\nSee **[references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md)** for deep-dive content:\nsealed traits, extension traits, HRTBs, `'static` misconceptions, Pin\u002FUnpin, smart pointer\ndecision tree, interior mutability, serde advanced patterns, tracing layers, CI pipeline tools,\nproperty-based testing, snapshot testing, and Rust 2024 edition features.\n\n## Project Defaults (apply unless explicitly overridden)\n\n- **Error Handling:** `thiserror` for library crates, `anyhow` for application crates\n- **Async Runtime:** `tokio` (multi-threaded by default)\n- **HTTP Server:** `axum` with `tower` middleware\n- **HTTP Client:** `reqwest`\n- **CLI:** `clap` with derive macros\n- **Serialization:** `serde` + `serde_json`\n- **Logging:** `tracing` + `tracing-subscriber` (NEVER `println!` for diagnostics)\n- **TUI:** `ratatui` + `crossterm`\n- **Data Processing:** `polars` (NEVER other dataframe libraries)\n- **CPU Parallelism:** `rayon`\n- **Progress Bars:** `indicatif` with contextually sensitive messages\n- **Packaging:** `cargo` for builds, deps, and workspace management\n\n## When to Apply\n\nUse this skill whenever you:\n- create or refactor Rust crates, binaries, libraries, or workspaces\n- add error handling, async code, or network calls\n- change `Cargo.toml` dependencies or workspace structure\n- add tests or fix bugs\n- build WASM or PyO3\u002Fmaturin bridges\n\n## Categories (priority order)\n\n1. Correctness & Ownership (CRITICAL\u002FHIGH): `correctness-`\n2. Security (CRITICAL\u002FHIGH): `security-`\n3. Error Handling (CRITICAL): `errors-`\n4. Type System (HIGH): `types-`\n5. Conventions (HIGH): `conventions-`\n6. Async & Concurrency (HIGH\u002FMEDIUM): `async-`\n7. Testing (HIGH\u002FMEDIUM): `testing-`\n8. Performance & Memory (MEDIUM): `perf-`\n9. Cargo & Workspaces (MEDIUM): `cargo-`\n10. Documentation (MEDIUM): `docs-`\n11. Style & Maintainability (MEDIUM\u002FLOW): `style-`\n\n## Quick Reference (house rules)\n\n- `correctness-ownership` — understand move vs borrow; prefer borrowing\n- `correctness-lifetimes` — let the compiler infer; annotate only when required\n- `correctness-clone-explicit` — call `.clone()` explicitly on non-`Copy` types\n- `correctness-let-else` — use `let-else` for early returns on pattern failure\n- `errors-thiserror-libraries` — use `thiserror` in library crates\n- `errors-anyhow-applications` — use `anyhow` in application\u002Fbinary crates\n- `errors-no-unwrap` — NEVER `.unwrap()` in production code\n- `errors-context` — add `.context()` to every `?` at module boundaries\n- `errors-boundary-pattern` — three zones: library\u002Fapp\u002FAPI boundary\n- `conventions-tracing` — use `tracing` for all observability\n- `conventions-clap-derive` — use `clap` derive macros for CLI\n- `conventions-serde` — use `serde` for all serialization\n- `conventions-reqwest` — use `reqwest` with shared client for HTTP\n- `conventions-no-emoji` — NEVER use emoji or unicode emoji-like chars\n- `conventions-cargo-deps-complete` — every `use` needs a `Cargo.toml` entry\n- `conventions-function-design` — single responsibility, max 5 params\n- `conventions-no-debug-output` — NEVER commit `println!`\u002F`dbg!`\n- `types-newtype` — use newtypes to distinguish semantically different values\n- `types-typestate` — use the Type State Pattern for compile-time state machines\n- `types-sealed-trait` — seal public traits in libraries to allow evolution\n- `types-option-over-sentinel` — prefer `Option\u003CT>` over sentinel values\n- `async-structured` — use structured concurrency with `JoinSet`\n- `async-spawn-blocking` — offload CPU-bound work to `spawn_blocking`\n- `async-send-sync` — understand `Send`\u002F`Sync` bounds for threaded runtimes\n- `async-cancellation` — use `CancellationToken` for graceful shutdown\n- `async-mutex-vs-rwlock` — `RwLock` for read-heavy, `Mutex` for simple exclusive\n- `perf-borrow-first` — prefer `&T` over owned `T` in function params\n- `perf-cow` — use `Cow\u003C'_, str>` when ownership is conditionally needed\n- `perf-vec-capacity` — use `Vec::with_capacity()` when size is known\n- `perf-iterators` — prefer iterator combinators over manual loops\n- `testing-arrange-act-assert` — follow AAA pattern in all tests\n- `testing-proptest` — property-based tests for roundtrip\u002Finvariant checks\n- `testing-doc-tests` — doc examples are compiled and run by `cargo test`\n- `cargo-workspace` — share deps via `[workspace.dependencies]`\n- `cargo-features` — additive feature flags, minimal defaults\n- `cargo-ci-tools` — `cargo-deny`, `cargo-audit`, `cargo-machete` in CI\n- `style-rustfmt` — all code formatted with `rustfmt`\n- `style-clippy-clean` — zero clippy warnings (`-D warnings`)\n- `docs-public-items` — doc comments on all public items\n\n---\n\n## 1. Correctness & Ownership (CRITICAL)\n\nRust's ownership system is the biggest difference from Python. In Python, everything is\nreference-counted and garbage-collected. In Rust, each value has exactly one owner, and\nthe compiler enforces this at compile time — no GC overhead, no use-after-free.\n\n### Rule: `correctness-ownership`\n\nUnderstand the three modes of passing data:\n\n```rust\n\u002F\u002F MOVE: caller gives up ownership (like Python's only mode, but enforced)\nfn consume(data: String) { \u002F* data is owned here, freed when function ends *\u002F }\n\n\u002F\u002F BORROW: caller lends read-only access (like a const reference)\nfn inspect(data: &str) { \u002F* can read data, can't modify or store it *\u002F }\n\n\u002F\u002F MUTABLE BORROW: caller lends exclusive write access\nfn modify(data: &mut String) { \u002F* can modify, but no other refs can exist *\u002F }\n```\n\n**Default to borrowing.** Only take ownership when you need to store or move the value.\nThink of `&T` as Python's normal function args, and owned `T` as \"I'm taking this from you.\"\n\n### Rule: `correctness-lifetimes`\n\nLet the compiler infer lifetimes. Only annotate when the compiler asks:\n\n```rust\n\u002F\u002F GOOD: compiler infers lifetimes automatically (elision rules)\nfn first_word(s: &str) -> &str {\n    s.split_whitespace().next().unwrap_or(\"\")\n}\n\n\u002F\u002F ONLY annotate when the compiler needs help (multiple references in, one out)\nfn longest\u003C'a>(x: &'a str, y: &'a str) -> &'a str {\n    if x.len() > y.len() { x } else { y }\n}\n\u002F\u002F 'a means: the returned reference lives as long as BOTH inputs.\n\u002F\u002F Python equivalent: this is like guaranteeing the return value won't\n\u002F\u002F outlive either of the inputs — the compiler checks this for you.\n```\n\n### Rule: `correctness-clone-explicit`\n\nMUST call `.clone()` explicitly on non-`Copy` types. Never hide clones in closures:\n\n```rust\n\u002F\u002F BAD: hidden clone inside closure — easy to miss the allocation\nlet names: Vec\u003CString> = items.iter().map(|i| i.name).collect(); \u002F\u002F won't compile\n\n\u002F\u002F GOOD: explicit clone makes the cost visible\nlet names: Vec\u003CString> = items.iter().map(|i| i.name.clone()).collect();\n\n\u002F\u002F BETTER: borrow if you don't need ownership\nlet names: Vec\u003C&str> = items.iter().map(|i| i.name.as_str()).collect();\n```\n\n### Rule: `correctness-let-else`\n\nUse `let-else` for early returns on pattern match failure (Rust 1.65+):\n\n```rust\n\u002F\u002F BAD: nested match\nfn process(input: Option\u003C&str>) -> Result\u003C()> {\n    match input {\n        Some(val) => {\n            \u002F\u002F deeply nested logic...\n        }\n        None => return Err(anyhow!(\"missing input\")),\n    }\n}\n\n\u002F\u002F GOOD: flat control flow with let-else\nfn process(input: Option\u003C&str>) -> Result\u003C()> {\n    let Some(val) = input else {\n        return Err(anyhow!(\"missing input\"));\n    };\n    \u002F\u002F val is bound here, no nesting\n    Ok(())\n}\n```\n\n---\n\n## 2. Security (CRITICAL)\n\n### Rule: `security-no-secrets-in-code`\n\nNEVER store secrets, API keys, or passwords in code. Use `.env` files:\n\n```rust\nuse dotenvy::dotenv;\n\nfn main() {\n    dotenv().ok();\n    let api_key = std::env::var(\"API_KEY\")\n        .expect(\"API_KEY must be set\");\n}\n```\n\nEnsure `.env` is in `.gitignore`.\n\n### Rule: `security-no-log-secrets`\n\nNEVER log sensitive information. Use the `secrecy` crate for sensitive data types:\n\n```rust\nuse secrecy::{Secret, ExposeSecret};\n\nstruct Config {\n    api_key: Secret\u003CString>,  \u002F\u002F Debug\u002FDisplay print \"[REDACTED]\"\n}\n\n\u002F\u002F Only expose when actually needed for the API call\nfn make_request(config: &Config) {\n    let key = config.api_key.expose_secret();\n    \u002F\u002F key is &str — use it, then it's dropped\n}\n```\n\n### Rule: `security-no-unsafe`\n\nNEVER use `unsafe` unless absolutely necessary. When required, document safety invariants\nwith a `\u002F\u002F SAFETY:` comment explaining why the invariants hold:\n\n```rust\n\u002F\u002F SAFETY: `ptr` is guaranteed non-null and properly aligned because\n\u002F\u002F it was obtained from `Box::into_raw` on the line above, and no\n\u002F\u002F other code has accessed or freed it since.\nunsafe { *ptr = value; }\n```\n\n### Rule: `security-input-validation`\n\nValidate all external input at system boundaries. Use newtypes with validation:\n\n```rust\nstruct Port(u16);\nimpl Port {\n    fn new(value: u16) -> Result\u003CSelf, anyhow::Error> {\n        anyhow::ensure!(value > 0 && value \u003C 65536, \"invalid port: {value}\");\n        Ok(Self(value))\n    }\n}\n```\n\n---\n\n## 3. Error Handling (CRITICAL)\n\n### Rule: `errors-thiserror-libraries`\n\nLibrary crates MUST define structured error types with `thiserror`:\n\n```rust\nuse thiserror::Error;\n\n#[derive(Debug, Error)]\npub enum ParseError {\n    #[error(\"invalid header at byte {offset}: {reason}\")]\n    InvalidHeader { offset: usize, reason: String },\n\n    #[error(\"unsupported version {0}\")]\n    UnsupportedVersion(u32),\n\n    \u002F\u002F #[from] auto-implements From\u003Cstd::io::Error> for ParseError\n    #[error(transparent)]\n    Io(#[from] std::io::Error),\n}\n```\n\n### Rule: `errors-anyhow-applications`\n\nApplication\u002Fbinary crates use `anyhow` for ad-hoc error context:\n\n```rust\nuse anyhow::{Context, Result};\n\nfn load_config(path: &Path) -> Result\u003CConfig> {\n    let contents = std::fs::read_to_string(path)\n        .context(\"failed to read config file\")?;  \u002F\u002F Always add context\n    let config: Config = toml::from_str(&contents)\n        .with_context(|| format!(\"failed to parse {}\", path.display()))?;\n    Ok(config)\n}\n```\n\n### Rule: `errors-no-unwrap`\n\n- **NEVER** use `.unwrap()` in production code paths\n- Use `.expect(\"invariant: reason\")` ONLY for true invariant violations with a descriptive message\n- In library code, NEVER use `.unwrap()` or `.expect()` — always return `Result`\n\n### Rule: `errors-context`\n\nEvery `?` propagation at a module boundary MUST have `.context()` or `.with_context()`:\n\n```rust\n\u002F\u002F BAD: raw ? loses context — error says \"No such file\" with no clue WHICH file\nlet data = std::fs::read(path)?;\n\n\u002F\u002F GOOD: context explains what we were trying to do\nlet data = std::fs::read(path)\n    .with_context(|| format!(\"reading input file {}\", path.display()))?;\n```\n\n### Rule: `errors-boundary-pattern`\n\nError handling has three zones:\n1. **Library internals** — `thiserror` enums, no `anyhow`\n2. **Application logic** — `anyhow::Result`, `.context()` everywhere\n3. **API boundaries** (axum handlers, CLI) — convert to user-facing messages, log internal details\n\n```rust\n\u002F\u002F axum handler: boundary between internal errors and HTTP responses\nasync fn get_item(Path(id): Path\u003Cu64>) -> Result\u003CJson\u003CItem>, AppError> {\n    let item = db::find_item(id)\n        .await\n        .context(\"database lookup failed\")?;  \u002F\u002F anyhow context\n    Ok(Json(item))\n}\n\n\u002F\u002F AppError converts anyhow::Error to HTTP status + log\nstruct AppError(anyhow::Error);\nimpl IntoResponse for AppError {\n    fn into_response(self) -> Response {\n        tracing::error!(error = %self.0, \"request failed\");\n        (StatusCode::INTERNAL_SERVER_ERROR, \"internal error\").into_response()\n    }\n}\n```\n\n---\n\n\nSee [RULES_DETAILED.md](references\u002FRULES_DETAILED.md) for detailed rules on type system, conventions, async\u002Fconcurrency, axum, testing, performance, cargo workspaces, documentation, and style.\n","# Rust Best Practices (Project Skill)\n\nThis skill is a curated set of atomic rules for writing and refactoring Rust in *this* repo.\nAssume the reader is a Python expert but a Rust novice. Include additional code comments\naround Rust-specific nuances that a Python developer may not recognize.\n\n## Advanced Patterns Reference\n\nSee **[references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md)** for deep-dive content:\nsealed traits, extension traits, HRTBs, `'static` misconceptions, Pin\u002FUnpin, smart pointer\ndecision tree, interior mutability, serde advanced patterns, tracing layers, CI pipeline tools,\nproperty-based testing, snapshot testing, and Rust 2024 edition features.\n\n## Project Defaults (apply unless explicitly overridden)\n\n- **Error Handling:** `thiserror` for library crates, `anyhow` for application crates\n- **Async Runtime:** `tokio` (multi-threaded by default)\n- **HTTP Server:** `axum` with `tower` middleware\n- **HTTP Client:** `reqwest`\n- **CLI:** `clap` with derive macros\n- **Serialization:** `serde` + `serde_json`\n- **Logging:** `tracing` + `tracing-subscriber` (NEVER `println!` for diagnostics)\n- **TUI:** `ratatui` + `crossterm`\n- **Data Processing:** `polars` (NEVER other dataframe libraries)\n- **CPU Parallelism:** `rayon`\n- **Progress Bars:** `indicatif` with contextually sensitive messages\n- **Packaging:** `cargo` for builds, deps, and workspace management\n\n## When to Apply\n\nUse this skill whenever you:\n- create or refactor Rust crates, binaries, libraries, or workspaces\n- add error handling, async code, or network calls\n- change `Cargo.toml` dependencies or workspace structure\n- add tests or fix bugs\n- build WASM or PyO3\u002Fmaturin bridges\n\n## Categories (priority order)\n\n1. Correctness & Ownership (CRITICAL\u002FHIGH): `correctness-`\n2. Security (CRITICAL\u002FHIGH): `security-`\n3. Error Handling (CRITICAL): `errors-`\n4. Type System (HIGH): `types-`\n5. Conventions (HIGH): `conventions-`\n6. Async & Concurrency (HIGH\u002FMEDIUM): `async-`\n7. Testing (HIGH\u002FMEDIUM): `testing-`\n8. Performance & Memory (MEDIUM): `perf-`\n9. Cargo & Workspaces (MEDIUM): `cargo-`\n10. Documentation (MEDIUM): `docs-`\n11. Style & Maintainability (MEDIUM\u002FLOW): `style-`\n\n## Quick Reference (house rules)\n\n- `correctness-ownership` — understand move vs borrow; prefer borrowing\n- `correctness-lifetimes` — let the compiler infer; annotate only when required\n- `correctness-clone-explicit` — call `.clone()` explicitly on non-`Copy` types\n- `correctness-let-else` — use `let-else` for early returns on pattern failure\n- `errors-thiserror-libraries` — use `thiserror` in library crates\n- `errors-anyhow-applications` — use `anyhow` in application\u002Fbinary crates\n- `errors-no-unwrap` — NEVER `.unwrap()` in production code\n- `errors-context` — add `.context()` to every `?` at module boundaries\n- `errors-boundary-pattern` — three zones: library\u002Fapp\u002FAPI boundary\n- `conventions-tracing` — use `tracing` for all observability\n- `conventions-clap-derive` — use `clap` derive macros for CLI\n- `conventions-serde` — use `serde` for all serialization\n- `conventions-reqwest` — use `reqwest` with shared client for HTTP\n- `conventions-no-emoji` — NEVER use emoji or unicode emoji-like chars\n- `conventions-cargo-deps-complete` — every `use` needs a `Cargo.toml` entry\n- `conventions-function-design` — single responsibility, max 5 params\n- `conventions-no-debug-output` — NEVER commit `println!`\u002F`dbg!`\n- `types-newtype` — use newtypes to distinguish semantically different values\n- `types-typestate` — use the Type State Pattern for compile-time state machines\n- `types-sealed-trait` — seal public traits in libraries to allow evolution\n- `types-option-over-sentinel` — prefer `Option\u003CT>` over sentinel values\n- `async-structured` — use structured concurrency with `JoinSet`\n- `async-spawn-blocking` — offload CPU-bound work to `spawn_blocking`\n- `async-send-sync` — understand `Send`\u002F`Sync` bounds for threaded runtimes\n- `async-cancellation` — use `CancellationToken` for graceful shutdown\n- `async-mutex-vs-rwlock` — `RwLock` for read-heavy, `Mutex` for simple exclusive\n- `perf-borrow-first` — prefer `&T` over owned `T` in function params\n- `perf-cow` — use `Cow\u003C'_, str>` when ownership is conditionally needed\n- `perf-vec-capacity` — use `Vec::with_capacity()` when size is known\n- `perf-iterators` — prefer iterator combinators over manual loops\n- `testing-arrange-act-assert` — follow AAA pattern in all tests\n- `testing-proptest` — property-based tests for roundtrip\u002Finvariant checks\n- `testing-doc-tests` — doc examples are compiled and run by `cargo test`\n- `cargo-workspace` — share deps via `[workspace.dependencies]`\n- `cargo-features` — additive feature flags, minimal defaults\n- `cargo-ci-tools` — `cargo-deny`, `cargo-audit`, `cargo-machete` in CI\n- `style-rustfmt` — all code formatted with `rustfmt`\n- `style-clippy-clean` — zero clippy warnings (`-D warnings`)\n- `docs-public-items` — doc comments on all public items\n\n---\n\n## 1. Correctness & Ownership (CRITICAL)\n\nRust's ownership system is the biggest difference from Python. In Python, everything is\nreference-counted and garbage-collected. In Rust, each value has exactly one owner, and\nthe compiler enforces this at compile time — no GC overhead, no use-after-free.\n\n### Rule: `correctness-ownership`\n\nUnderstand the three modes of passing data:\n\n```rust\n\u002F\u002F MOVE: caller gives up ownership (like Python's only mode, but enforced)\nfn consume(data: String) { \u002F* data is owned here, freed when function ends *\u002F }\n\n\u002F\u002F BORROW: caller lends read-only access (like a const reference)\nfn inspect(data: &str) { \u002F* can read data, can't modify or store it *\u002F }\n\n\u002F\u002F MUTABLE BORROW: caller lends exclusive write access\nfn modify(data: &mut String) { \u002F* can modify, but no other refs can exist *\u002F }\n```\n\n**Default to borrowing.** Only take ownership when you need to store or move the value.\nThink of `&T` as Python's normal function args, and owned `T` as \"I'm taking this from you.\"\n\n### Rule: `correctness-lifetimes`\n\nLet the compiler infer lifetimes. Only annotate when the compiler asks:\n\n```rust\n\u002F\u002F GOOD: compiler infers lifetimes automatically (elision rules)\nfn first_word(s: &str) -> &str {\n    s.split_whitespace().next().unwrap_or(\"\")\n}\n\n\u002F\u002F ONLY annotate when the compiler needs help (multiple references in, one out)\nfn longest\u003C'a>(x: &'a str, y: &'a str) -> &'a str {\n    if x.len() > y.len() { x } else { y }\n}\n\u002F\u002F 'a means: the returned reference lives as long as BOTH inputs.\n\u002F\u002F Python equivalent: this is like guaranteeing the return value won't\n\u002F\u002F outlive either of the inputs — the compiler checks this for you.\n```\n\n### Rule: `correctness-clone-explicit`\n\nMUST call `.clone()` explicitly on non-`Copy` types. Never hide clones in closures:\n\n```rust\n\u002F\u002F BAD: hidden clone inside closure — easy to miss the allocation\nlet names: Vec\u003CString> = items.iter().map(|i| i.name).collect(); \u002F\u002F won't compile\n\n\u002F\u002F GOOD: explicit clone makes the cost visible\nlet names: Vec\u003CString> = items.iter().map(|i| i.name.clone()).collect();\n\n\u002F\u002F BETTER: borrow if you don't need ownership\nlet names: Vec\u003C&str> = items.iter().map(|i| i.name.as_str()).collect();\n```\n\n### Rule: `correctness-let-else`\n\nUse `let-else` for early returns on pattern match failure (Rust 1.65+):\n\n```rust\n\u002F\u002F BAD: nested match\nfn process(input: Option\u003C&str>) -> Result\u003C()> {\n    match input {\n        Some(val) => {\n            \u002F\u002F deeply nested logic...\n        }\n        None => return Err(anyhow!(\"missing input\")),\n    }\n}\n\n\u002F\u002F GOOD: flat control flow with let-else\nfn process(input: Option\u003C&str>) -> Result\u003C()> {\n    let Some(val) = input else {\n        return Err(anyhow!(\"missing input\"));\n    };\n    \u002F\u002F val is bound here, no nesting\n    Ok(())\n}\n```\n\n---\n\n## 2. Security (CRITICAL)\n\n### Rule: `security-no-secrets-in-code`\n\nNEVER store secrets, API keys, or passwords in code. Use `.env` files:\n\n```rust\nuse dotenvy::dotenv;\n\nfn main() {\n    dotenv().ok();\n    let api_key = std::env::var(\"API_KEY\")\n        .expect(\"API_KEY must be set\");\n}\n```\n\nEnsure `.env` is in `.gitignore`.\n\n### Rule: `security-no-log-secrets`\n\nNEVER log sensitive information. Use the `secrecy` crate for sensitive data types:\n\n```rust\nuse secrecy::{Secret, ExposeSecret};\n\nstruct Config {\n    api_key: Secret\u003CString>,  \u002F\u002F Debug\u002FDisplay print \"[REDACTED]\"\n}\n\n\u002F\u002F Only expose when actually needed for the API call\nfn make_request(config: &Config) {\n    let key = config.api_key.expose_secret();\n    \u002F\u002F key is &str — use it, then it's dropped\n}\n```\n\n### Rule: `security-no-unsafe`\n\nNEVER use `unsafe` unless absolutely necessary. When required, document safety invariants\nwith a `\u002F\u002F SAFETY:` comment explaining why the invariants hold:\n\n```rust\n\u002F\u002F SAFETY: `ptr` is guaranteed non-null and properly aligned because\n\u002F\u002F it was obtained from `Box::into_raw` on the line above, and no\n\u002F\u002F other code has accessed or freed it since.\nunsafe { *ptr = value; }\n```\n\n### Rule: `security-input-validation`\n\nValidate all external input at system boundaries. Use newtypes with validation:\n\n```rust\nstruct Port(u16);\nimpl Port {\n    fn new(value: u16) -> Result\u003CSelf, anyhow::Error> {\n        anyhow::ensure!(value > 0 && value \u003C 65536, \"invalid port: {value}\");\n        Ok(Self(value))\n    }\n}\n```\n\n---\n\n## 3. Error Handling (CRITICAL)\n\n### Rule: `errors-thiserror-libraries`\n\nLibrary crates MUST define structured error types with `thiserror`:\n\n```rust\nuse thiserror::Error;\n\n#[derive(Debug, Error)]\npub enum ParseError {\n    #[error(\"invalid header at byte {offset}: {reason}\")]\n    InvalidHeader { offset: usize, reason: String },\n\n    #[error(\"unsupported version {0}\")]\n    UnsupportedVersion(u32),\n\n    \u002F\u002F #[from] auto-implements From\u003Cstd::io::Error> for ParseError\n    #[error(transparent)]\n    Io(#[from] std::io::Error),\n}\n```\n\n### Rule: `errors-anyhow-applications`\n\nApplication\u002Fbinary crates use `anyhow` for ad-hoc error context:\n\n```rust\nuse anyhow::{Context, Result};\n\nfn load_config(path: &Path) -> Result\u003CConfig> {\n    let contents = std::fs::read_to_string(path)\n        .context(\"failed to read config file\")?;  \u002F\u002F Always add context\n    let config: Config = toml::from_str(&contents)\n        .with_context(|| format!(\"failed to parse {}\", path.display()))?;\n    Ok(config)\n}\n```\n\n### Rule: `errors-no-unwrap`\n\n- **NEVER** use `.unwrap()` in production code paths\n- Use `.expect(\"invariant: reason\")` ONLY for true invariant violations with a descriptive message\n- In library code, NEVER use `.unwrap()` or `.expect()` — always return `Result`\n\n### Rule: `errors-context`\n\nEvery `?` propagation at a module boundary MUST have `.context()` or `.with_context()`:\n\n```rust\n\u002F\u002F BAD: raw ? loses context — error says \"No such file\" with no clue WHICH file\nlet data = std::fs::read(path)?;\n\n\u002F\u002F GOOD: context explains what we were trying to do\nlet data = std::fs::read(path)\n    .with_context(|| format!(\"reading input file {}\", path.display()))?;\n```\n\n### Rule: `errors-boundary-pattern`\n\nError handling has three zones:\n1. **Library internals** — `thiserror` enums, no `anyhow`\n2. **Application logic** — `anyhow::Result`, `.context()` everywhere\n3. **API boundaries** (axum handlers, CLI) — convert to user-facing messages, log internal details\n\n```rust\n\u002F\u002F axum handler: boundary between internal errors and HTTP responses\nasync fn get_item(Path(id): Path\u003Cu64>) -> Result\u003CJson\u003CItem>, AppError> {\n    let item = db::find_item(id)\n        .await\n        .context(\"database lookup failed\")?;  \u002F\u002F anyhow context\n    Ok(Json(item))\n}\n\n\u002F\u002F AppError converts anyhow::Error to HTTP status + log\nstruct AppError(anyhow::Error);\nimpl IntoResponse for AppError {\n    fn into_response(self) -> Response {\n        tracing::error!(error = %self.0, \"request failed\");\n        (StatusCode::INTERNAL_SERVER_ERROR, \"internal error\").into_response()\n    }\n}\n```\n\n---\n\n\nSee [RULES_DETAILED.md](references\u002FRULES_DETAILED.md) for detailed rules on type system, conventions, async\u002Fconcurrency, axum, testing, performance, cargo workspaces, documentation, and style.\n",{"name":5,"license":14,"composes":48,"metadata":49,"provides":74,"taxonomy":75,"triggers":78,"description":89},[],{"edition":37,"defaults":50,"language":25,"rust_versions":72},{"cli":51,"tui":52,"style":53,"logging":60,"testing":61,"progress":64,"packaging":65,"http_client":66,"http_server":30,"parallelism":67,"async_runtime":40,"serialization":68,"error_handling":69,"data_processing":28},"clap (derive)","ratatui + crossterm",{"naming":54,"indentation":58,"max_line_length":59},{"types":55,"constants":56,"functions":57},"PascalCase","SCREAMING_SNAKE_CASE","snake_case","4 spaces",100,"tracing + tracing-subscriber",{"runner":62,"framework":63},"cargo test","built-in (#[test])","indicatif","cargo","reqwest","rayon","serde + serde_json",{"libraries":70,"applications":71},"thiserror","anyhow",[73],"1.85+",[5],[76,77,33],"validation","precision",[23,79,80,81,82,83,29,84,85,86,87,88],"rust conventions","rust code review","cargo workspace","thiserror anyhow","tokio async","axum server","clap cli","rust performance","rust ownership lifetimes","rust edition 2024","Repo-specific Rust best practices for agentic coding: thiserror + anyhow error handling, tokio async runtime, tracing for observability, clap for CLI, axum for HTTP, serde patterns, cargo workspace conventions, ownership and lifetimes, and idiomatic Rust 2024 edition patterns.\n","main","92d3cf5de96f8f7e1668e121e82a95faaa78a995","skills\u002Fbest-practices-rust",2,"https:\u002F\u002Fgithub.com\u002Fcateyephotos\u002Fagent-skills","https:\u002F\u002Fgithub.com\u002Fcateyephotos","2026-06-13 12:05:20",{"source":8,"skillName":5,"commands":98,"prompt":108,"zipAvailable":109},[99,102,105],{"tool":100,"command":101},"npx","npx skills add cateyephotos\u002Fagent-skills --skill best-practices-rust",{"tool":103,"command":104},"bunx","bunx skills add cateyephotos\u002Fagent-skills --skill best-practices-rust",{"tool":106,"command":107},"pnpm","pnpm dlx skills add cateyephotos\u002Fagent-skills --skill best-practices-rust","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fcateyephotos\u002Fagent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fbest-practices-rust\u002FSKILL.md",true,[],[112,138,165,190,208,227],{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":118,"publishedAt":43},"01M71DBADHWPBVJWYQT9VAD1XE","best-practices-streamdeck","Project-specific best practices for the Stream Deck control suite: icon format constraints, socket vs config boundaries, widget button lifecycle, page creation via build_page, ArangoDB fallback patterns, and NVIS palette compliance.","https:\u002F\u002Fgithub.com\u002Fcateyephotos\u002Fagent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fbest-practices-streamdeck\u002FSKILL.md",[],[24,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137],"best practices streamdeck","creation","for","project","page","static","deck","socket","lifecycle","monitor","typer","best-practices","icon","task","palette","control","native","via","build",{"skillNo":139,"name":140,"nameZh":6,"description":141,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":142,"categories":143,"keywords":147,"publishedAt":43},"01M71DARX9YN0QEXS6EM2C6E4X","best-practices-scillm","Error recovery and anti-patterns for scillm LLM proxy. Load this when scillm calls fail, timeout, or return unexpected results. Covers batch sizing, header requirements, model selection, and debugging workflow.","https:\u002F\u002Fgithub.com\u002Fcateyephotos\u002Fagent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fbest-practices-scillm\u002FSKILL.md",[144],{"categoryNo":145,"categoryName":146,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000023","Skill与智能体开发",[148,24,149,42,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,121],"best practices scillm","scillm","processing","model","selection","model selection","error recovery","debugging","when","workflow","batch","anti-patterns","rate","rate limit","patterns","limit","proxy",{"skillNo":166,"name":167,"nameZh":6,"description":168,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":169,"categories":170,"keywords":174,"publishedAt":43},"01M71DACXQ43RCTYYCB8WB1KPG","react-native-skills","React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.","https:\u002F\u002Fgithub.com\u002Fcateyephotos\u002Fagent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fbest-practices-react\u002Fskills\u002Freact-native-skills\u002FSKILL.md",[171],{"categoryNo":172,"categoryName":173,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000009","前端开发",[175,176,135,177,178,179,180,121,39,181,182,183,184,185,186,156,24,187,188,189],"react","react native","react native skills","modules","platform","animations","vercel","implementing","triggers","use","react native components","apps","tasks","components","with",{"skillNo":191,"name":192,"nameZh":6,"description":193,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":194,"categories":195,"keywords":197,"publishedAt":43},"01M71DA9YZ05NTRPEK9JAX283K","react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002Fcateyephotos\u002Fagent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fbest-practices-react\u002Fskills\u002Freact-best-practices\u002FSKILL.md",[196],{"categoryNo":172,"categoryName":173,"taxonomyType":20,"taxonomyTypeDesc":21},[175,198,24,39,199,156,35,187,188,200,201,202,203,204,162,205,181,206,183,207],"react best practices","writing","data fetching","react components","next","refactoring","data","Optimization","guidelines","pages",{"skillNo":209,"name":210,"nameZh":6,"description":211,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":212,"categories":213,"keywords":215,"publishedAt":43},"01M71DA77CYKDT0Q7VAXG4Y9QW","composition-patterns","React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes.","https:\u002F\u002Fgithub.com\u002Fcateyephotos\u002Fagent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fbest-practices-react\u002Fskills\u002Fcomposition-patterns\u002FSKILL.md",[214],{"categoryNo":172,"categoryName":173,"taxonomyType":20,"taxonomyTypeDesc":21},[216,217,162,218,219,181,220,183,221,222,184,156,223,187,188,224,225,226,175,189],"Composition","composition patterns","react composition patterns","react 19","render","boolean","component architecture","reusable","architecture","react composition","api",{"skillNo":228,"name":229,"nameZh":6,"description":230,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":231,"categories":232,"keywords":234,"publishedAt":43},"01M71DA084TD9WEW07QP9PXDH4","best-practices-react","React, Next.js, React Native, and web design best practices from Vercel Engineering.\nUse when writing, reviewing, or refactoring React\u002FNext.js\u002FReact Native components,\noptimizing performance, auditing UI accessibility, or designing component APIs.\nTriggers: \"review react\", \"optimize component\", \"check accessibility\", \"react best practices\",\n\"component architecture\", \"react native performance\".","https:\u002F\u002Fgithub.com\u002Fcateyephotos\u002Fagent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fbest-practices-react\u002FSKILL.md",[233],{"categoryNo":172,"categoryName":173,"taxonomyType":20,"taxonomyTypeDesc":21},[175,235,24,236,222,199,188,224,176,237,203,238,198,239,183,130,184,240,241,242],"best practices react","design","component","typescript","ui","Next.js","check","react component"]