Skip to content

feat(rules): add Rust language rules (rebased #660)#686

Merged
affaan-m merged 4 commits intomainfrom
community/pr-660-rust-rules
Mar 20, 2026
Merged

feat(rules): add Rust language rules (rebased #660)#686
affaan-m merged 4 commits intomainfrom
community/pr-660-rust-rules

Conversation

@affaan-m
Copy link
Copy Markdown
Owner

@affaan-m affaan-m commented Mar 20, 2026

Summary

  • Rebased community PR feat(rules): add Rust language rules #660 by @chris-yyau onto latest main
  • Adds Rust language rules: coding style, hooks, patterns, testing, and security
  • Resolved AGENTS.md catalog count conflict (27 agents, 113 skills, 58 commands)
  • All 1421 tests passing

Original PR

Closes #660

Test plan

  • All 1421 tests pass after rebase
  • Catalog counts match filesystem
  • Conflict in AGENTS.md resolved correctly

Summary by cubic

Adds Rust language rules extending the common set across coding style, hooks, patterns, testing, and security. Updates catalog counts in AGENTS.md and README.md (27 agents, 113 skills, 58 commands) and incorporates review fixes to examples, SQL placeholders, and hook paths.

  • New Features

    • Coding style: cargo fmt, clippy, ownership/borrowing, error handling (anyhow/thiserror), iterators, module layout.
    • Hooks: PostToolUse for cargo fmt, cargo clippy, cargo check.
    • Patterns: repository traits, newtype, enum state machines, builder, sealed traits, API response envelope.
    • Testing: #[test], #[tokio::test], rstest, proptest, mockall, coverage via cargo-llvm-cov.
    • Security: env secrets, parameterized SQL with sqlx, unsafe audit, dependency checks (cargo audit, cargo deny), safe error responses.
  • Bug Fixes

    • Examples: add missing imports, use anyhow::Result consistently, correct #[tokio::test].
    • SQL/hooks: switch sqlx placeholders to Postgres $1; exclude Cargo.lock from hook paths.
    • Testing docs: fix mockall name collision and cargo test --test api_test command.

Written for commit db2ff64. Summary will update on new commits.

Summary by CodeRabbit

  • Documentation
    • Updated capability inventory: increased workflow skills by 4 and slash commands by 1.
    • Introduced comprehensive Rust-specific guidance covering coding style conventions, security best practices, design patterns, testing frameworks and strategies, and auto-formatting hooks.

chris-yyau and others added 4 commits March 20, 2026 00:55
Add language-specific rules for Rust extending the common rule set:
- coding-style.md: rustfmt, clippy, ownership idioms, error handling,
  iterator patterns, module organization, visibility
- hooks.md: PostToolUse hooks for rustfmt, clippy, cargo check
- patterns.md: trait-based repository, newtype, enum state machines,
  builder, sealed traits, API response envelope

Rules reference existing rust-patterns skill for deep content.

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
Add remaining Rust language-specific rules:
- testing.md: cargo test, rstest parameterized tests, mockall mocking
  with mock! macro, tokio async tests, cargo-llvm-cov coverage
- security.md: secrets via env vars, parameterized SQL with sqlx,
  parse-don't-validate input validation, unsafe code audit requirements,
  cargo-audit dependency scanning, proper HTTP error status codes

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
Fixes from Copilot, Greptile, Cubic, and CodeRabbit reviews:
- Add missing imports: use std::borrow::Cow, use anyhow::Context
- Use anyhow::Result<T> consistently (patterns.md, security.md)
- Change sqlx placeholder from ? to $1 (Postgres is most common)
- Remove Cargo.lock from hooks.md paths (auto-generated file)
- Fix tokio::test to show attribute form #[tokio::test]
- Fix mockall mock! name collision, wrap in #[cfg(test)] mod tests
- Fix --test target to match file layout (api_test, not integration)

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
Update documented counts to match actual repository state after rebase:
- Skills: 109 → 113 (new skills merged to main)
- Commands: 57 → 58 (new command merged to main)

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 20, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 003117fd-e731-45f5-9018-3ef4884c55c1

📥 Commits

Reviewing files that changed from the base of the PR and between 07f6156 and db2ff64.

📒 Files selected for processing (7)
  • AGENTS.md
  • README.md
  • rules/rust/coding-style.md
  • rules/rust/hooks.md
  • rules/rust/patterns.md
  • rules/rust/security.md
  • rules/rust/testing.md

📝 Walkthrough

Walkthrough

This PR adds five new Rust language-specific rule files—coding style, testing, patterns, hooks, and security—that extend the common rule set, and updates catalog counts in documentation from 109→113 skills and 57→58 commands.

Changes

Cohort / File(s) Summary
Rust Language Rules
rules/rust/coding-style.md, rules/rust/testing.md, rules/rust/patterns.md, rules/rust/hooks.md, rules/rust/security.md
Five new documentation files providing Rust-specific guidance on formatting (rustfmt/clippy), testing frameworks (rstest, proptest, mockall), design patterns (traits, newtypes, state machines, builders), PostToolUse hooks, and security practices (secrets, SQL injection prevention, unsafe code, dependency auditing).
Documentation Counts
README.md, AGENTS.md
Updated catalog counts: skills incremented from 109 to 113 and slash commands from 57 to 58.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Poem

🐰 Five scrolls of Rust wisdom unfurled with care,
From clippy's wise counsel to safety's snare,
With traits, tests, and secrets all neatly penned,
The hopping compiler hops 'round the bend! 🦀

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding Rust language rules with a clear reference to the rebased PR #660.
Linked Issues check ✅ Passed All objectives from #660 are met: five Rust rule files (coding-style, testing, patterns, hooks, security) added with YAML frontmatter, examples addressing security concerns, and catalog counts updated.
Out of Scope Changes check ✅ Passed All changes are in-scope: five new Rust rule files match the requirements in #660, plus README and AGENTS.md updates for catalog counts.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch community/pr-660-rust-rules
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@affaan-m affaan-m force-pushed the community/pr-660-rust-rules branch from ca5d166 to db2ff64 Compare March 20, 2026 07:56
@ecc-tools
Copy link
Copy Markdown
Contributor

ecc-tools bot commented Mar 20, 2026

Analyzing 5000 commits...

1 similar comment
@ecc-tools
Copy link
Copy Markdown
Contributor

ecc-tools bot commented Mar 20, 2026

Analyzing 5000 commits...

@ecc-tools
Copy link
Copy Markdown
Contributor

ecc-tools bot commented Mar 20, 2026

Analysis Complete

Generated ECC bundle from 500 commits | Confidence: 100%

View Pull Request #685

Repository Profile
Attribute Value
Language JavaScript
Framework Not detected
Commit Convention conventional
Test Directory separate
Detected Workflows (9)
Workflow Description
feature-development Standard feature implementation workflow
add-new-skill Adds a new skill to the repository, including documentation and review-driven iteration.
add-new-agent Adds a new agent to the repository, registers it in documentation, and updates agent catalogs.
add-language-rules Adds a new set of language-specific rules (coding-style, hooks, patterns, security, testing) for a programming language.
add-command-and-backing-skill Adds a new command (slash command) and a backing skill, with review-driven iteration.
Generated Instincts (17)
Domain Count
git 2
code-style 3
testing 3
workflow 9

After merging, import with:

/instinct-import .claude/homunculus/instincts/inherited/everything-claude-code-instincts.yaml

Files

  • .claude/ecc-tools.json
  • .claude/skills/everything-claude-code/SKILL.md
  • .agents/skills/everything-claude-code/SKILL.md
  • .agents/skills/everything-claude-code/agents/openai.yaml
  • .claude/identity.json
  • .codex/config.toml
  • .codex/AGENTS.md
  • .codex/agents/explorer.toml
  • .codex/agents/reviewer.toml
  • .codex/agents/docs-researcher.toml
  • .claude/homunculus/instincts/inherited/everything-claude-code-instincts.yaml
  • .claude/rules/everything-claude-code-guardrails.md
  • .claude/research/everything-claude-code-research-playbook.md
  • .claude/team/everything-claude-code-team-config.json
  • .claude/enterprise/controls.md
  • .claude/commands/feature-development.md
  • .claude/commands/add-new-skill.md
  • .claude/commands/add-new-agent.md

ECC Tools | Everything Claude Code

@ecc-tools
Copy link
Copy Markdown
Contributor

ecc-tools bot commented Mar 20, 2026

Analysis Complete

Generated ECC bundle from 500 commits | Confidence: 100%

View Pull Request #685

Repository Profile
Attribute Value
Language JavaScript
Framework Not detected
Commit Convention conventional
Test Directory separate
Detected Workflows (9)
Workflow Description
feature-development Standard feature implementation workflow
add-new-skill Adds a new skill to the repository, including documentation and review fixes.
add-new-agent Adds a new agent to the repository, registers it in documentation, and updates agent tables.
add-language-rules-suite Adds a full set of language-specific rules (coding-style, hooks, patterns, security, testing) for a new language.
add-new-command-and-backing-skill Adds a new slash command and its backing skill, with review and sample output fixes.
Generated Instincts (17)
Domain Count
git 2
code-style 3
testing 3
workflow 9

After merging, import with:

/instinct-import .claude/homunculus/instincts/inherited/everything-claude-code-instincts.yaml

Files

  • .claude/ecc-tools.json
  • .claude/skills/everything-claude-code/SKILL.md
  • .agents/skills/everything-claude-code/SKILL.md
  • .agents/skills/everything-claude-code/agents/openai.yaml
  • .claude/identity.json
  • .codex/config.toml
  • .codex/AGENTS.md
  • .codex/agents/explorer.toml
  • .codex/agents/reviewer.toml
  • .codex/agents/docs-researcher.toml
  • .claude/homunculus/instincts/inherited/everything-claude-code-instincts.yaml
  • .claude/rules/everything-claude-code-guardrails.md
  • .claude/research/everything-claude-code-research-playbook.md
  • .claude/team/everything-claude-code-team-config.json
  • .claude/enterprise/controls.md
  • .claude/commands/feature-development.md
  • .claude/commands/add-new-skill.md
  • .claude/commands/add-new-agent.md

ECC Tools | Everything Claude Code

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 7 files

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps bot commented Mar 20, 2026

Greptile Summary

This PR rebases community PR #660 onto the latest main, adding five Rust language rule files (coding-style.md, hooks.md, patterns.md, security.md, testing.md) under rules/rust/ and updating the skill/command counts in AGENTS.md and README.md to match the current filesystem state (113 skills, 58 commands).

The new rule files are well-structured and technically sound — they follow the same conventions as the existing Go, Python, and TypeScript rule directories (YAML frontmatter with glob paths, extends-comment referencing the common counterpart, code examples, and skill references).

Key observations:

  • Installer gapscripts/lib/install-manifests.js does not include rust in LEGACY_LANGUAGE_ALIAS_TO_CANONICAL. Running ./install.sh rust (the recommended method shown in rules/README.md) will fail with an "Unknown legacy language" error. The same gap exists for cpp, suggesting this is a recurring pattern when new language directories are added. Users must fall back to the manual cp -r rules/rust ~/.claude/rules/rust approach.
  • rules/README.md not updated — The directory structure listing and example install commands still only enumerate typescript, python, golang, swift, and php. Rust (and the several other languages added since v1.4.0) is absent, making the file misleading for newcomers.
  • Sync-only repository trait in patterns.md — The OrderRepository example uses synchronous methods. Most real-world Rust DB crates (sqlx, sea-orm) expose async APIs, so readers may be confused when they try to adapt this pattern.
  • Hand-rolled email validation in security.md — The Email::parse example implements its own @-position logic and is immediately qualified with "use a validated email crate for production." Leading with the insecure hand-rolled approach risks copy-paste misuse; the crate-based pattern should be the primary example.
  • Count rebase resolution — The 109 → 113 skills and 57 → 58 commands delta is accurate; the new counts match the actual filesystem contents and were already present on main from other merged PRs.

Confidence Score: 4/5

  • Safe to merge — documentation and content only; no runtime code paths are affected. Minor follow-up work needed for installer registration and README updates.
  • All changes are Markdown documentation files and count-string updates. No logic, security-sensitive code, or breaking changes are introduced. The Rust rule content is technically accurate and follows the established pattern. The main gaps (installer not registering rust, rules/README.md not updated) are documentation/discoverability issues rather than correctness bugs, and they mirror the same pattern seen when cpp was added.
  • No files require special attention for merging. Follow-up items: add rust to LEGACY_LANGUAGE_ALIAS_TO_CANONICAL in scripts/lib/install-manifests.js, and update rules/README.md to include Rust in the structure listing and install examples.

Important Files Changed

Filename Overview
rules/rust/coding-style.md New Rust coding style rule file — well-structured with correct YAML frontmatter, good coverage of Rust idioms (immutability, borrowing, error handling with thiserror/anyhow, iterators, module organization). No issues found.
rules/rust/hooks.md New minimal Rust hooks file listing cargo fmt, clippy, and cargo check as PostToolUse hooks. Consistent with the pattern used in golang/hooks.md. No issues.
rules/rust/patterns.md New Rust patterns file covering repository pattern, service layer, newtype, enum state machines, builder, sealed traits, and API response envelope. The repository trait is sync-only which may mislead async-Rust users — most real-world DB interactions in Rust are async.
rules/rust/security.md New Rust security rule file covering secrets, SQL injection, input validation, unsafe code, dependency security, and error messages. The manual email validation example contains logic that can produce edge-case false positives and is immediately qualified with "use a crate instead" — the example should lead with the crate approach.
rules/rust/testing.md New Rust testing rule file covering unit tests, parameterized tests with rstest, async tests with tokio::test, mocking with mockall, coverage with cargo-llvm-cov. The mockall::mock! example omits a version requirement comment which could confuse users on older toolchains.
AGENTS.md Updated skill/command counts from 109/57 to 113/58, matching the actual filesystem counts (113 skills, 58 commands). The rebase conflict was resolved correctly.
README.md Updated skill/command counts in the quick-start text and comparison table. The "29 rules" row in the comparison table was not updated, but that count predates this PR and was already stale — not introduced by this PR.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[User installs ECC plugin] --> B{Install Rust rules}
    B --> C["Option 1: ./install.sh rust\n(⚠️ not yet registered in\ninstall-manifests.js)"]
    B --> D["Option 2: Manual copy\ncp -r rules/rust ~/.claude/rules/rust"]
    D --> E[Claude Code loads rule files]
    E --> F{Rule file applies when\nmatching path glob}
    F --> G["**/*.rs → coding-style.md\npatterns.md, security.md\ntesting.md, hooks.md"]
    F --> H["**/Cargo.toml → hooks.md"]
    G --> I[Claude follows Rust-specific\nguidelines during code generation]
    H --> I
    I --> J["cargo fmt / clippy / check\nhints via hooks.md"]
    I --> K["thiserror/anyhow error patterns\nfrom coding-style.md"]
    I --> L["Repository/Builder/Newtype\npatterns from patterns.md"]
    I --> M["SQL injection, unsafe audits\nfrom security.md"]
    I --> N["rstest / mockall / tokio::test\nfrom testing.md"]
Loading

Last reviewed commit: "fix: update catalog ..."

Comment on lines +119 to +137
}
```

## Test Naming

Use descriptive names that explain the scenario:
- `creates_user_with_valid_email()`
- `rejects_order_when_insufficient_stock()`
- `returns_none_when_not_found()`

## Coverage

- Target 80%+ line coverage
- Use **cargo-llvm-cov** for coverage reporting
- Focus on business logic — exclude generated code and FFI bindings

```bash
cargo llvm-cov # Summary
cargo llvm-cov --html # HTML report
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 mockall::mock! macro name conflict

The mock! block names the struct Repo, which generates MockRepo. However, the trait UserRepository is defined in the outer use super::* scope. mockall::mock! regenerates the trait's impl inside the macro — it doesn't auto-detect the outer trait. If UserRepository is an external/imported trait, this is fine. But the example could cause confusion because pub Repo {} body is empty (no inherent methods) yet the impl block expects the full method list.

More importantly, the mockall::mock! syntax is correct for mockall ≥ 0.11, but older versions require automock or a slightly different macro form. Consider adding a version note (e.g., # Cargo.toml: mockall = "0.13") to the code block header or a comment, so readers know which API revision is being demonstrated.

Suggested change
}
```
## Test Naming
Use descriptive names that explain the scenario:
- `creates_user_with_valid_email()`
- `rejects_order_when_insufficient_stock()`
- `returns_none_when_not_found()`
## Coverage
- Target 80%+ line coverage
- Use **cargo-llvm-cov** for coverage reporting
- Focus on business logic — exclude generated code and FFI bindings
```bash
cargo llvm-cov # Summary
cargo llvm-cov --html # HTML report
mockall::mock! {
// Requires mockall ≥ 0.11 — add to Cargo.toml: mockall = "0.13"
pub Repo {}
impl UserRepository for Repo {
fn find_by_id(&self, id: u64) -> Option<User>;
}
}

Comment on lines +13 to +20
```rust
pub trait OrderRepository: Send + Sync {
fn find_by_id(&self, id: u64) -> Result<Option<Order>, StorageError>;
fn find_all(&self) -> Result<Vec<Order>, StorageError>;
fn save(&self, order: &Order) -> Result<Order, StorageError>;
fn delete(&self, id: u64) -> Result<(), StorageError>;
}
```
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Sync-only repository trait may mislead async Rust users

The OrderRepository trait exposes only synchronous methods. In practice, nearly all Rust database crates (sqlx, sea-orm, diesel async) expose async fn interfaces. A developer following this pattern verbatim will hit a wall when they try to call .await — and working around sync traits with blocking executors in async contexts can introduce subtle deadlocks.

Consider adding either an async variant or an explicit note that this pattern is for synchronous storage only, and pointing readers to an async version (e.g., using async_trait or Rust 1.75+ async fn in trait):

// For async storage backends (sqlx, sea-orm, etc.) use async fn:
use async_trait::async_trait; // or native async fn in trait (Rust ≥ 1.75)

#[async_trait]
pub trait OrderRepository: Send + Sync {
    async fn find_by_id(&self, id: u64) -> Result<Option<Order>, StorageError>;
    async fn find_all(&self) -> Result<Vec<Order>, StorageError>;
    async fn save(&self, order: &Order) -> Result<Order, StorageError>;
    async fn delete(&self, id: u64) -> Result<(), StorageError>;
}

Comment on lines +63 to +80
if trimmed.len() > 254 || !domain.contains('.') {
return Err(ValidationError::InvalidEmail(input.to_string()));
}
// For production use, prefer a validated email crate (e.g., `email_address`)
Ok(Self(trimmed.to_string()))
}

