Skip to content

Tighten linting and harden CLI tests - #19

Merged
leynos merged 7 commits into
mainfrom
codex/update-cargo.toml-and-clippy.toml-settings
Oct 26, 2025
Merged

leynos merged 7 commits into
mainfrom
codex/update-cargo.toml-and-clippy.toml-settings

Conversation

@leynos

@leynos leynos commented Oct 24, 2025 •

Copy link
Copy Markdown
Owner

Summary

  • align the workspace lint configuration with the stricter clippy and rust rules
  • refactor the CLI test support to use anyhow-powered fallible helpers and reduce nesting
  • update CLI behaviour and unit tests to propagate errors instead of panicking

Testing

  • make check-fmt
  • make lint
  • make test

https://chatgpt.com/codex/tasks/task_e_68fbfe4e32648322a04db1753cd58835

Summary by Sourcery

Tighten linting rules across the workspace and harden the CLI test suite by refactoring tests to use fallible helpers with anyhow, extracting shared networking logic, and replacing panics with propagated errors

Enhancements:

  • Align workspace and clippy lint configurations with stricter deny rules and reduced complexity thresholds
  • Refactor CLI test support by extracting common daemon connection logic into fallible helpers using anyhow

Build:

  • Add anyhow as a workspace and crate dependency

Tests:

  • Convert unit and behaviour tests to return Result and replace unwraps/expect with error propagation and context
  • Update TestWorld and FakeDaemon support methods to use anyhow-based error handling and ensure assertions return Results

@sourcery-ai

sourcery-ai Bot commented Oct 24, 2025 •

Copy link
Copy Markdown

Reviewer's Guide

This PR enforces stricter lint rules, introduces anyhow-powered error propagation in CLI tests and support code by converting panicking calls into fallible helpers and Context-based errors, restructures daemon simulation helpers to reduce nesting, and updates Cargo manifests to add the anyhow dependency.

Entity relationship diagram for new dependency on anyhow

erDiagram
"weaver-cli" ||--o{ "anyhow" : uses
"workspace" ||--o{ "anyhow" : uses
Loading

Class diagram for updated CLI test support helpers

classDiagram
class CliTestSupport {
  +run_command(args) Result
  +simulate_daemon() Result
}

class Result {
}

CliTestSupport --> Result: returns
Loading

Class diagram for error propagation in CLI tests

classDiagram
class BehaviourTest {
  +test_case() Result
}

class UnitTest {
  +test_case() Result
}

class Result {
}

BehaviourTest --> Result: returns
UnitTest --> Result: returns
Loading

File-Level Changes

Change Details Files
Enforce stricter linting policies
  • Add new deny lints under workspace.lints in Cargo.toml
  • Tighten clippy thresholds and allow-expect-in-tests in clippy.toml
Cargo.toml
clippy.toml
Add anyhow dependency
  • Include anyhow = "1.0" in top-level workspace dependencies
  • Add anyhow to crates/weaver-cli dev-dependencies
Cargo.toml
crates/weaver-cli/Cargo.toml
Migrate unit tests to anyhow-based fallible functions
  • Change test fn signatures to return Result<()>
  • Replace expect/unwrap calls with .context(...) and '?'
  • Introduce accept_tcp/accept_unix_connection and respond_to_request helpers
  • Implement TryCloneStream trait for stream cloning
crates/weaver-cli/src/tests/unit.rs
Harden TestWorld support code with error handling
  • Change TestWorld methods to return Result
  • Convert FakeDaemon.spawn and take_requests to propagate errors
  • Refactor serve_client, record_request, and stream_responses helpers
crates/weaver-cli/src/tests/support.rs
Convert behaviour tests to return Result and propagate errors
  • Change rstest-bdd step functions to return Result<()>
  • Replace world.run/assert_* calls to use '?' and ensure!
crates/weaver-cli/src/tests/behaviour.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Oct 24, 2025 •

Copy link
Copy Markdown

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Summary by CodeRabbit

  • Chores
    • Enhanced code quality checks by increasing strictness of linting rules across the workspace.
    • Improved error handling in test infrastructure with better propagation and reporting mechanisms.
    • Added dependency support for enhanced error context management.

Summary by CodeRabbit

Release Notes

  • Tests

    • Improve error handling in test suite with anyhow-based Result propagation and richer context.
    • Strengthen test infrastructure with socket helpers and clonable stream abstraction.
  • Chores

    • Enforce stricter workspace linting rules and lower complexity thresholds.
    • Add workspace lint entries for missing_docs and missing_crate_level_docs.

Walkthrough

Tighten workspace linting (many new deny rules and reduced thresholds) and refactor weaver-cli tests and test support to use anyhow::Result with contextual error handling; add socket helpers and a TryCloneStream abstraction.

Changes

Cohort / File(s) Summary
Workspace linting
Cargo.toml, clippy.toml
Add numerous new deny clippy/rust-lint rules and workspace lint entries (unknown_lints, renamed_and_removed_lints, missing_docs, missing_crate_level_docs). Lower cognitive-complexity threshold (12→9) and add thresholds: too-many-arguments=4, too-many-lines=70, excessive-nesting=4; set allow-expect-in-tests = true.
Dependencies
crates/weaver-cli/Cargo.toml
Add anyhow = { workspace = true } as a dev-dependency.
Behaviour tests
crates/weaver-cli/src/tests/behaviour.rs
Convert step-definition functions to return anyhow::Result<()>, import anyhow::Result, propagate errors with ?, and add Ok(()) returns.
Test support
crates/weaver-cli/src/tests/support.rs
Change TestWorld and FakeDaemon APIs to return Result (start/run/spawn/take_requests/etc.), convert stdout/stderr accessors and assertions to return Result, add helpers for accepting connections, streaming responses, TryCloneStream usage, and use anyhow::Context/ensure.
Unit tests and helpers
crates/weaver-cli/src/tests/unit.rs
Convert multiple tests to return Result<()>, add TryCloneStream trait and impls for TcpStream (and UnixStream on unix), add helpers accept_tcp_connection, accept_unix_connection, respond_to_request, write_lines, and refactor listener/test setup to propagate contextual errors.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Runner as Test runner
  participant World as TestWorld
  participant Daemon as FakeDaemon
  participant Socket as Client socket

  Note over Runner,World: Behaviour steps now return Result and propagate errors
  Runner->>World: start_daemon() ?
  World->>Daemon: spawn(lines) ?
  Daemon-->>World: spawn Result (handle)
  Runner->>Socket: connect & send request
  Socket->>Daemon: accept connection
  Daemon->>Daemon: record_request() / stream_responses()
  Daemon-->>Socket: response lines
  Note over Runner,World: Errors bubble up as anyhow::Result with Context
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35–45 minutes

  • Inspect FakeDaemon spawn/accept/serve logic for race conditions and timeouts.
  • Verify updated public/test API signatures and all call sites propagate Result correctly.
  • Validate TryCloneStream trait and TcpStream/UnixStream implementations for correct cloning semantics.
  • Confirm read_fixture, decode_utf8 and assertion helpers use Context/ensure and provide clear diagnostics.

Poem

🔧 Lints grow sharp, thresholds set to keen,
Tests now speak in Result, wrapped and clean,
Streams clone and sockets sing in tune,
Context sheds light, reveals the rune,
Ship the tidy tests and dance under the moon ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.90% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Tighten linting and harden CLI tests" accurately captures the two primary objectives of this changeset. "Tighten linting" directly maps to the new Clippy deny rules in Cargo.toml and the updated thresholds in clippy.toml, whilst "harden CLI tests" refers to the refactoring across behaviour.rs, support.rs, and unit.rs to replace panic-prone patterns with anyhow-based error handling. The title is concise, specific, and sufficiently clear for a teammate scanning commit history to understand the core intent.
Description Check ✅ Passed The description is substantively related to the changeset across all three major aspects: aligning workspace lint configuration with stricter Clippy and Rust rules (evidenced by the Cargo.toml and clippy.toml modifications), refactoring CLI test support to use anyhow-powered fallible helpers (reflected in support.rs, behaviour.rs, and unit.rs), and updating tests to propagate errors instead of panicking (demonstrated by the Result-returning test functions and error propagation patterns). The description provides meaningful detail about testing and includes verification steps, avoiding vague or generic language.

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

sourcery-ai[bot]

This comment was marked as resolved.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
crates/weaver-cli/Cargo.toml (1)

14-23: Use explicit caret (^) versions per policy.

Enforce caret requirements across non-workspace deps. Update these entries.

 [target.'cfg(unix)'.dependencies]
-socket2 = { version = "0.5" }
+socket2 = { version = "^0.5" }

 [dev-dependencies]
 anyhow = { workspace = true }
-rstest = { workspace = true }
-rstest-bdd = { workspace = true }
-rstest-bdd-macros = { workspace = true }
-assert_cmd = "2.0"
-predicates = "3.0"
-tempfile = { workspace = true }
+rstest = { workspace = true }
+rstest-bdd = { workspace = true }
+rstest-bdd-macros = { workspace = true }
+assert_cmd = "^2.0"
+predicates = "^3.0"
+tempfile = { workspace = true }

As per coding guidelines.

Cargo.toml (1)

14-28: Make caret explicit on all workspace dependencies.

Apply caret prefixes to satisfy the dependency policy.

 [workspace.dependencies]
-anyhow = "1.0"
-camino = { version = "1.1", features = ["serde1"] }
-clap = { version = "4.5", features = ["derive"] }
-once_cell = "1.19"
-ortho_config = "0.5.0"
-rstest = "0.23"
-rstest-bdd = "0.1.0-alpha4"
-rstest-bdd-macros = "0.1.0-alpha4"
-serde = { version = "1.0", features = ["derive"] }
-serde_json = "1.0"
-thiserror = "2.0"
-tempfile = "3.10"
-dirs = "6.0"
+anyhow = "^1.0"
+camino = { version = "^1.1", features = ["serde1"] }
+clap = { version = "^4.5", features = ["derive"] }
+once_cell = "^1.19"
+ortho_config = "^0.5.0"
+rstest = "^0.23"
+rstest-bdd = "^0.1.0-alpha4"
+rstest-bdd-macros = "^0.1.0-alpha4"
+serde = { version = "^1.0", features = ["derive"] }
+serde_json = "^1.0"
+thiserror = "^2.0"
+tempfile = "^3.10"
+dirs = "^6.0"

As per coding guidelines.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e1485ea and 755db29.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • Cargo.toml (2 hunks)
  • clippy.toml (1 hunks)
  • crates/weaver-cli/Cargo.toml (1 hunks)
  • crates/weaver-cli/src/tests/behaviour.rs (2 hunks)
  • crates/weaver-cli/src/tests/support.rs (7 hunks)
  • crates/weaver-cli/src/tests/unit.rs (7 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Clarity over cleverness: prefer explicit, readable Rust code over terse/obscure idioms
Use functions and composition; avoid repetition; prefer generators/comprehensions and declarative code when readable
Small, meaningful functions with single responsibility and command-query segregation
Name things precisely; boolean names should use is/has/should
Keep file size manageable: no single Rust file longer than 400 lines; split long switches/dispatch tables; move large test data to external files
Fix warnings emitted during tests in code; do not silence them
Extract helper functions when a function is too long, adhering to separation of concerns and CQRS
Group many parameters into meaningful structs when a function has too many parameters
When returning large errors, consider using Arc to reduce returned data size
Write unit and behavioural tests for new functionality and run before/after changes
Prefer immutable data; avoid unnecessary mut bindings
Handle errors with Result instead of panicking where feasible
Avoid unsafe code unless absolutely necessary; document any usage clearly
Place function attributes after doc comments
Do not use return in single-line functions
Use predicate functions for conditionals with more than two branches
Do not silence lints except as a last resort
Lint suppressions must be tightly scoped and include a clear reason
Prefer #[expect] over #[allow] for lint justifications
Prefer .expect() over .unwrap()
Use concat!() to combine long string literals rather than escaping newlines
Prefer single-line versions of trivial functions when appropriate
Use NewTypes to model domain values; consider newt-hype, tuple structs, the-newtype per context; implement appropriate traits and shims
Prefer semantic error enums deriving std::error::Error via thiserror for inspectable conditions

Files:

  • crates/weaver-cli/src/tests/support.rs
  • crates/weaver-cli/src/tests/behaviour.rs
  • crates/weaver-cli/src/tests/unit.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -yse / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such

    • For testing of functionality depending upon environment variables, dependency injection and the mockable crate are the preferred option.
    • If mockable cannot be used, env mutations in...

Files:

  • crates/weaver-cli/src/tests/support.rs
  • crates/weaver-cli/src/tests/behaviour.rs
  • crates/weaver-cli/src/tests/unit.rs
**/*.{rs,md}

📄 CodeRabbit inference engine (AGENTS.md)

Use consistent en-GB-oxendict spelling/grammar in comments and documentation (except LICENSE naming)

Files:

  • crates/weaver-cli/src/tests/support.rs
  • crates/weaver-cli/src/tests/behaviour.rs
  • crates/weaver-cli/src/tests/unit.rs
**/src/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/src/**/*.rs: Illustrate functions with clear examples in documentation comments; omit redundant examples in test docs
Every module must begin with a module-level //! comment explaining its purpose
Document public APIs with Rustdoc comments (///) so cargo doc can generate docs

Files:

  • crates/weaver-cli/src/tests/support.rs
  • crates/weaver-cli/src/tests/behaviour.rs
  • crates/weaver-cli/src/tests/unit.rs
Cargo.toml

📄 CodeRabbit inference engine (AGENTS.md)

Cargo.toml: Use explicit version ranges in Cargo.toml and keep dependencies up to date
Mandate caret requirements for all dependencies (SemVer-compatible ^)
Prohibit wildcard (*) and >= requirements; use ~ only with documented reason

Files:

  • Cargo.toml
🧬 Code graph analysis (3)
crates/weaver-cli/src/tests/support.rs (2)
crates/weaver-cli/src/lib.rs (2)
  • run_with_loader (122-161)
  • run (44-51)
crates/weaver-config/src/socket.rs (1)
  • tcp (38-43)
crates/weaver-cli/src/tests/behaviour.rs (1)
crates/weaver-cli/src/tests/support.rs (4)
  • world (255-257)
  • new (27-29)
  • stdout_text (96-98)
  • stderr_text (100-102)
crates/weaver-cli/src/tests/unit.rs (4)
crates/weaver-cli/src/tests/support.rs (4)
  • read_fixture (237-244)
  • new (27-29)
  • port (174-176)
  • default_daemon_lines (246-252)
crates/weaver-cli/src/lib.rs (1)
  • read_daemon_messages (183-234)
crates/weaver-cli/src/transport.rs (1)
  • connect (60-91)
crates/weaver-config/src/socket.rs (2)
  • tcp (38-43)
  • unix (32-34)
⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Sourcery review
  • GitHub Check: build-test
🔇 Additional comments (6)
clippy.toml (1)

2-7: Tighten thresholds acknowledged; keep “expect in tests” allowed.

Proceed with these stricter gates; they align with the repo guidelines’ stance on panics in tests vs production. No changes requested.

Cargo.toml (2)

91-93: Validate docs-gates before merge.

missing_docs = "deny" and missing_crate_level_docs = "deny" will fail builds if any crate or public item lacks docs. Verify completeness.

#!/bin/bash
# Check crate-level docs and public items with no docs.
# 1) Ensure each crate root has a crate-level //! doc.
fd -a '^lib\.rs$' crates | xargs -I{} rg -n --trim '^\s*//!' {} -C0

# 2) Spot obvious public items without docs (heuristic).
rg -nP --type=rust '^\s*pub\s+(struct|enum|fn|trait)\s' -g '!**/tests/**' | \
  gawk 'BEGIN{FS=":"}{print $0}' | \
  rg -nP -v '^\s*///'

As per coding guidelines.


10-13: Pin toolchain to match edition = "2024" and rust-version = "1.85".

Ensure CI/tooling uses Rust 1.85 with edition 2024 to avoid lint/feature drift.

#!/bin/bash
# Verify rust-toolchain manifests pin to 1.85.
fd -a 'rust-toolchain(\.toml)?$' -HI | xargs -I{} sh -c 'echo ">>> {}"; cat "{}"'
crates/weaver-cli/src/tests/support.rs (1)

48-58: Result-based test helpers: good propagation and context.

Retain this pattern; it improves failure diagnostics and aligns with the repo’s error-handling guidance.

Also applies to: 68-81, 96-103, 104-112, 114-122, 124-137, 139-147, 178-189, 201-216, 218-226, 237-244

crates/weaver-cli/src/tests/behaviour.rs (1)

11-17: Adopt Result-returning steps across BDD suite.

Keep this structure; it reduces panic-based flakiness and produces clearer errors.

Also applies to: 24-36, 38-45, 47-55, 57-63, 65-71, 73-85, 87-95, 97-101, 103-106

crates/weaver-cli/src/tests/unit.rs (1)

299-324: Solid test refactor: readable helpers, trait for cloneable streams, and Result flow.

Proceed; helpers remove duplication and the trait abstracts stream cloning cleanly.

Also applies to: 326-332, 334-346, 348-355, 255-270, 272-297, 20-35, 92-102, 104-118, 120-128, 130-155, 157-220, 222-253

Comment thread Cargo.toml Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 755db29 and e1fff79.

📒 Files selected for processing (1)
  • crates/weaver-cli/src/tests/support.rs (7 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Clarity over cleverness: prefer explicit, readable Rust code over terse/obscure idioms
Use functions and composition; avoid repetition; prefer generators/comprehensions and declarative code when readable
Small, meaningful functions with single responsibility and command-query segregation
Name things precisely; boolean names should use is/has/should
Keep file size manageable: no single Rust file longer than 400 lines; split long switches/dispatch tables; move large test data to external files
Fix warnings emitted during tests in code; do not silence them
Extract helper functions when a function is too long, adhering to separation of concerns and CQRS
Group many parameters into meaningful structs when a function has too many parameters
When returning large errors, consider using Arc to reduce returned data size
Write unit and behavioural tests for new functionality and run before/after changes
Prefer immutable data; avoid unnecessary mut bindings
Handle errors with Result instead of panicking where feasible
Avoid unsafe code unless absolutely necessary; document any usage clearly
Place function attributes after doc comments
Do not use return in single-line functions
Use predicate functions for conditionals with more than two branches
Do not silence lints except as a last resort
Lint suppressions must be tightly scoped and include a clear reason
Prefer #[expect] over #[allow] for lint justifications
Prefer .expect() over .unwrap()
Use concat!() to combine long string literals rather than escaping newlines
Prefer single-line versions of trivial functions when appropriate
Use NewTypes to model domain values; consider newt-hype, tuple structs, the-newtype per context; implement appropriate traits and shims
Prefer semantic error enums deriving std::error::Error via thiserror for inspectable conditions

Files:

  • crates/weaver-cli/src/tests/support.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -yse / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such

    • For testing of functionality depending upon environment variables, dependency injection and the mockable crate are the preferred option.
    • If mockable cannot be used, env mutations in...

Files:

  • crates/weaver-cli/src/tests/support.rs
**/*.{rs,md}

📄 CodeRabbit inference engine (AGENTS.md)

Use consistent en-GB-oxendict spelling/grammar in comments and documentation (except LICENSE naming)

Files:

  • crates/weaver-cli/src/tests/support.rs
**/src/**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/src/**/*.rs: Illustrate functions with clear examples in documentation comments; omit redundant examples in test docs
Every module must begin with a module-level //! comment explaining its purpose
Document public APIs with Rustdoc comments (///) so cargo doc can generate docs

Files:

  • crates/weaver-cli/src/tests/support.rs
🧬 Code graph analysis (1)
crates/weaver-cli/src/tests/support.rs (2)
crates/weaver-cli/src/lib.rs (2)
  • run_with_loader (122-161)
  • run (44-51)
crates/weaver-config/src/socket.rs (1)
  • tcp (38-43)
🔍 Remote MCP

Based on the repository documentation I've gathered, here's the relevant context for reviewing this pull request:

Relevant Context for PR #19 Review

Project Background

The weaver project is a code intelligence platform (written in Python, not Rust as suggested by the Cargo.toml files) that consists of three main components:

  1. weaver CLI - Lightweight client using typer for command-line interaction
  2. weaverd daemon - Asyncio-based background service maintaining language server connections
  3. weaver_schemas - Shared data models using msgspec for RPC communication

However, there appears to be a component mismatch: The PR focuses on crates/weaver-cli/ suggesting a Rust implementation, but the repository documentation indicates a Python project. This may indicate the PR is for a different project or represents a language transition.

Development Philosophy Relevant to This PR

  1. Strict Typing Requirements: [::Deepwiki_read_wiki_contents::] indicates the project uses pyright in strict mode with comprehensive type annotations. The transition to Result<()> error handling aligns with this philosophy.

  2. Error Handling Approach: The codebase emphasizes structured error objects (SchemaError) and graceful error propagation rather than panics, which matches the PR's objective to "replace panics with propagated errors."

  3. Testing Standards: The documentation shows comprehensive testing infrastructure with unit tests, integration tests, and BDD features - critical for validating the test refactoring changes in this PR.

Specific Patterns in Documentation

  • OODA Loop Organization: Commands are organized around Observe-Orient-Decide-Act framework, suggesting structured error handling is important for maintaining this abstraction
  • Resource Management: The daemon emphasizes "graceful degradation" and "structured error responses" preventing daemon crashes
  • Transient Edit System: Complex speculative analysis requires reliable error propagation to maintain correctness

Import and Configuration Standards

The documentation indicates the project enforces specific import patterns and has strict linting rules - the Clippy configuration changes in the PR (cognitive complexity thresholds, strictness levels) align with this existing quality-focused culture.,

⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (10)
crates/weaver-cli/src/tests/support.rs (10)

10-11: LGTM!

The new imports support the enhanced error handling (anyhow) and non-blocking daemon timeout logic (Duration, Instant, io, TcpListener, TcpStream).

Also applies to: 16-16, 19-19


50-59: LGTM!

Clean error propagation from FakeDaemon::spawn through the daemon startup methods.


69-82: LGTM!

The method correctly propagates errors from take_requests() and returns Result<()> for fallible test operations.


97-103: LGTM!

UTF-8 conversion can fail; wrapping in Result with descriptive context is appropriate.


105-123: LGTM!

Idiomatic use of ensure! for test assertions with clear error messages. The error context propagation is sound.


125-148: LGTM!

The golden-file and capabilities assertions provide clear error messages with expected vs actual output. Error propagation from read_fixture is correct.


182-193: LGTM!

Correctly propagates errors from the daemon thread (catching panics) and from mutex locks.


221-236: LGTM!

The request recording correctly handles stream cloning, reading, and mutex locking with appropriate error context.


238-246: LGTM!

Socket write operations correctly propagate errors with descriptive context.


257-263: LGTM!

The contextual error message includes the fixture path, which aids debugging when fixture loading fails.

Comment thread crates/weaver-cli/src/tests/support.rs Resolved
Comment thread crates/weaver-cli/src/tests/support.rs Resolved
@leynos

leynos commented Oct 25, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai Have the following now been resolved?

Prompt for AI Agents

Please address the comments from this code review:

Overall Comments

  • Consider moving the new TryCloneStream/accept_*/respond_to_request helpers out of unit.rs into your existing support module to keep the test file focused on test logic.
  • Double-check that fallible tests (#[test] fn ... -> Result<()>) are supported on your minimum Rust toolchain, or pin your rust-version so the harness can handle Result-returning tests.
  • A lot of .context(...) calls repeat the same UTF-8 decoding logic—think about adding a small helper or macro for decoding buffers to reduce boilerplate and improve readability.

@coderabbitai

coderabbitai Bot commented Oct 25, 2025

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if TryCloneStream trait and helpers are still in unit.rs
echo "=== Checking for TryCloneStream and helpers in unit.rs ==="
rg -n "trait TryCloneStream|fn accept_tcp_connection|fn accept_unix_connection|fn respond_to_request" crates/weaver-cli/src/tests/unit.rs

echo ""
echo "=== Checking if helpers were moved to support.rs ==="
rg -n "trait TryCloneStream|fn accept_tcp_connection|fn accept_unix_connection|fn respond_to_request" crates/weaver-cli/src/tests/support.rs

echo ""
echo "=== Checking rust-version in Cargo.toml files ==="
rg -n "rust-version" Cargo.toml crates/weaver-cli/Cargo.toml

echo ""
echo "=== Checking for UTF-8 decoding context patterns ==="
rg -n "from_utf8.*context|context.*from_utf8|context.*UTF-8" crates/weaver-cli/src/tests/

Length of output: 640


🏁 Script executed:

#!/bin/bash
# Look for UTF-8 conversion patterns more broadly
echo "=== Looking for from_utf8 usage patterns ==="
rg -n "from_utf8" crates/weaver-cli/src/tests/ -A 1 -B 1

echo ""
echo "=== Check for any helper functions that might handle UTF-8 decoding ==="
ast-grep --pattern 'fn $FUNC($_) -> $_ {
  $$$
  from_utf8($$$)
  $$$
}'

echo ""
echo "=== Look at the full context around the UTF-8 helper in support.rs ==="
sed -n '330,345p' crates/weaver-cli/src/tests/support.rs

Length of output: 1111


@leynos: Yes, all three review comments have been resolved:

  1. Helper functions moved to support module ✓
    The TryCloneStream trait and helper functions (accept_tcp_connection, accept_unix_connection, respond_to_request) have been moved from unit.rs to support.rs with pub(super) visibility, keeping the test file focused on test logic.

  2. Rust version pinned ✓
    rust-version = "1.85" is now set in Cargo.toml, ensuring fallible test support (#[test] fn ... -> Result<()>) is guaranteed on the toolchain.

  3. UTF-8 decoding boilerplate reduced ✓
    A decode_utf8 helper function has been added in support.rs (lines 336-338) that encapsulates the String::from_utf8(buffer).with_context(|| format!("{label} utf8")) pattern, eliminating repetitive boilerplate.

The refactoring looks good!

@leynos

leynos commented Oct 25, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai Have the following now been resolved?

  • Consider moving the new TryCloneStream/accept_*/respond_to_request helpers out of unit.rs into your existing support module to keep the test file focused on test logic.
  • Double-check that fallible tests (#[test] fn ... -> Result<()>) are supported on your minimum Rust toolchain, or pin your rust-version so the harness can handle Result-returning tests.
  • A lot of .context(...) calls repeat the same UTF-8 decoding logic—think about adding a small helper or macro for decoding buffers to reduce boilerplate and improve readability.

@coderabbitai

coderabbitai Bot commented Oct 25, 2025

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash

echo "=== 1. Checking if TryCloneStream trait and helpers are in unit.rs ==="
rg -n "trait TryCloneStream|fn accept_tcp_connection|fn accept_unix_connection|fn respond_to_request|fn write_lines" crates/weaver-cli/src/tests/unit.rs

echo ""
echo "=== 2. Checking if helpers were moved to support.rs ==="
rg -n "trait TryCloneStream|fn accept_tcp_connection|fn accept_unix_connection|fn respond_to_request|fn write_lines" crates/weaver-cli/src/tests/support.rs

echo ""
echo "=== 3. Checking rust-version in Cargo.toml files ==="
rg -n "rust-version" Cargo.toml crates/weaver-cli/Cargo.toml

echo ""
echo "=== 4. Looking for UTF-8 decoding helper function ==="
rg -n "fn.*decode.*utf8|fn.*utf8.*decode" crates/weaver-cli/src/tests/

echo ""
echo "=== 5. Checking for repetitive UTF-8 context patterns ==="
rg -n "from_utf8.*context|context.*from_utf8" crates/weaver-cli/src/tests/ | head -20

Length of output: 930


@leynos: Yes, all three review comments have been resolved:

  1. Helper functions moved to support module ✓
    TryCloneStream trait and all helper functions (accept_tcp_connection, accept_unix_connection, respond_to_request, write_lines) have been moved to support.rs with pub(super) visibility (lines 269-304). They no longer appear in unit.rs.

  2. Rust version pinned ✓
    rust-version = "1.85" is set in the workspace Cargo.toml (line 12), ensuring fallible test support (#[test] fn ... -> Result<()>) is available.

  3. UTF-8 decoding boilerplate reduced ✓
    A decode_utf8 helper function has been added in support.rs (line 336) that encapsulates the String::from_utf8(buffer).with_context(|| format!("{label} utf8")) pattern. The repetitive pattern now appears only once (in the helper itself).

The refactoring looks good!

@leynos

leynos commented Oct 25, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 25, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e1fff79 and 07c8a27.

📒 Files selected for processing (2)
  • crates/weaver-cli/src/tests/support.rs (6 hunks)
  • crates/weaver-cli/src/tests/unit.rs (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -yse / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such

    • For testing of functionality depending upon environment variables, dependency injection and the mockable crate are the preferred option.
    • If mockable cannot be used, env mutations in...

Files:

  • crates/weaver-cli/src/tests/support.rs
  • crates/weaver-cli/src/tests/unit.rs
🔍 Remote MCP Deepwiki

Summary of additional repository context relevant to this PR review

  • Project is a Python client/daemon with strong testing, strict typing and linting culture; repository uses msgspec-based schemas and an RPC client-daemon pattern — changing test error flows touches canonical testing and IPC patterns.

  • Test infra expectations:

    • Tests run under pytest with asyncio fixtures and a 30s timeout; integration/BDD tests spawn a daemon and exercise UNIX-socket RPC flows (so changing test signatures to fallible Results must preserve test harness semantics).
    • CI and local commands referenced by PR (run formatting, lint, tests) align with repo tooling (ruff/pyright/pytest).
  • Relevant patterns/constraints that affect this PR:

    • The project enforces strict linting/type rules and centralized tooling (pyproject.toml / ruff / pyright). The PR’s workspace-level lint tightening and added denies are consistent with repository emphasis on strict quality gates.
    • Tests and helpers historically colocated; prior reviewer requested moving socket/stream helpers out of unit tests into support module — PR summary indicates helpers were moved to support.rs and made pub(super). Verify the final locations and visibilities to match that resolution.
  • Practical review touchpoints (what to check in this PR):

    • Dependency changes: ensure workspace addition of anyhow (and workspace rust-version pin) is minimal and does not conflict with packaging/tooling. Confirm workspace rust-version pin (1.85) matches CI/tooling expectations for fallible tests.
    • Public API/signature changes: many test-support APIs changed to return Result. Verify any callers outside tests are updated and exported visibility is appropriate (pub vs pub(super)).
    • Helper placement & duplication: confirm TryCloneStream, decode_utf8 and socket helpers are only in support module (not duplicated in unit.rs) and have appropriate #[cfg(unix)] guards where needed.
    • Error/context handling: ensure conversions to anyhow::Context preserve diagnostic messages used by BDD/integration assertions (golden fixtures, stderr matching).
    • Lint thresholds: validate new clippy.toml thresholds (cognitive_complexity, too-many-args/lines, nesting) are achievable for existing code or that PR updates reconcile failures. Run make lint to confirm.
    • Test harness compatibility: because tests now return Result<()>, confirm CI Rust toolchain (or pinned rust-version) used in CI matches to avoid false failures.

Citations

  • Repository documentation and test/CI/tooling details:
⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (8)
crates/weaver-cli/src/tests/support.rs (5)

53-85: Daemon lifecycle methods correctly propagate errors.

The refactoring to return Result<()> from start_daemon, start_daemon_with_lines, and run aligns well with the PR objectives. The error propagation using ? is clean, and the daemon request collection at line 81 properly handles the fallible take_requests call.


162-209: Past review comments on thread error handling comprehensively addressed.

The implementation now stores the thread outcome in Arc<Mutex<Option<Result<()>>>> (lines 169-176) and checks it in take_requests (lines 196-203), eliminating the panic-on-error pattern. The thread join at lines 192-194 catches panics explicitly. This is a robust solution.


211-236: Deadline optimisation correctly implemented.

The deadline check now occurs only within the WouldBlock match arms (lines 224, 228), avoiding unnecessary Instant::now() calls on successful accepts. The dual pattern at lines 224 and 228 correctly distinguishes between "before deadline, sleep and retry" and "after deadline, exit cleanly". Well done.


269-325: Socket helper functions well-organised and appropriately abstracted.

The TryCloneStream trait (lines 304-325) provides a clean abstraction for TCP and Unix socket cloning, with proper #[cfg(unix)] guards. The helper functions (respond_to_request, write_lines, accept_tcp_connection, accept_unix_connection) are appropriately scoped with pub(super) visibility and eliminate duplication between test cases.


336-338: UTF-8 decoding helper successfully eliminates boilerplate.

The decode_utf8 function centralises the repetitive .context(...) pattern for UTF-8 decoding, improving readability across the test suite. The consistent usage in stdout_text, stderr_text, and throughout unit.rs demonstrates the value of this refactor.

crates/weaver-cli/src/tests/unit.rs (3)

23-38: Test refactoring to fallible signature improves error clarity.

Returning Result<()> and using ? for error propagation (lines 33, 34, 35) makes test failures more informative than the previous panic-based approach. The use of decode_utf8 helper reduces boilerplate.


224-252: Generic test helper eliminates TCP/Unix duplication effectively.

The test_daemon_connection function abstracts the connection lifecycle, allowing TCP (lines 255-269) and Unix socket (lines 273-296) tests to share the same verification logic. The closure-based setup pattern (line 226) is flexible, and thread panics are properly caught and converted to errors (lines 248-250).


255-296: Socket connection tests leverage the new helper infrastructure cleanly.

Both connect_successfully_establishes_tcp_connection and connect_supports_unix_sockets use the helpers imported from support (accept_tcp_connection, accept_unix_connection), confirming that the refactoring successfully moved shared logic out of test code. The Unix test is properly gated with #[cfg(unix)].

Comment thread crates/weaver-cli/src/tests/unit.rs Resolved
@leynos

leynos commented Oct 25, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Oct 25, 2025

Copy link
Copy Markdown
✅ Actions performed

Reviews paused.

@leynos
leynos merged commit afb6ade into main Oct 26, 2025
@leynos
leynos deleted the codex/update-cargo.toml-and-clippy.toml-settings branch October 26, 2025 00:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant