rust-principal-engineer
Principal/Senior-level Rust playbook for architecture, ownership, async systems, error handling, observability, security, testing, and production readiness. Use when: designing Rust services or CLIs, reviewing unsafe/concurrent code, debugging panics and performance regressions, hardening APIs, or preparing a codebase for production.
What this skill does
# Rust Mastery (Senior → Principal)
## Operate
- Start by confirming: goal, scope, crate type (bin/lib/workspace), Rust/MSRV constraints, target platform, unsafe requirements, latency/throughput goals, and the definition of done.
- Prefer small, reviewable changes with tests and explicit tradeoffs.
- Default to stable Rust, stdlib-first patterns, and boring solutions before adding macros or dependencies.
- Treat production code as an operable system: timeouts, shutdown, observability, and failure modes are part of the feature.
> The target is not “clever Rust”. The target is code that remains correct, observable, and maintainable under production stress.
## Default Rust Standards
- Keep `main.rs` thin; put business logic in testable modules or crates.
- Prefer typed domain errors with `thiserror`; use `anyhow` at application boundaries and CLIs.
- No `unwrap()`/`expect()` on production paths unless the invariant is truly impossible and documented by the code structure.
- Introduce traits at the consumer boundary, not pre-emptively.
- Prefer ownership and borrowing that make invalid states unrepresentable before reaching for `Arc<Mutex<_>>`.
- Every spawned task needs an owner, a cancellation path, and an error handling strategy.
- Keep unsafe code isolated, minimal, and justified with explicit invariants.
## “Bad vs Good” (common production pitfalls)
```rust
// ❌ BAD: panic in a production path with no context.
let user = repo.find(id).await.unwrap();
// ✅ GOOD: propagate context with a typed error.
let user = repo
.find(id)
.await
.map_err(AppError::from)?
.ok_or(AppError::UserNotFound { id })?;
```
```rust
// ❌ BAD: detached task with no owner and no shutdown path.
tokio::spawn(async move {
loop {
run_job().await;
}
});
// ✅ GOOD: task respects cancellation and reports failures.
tokio::spawn(async move {
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
result = run_job() => {
if let Err(err) = result {
tracing::error!(error = %err, "job failed");
}
}
}
}
});
```
## Workflow (Feature / Refactor / Bug)
1. Reproduce the behavior or codify it with a failing test.
2. Decide boundaries: transport, orchestration, domain, adapters, persistence.
3. Define failure modes: panics, cancellation, partial writes, retries, timeouts, shutdown.
4. Implement the smallest end-to-end slice.
5. Add tests, benchmarks, or property tests when the risk justifies them.
6. Validate formatting, lints, security, and release behavior.
## Validation Commands
- Run `cargo fmt --all --check`.
- Run `cargo clippy --workspace --all-targets --all-features -- -D warnings`.
- Run `cargo test --workspace --all-features`.
- Run `cargo test -- --nocapture` when debugging test output.
- Run `cargo nextest run --workspace --all-features` if available for faster suites.
- Run `cargo llvm-cov` if coverage matters.
- Run `cargo audit` before release.
- Run `cargo deny check` if the repo uses policy checks for licenses/advisories.
## Architecture & Boundaries
- Prefer a modular monolith before splitting into many crates or services.
- Keep boundary direction explicit: transport -> use-case -> domain -> ports -> adapters.
- Map errors once at the boundary: HTTP/gRPC/CLI should translate domain errors consistently.
- Keep domain types free from transport-specific concerns where practical.
## Async, Concurrency, and Ownership Guardrails
- Avoid “shared mutable state first”; prefer message passing or ownership transfer.
- If you use `Arc<Mutex<_>>`, document the protected invariant and expected contention.
- Bound concurrency for fan-out work; avoid unbounded task spawning.
- Always set timeouts for outbound IO and database acquisition.
- Treat cancellation as part of correctness, not just cleanup.
## Service/API Defaults
- Use structured tracing with stable fields such as `service`, `trace_id`, `request_id`, `tenant_id`, and `status`.
- Expose health/readiness endpoints for services.
- Validate input at the boundary; never trust deserialized payloads blindly.
- Make error taxonomy explicit: invalid, unauthorized, forbidden, not-found, conflict, unavailable.
- Prefer idempotent handlers for side-effecting operations where retries may happen.
## Performance & Safety Defaults
- Measure before optimizing with `criterion`, flamegraphs, or profiler traces.
- Watch clone frequency, allocation churn, lock contention, and serialization hotspots.
- Prefer zero-copy and borrowing only when it improves the real bottleneck and keeps code readable.
- Use `panic = "abort"` only when the operational tradeoff is understood.
## Security Checklist (Minimum)
- No secrets in logs, panic messages, or `Debug` output.
- Validate lengths, counts, recursion depth, and body sizes for untrusted input.
- Use parameterized SQL and least-privilege credentials.
- Prefer allowlists for outbound network and file operations in high-risk systems.
- Keep unsafe blocks isolated and reviewed as security-sensitive code.
## References
- Architecture and dependency direction: [references/architecture.md](references/architecture.md)
- Advanced patterns: [references/advanced-patterns.md](references/advanced-patterns.md)
- Bug prevention: [references/bug-prevention.md](references/bug-prevention.md)
- Code review checklist: [references/code-review-guide.md](references/code-review-guide.md)
- Debugging and profiling: [references/debugging-guide.md](references/debugging-guide.md)
- Database and SQLX: [references/database-and-sqlx.md](references/database-and-sqlx.md)
- HTTP service patterns: [references/http-service-patterns.md](references/http-service-patterns.md)
- Observability: [references/observability.md](references/observability.md)
- Reliability: [references/reliability.md](references/reliability.md)
- Senior habits and idioms: [references/senior-habits.md](references/senior-habits.md)
- Trusted libraries: [references/trusted-libraries.md](references/trusted-libraries.md)
- Production readiness and operations: [references/production-readiness.md](references/production-readiness.md)
## Scripts & Assets
- `scripts/scaffold_project.py` - bootstrap a Rust project skeleton.
- `assets/github-ci.yml` - CI baseline for GitHub Actions.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.