Skip to content

Act refactor: require provider/refactoring/file and render contract#102

Open
leynos wants to merge 11 commits intomainfrom
feat-act-refactor-arg-requirements-p35mzy
Open

Act refactor: require provider/refactoring/file and render contract#102
leynos wants to merge 11 commits intomainfrom
feat-act-refactor-arg-requirements-p35mzy

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Apr 10, 2026

Summary

  • Implements the canonical, operator-facing requirements for weaver act refactor (2.3.4): require provider, refactoring, and file flags, plus a deterministic, full-contract error when arguments are missing. Adds an ExecPlan living document to guide implementation, testing, and docs.
  • Introduces a central requirements helper to expose valid providers, refactorings, and the required argument set, ensuring single-source truth across validation, tests, and user-facing guidance.
  • Updates the argument parsing and routing flow to validate the full contract before runtime resolution and plugin execution.
  • Extends tests (unit, contract, and feature) to cover the complete missing-arguments path, unsupported values, and explicit-provider scenarios.
  • Updates docs and roadmaps to reflect the final MVP contract and validation gates.

Changes

  • Added new file: crates/weaverd/src/dispatch/act/refactor/requirements.rs
  • Updated parsing/validation to require all three flags and to validate provider/refactoring against a canonical list
  • Made provider a required field in RefactorArgs and tightened the build/validation flow
  • Updated crates/weaverd/src/dispatch/act/refactor/mod.rs to reflect the new required-arguments contract in the command handler and logging
  • Expanded tests:
    • Updated unit tests in crates/weaverd/src/dispatch/act/refactor/arguments.rs
    • Extended contract tests (crates/weaverd/src/dispatch/act/refactor/contract_tests.rs)
    • Extended refactor feature tests (crates/weaverd/tests/features/refactor.feature)
    • Amended router tests to reflect the new error surface for missing required flags
  • Added ExecPlan doc: docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md
  • Documentation updates:
    • docs/weaver-design.md updated to describe the MVP contract with explicit provider/refactoring validation
    • docs/users-guide.md updated to reflect the required flags and valid values
    • docs/roadmap.md updated to mark 2.3.4 as done where applicable

Rationale

  • The roadmap item 2.3.4 calls for surfacing the full operator contract when required arguments are missing, including the complete set of required flags and valid values. This change centralizes required flags, valid providers, and supported refactorings to a single source of truth and renders a deterministic, actionable error in one response, aligning with the Level 10 error-template policy and ensuring consistent behavior across parser, router, and runtime paths.
  • By enforcing the contract before plugin resolution, file I/O, or backend startup, we reduce ambiguity for users and testers and keep the existing safety pipeline intact.

Review guidance

  • Verify that the ExecPlan communicates the complete contract, acceptance criteria, and staged approach.
  • Ensure the new canonical requirements helper aligns with validation code, tests, and docs.
  • Confirm that the updated error messages and guidance lines reflect the canonical provider/refactoring lists and the next-step command.
  • Check alignment with related docs (weaver-design.md, users-guide.md, roadmap.md) as they are updated.

Implementation plan (summary)

  • Stage A: lock in required behavior with failing tests (missing-arguments path surfaces full contract)
  • Stage B: introduce canonical requirements model (providers/refactorings/flags/public messages)
  • Stage C: enforce the contract in parsing and routing (reject incomplete requests with single, actionable error)
  • Stage D: update design and user docs to reflect final MVP contract
  • Stage E: validate end-to-end (docs validators, Rust gates, tests)

Validation plan

  • Red-phase unit tests asserting the full missing-arguments contract is rendered
  • Behavioural tests validating happy path, missing-arguments, and edge cases (partial flags, invalid values)
  • Optional end-to-end CLI assertion to ensure operator-facing output matches acceptance criteria

Docs impact

  • ExecPlan doc added for 2.3.4
  • Design and user docs updated to reflect the new contract and values
  • Roadmap item 2.3.4 marked appropriately after verification

Progress tracking

  • This PR introduces the ExecPlan living document and implements the complete 2.3.4 argument contract for act refactor. Ongoing progress and status updates will be reflected in the docs as work proceeds.

◳ Generated by DevBoxer

ℹ️ Tag @devboxerhub to address PR feedback

📎 Task: https://www.devboxer.com/task/c84a1800-74c2-4659-a655-422bcd862e05

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 10, 2026

Walkthrough

Enforce explicit --provider selection in act refactor command dispatch by making the flag required, centralise supported provider and refactoring names in a new requirements module with validation functions, update argument parsing to reject invalid values and trailing tokens upfront, and make DomainRouter and DispatchConnectionHandler constructors fallible to validate workspace roots.

Changes

Cohort / File(s) Summary
Argument parsing and requirements
crates/weaverd/src/dispatch/act/refactor/arguments.rs, crates/weaverd/src/dispatch/act/refactor/requirements.rs
Make RefactorArgs.provider required (String instead of Option<String>); add validation of required flags and supported provider/refactoring values during builder construction; reject malformed trailing arguments via DispatchError::invalid_arguments; introduce new requirements.rs module centralising supported lists, validation, and error construction.
Refactor helper and test updates
crates/weaverd/src/dispatch/act/refactor/refactor_helpers.rs, crates/weaverd/src/dispatch/act/refactor/behaviour.rs, crates/weaverd/src/dispatch/act/refactor/contract_tests.rs, crates/weaverd/src/dispatch/act/refactor/tests.rs, crates/weaverd/src/dispatch/act/refactor/rollback_tests.rs, crates/weaverd/src/dispatch/act/refactor/mod.rs
Refactor standard_rename_args to delegate to new standard_rename_args_for_provider with explicit provider; update test setup and BDD steps to use explicit provider selection; switch capability resolution from Automatic to ExplicitProvider mode; update logging and resolution parameters to treat provider as non-optional; adjust error assertions to accept both Ok(status: 1) and Err dispatch results.
Request building refactoring
crates/weaverd/src/dispatch/act/refactor/request_building.rs
Replace local effective_operation and capability_from_operation functions with calls to centralised requirements helpers; use supported_effective_operation for mapping and capability_for_operation for capability selection.
Router and handler fallibility
crates/weaverd/src/dispatch/router.rs, crates/weaverd/src/dispatch/handler.rs, crates/weaverd/src/process/launch.rs
Make DomainRouter::new and DispatchConnectionHandler::new return Result<Self, DispatchError> to validate absolute workspace roots; propagate initialisation failures via ? and map to LaunchError::WorkspaceRoot.
Test harness updates
crates/weaverd/src/dispatch/router/tests.rs, crates/weaverd/src/tests/dispatch_behaviour.rs, crates/weaverd/src/tests/get_card_behaviour.rs, crates/weaver-e2e/tests/test_support/mod.rs
Handle fallible handler/router construction with unwrap or error mapping; add test case for relative workspace root rejection; broaden refactor invalid-arguments assertion to generic "missing required flags" message.
Plugin manifests
crates/weaverd/src/dispatch/act/refactor/manifests.rs
Centralise manifest construction via manifest_from_spec helper driven by BuiltInProviderSpec constants; add built_in_provider_names() API; make timeout conditional per provider spec.
Feature and acceptance tests
crates/weaverd/tests/features/refactor.feature
Update test scenarios to use explicit provider selection steps instead of automatic routing; adjust scenario titles and request setup assertions accordingly.
Documentation
docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md, docs/roadmap.md, docs/users-guide.md, docs/weaver-design.md, docs/developers-guide.md
Add new ExecPlan for required-flags contract; mark roadmap item 2.3.4 complete; update act refactor documentation to make --provider mandatory, specify built-in provider names, describe deterministic validation failure modes, and replace automatic routing examples with explicit provider invocation; reframe daemon-design narrative as operator-facing contract-driven interface; document requirements.rs as single source of truth.

Possibly related PRs

Suggested labels

Roadmap

Poem

A provider now required, no more ambiguity,
Validation gates the path with certainty,
Arguments enforced with strict contract's call,
Operators command with clear protocol,
Rope and rust-analyser, no guessing left at all. 🛠️✨


Caution

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore

❌ Failed checks (2 errors, 6 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Module-Level Documentation ❌ Error The public function standard_rename_args_for_provider() lacks required documentation with no /// docstring explaining its purpose or parameters. Add a docstring to standard_rename_args_for_provider() immediately before the function signature explaining its purpose and parameters.
Unit Architecture ❌ Error Three explicit review comments requesting architectural refinements remain unresolved: hard-coded sentinel duplicates contract logic in requirements.rs, test helper uses panic instead of Result propagation, and test_support duplicates error-unwrapping logic instead of utilising shared helper. Apply three refactoring diffs: modify map_effective_operation() to return Result<(String, CapabilityId), DispatchError>, convert then_dispatch_error_contains() to use ok_or_else() instead of panic, replace inline match in test_support with required_result() helper.
User-Facing Documentation ⚠️ Warning PR introduces breaking change to CLI interface by making --provider mandatory, but lacks a dedicated migration document per repository patterns. Create a migration guide following established conventions (e.g., weaver-v0-1-1-migration-guide.md) with breaking changes table, before/after examples, and rationale for the change.
Developer Documentation ⚠️ Warning The new pub(crate) function standard_rename_args_for_provider() lacks a docstring and is not explicitly documented in the developers-guide. Add a /// docstring to standard_rename_args_for_provider() and update docs/developers-guide.md to explicitly list it alongside standard_rename_args().
Testing (Unit) ⚠️ Warning Three unaddressed review comments remain: panic in behaviour.rs violates Result error propagation, redundant capability_for_operation call in request_building.rs, and inconsistent error-handling in test_support/mod.rs. Apply three pending refactors: replace panic with .ok_or_else, refactor map_effective_operation to return (String, CapabilityId), and consolidate error-unwrapping logic using required_result helper.
Testing (Compile-Time / Ui) ⚠️ Warning PR introduces deterministic error messages forming a structured operator contract, but tests use only substring assertions without snapshot testing to validate the complete UI contract structure and formatting stability. Add snapshot tests using insta to validate complete error message output for each failure path, capturing required flags, provider/refactoring lists, and next-command guidance with full contract structure.
Domain Architecture ⚠️ Warning Pull request violates domain architecture by maintaining a hardcoded "rename-symbol" string sentinel in request_building.rs instead of deriving operation-specific behaviour from the resolved CapabilityId. Refactor map_effective_operation to return both the operation string and its resolved CapabilityId, obtained via capability_for_operation. Match on the resolved CapabilityId (not the string) to decide whether to apply rename-symbol-specific argument transformations. Additionally, replace the inline match in test_support/mod.rs at lines 81–85 with the existing required_result helper to eliminate duplication.
Observability ⚠️ Warning PR introduces operational validation gate without observability infrastructure: no metrics for failure categorisation, no structured logging at validation boundaries, and no tracing spans around validation flow. Add structured logging at validation decision point, introduce metrics for failure types (missing-provider, unsupported-provider, unsupported-refactoring, malformed-arguments), and implement trace spans around validation flow.
Testing (Overall) ❓ Inconclusive Insufficient evidence to determine if all introduced behaviours are rigorously tested across multiple modules and validation paths. Review test implementations in requirements.rs, arguments.rs, and feature tests, verifying assertions depend on actual validation logic. Add targeted negative–positive tests that would fail if validation were bypassed.
✅ Passed checks (9 passed)
Check name Status Explanation
Title check ✅ Passed The title directly corresponds to the main change: requiring provider/refactoring/file flags and rendering the deterministic contract error for weaver act refactor, which maps to the implemented roadmap item 2.3.4.
Description check ✅ Passed The description comprehensively details the changes, rationale, and implementation approach for requiring the three flags and rendering the contract error, with clear alignment to the changeset across argument parsing, routing, tests, and documentation.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Testing (Property / Proof) ✅ Passed The PR introduces fixed, compile-time-known invariants (2 providers, 1 refactoring, 3 flags) with deterministic table lookups. Existing unit tests exhaustively verify all possible inputs in these bounded sets and mapping consistency. Property testing and formal verification are unnecessary for simple membership checks on static arrays.
Security And Privacy ✅ Passed Pull request implements robust security controls: multi-layered path-traversal prevention, centralised input validation with static allowlists, safe JSON-serialisation of plugin arguments, absolute workspace-root enforcement, and appropriate error messaging without secrets exposure.
Performance And Resource Use ✅ Passed The pull request introduces validation logic at daemon startup and argument-build time only, avoiding hot-path performance concerns. Path validation uses is_absolute() without filesystem I/O. Provider and refactoring validation iterate simple string lists only at build time, not per-request. Error-path allocations are acceptable. No unbounded resource growth, algorithmic regressions, or avoidable cloning detected.
Concurrency And State ✅ Passed The PR introduces no new concurrency issues; workspace root validation occurs synchronously during single-threaded initialisation before Arc sharing, and all subsequent accesses are read-only.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat-act-refactor-arg-requirements-p35mzy

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

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Apr 10, 2026

Reviewer's Guide

This PR centralizes the operator-facing contract for weaver act refactor by introducing a canonical requirements module, making --provider, --refactoring, and --file mandatory, validating provider and refactoring names up front, emitting a single deterministic InvalidArguments error that lists the full contract and valid values, and updating tests and documentation (plus adding an ExecPlan doc) to align with the new behaviour.

Sequence diagram for act_refactor validation and execution flow

sequenceDiagram
    actor Operator
    participant WeaverCLI
    participant RefactorArgsParser
    participant RefactorRequirements
    participant RefactorHandler
    participant Runtime
    participant Plugin

    Operator->>WeaverCLI: run weaver act refactor [args]
    WeaverCLI->>RefactorArgsParser: parse_refactor_args(args)

    alt missing_required_flags
        RefactorArgsParser->>RefactorRequirements: missing_requirements_error()
        RefactorRequirements-->>RefactorArgsParser: DispatchError InvalidArguments
        RefactorArgsParser-->>WeaverCLI: Err InvalidArguments
        WeaverCLI-->>Operator: print full contract error
    else unsupported_provider_or_refactoring
        RefactorArgsParser->>RefactorRequirements: validate_provider(provider)
        RefactorRequirements-->>RefactorArgsParser: Err InvalidArguments
        RefactorArgsParser-->>WeaverCLI: Err InvalidArguments
        WeaverCLI-->>Operator: print supported providers/refactorings
    else all_arguments_valid
        RefactorArgsParser-->>WeaverCLI: Ok RefactorArgs
        WeaverCLI->>RefactorHandler: handle(args)
        RefactorHandler->>Runtime: resolve(capability, file_path, Some(provider))
        Runtime-->>RefactorHandler: CapabilityResolution
        RefactorHandler->>Plugin: execute rename-symbol
        Plugin-->>RefactorHandler: diff
        RefactorHandler-->>WeaverCLI: DispatchResult status 0
        WeaverCLI-->>Operator: success output
    end
Loading

Updated class diagram for act_refactor argument handling and requirements

classDiagram
    direction LR

    class RefactorArgsBuilder {
        -provider: Option~String~
        -refactoring: Option~String~
        -file: Option~String~
        -extra: Vec~String~
        +build() Result~RefactorArgs, DispatchError~
    }

    class RefactorArgs {
        +provider: String
        +refactoring: String
        +file: String
        +extra: Vec~String~
    }

    class RefactorRequirements {
        +supported_provider_names() &'static [&'static str]
        +supported_refactoring_names() &'static [&'static str]
        +validate_provider(provider: &str) Result~(), DispatchError~
        +validate_refactoring(refactoring: &str) Result~(), DispatchError~
        +missing_requirements_error() DispatchError
        -validate_value(kind: &str, supported: &[&str], value: &str) Result~(), DispatchError~
        -guidance_lines() String
        -format_required_flags() String
    }

    class RefactorHandler {
        +handle(writer: W, context: Context, request: CommandRequest) DispatchResult
    }

    class Runtime {
        +resolve(request: ResolutionRequest) Result~CapabilityResolution, RuntimeError~
    }

    class DispatchError {
        +InvalidArguments message: String
        +invalid_arguments(message: String) DispatchError
    }

    class RefactorHelpers {
        +standard_rename_args(file: &str) Vec~String~
        -provider_for_file(file: &str) &'static str
    }

    RefactorArgsBuilder --> RefactorArgs : builds
    RefactorArgsBuilder --> RefactorRequirements : uses
    RefactorHandler --> RefactorArgs : consumes
    RefactorHandler --> Runtime : resolve
    RefactorRequirements --> DispatchError : returns
    RefactorArgsBuilder --> DispatchError : returns
    RefactorHelpers --> RefactorArgsBuilder : provides_args
Loading

File-Level Changes

Change Details Files
Enforce a canonical required-arguments contract for act refactor, including provider/refactoring validation and unified error messaging.
  • Introduce a requirements helper module that defines required flags, supported providers/refactorings, and renders the Level 10-style guidance message.
  • Refactor RefactorArgsBuilder::build to require provider, refactoring, and file, and to validate provider/refactoring against the canonical lists before returning.
  • Update router and handler expectations so act refactor now fails with a single InvalidArguments error describing all missing flags and valid values.
crates/weaverd/src/dispatch/act/refactor/requirements.rs
crates/weaverd/src/dispatch/act/refactor/arguments.rs
crates/weaverd/src/dispatch/router/tests.rs
crates/weaverd/src/dispatch/act/refactor/mod.rs
Align tests and behaviour specs with the new required-arguments contract and explicit-provider usage.
  • Extend unit tests around argument parsing to cover complete/missing flags, unsupported provider/refactoring values, and to assert the full error contract.
  • Update handler tests, contract tests, and BDD scenarios to always pass an explicit provider and to assert the new error surfaces, including behaviour when resolution is refused or required flags are missing.
  • Adjust generic failure expectations so act refactor missing-argument flows are treated as InvalidArguments with exit status 1.
crates/weaverd/src/dispatch/act/refactor/arguments.rs
crates/weaverd/src/dispatch/act/refactor/tests.rs
crates/weaverd/src/dispatch/act/refactor/behaviour.rs
crates/weaverd/tests/features/refactor.feature
crates/weaverd/src/dispatch/act/refactor/contract_tests.rs
Update documentation and add an ExecPlan to describe and track the act refactor argument-requirements contract.
  • Add an ExecPlan markdown document for roadmap item 2.3.4, detailing purpose, constraints, risks, implementation stages, and validation steps.
  • Update the user guide to make --provider required, document valid provider/refactoring values, show the new all-in-one error message, and adjust worked examples to use explicit providers.
  • Update design docs and roadmap to describe the new canonical requirements model, the required flags, and to mark roadmap item 2.3.4 as completed.
docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md
docs/users-guide.md
docs/weaver-design.md
docs/roadmap.md

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

codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos leynos changed the title Create ExecPlan: 2.3.4 return argument requirements for act refactor Act refactor: enforce complete required-args contract and add ExecPlan Apr 12, 2026
codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Apr 12, 2026

@coderabbitai Please suggest a fix for this issue and supply a prompt for an AI coding agent to enable it to apply the fix:

crates/weaverd/src/dispatch/act/refactor/requirements.rs

Comment on file

pub(crate) fn validate_provider(provider: &str) -> Result<(), DispatchError> {
    if supported_provider_names().contains(&provider) {
        Ok(())
    } else {
        Err(DispatchError::invalid_arguments(format!(
            "act refactor does not support provider '{provider}'\n\n{}",
            guidance_lines()
        )))
    }
}

❌ New issue: Code Duplication
The module contains 2 functions with similar structure: validate_provider,validate_refactoring

@coderabbitai

This comment was marked as resolved.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos leynos marked this pull request as ready for review April 19, 2026 15:22
sourcery-ai[bot]

This comment was marked as resolved.

@coderabbitai coderabbitai Bot added the Roadmap label Apr 19, 2026
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: 69256c779e

ℹ️ 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 thread crates/weaverd/src/dispatch/act/refactor/refactor_helpers.rs Outdated
coderabbitai[bot]

This comment was marked as resolved.

@leynos leynos changed the title Act refactor: enforce complete required-args contract and add ExecPlan Act refactor: enforce complete required-args contract (2.3.4) Apr 21, 2026
codescene-delta-analysis[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as resolved.

@devboxerhub devboxerhub Bot force-pushed the feat-act-refactor-arg-requirements-p35mzy branch from c6109bd to 5d6cb0b Compare April 23, 2026 13:28
codescene-delta-analysis[bot]

This comment was marked as outdated.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

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 (1)
crates/weaverd/src/dispatch/act/refactor/tests.rs (1)

76-83: ⚠️ Potential issue | 🟡 Minor

Keep the mocked resolution metadata consistent with these explicit requests.

Stop pairing --provider rope requests with automatic_selection(...) fixtures. Those envelopes still encode requested_provider: None and SelectionMode::Automatic, so this test file can miss regressions in explicit-provider propagation even though the CLI contract is now provider-explicit.

Also applies to: 146-153, 200-207, 257-264

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/tests.rs` around lines 76 - 83, The
test builds a CLI request with command_request including "--provider", "rope"
but still uses automatic_selection(...) fixtures that encode requested_provider:
None and SelectionMode::Automatic; update the mocked resolution metadata to
match the explicit provider: replace uses of automatic_selection(...) for the
request variable (and the other occurrences at the ranges noted) with a fixture
or envelope that sets requested_provider: Some("rope") and
SelectionMode::Explicit (or an explicit_selection(...) helper) so the test
verifies explicit-provider propagation correctly.
♻️ Duplicate comments (4)
crates/weaverd/src/dispatch/act/refactor/arguments.rs (1)

40-44: ⚠️ Potential issue | 🟠 Major

Reject malformed trailing arguments here.

Reject any trailing token that is not valid KEY=VALUE. The current check only blocks --*, so inputs such as weaver act refactor --provider rope --refactoring rename --file src/main.py offset still parse and slip past the deterministic pre-runtime contract, only to fail indirectly later.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/arguments.rs` around lines 40 - 44,
The current check only rejects tokens starting with "--" but allows malformed
trailing args (like plain words) to slip through; update the validation over
self.extra to find any token that is not a valid KEY=VALUE pair (i.e., does not
contain an '=' with non-empty key) and return DispatchError::invalid_arguments
with a clear message listing the offending token(s). Locate the block using
self.extra.iter().find(|extra| extra.starts_with("--")) and replace/augment it
so it also checks for tokens where extra.splitn(2, '=').next() is empty or
extra.splitn(2, '=').nth(1) is None, returning an error referencing
DispatchError::invalid_arguments and the offending token(s).
crates/weaverd/src/dispatch/act/refactor/requirements.rs (2)

82-91: 🧹 Nitpick | 🔵 Trivial

Generate the supported capability-operation list from the catalogue.

Line 89 hard-codes rename-symbol into the fallback text. The moment another entry lands in SUPPORTED_REFACTORINGS, this error drifts from the table even though the rest of the module is catalogue-driven. Build the alternatives string from SUPPORTED_REFACTORINGS instead.

Patch sketch
     SUPPORTED_REFACTORINGS
         .iter()
         .find(|supported| supported.capability_operation == operation)
         .map(|supported| supported.capability)
         .ok_or_else(|| {
+            let supported = SUPPORTED_REFACTORINGS
+                .iter()
+                .map(|supported| supported.capability_operation)
+                .collect::<Vec<_>>()
+                .join(", ");
             DispatchError::invalid_arguments(format!(
-                "act refactor does not support capability resolution for '{operation}' (only 'rename-symbol' is currently implemented)"
+                "act refactor does not support capability resolution for '{operation}' (supported operations: {supported})"
             ))
         })
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/requirements.rs` around lines 82 -
91, The error message in capability_for_operation hard-codes "rename-symbol";
instead generate the alternatives list from SUPPORTED_REFACTORINGS and include
it in the DispatchError::invalid_arguments text. Modify capability_for_operation
to build a string (e.g., by iterating SUPPORTED_REFACTORINGS and collecting each
supported.capability_operation, joining them with ", " or "', '" as you prefer)
and use that string in the format! call so the fallback message accurately
reflects the current SUPPORTED_REFACTORINGS entries when capability resolution
fails.

58-108: 🛠️ Refactor suggestion | 🟠 Major

Document the crate-visible contract helpers.

Document the pub(crate) functions in this module with Rustdoc so cargo doc captures the supported lists, mapping rules, and error semantics that now define the act refactor contract.

As per coding guidelines "Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/requirements.rs` around lines 58 -
108, Add Rustdoc comments (///) to each crate-visible helper to document the act
refactor contract: for supported_provider_names and supported_refactoring_names
describe what lists they return; for validate_provider and validate_refactoring
explain they validate input and return DispatchError on invalid values; for
effective_operation and capability_for_operation document the mapping rules they
perform and the exact error semantics (what DispatchError is returned when not
found); for missing_requirements_error describe the composed error message and
when it is used; also briefly document validate_value (or note it as an internal
helper) and include examples or expected values where helpful so cargo doc will
capture supported lists, mappings, and error behavior.
docs/users-guide.md (1)

1028-1030: ⚠️ Potential issue | 🟡 Minor

State that --refactoring and --file can be missing as well.

The failure-condition table still omits missing flags for these two rows, even though the handler now rejects any invocation missing --provider, --refactoring, or --file in one pass. Align the table with the shipped contract.

Patch sketch
-| `--refactoring` | Refactoring operation requested from the plugin. The handler maps `rename` to the `rename-symbol` capability contract before forwarding to the plugin. | Currently only `rename` is implemented by built-in `rope` and `rust-analyzer` plugins.   | Missing value, or unsupported operation name (for example `extract_method`) causes failure. |
-| `--file`        | Target file to load and refactor.                                                                                                                      | Workspace-relative path to an existing readable file (for example `src/main.py`).        | Absolute paths, parent traversal (`..`), or unreadable/missing files cause failure.         |
+| `--refactoring` | Refactoring operation requested from the plugin. The handler maps `rename` to the `rename-symbol` capability contract before forwarding to the plugin. | Currently only `rename` is implemented by built-in `rope` and `rust-analyzer` plugins.   | Missing flag, missing value, or unsupported operation name (for example `extract_method`) causes failure. |
+| `--file`        | Target file to load and refactor.                                                                                                                      | Workspace-relative path to an existing readable file (for example `src/main.py`).        | Missing flag, missing value, absolute paths, parent traversal (`..`), or unreadable/missing files cause failure. |

As per coding guidelines "Ensure that any API or behavioural changes are reflected in the documentation in docs/".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/users-guide.md` around lines 1028 - 1030, The failure-condition table
for the CLI flags is out of sync with the handler: update the three rows for
`--provider`, `--refactoring`, and `--file` in docs/users-guide.md so their
"Failure condition" column explicitly includes "missing flag" (or "missing
value" where applicable) to reflect that the handler rejects invocations missing
any of `--provider`, `--refactoring`, or `--file` in one pass; ensure the
`--refactoring` row still lists unsupported operations (e.g. `extract_method`)
and the `--file` row still lists invalid paths (absolute, `..`, unreadable)
while adding "missing flag" for all three to match the shipped handler behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/weaverd/src/dispatch/act/refactor/mod.rs`:
- Around line 185-187: The rename mapping is being built from the
workspace-relative args.file which yields incorrect URIs; change the call in the
dispatch flow so apply_rename_symbol_mapping receives the resolved absolute
PathBuf (file_path) instead of &args.file, refactor apply_rename_symbol_mapping
to accept &Path and construct the file URI from that absolute path, and replace
the brittle to_file_uri string logic with url::Url::from_file_path(...) to
produce a correct platform-safe file URI. Ensure all call sites and the helper
signature are updated accordingly so providers keyed by uri get the
absolute-file URI.

In `@crates/weaverd/tests/features/refactor.feature`:
- Around line 62-70: Remove the entire scenario titled "Scenario: Refactor
reports the complete required argument contract" from the feature file and
delete the step "And a valid auto-routed act refactor request resolved to rope"
elsewhere in the same feature; then update the scenario "Scenario: Refactor
rejects successful plugin responses without diffs" to use the explicit-provider
step (replace any auto-routed or implicit provider steps with the
explicit-provider step so the scenario asserts a required --provider flag
consistently). Ensure you only remove the auto-routed scenario and replace
references to auto-routing with the explicit-provider step in the named
scenario.

---

Outside diff comments:
In `@crates/weaverd/src/dispatch/act/refactor/tests.rs`:
- Around line 76-83: The test builds a CLI request with command_request
including "--provider", "rope" but still uses automatic_selection(...) fixtures
that encode requested_provider: None and SelectionMode::Automatic; update the
mocked resolution metadata to match the explicit provider: replace uses of
automatic_selection(...) for the request variable (and the other occurrences at
the ranges noted) with a fixture or envelope that sets requested_provider:
Some("rope") and SelectionMode::Explicit (or an explicit_selection(...) helper)
so the test verifies explicit-provider propagation correctly.

---

Duplicate comments:
In `@crates/weaverd/src/dispatch/act/refactor/arguments.rs`:
- Around line 40-44: The current check only rejects tokens starting with "--"
but allows malformed trailing args (like plain words) to slip through; update
the validation over self.extra to find any token that is not a valid KEY=VALUE
pair (i.e., does not contain an '=' with non-empty key) and return
DispatchError::invalid_arguments with a clear message listing the offending
token(s). Locate the block using self.extra.iter().find(|extra|
extra.starts_with("--")) and replace/augment it so it also checks for tokens
where extra.splitn(2, '=').next() is empty or extra.splitn(2, '=').nth(1) is
None, returning an error referencing DispatchError::invalid_arguments and the
offending token(s).

In `@crates/weaverd/src/dispatch/act/refactor/requirements.rs`:
- Around line 82-91: The error message in capability_for_operation hard-codes
"rename-symbol"; instead generate the alternatives list from
SUPPORTED_REFACTORINGS and include it in the DispatchError::invalid_arguments
text. Modify capability_for_operation to build a string (e.g., by iterating
SUPPORTED_REFACTORINGS and collecting each supported.capability_operation,
joining them with ", " or "', '" as you prefer) and use that string in the
format! call so the fallback message accurately reflects the current
SUPPORTED_REFACTORINGS entries when capability resolution fails.
- Around line 58-108: Add Rustdoc comments (///) to each crate-visible helper to
document the act refactor contract: for supported_provider_names and
supported_refactoring_names describe what lists they return; for
validate_provider and validate_refactoring explain they validate input and
return DispatchError on invalid values; for effective_operation and
capability_for_operation document the mapping rules they perform and the exact
error semantics (what DispatchError is returned when not found); for
missing_requirements_error describe the composed error message and when it is
used; also briefly document validate_value (or note it as an internal helper)
and include examples or expected values where helpful so cargo doc will capture
supported lists, mappings, and error behavior.

In `@docs/users-guide.md`:
- Around line 1028-1030: The failure-condition table for the CLI flags is out of
sync with the handler: update the three rows for `--provider`, `--refactoring`,
and `--file` in docs/users-guide.md so their "Failure condition" column
explicitly includes "missing flag" (or "missing value" where applicable) to
reflect that the handler rejects invocations missing any of `--provider`,
`--refactoring`, or `--file` in one pass; ensure the `--refactoring` row still
lists unsupported operations (e.g. `extract_method`) and the `--file` row still
lists invalid paths (absolute, `..`, unreadable) while adding "missing flag" for
all three to match the shipped handler behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 30386ec3-4715-47d6-9d7e-adfcd074743d

📥 Commits

Reviewing files that changed from the base of the PR and between c6109bd and 5d6cb0b.

📒 Files selected for processing (15)
  • crates/weaverd/src/dispatch/act/refactor/arguments.rs
  • crates/weaverd/src/dispatch/act/refactor/behaviour.rs
  • crates/weaverd/src/dispatch/act/refactor/contract_tests.rs
  • crates/weaverd/src/dispatch/act/refactor/manifests.rs
  • crates/weaverd/src/dispatch/act/refactor/mod.rs
  • crates/weaverd/src/dispatch/act/refactor/refactor_helpers.rs
  • crates/weaverd/src/dispatch/act/refactor/requirements.rs
  • crates/weaverd/src/dispatch/act/refactor/rollback_tests.rs
  • crates/weaverd/src/dispatch/act/refactor/tests.rs
  • crates/weaverd/src/dispatch/router/tests.rs
  • crates/weaverd/tests/features/refactor.feature
  • docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md
  • docs/roadmap.md
  • docs/users-guide.md
  • docs/weaver-design.md

Comment thread crates/weaverd/src/dispatch/act/refactor/mod.rs Outdated
Comment thread crates/weaverd/tests/features/refactor.feature Outdated
@leynos leynos changed the title Act refactor: enforce complete required-args contract (2.3.4) Act refactor: enforce complete required-args contract with canonical requirements (2.3.4) Apr 23, 2026
codescene-delta-analysis[bot]

This comment was marked as outdated.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/weaverd/src/dispatch/act/refactor/mod.rs`:
- Around line 185-187: The code assumes file_path (derived from workspace_root)
is absolute when calling apply_rename_symbol_mapping after computing
effective_operation (effective_operation and apply_rename_symbol_mapping), but
DomainRouter::new (and its workspace_root) isn't validating absoluteness; either
document the absolute-path precondition on DomainRouter::new/workspace_root or
add a runtime check at the router boundary that verifies
workspace_root.is_absolute() and returns an error (or panics with a clear
message) if not; update docs/comments on DomainRouter::new to state the
requirement if you choose documentation instead of a runtime guard so callers
(tests and production) are explicit about passing absolute paths.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 74063d09-5f41-4043-8ce3-325391cd7b8b

📥 Commits

Reviewing files that changed from the base of the PR and between 5d6cb0b and 9523781.

📒 Files selected for processing (11)
  • crates/weaverd/src/dispatch/act/refactor/arguments.rs
  • crates/weaverd/src/dispatch/act/refactor/behaviour.rs
  • crates/weaverd/src/dispatch/act/refactor/contract_tests.rs
  • crates/weaverd/src/dispatch/act/refactor/mod.rs
  • crates/weaverd/src/dispatch/act/refactor/requirements.rs
  • crates/weaverd/src/dispatch/act/refactor/tests.rs
  • crates/weaverd/tests/features/refactor.feature
  • docs/developers-guide.md
  • docs/execplans/3-1-1b-plugin-for-rust-analyzer.md
  • docs/execplans/phase-1-end-to-end-domain-command-execution.md
  • docs/users-guide.md

Comment on lines +185 to +187
let effective_operation = effective_operation(&args.refactoring)?;
if effective_operation == "rename-symbol" {
apply_rename_symbol_mapping(&mut plugin_args, file_path.as_path())?;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '== RefactorContext constructors ==\n'
rg -n -C3 'RefactorContext\s*\{' --type rust

printf '\n== workspace_root assignments and derivations ==\n'
rg -n -C4 'workspace_root\s*:' --type rust

printf '\n== workspace_root field references and derivations ==\n'
rg -n -C3 'workspace_root' crates/weaverd/src --type rust

Repository: leynos/weaver

Length of output: 49669


Consider adding a defensive validation or clear documentation of the absolute-path precondition.

All current callers pass absolute workspace roots (env::current_dir() in production, workspace.path() in tests), so the code functions correctly. However, DomainRouter::new (line 141 in router.rs) does not validate that workspace_root is absolute. Document this precondition explicitly, or add a runtime check at the boundary to catch future violations early.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/mod.rs` around lines 185 - 187, The
code assumes file_path (derived from workspace_root) is absolute when calling
apply_rename_symbol_mapping after computing effective_operation
(effective_operation and apply_rename_symbol_mapping), but DomainRouter::new
(and its workspace_root) isn't validating absoluteness; either document the
absolute-path precondition on DomainRouter::new/workspace_root or add a runtime
check at the router boundary that verifies workspace_root.is_absolute() and
returns an error (or panics with a clear message) if not; update docs/comments
on DomainRouter::new to state the requirement if you choose documentation
instead of a runtime guard so callers (tests and production) are explicit about
passing absolute paths.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Apr 23, 2026

@coderabbitai Have the following now been resolved?

docs/users-guide.md (1)

881-929: ⚠️ Potential issue | 🟡 Minor
Remove the omitted-provider routing guidance later in the guide.
This section makes --provider mandatory, but the later plugin-capabilities

section still says the daemon selects rope or rust-analyzer when

--provider is omitted. Delete or rewrite that later text, otherwise the guide

documents two incompatible operator flows.
As per coding guidelines "Ensure that any API or behavioural changes are reflected in the documentation in docs/".

🤖 Prompt for AI Agents

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 23, 2026

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the plugin-capabilities section and any auto-selection language in users-guide.md
grep -n -i "omit\|auto\|automatic\|select\|default\|without.*provider\|provider.*omit\|rope\|rust-analyzer" docs/users-guide.md | head -80

Length of output: 5534


🏁 Script executed:

#!/bin/bash
# Read lines around the plugin-capabilities section that may still describe auto-selection
sed -n '1310,1380p' docs/users-guide.md

Length of output: 3178


@leynos: Yes, this has been resolved. The plugin-capabilities section (around line 1328) now reads:

"For act refactor, operators must still pass --provider explicitly, using rope for Python rename flows or rust-analyzer for Rust rename flows. The daemon refuses deterministically for unsupported languages, unknown providers, and explicit provider/language mismatches."

The earlier text describing automatic rope/rust-analyzer selection when --provider is omitted has been removed. Both the parameter table and the capability-declarations prose now consistently require explicit provider selection, so the two incompatible operator flows no longer co-exist in the guide.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Apr 23, 2026

@coderabbitai Please suggest a fix for this issue and supply a prompt for an AI coding agent to enable it to apply the fix. Include the file and symbol names indicated in the issue at the head of your response.

crates/weaverd/src/dispatch/act/refactor/arguments.rs

Comment on file

    #[test]
    fn missing_file_is_rejected() {
    fn missing_flag_value_is_rejected() {

❌ New issue: Code Duplication
The module contains 6 functions with similar structure: tests.flag_as_value_is_rejected,tests.malformed_trailing_arguments_are_rejected,tests.missing_flag_value_is_rejected,tests.unexpected_top_level_flag_is_rejected and 2 more functions

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Apr 23, 2026

@coderabbitai Has this now been resolved in the latest commit?

Use codegraph analysis to determine your answer.

If this comment is now resolved, please mark it as such using the API. Otherwise, please provide an AI agent prompt for the remaining work to be done to address this comment.

Please address the comments from this code review:

## Overall Comments
- The canonical `SUPPORTED_PROVIDERS`/`SUPPORTED_REFACTORINGS` lists in `requirements.rs` are still manually duplicated; consider deriving them from the same manifest/runtime source that registers providers/refactorings so they can't silently drift when new capabilities are added.
- In `refactor_helpers::provider_for_file`, defaulting unknown extensions to `"rope"` can hide misconfigured tests or new-language scenarios; consider restricting this helper to known extensions and failing loudly (or requiring explicit provider in tests) when the mapping is incomplete.

## Individual Comments

### Comment 1
<location path="docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md" line_range="15" />
<code_context>
+
+## Purpose / big picture
+
+Roadmap item `2.3.4` closes UI gap `5b` by making `weaver act refactor` surface
+the full operator contract when required arguments are missing. Today the
+daemon stops at the first missing field and returns only one message, for
</code_context>
<issue_to_address>
**suggestion (review_instructions):** UI is introduced without being expanded; please define it on first use (for example, “user interface (UI) gap”).

<details>
<summary>Review instructions:</summary>

**Path patterns:** `**/*.md`

**Instructions:**
Define uncommon acronyms on first use.

</details>
</issue_to_address>

### Comment 2
<location path="docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md" line_range="57" />
<code_context>
+- Add both unit coverage and behavioural coverage using `rstest-bdd` v0.5.0.
+  Reuse the existing `act refactor` feature harness in `crates/weaverd/` rather
+  than creating a second bespoke BDD harness.
+- Keep the JSONL transport envelope unchanged. This task may improve the
+  `InvalidArguments` message body, but it must not add a new top-level response
+  type or widen the `stream` / `exit` protocol contract.
</code_context>
<issue_to_address>
**suggestion (review_instructions):** JSONL is introduced here without expansion; please define it on first use (for example, “JSON Lines (JSONL) transport envelope”).

<details>
<summary>Review instructions:</summary>

**Path patterns:** `**/*.md`

**Instructions:**
Define uncommon acronyms on first use.

</details>
</issue_to_address>

### Comment 3
<location path="docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md" line_range="269" />
<code_context>
+contract.
+
+`crates/weaver-e2e/tests/refactor_rope_cli_snapshots.rs` and
+`crates/weaver-e2e/tests/refactor_rust_analyzer_cli_snapshots.rs` exercise the
+operator-facing CLI workflows. A small end-to-end assertion or snapshot should
+be added here if needed to prove that the human-visible `weaver act refactor`
</code_context>
<issue_to_address>
**suggestion (review_instructions):** CLI is used for the first time in this section in “CLI workflows” without definition; please introduce it as “command-line interface (CLI)” on first use.

<details>
<summary>Review instructions:</summary>

**Path patterns:** `**/*.md`

**Instructions:**
Define uncommon acronyms on first use.

</details>
</issue_to_address>

### Comment 4
<location path="docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md" line_range="174" />
<code_context>
+
+- The current missing-argument logic lives in the parser builder, not in the
+  handler. That is the right seam for this work because it lets the daemon
+  reject incomplete requests before plugin resolution, file I/O, or backend
+  startup.
+
</code_context>
<issue_to_address>
**suggestion (review_instructions):** I/O is introduced here without expansion; please define it as “input/output (I/O)” the first time it appears.

<details>
<summary>Review instructions:</summary>

**Path patterns:** `**/*.md`

**Instructions:**
Define uncommon acronyms on first use.

</details>
</issue_to_address>

@leynos

This comment was marked as resolved.

@coderabbitai

This comment was marked as resolved.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 23, 2026

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check current state of arguments.rs tests for duplication
fd 'arguments.rs' --search-path crates/weaverd/src/dispatch/act/refactor --exec cat {}

echo "=== requirements.rs ==="
fd 'requirements.rs' --search-path crates/weaverd/src/dispatch/act/refactor --exec cat {}

echo "=== refactor_helpers.rs ==="
fd 'refactor_helpers.rs' --search-path crates/weaverd/src/dispatch/act/refactor --exec cat {}

echo "=== execplan doc ==="
cat docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md

Length of output: 45648


@leynos: Here is the assessment based on the current state of the files.


Individual Comments (acronym definitions in the execplan doc) — All Resolved ✅

All four undefined-acronym issues are addressed in the current document:

Comment Before After
1 — UI UI gap user interface (UI) gap
2 — JSONL JSONL transport envelope JSON Lines (JSONL) transport envelope
3 — CLI CLI workflows command-line interface (CLI) workflows
4 — I/O file I/O file input/output (I/O)

Overall Comments — Status Mixed

Comment 1 — SUPPORTED_PROVIDERS/SUPPORTED_REFACTORINGS manual duplication:
Substantially addressed. In the current requirements.rs, supported_provider_names() delegates entirely to built_in_provider_names() (sourced from manifests.rs), so the provider list is not manually duplicated. Refactoring names are driven by the supported_refactoring_catalogue! macro, which keeps the user-facing name, capability operation, and CapabilityId co-located in one declaration. This satisfies the single-source-of-truth spirit of the suggestion, though refactoring definitions are still local to the module rather than derived from a runtime registry. As it is a "consider" suggestion and the risk of silent drift is materially reduced, no further action is strictly required.

Comment 2 — refactor_helpers::provider_for_file defaulting to "rope":
No longer applicable. There is no provider_for_file function in refactor_helpers.rs. The related helper, classify_file, returns a FileKind enum (Python / Rust / Other) without producing a provider string at all. The Other variant does not silently default to "rope". This concern is resolved by the current design.


In summary: all four individual acronym comments are resolved, and both overall comments are either addressed or no longer applicable. I'll mark this comment as resolved.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot added Roadmap and removed Issue labels Apr 24, 2026
coderabbitai[bot]

This comment was marked as resolved.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 24, 2026

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== developers-guide.md: requirements mentions ==="
grep -n -i "requirements" docs/developers-guide.md | head -30

echo ""
echo "=== developers-guide.md: SelectionMode/ExplicitProvider/Automatic ==="
grep -n "SelectionMode\|ExplicitProvider\|Automatic\|requested_provider" docs/developers-guide.md | head -20

echo ""
echo "=== manifests.rs: built_in_provider_names with context ==="
grep -n -B5 "pub(crate) fn built_in_provider_names" crates/weaverd/src/dispatch/act/refactor/manifests.rs

echo ""
echo "=== refactor_helpers.rs: standard_rename_args_for_provider with context ==="
grep -n -B5 "pub(crate) fn standard_rename_args_for_provider" crates/weaverd/src/dispatch/act/refactor/refactor_helpers.rs

Length of output: 1372


@leynos: Both checks are now fully resolved.

Check Status Evidence
Developer Documentation ✅ Resolved requirements.rs section added at line 515 of docs/developers-guide.md, documenting all seven pub(crate) functions. The outdated code example now correctly shows SelectionMode::ExplicitProvider / requested_provider: Some("rope") at lines 500–501.
Module-Level Documentation ✅ Resolved built_in_provider_names() in manifests.rs has a full /// doc block (lines 75–79). standard_rename_args_for_provider() in refactor_helpers.rs has a full /// doc block (lines 48–52).

No further work is required for either warning.

@leynos leynos changed the title Act refactor: enforce complete argument contract (2.3.4) Act refactor: require provider/refactoring/file and render contract Apr 24, 2026
codescene-delta-analysis[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot added Issue and removed Roadmap labels Apr 24, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/weaverd/src/dispatch/act/refactor/arguments.rs`:
- Around line 40-54: The parser currently flattens non-flag tokens into
self.extra in apply_flag(), losing ordering and allowing interleaved KEY=VALUE
before later flags; to fix, enforce the "trailing" requirement during parsing by
rejecting any flag seen after self.extra has non-empty entries (or alternatively
stop flattening extras once a flag appears). Update apply_flag() to check if
self.extra.is_empty() before accepting a flag (or if a flag is processed and
self.extra is non-empty, return DispatchError::invalid_arguments with a message
about interleaved KEY=VALUE), and keep references to is_valid_extra_argument and
build() behavior unchanged so the later validation still checks content but
ordering is enforced at parse time.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: bcc894b1-ba7a-4887-b141-ce1b6d494e51

📥 Commits

Reviewing files that changed from the base of the PR and between d0d4131 and daf734d.

📒 Files selected for processing (2)
  • crates/weaverd/src/dispatch/act/refactor/arguments.rs
  • docs/developers-guide.md

Comment on lines +40 to +54
let invalid_extra_arguments: Vec<&str> = self
.extra
.iter()
.map(String::as_str)
.filter(|extra| !is_valid_extra_argument(extra))
.collect();
if !invalid_extra_arguments.is_empty() {
let offending_tokens = invalid_extra_arguments
.iter()
.map(|token| format!("'{token}'"))
.collect::<Vec<_>>()
.join(", ");
return Err(DispatchError::invalid_arguments(format!(
"act refactor only accepts trailing KEY=VALUE arguments; invalid trailing arguments: {offending_tokens}. Use only --provider <plugin>, --refactoring <operation>, --file <path>, and trailing KEY=VALUE arguments"
)));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Enforce the “trailing” requirement during parsing.

Reject interleaved KEY=VALUE tokens before build(). By the time this block runs,
apply_flag() has already flattened every non-flag token into self.extra, so
the original ordering is gone. That means
new_name=woven --provider rope --refactoring rename --file src/main.py still
parses successfully even though the contract and this error text both require
trailing KEY=VALUE arguments.

🩹 Proposed fix
 struct RefactorArgsBuilder {
     provider: Option<String>,
     refactoring: Option<String>,
     file: Option<String>,
     extra: Vec<String>,
+    saw_extra: bool,
 }
@@
 fn apply_flag<'a>(
     arg: &str,
     iter: &mut impl Iterator<Item = &'a String>,
     builder: &mut RefactorArgsBuilder,
 ) -> Result<(), DispatchError> {
+    if builder.saw_extra && arg.starts_with("--") {
+        return Err(DispatchError::invalid_arguments(format!(
+            "act refactor only accepts trailing KEY=VALUE arguments; unexpected flag '{arg}' after trailing arguments"
+        )));
+    }
     match arg {
         "--provider" => builder.provider = Some(parse_flag_value(arg, iter)?),
         "--refactoring" => builder.refactoring = Some(parse_flag_value(arg, iter)?),
         "--file" => builder.file = Some(parse_flag_value(arg, iter)?),
-        other => builder.extra.push(other.to_owned()),
+        other => {
+            builder.saw_extra = true;
+            builder.extra.push(other.to_owned());
+        }
     }
     Ok(())
 }

Add a regression case for an interleaved extra followed by a recognised flag.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/arguments.rs` around lines 40 - 54,
The parser currently flattens non-flag tokens into self.extra in apply_flag(),
losing ordering and allowing interleaved KEY=VALUE before later flags; to fix,
enforce the "trailing" requirement during parsing by rejecting any flag seen
after self.extra has non-empty entries (or alternatively stop flattening extras
once a flag appears). Update apply_flag() to check if self.extra.is_empty()
before accepting a flag (or if a flag is processed and self.extra is non-empty,
return DispatchError::invalid_arguments with a message about interleaved
KEY=VALUE), and keep references to is_valid_extra_argument and build() behavior
unchanged so the later validation still checks content but ordering is enforced
at parse time.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Apr 29, 2026

@coderabbitai Have the following now been resolved?

docs/developers-guide.md (1)

500-507: ⚠️ Potential issue | 🟡 Minor
Align the explicit-provider example end-to-end.
Replace standard_rename_args("notes.py") with

standard_rename_args_for_provider("notes.py", "rope") so the request example

matches SelectionMode::ExplicitProvider and

requested_provider: Some("rope").

Suggested doc patch
-let request = command_request(standard_rename_args("notes.py"));
+let request = command_request(standard_rename_args_for_provider("notes.py", "rope"));

Triage: [type:docstyle]

🤖 Prompt for AI Agents

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 29, 2026

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== developers-guide.md lines 495-515 ==="
sed -n '495,515p' docs/developers-guide.md

echo ""
echo "=== grep for standard_rename_args in developers-guide.md ==="
grep -n "standard_rename_args" docs/developers-guide.md

Length of output: 1108


@leynos: Yes, this is resolved. Line 506 of docs/developers-guide.md now reads:

let request = command_request(standard_rename_args_for_provider("notes.py", "rope"));

This is fully aligned with SelectionMode::ExplicitProvider and requested_provider: Some("rope") on the preceding lines. The suggested patch has been applied correctly.

leynos and others added 11 commits April 29, 2026 09:26
…efactor

Introduce a detailed execution plan outlining the roadmap item 2.3.4 to enhance `weaver act refactor` command by reporting all missing required arguments (`--provider`, `--refactoring`, and `--file`) in a single response, along with valid provider and refactoring values. This living document sets constraints, risks, testing strategies, and documentation updates needed before implementation, ensuring consistent operator experience and compliance with the new error-template policy.

Co-authored-by: devboxerhub[bot] <devboxerhub[bot]@users.noreply.github.com>
…-file for act refactor

This change enforces a complete operator-facing contract for the `act refactor` command, making `--provider` a required flag alongside the existing `--refactoring` and `--file` flags. It adds a canonical requirements helper module that declares supported providers and refactorings, centralizing validation and error message generation.

Missing any required flag now results in one deterministic actionable error listing all required flags, supported providers, supported refactorings, and a concrete next command example. Existing code paths that formerly allowed omitted `--provider` now require explicit specification or fail early.

Behavioral scenarios, tests, and documentation are updated accordingly to reflect these stricter and clearer requirements, improving user experience and reducing partial failure modes.

This is a non-breaking change for internal APIs but slightly changes CLI usage contract, enforcing explicit provider specification for disambiguation and validation.

Refs: docs/execplans/2-3-4-return-argument-requirements-for-act-refactor.md, #Gap 5b

Co-authored-by: devboxerhub[bot] <devboxerhub[bot]@users.noreply.github.com>
…efactoring

Extracted common logic for validating provider and refactoring names into a single helper function `validate_value` to avoid code duplication and improve maintainability.

Co-authored-by: devboxerhub[bot] <devboxerhub[bot]@users.noreply.github.com>
…rovider/refactoring specs

- Reject unexpected top-level flags in act refactor arguments with clear error messages.
- Introduce a unified built-in provider specification structure for plugin manifests.
- Centralize supported refactorings with capability and operation mappings.
- Replace ad hoc mappings with supported refactoring catalogue for validation.
- Improve guidance output listing all required flags, providers, and refactorings.
- Update tests to cover validation and operation-capability mapping.
- Refactor argument builders and test requests to include explicit provider flags.
- Clean up capability resolution to use centralized refactoring capability mappings.
- Update documentation to reflect required explicit provider usage and improved UX guidance.

This change enhances user experience by enforcing correct argument usage upfront, simplifying provider manifest definitions, and consolidating refactoring capability logic for maintainability and extensibility.

Co-authored-by: devboxerhub[bot] <devboxerhub[bot]@users.noreply.github.com>
Restore the provider-aware refactor test helper after the rebase and\nupdate rollback tests to use the explicit provider contract.\n\nThis preserves the branch's required --provider behaviour while\nkeeping the rollback coverage aligned with the current act refactor\nrequest shape on main.
Validate that all trailing extra arguments for `act refactor` are in key=value form and reject flags or malformed arguments. Previously, unrecognized top-level flags were rejected but malformed trailing arguments (e.g., missing `=`) were not properly detected. This change produces clearer errors listing the offending tokens and enforces the requirement that only trailing key=value arguments are allowed after the standard flags. Added tests to verify rejection of malformed trailing arguments.

Co-authored-by: devboxerhub[bot] <devboxerhub[bot]@users.noreply.github.com>
Added an assertion to ensure that the DomainRouter's workspace_root is always an absolute path. This prevents issues in dispatch handlers that rely on workspace-root-relative file paths to construct canonical file URIs. Included tests to verify that providing a relative path causes a panic with a clear error message.

Co-authored-by: devboxerhub[bot] <devboxerhub[bot]@users.noreply.github.com>
…ation

Add comprehensive documentation to the developers guide describing the
`weaverd/src/dispatch/act/refactor/requirements.rs` module. This module is the
single source of truth for the operator-facing contract of `act refactor` and is
used by both argument-parsing logic and tests to maintain consistency in
validation, guidance text, and lists of supported values. The docs detail the
seven public functions exposed, their roles in validating providers and
refactorings, mapping operations to capabilities, and generating standardized
error messages for missing requirements.

Also include minor related code comments and a helper function to support
explicit-provider test paths.

Co-authored-by: devboxerhub[bot] <devboxerhub[bot]@users.noreply.github.com>
Previously, DomainRouter::new and DispatchConnectionHandler::new assumed the workspace_root path was absolute and would panic otherwise. This change replaces panics with proper error handling by returning DispatchError::InvalidArguments if the workspace_root is not absolute. All call sites have been updated to handle this error appropriately. Added tests to verify that relative workspace roots are rejected with errors rather than panics.

This improves robustness of workspace root validation and prevents unexpected panics at runtime.

Co-authored-by: devboxerhub[bot] <devboxerhub[bot]@users.noreply.github.com>
…r_provider

Update the sample code in the developers guide to use `standard_rename_args_for_provider` instead of `standard_rename_args`, reflecting the required provider argument for the rename command.

Co-authored-by: devboxerhub[bot] <devboxerhub[bot]@users.noreply.github.com>
Restore test module wiring and BDD step registration after the
rebase onto origin/main, and adjust helper panic patterns so
whitaker accepts the merged test support code without suppressing
lint rules.
@lodyai lodyai Bot force-pushed the feat-act-refactor-arg-requirements-p35mzy branch from daf734d to 367baa2 Compare April 29, 2026 07:50
Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Gates Failed
Enforce advisory code health rules (1 file with Code Duplication)

Gates Passed
5 Quality Gates Passed

See analysis details in CodeScene

Reason for failure
Enforce advisory code health rules Violations Code Health Impact
arguments.rs 1 advisory rule 10.00 → 9.39 Suppress

Quality Gate Profile: Pay Down Tech Debt
Install CodeScene MCP: safeguard and uplift AI-generated code. Catch issues early with our IDE extension and CLI tool.

Comment thread crates/weaverd/src/dispatch/act/refactor/arguments.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Apr 29, 2026

@coderabbitai Please suggest a fix for this issue and supply a prompt for an AI coding agent to enable it to apply the fix. Include the file and symbol names indicated in the issue at the head of your response.

crates/weaverd/src/dispatch/act/refactor/arguments.rs

Comment on file

    #[test]
    fn missing_file_is_rejected() {
    fn missing_flag_value_is_rejected() {

❌ New issue: Code Duplication
The module contains 6 functions with similar structure: tests.flag_as_value_is_rejected,tests.malformed_trailing_arguments_are_rejected,tests.missing_flag_value_is_rejected,tests.unexpected_top_level_flag_is_rejected and 2 more functions

@coderabbitai

This comment was marked as resolved.

@coderabbitai coderabbitai Bot added Roadmap and removed Issue labels Apr 29, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)
crates/weaverd/src/dispatch/act/refactor/refactor_helpers.rs (1)

41-63: ⚠️ Potential issue | 🟠 Major

Stop inferring the provider in shared rename args.

standard_rename_args() still fabricates --provider from the file extension, and the _ => "rope" fallback lets new tests pass without naming the provider under test. Remove the implicit helper, or fail fast on unknown extensions, so every caller states the provider explicitly.

🩹 Proposed refactor
-    pub(crate) fn standard_rename_args(file: &str) -> Vec<String> {
-        standard_rename_args_for_provider(file, provider_for_file(file))
-    }
-
     pub(crate) fn standard_rename_args_for_provider(file: &str, provider: &str) -> Vec<String> {
         vec![
             String::from("--provider"),
             String::from(provider),
             String::from("--refactoring"),
             String::from("rename"),
             String::from("--file"),
             String::from(file),
             String::from("offset=1"),
             String::from("new_name=woven"),
         ]
     }
-
-    fn provider_for_file(file: &str) -> &'static str {
-        match Path::new(file).extension().and_then(|ext| ext.to_str()) {
-            Some("rs") => "rust-analyzer",
-            _ => "rope",
-        }
-    }
@@
-    const _: fn(&str) -> Vec<String> = standard_rename_args;
     const _: fn(&str, &str) -> Vec<String> = standard_rename_args_for_provider;
-    const _: fn(&str) -> &'static str = provider_for_file;

Based on learnings, act refactor must require --provider, --refactoring, and --file flags; missing or incomplete invocations must be rejected before plugin resolution or file I/O.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/refactor_helpers.rs` around lines 41
- 63, standard_rename_args currently infers a provider via provider_for_file
which hides the required --provider flag; remove that implicit behavior by
deleting provider_for_file and standard_rename_args, and update all call sites
to call standard_rename_args_for_provider(file, provider) with an explicit
provider string (ensuring callers supply the correct provider); this enforces
that every caller names the provider and prevents falling back to "rope".
♻️ Duplicate comments (3)
crates/weaverd/src/dispatch/act/refactor/arguments.rs (2)

135-151: 🛠️ Refactor suggestion | 🟠 Major

Delete the duplicated negative-path tests.

Keep invalid_arguments_are_rejected as the single table for these cases and drop the repeated one-off tests below it. The current mix reintroduces the duplication this file was already flagged for and makes future message changes twice as expensive to maintain.

As per coding guidelines: "Replace duplicated tests with #[rstest(...)] parameterised cases in Rust."

Also applies to: 305-392

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/arguments.rs` around lines 135 -
151, Remove the duplicated negative-path one-off tests (e.g.,
flag_as_value_is_rejected and any other individual invalid cases) and
consolidate them into the existing parameterized test table used by
invalid_arguments_are_rejected; for each removed test add its args vector as an
additional case in the #[rstest(...)] list so parse_refactor_args is exercised
with those inputs, and delete the redundant test functions (including references
to flag_as_value_is_rejected and other one-off invalid tests) so only the single
rstest-based invalid_arguments_are_rejected remains.

89-100: ⚠️ Potential issue | 🟠 Major

Reject recognised flags after the first trailing argument.

apply_flag() still accepts new_name=woven --provider rope --refactoring rename --file src/main.py because it records new_name=woven in extra and then happily parses later flags. That breaks the documented “trailing KEY=VALUE only” contract and lets malformed invocations survive parsing.

🩹 Proposed fix
 struct RefactorArgsBuilder {
     provider: Option<String>,
     refactoring: Option<String>,
     file: Option<String>,
     extra: Vec<String>,
+    saw_extra: bool,
 }
@@
 fn apply_flag<'a>(
     arg: &str,
     iter: &mut impl Iterator<Item = &'a String>,
     builder: &mut RefactorArgsBuilder,
 ) -> Result<(), DispatchError> {
+    if builder.saw_extra && arg.starts_with("--") {
+        return Err(DispatchError::invalid_arguments(format!(
+            "act refactor only accepts trailing KEY=VALUE arguments; unexpected flag '{arg}' after trailing arguments"
+        )));
+    }
+
     match arg {
         "--provider" => builder.provider = Some(parse_flag_value(arg, iter)?),
         "--refactoring" => builder.refactoring = Some(parse_flag_value(arg, iter)?),
         "--file" => builder.file = Some(parse_flag_value(arg, iter)?),
-        other => builder.extra.push(other.to_owned()),
+        other => {
+            builder.saw_extra = true;
+            builder.extra.push(other.to_owned());
+        }
     }
     Ok(())
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/arguments.rs` around lines 89 - 100,
apply_flag currently allows recognized flags even after a trailing positional
(stored in RefactorArgsBuilder.extra), violating the "trailing KEY=VALUE only"
rule; change apply_flag so that if builder.extra is non-empty and arg is one of
the recognized flags ("--provider", "--refactoring", "--file") it returns a
DispatchError (e.g. InvalidArgument or a suitable variant) instead of parsing
the flag with parse_flag_value, otherwise behave as before; update the match in
apply_flag to check builder.extra.is_empty() (or explicitly check before
matching) and return an error when a flag is seen after any trailing argument.
crates/weaverd/src/dispatch/act/refactor/requirements.rs (1)

27-42: 🛠️ Refactor suggestion | 🟠 Major

Collapse the refactoring catalogue into one definition.

SUPPORTED_REFACTORING_NAMES duplicates SUPPORTED_REFACTORINGS. The next refactoring added here can update effective_operation() yet still be rejected by validate_refactoring() and omitted from the guidance text. Generate the names view from the canonical table, or define both through one macro so they cannot drift.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/requirements.rs` around lines 27 -
42, SUPPORTED_REFACTORING_NAMES is a duplicate of SUPPORTED_REFACTORINGS which
can drift; remove the separate constant and make supported_refactoring_names()
derive its slice from the canonical SUPPORTED_REFACTORINGS (or replace both with
a single macro that emits the canonical &[SupportedRefactoring] and the
corresponding &[&str] simultaneously) so additions update effective_operation()
and validate_refactoring() and the guidance text atomically; update
supported_refactoring_names(), and keep references to SUPPORTED_REFACTORINGS,
supported_refactoring_names(), effective_operation(), and validate_refactoring()
in mind when changing the definition.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/weaver-e2e/tests/test_support/mod.rs`:
- Around line 80-85: Replace the inline match used to construct the
DispatchConnectionHandler with the shared required_result helper: call
required_result(DispatchConnectionHandler::new(backend_manager.clone(),
workspace_root)) to unwrap or fail uniformly, then wrap that result in Arc::new
and assign to handler; this removes the explicit match/Err panic and reuses the
test-support error-unwrapping logic (keep the variable name handler and the
Arc::new wrapper).

In `@crates/weaverd/src/dispatch/act/refactor/behaviour.rs`:
- Around line 372-385: The helper then_dispatch_error_contains currently panics
when world.dispatch_result is an Ok variant; change it to return a Result::Err
string instead so the function keeps the Result<(), String> failure shape. In
then_dispatch_error_contains, after obtaining result from
world.dispatch_result.as_ref().ok_or("result missing")?, match on result to
extract the Err(error) case and if it's an Ok(status) return
Err(format!("expected dispatch error, got status: {status:?}")); then continue
using error.to_string() and assert/return Err(...) on mismatch as before so all
failures propagate via Result rather than panic.

In `@crates/weaverd/src/dispatch/act/refactor/request_building.rs`:
- Around line 39-45: The code currently injects a hard-coded "refactoring"
sentinel ("rename-symbol") instead of using the resolved capability; update the
logic so the rename-specific argument rewrite is driven by the capability
returned from capability_for_operation (use the existing effective_operation and
capability variables) rather than a second hard-coded operation string, remove
the duplicated "rename-symbol" sentinel insertion, and apply the same change to
the duplicated block around the other occurrence (the block referenced at the
later 88-97 region) so requirements.rs remains the single source of truth.

---

Outside diff comments:
In `@crates/weaverd/src/dispatch/act/refactor/refactor_helpers.rs`:
- Around line 41-63: standard_rename_args currently infers a provider via
provider_for_file which hides the required --provider flag; remove that implicit
behavior by deleting provider_for_file and standard_rename_args, and update all
call sites to call standard_rename_args_for_provider(file, provider) with an
explicit provider string (ensuring callers supply the correct provider); this
enforces that every caller names the provider and prevents falling back to
"rope".

---

Duplicate comments:
In `@crates/weaverd/src/dispatch/act/refactor/arguments.rs`:
- Around line 135-151: Remove the duplicated negative-path one-off tests (e.g.,
flag_as_value_is_rejected and any other individual invalid cases) and
consolidate them into the existing parameterized test table used by
invalid_arguments_are_rejected; for each removed test add its args vector as an
additional case in the #[rstest(...)] list so parse_refactor_args is exercised
with those inputs, and delete the redundant test functions (including references
to flag_as_value_is_rejected and other one-off invalid tests) so only the single
rstest-based invalid_arguments_are_rejected remains.
- Around line 89-100: apply_flag currently allows recognized flags even after a
trailing positional (stored in RefactorArgsBuilder.extra), violating the
"trailing KEY=VALUE only" rule; change apply_flag so that if builder.extra is
non-empty and arg is one of the recognized flags ("--provider", "--refactoring",
"--file") it returns a DispatchError (e.g. InvalidArgument or a suitable
variant) instead of parsing the flag with parse_flag_value, otherwise behave as
before; update the match in apply_flag to check builder.extra.is_empty() (or
explicitly check before matching) and return an error when a flag is seen after
any trailing argument.

In `@crates/weaverd/src/dispatch/act/refactor/requirements.rs`:
- Around line 27-42: SUPPORTED_REFACTORING_NAMES is a duplicate of
SUPPORTED_REFACTORINGS which can drift; remove the separate constant and make
supported_refactoring_names() derive its slice from the canonical
SUPPORTED_REFACTORINGS (or replace both with a single macro that emits the
canonical &[SupportedRefactoring] and the corresponding &[&str] simultaneously)
so additions update effective_operation() and validate_refactoring() and the
guidance text atomically; update supported_refactoring_names(), and keep
references to SUPPORTED_REFACTORINGS, supported_refactoring_names(),
effective_operation(), and validate_refactoring() in mind when changing the
definition.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 9859e301-0bd1-425d-8820-56c3f5b74572

📥 Commits

Reviewing files that changed from the base of the PR and between daf734d and 367baa2.

📒 Files selected for processing (12)
  • crates/weaver-e2e/tests/test_support/mod.rs
  • crates/weaverd/src/dispatch/act/refactor/arguments.rs
  • crates/weaverd/src/dispatch/act/refactor/behaviour.rs
  • crates/weaverd/src/dispatch/act/refactor/contract_tests.rs
  • crates/weaverd/src/dispatch/act/refactor/manifests.rs
  • crates/weaverd/src/dispatch/act/refactor/mod.rs
  • crates/weaverd/src/dispatch/act/refactor/refactor_helpers.rs
  • crates/weaverd/src/dispatch/act/refactor/request_building.rs
  • crates/weaverd/src/dispatch/act/refactor/requirements.rs
  • crates/weaverd/src/dispatch/act/refactor/rollback_tests.rs
  • crates/weaverd/src/dispatch/act/refactor/tests.rs
  • crates/weaverd/src/dispatch/handler.rs

Comment on lines +80 to +85
let handler = Arc::new(
match DispatchConnectionHandler::new(backend_manager.clone(), workspace_root) {
Ok(handler) => handler,
Err(error) => panic!("absolute workspace root: {error}"),
},
);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Use the existing required_result helper for handler construction.

Replace the inline match at Line 81 with the shared helper to remove duplicated error-unwrapping logic and keep test-support code uniform.

Refactor diff
-        let handler = Arc::new(
-            match DispatchConnectionHandler::new(backend_manager.clone(), workspace_root) {
-                Ok(handler) => handler,
-                Err(error) => panic!("absolute workspace root: {error}"),
-            },
-        );
+        let handler = Arc::new(required_result(
+            DispatchConnectionHandler::new(backend_manager.clone(), workspace_root),
+            "absolute workspace root",
+        ));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let handler = Arc::new(
match DispatchConnectionHandler::new(backend_manager.clone(), workspace_root) {
Ok(handler) => handler,
Err(error) => panic!("absolute workspace root: {error}"),
},
);
let handler = Arc::new(required_result(
DispatchConnectionHandler::new(backend_manager.clone(), workspace_root),
"absolute workspace root",
));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaver-e2e/tests/test_support/mod.rs` around lines 80 - 85, Replace
the inline match used to construct the DispatchConnectionHandler with the shared
required_result helper: call
required_result(DispatchConnectionHandler::new(backend_manager.clone(),
workspace_root)) to unwrap or fail uniformly, then wrap that result in Arc::new
and assign to handler; this removes the explicit match/Err panic and reuses the
test-support error-unwrapping logic (keep the variable name handler and the
Arc::new wrapper).

Comment on lines +372 to +385
#[then("the dispatch error contains {text}")]
fn then_dispatch_error_contains(world: &mut RefactorWorld, text: String) -> Result<(), String> {
let needle = text.trim_matches('"');
let result = world.dispatch_result.as_ref().ok_or("result missing")?;
let Err(error) = result else {
panic!("expected dispatch error, got status: {result:?}");
};
let rendered = error.to_string();
assert!(
rendered.contains(needle),
"expected dispatch error to contain '{needle}', got: {rendered}"
);
Ok(())
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Return the step failure instead of panicking.

Keep this helper on the same Result<(), String> path as the rest of the module. The direct panic! makes the failure shape inconsistent and drops the useful ?-based chaining used elsewhere in these tests.

🩹 Proposed refactor
 fn then_dispatch_error_contains(world: &mut RefactorWorld, text: String) -> Result<(), String> {
     let needle = text.trim_matches('"');
     let result = world.dispatch_result.as_ref().ok_or("result missing")?;
-    let Err(error) = result else {
-        panic!("expected dispatch error, got status: {result:?}");
-    };
+    let error = result
+        .as_ref()
+        .err()
+        .ok_or_else(|| format!("expected dispatch error, got status: {result:?}"))?;
     let rendered = error.to_string();
     assert!(
         rendered.contains(needle),
         "expected dispatch error to contain '{needle}', got: {rendered}"
     );

Based on learnings, in this repo’s Rust code (especially within test modules/helpers), prefer propagating errors using Result<T, String> and the ? operator.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/behaviour.rs` around lines 372 -
385, The helper then_dispatch_error_contains currently panics when
world.dispatch_result is an Ok variant; change it to return a Result::Err string
instead so the function keeps the Result<(), String> failure shape. In
then_dispatch_error_contains, after obtaining result from
world.dispatch_result.as_ref().ok_or("result missing")?, match on result to
extract the Err(error) case and if it's an Ok(status) return
Err(format!("expected dispatch error, got status: {status:?}")); then continue
using error.to_string() and assert/return Err(...) on mismatch as before so all
failures propagate via Result rather than panic.

Comment on lines +39 to 45
let effective_operation = map_effective_operation(&mut plugin_args, args, &resolved_file.path)?;
plugin_args.insert(
String::from("refactoring"),
serde_json::Value::String(effective_operation.clone()),
);
let capability = capability_from_operation(&effective_operation)?;
let capability = capability_for_operation(&effective_operation)?;
let file_content = load_file_contents(&resolved_file.path)?;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Remove the duplicated rename-symbol sentinel.

Route the rename-specific argument rewrite from the resolved capability, not from a second hard-coded operation string. That keeps requirements.rs as the sole contract source and avoids silent drift if the mapping changes.

♻️ Proposed refactor
-    let effective_operation = map_effective_operation(&mut plugin_args, args, &resolved_file.path)?;
+    let (effective_operation, capability) =
+        map_effective_operation(&mut plugin_args, args, &resolved_file.path)?;
     plugin_args.insert(
         String::from("refactoring"),
         serde_json::Value::String(effective_operation.clone()),
     );
-    let capability = capability_for_operation(&effective_operation)?;
     let file_content = load_file_contents(&resolved_file.path)?;
@@
 fn map_effective_operation(
     plugin_args: &mut HashMap<String, serde_json::Value>,
     args: &arguments::RefactorArgs,
     file_path: &Path,
-) -> Result<String, DispatchError> {
+) -> Result<(String, CapabilityId), DispatchError> {
     let operation = supported_effective_operation(&args.refactoring)?;
-    if operation == "rename-symbol" {
-        apply_rename_symbol_mapping(plugin_args, file_path)?;
+    let capability = capability_for_operation(operation)?;
+    match capability {
+        CapabilityId::RenameSymbol => apply_rename_symbol_mapping(plugin_args, file_path)?,
+        _ => {}
     }
-    Ok(String::from(operation))
+    Ok((String::from(operation), capability))
 }

Also applies to: 88-97

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/weaverd/src/dispatch/act/refactor/request_building.rs` around lines 39
- 45, The code currently injects a hard-coded "refactoring" sentinel
("rename-symbol") instead of using the resolved capability; update the logic so
the rename-specific argument rewrite is driven by the capability returned from
capability_for_operation (use the existing effective_operation and capability
variables) rather than a second hard-coded operation string, remove the
duplicated "rename-symbol" sentinel insertion, and apply the same change to the
duplicated block around the other occurrence (the block referenced at the later
88-97 region) so requirements.rs remains the single source of truth.

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