pub fn as_str(&self) -> &str {
&self.0
}
}
```

## Unsafe Code

- Minimize `unsafe` blocks — prefer safe abstractions
- Every `unsafe` block must have a `// SAFETY:` comment explaining the invariant
- Never use `unsafe` to bypass the borrow checker for convenience
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Manual email validation logic is error-prone

The Email::parse example uses hand-rolled length and @-position checks, yet immediately notes "For production use, prefer a validated email crate." The manual logic can produce false positives and false negatives (e.g., a@@b.c passes the @-position filter; quoted local-parts, IP-literal hosts, and IDNs are not handled).

Since the document's own recommendation is to use a crate, consider leading with the crate-based approach and relegating the manual example to a "what the crate is doing under the hood" aside, so the primary pattern shown is the safe one:

// GOOD — use a well-tested crate at the boundary
use email_address::EmailAddress;

pub struct Email(String);

impl Email {
    pub fn parse(input: &str) -> Result<Self, ValidationError> {
        let trimmed = input.trim();
        if !EmailAddress::is_valid(trimmed) {
            return Err(ValidationError::InvalidEmail(trimmed.to_string()));
        }
        Ok(Self(trimmed.to_string()))
    }
}

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: db2ff64978

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1 to +5
---
paths:
- "**/*.rs"
---
# Rust Coding Style
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Wire the new Rust rule pack into the install flows

These files add a Rust-specific ruleset, but the install surfaces still exclude it. I checked rules/README.md:17-21,33-60, which still documents only TypeScript/Python/Go/Swift/PHP copies, and install.sh --help from scripts/install-apply.js:19-45, which still lists only go, golang, java, javascript, kotlin, perl, php, python, swift, typescript; scripts/lib/install-manifests.js:39-58 has no rust legacy mapping either. Because rules are installed separately from the plugin, a user following the documented Step 2 flow cannot discover or explicitly request these new Rust rules.

Useful? React with 👍 / 👎.

@affaan-m affaan-m merged commit 9a478ad into main Mar 20, 2026
28 of 38 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants