Skip to content

Integrate Tree-Sitter syntactic lock into weaverd safety harness - #39

Merged
leynos merged 4 commits into
mainfrom
terragon/feature/double-lock-syntactic-lock-s4w3mu
Dec 20, 2025
Merged

leynos merged 4 commits into
mainfrom
terragon/feature/double-lock-syntactic-lock-s4w3mu

Conversation

@leynos

@leynos leynos commented Dec 16, 2025 •

Copy link
Copy Markdown
Owner

Summary

  • Introduces a Tree-Sitter based syntactic lock adapter and integrates it into the weaverd safety harness
  • Replaces placeholder syntactic lock with production-ready tree-sitter validation across Rust, Python, and TypeScript
  • Adds pluggable syntactic lock support in the safety harness tests and BDD scenarios
  • Updates docs, tests, and harness to support the adapter

Changes

Core functionality

  • Add weaver-syntax as a dependency to weaverd
  • Implement TreeSitterSyntacticLockAdapter that wraps weaver_syntax::TreeSitterSyntacticLock and implements the harness's SyntacticLock trait
  • Implement boundary translation between weaver-syntax failures and harness verification failures (including location data)
  • Collect and aggregate failures across modified files, propagating parser/backend errors as syntactic lock failures
  • Provide unit tests for Rust, Python, and TypeScript syntactic validation, including pass/fail scenarios and per-file failure locations

Module exports & wiring

  • Update crates/weaverd/src/safety_harness/mod.rs to publicly export TreeSitterSyntacticLockAdapter
  • Update crates/weaverd/src/safety_harness/verification.rs to declare and re-export syntactic adapter
  • Add new module at crates/weaverd/src/safety_harness/verification/syntactic.rs

Safety harness tests & BDD integration

  • Extend safety harness test world to support a pluggable syntactic lock: either ConfigurableSyntacticLock or TreeSitterSyntacticLockAdapter
  • Update tests harness behaviour to switch between lock variants and drive scenarios
  • Expand BDD feature file (crates/weaverd/tests/features/safety_harness.feature) with Tree-sitter integration scenarios:
    • Valid Rust code passes Tree-sitter syntactic validation
    • Invalid Rust code fails with syntactic error and location
    • Unknown file extensions pass through Tree-Sitter validation
    • Invalid Python and TypeScript code fail Tree-Sitter validation
    • Mixed multi-language edits validate all languages together

Execution plan & roadmap

  • Add docs/execplans/phase-2-double-lock-on-syntactic-lock.md detailing the integration approach and decisions
  • Update docs/roadmap.md to mark the syntactic lock integration item as complete

Tests & test plans

  • Unit tests cover per-language validation paths (Rust, Python, TypeScript) and multi-file aggregation
  • BDD scenarios exercise end-to-end behavior with a syntactic lock in the safety harness

Documentation

  • Ensure internal references reflect the new adapter and its role in the harness
  • Provide usage notes for running tests with the new Tree-Sitter based syntactic lock

Why this change

  • Introduces a production-grade syntactic validation step via Tree-Sitter, enabling robust early detection of syntax errors in code changes
  • Keeps harness decoupled from weaver-syntax internals by wrapping it behind an adapter that implements the existing SyntacticLock trait
  • Enables comprehensive multi-language validation (Rust, Python, TypeScript) within the same double-lock flow

Potential impact & risk

  • Minor runtime overhead due to tree-sitter parsing and failure translation
  • Parser initialisation errors are surfaced as backend failures to avoid silent passes
  • No breaking changes for existing tests; ConfigurableSyntacticLock remains available for controlled scenarios

How to run & verify

  • Run cargo test for weaverd to exercise adapter unit tests
  • Execute the full test suite to exercise the BDD steps and feature scenarios
  • Ensure cargo lock updated to reflect weaver-syntax dependency (as included in this change)

Related notes

  • This PR aligns with the Execution Plan in docs/execplans/phase-2-double-lock-on-syntactic-lock.md and marks the corresponding roadmap item as complete
  • Future iterations may extend support for additional languages or finer-grained failure reporting as needed

🌿 Generated by Terry


ℹ️ Tag @terragon-labs to ask questions and address PR feedback

📎 Task: https://www.terragonlabs.com/task/98fd43dc-524a-464a-a0e9-f134a9c2c0ff

@sourcery-ai

sourcery-ai Bot commented Dec 16, 2025 •

Copy link
Copy Markdown

Reviewer's Guide

Integrates a production Tree-Sitter–backed syntactic lock into the weaverd double-lock safety harness via an adapter, wires it into the public API and BDD test world, and adds multi-language tests and documentation/roadmap updates around the new behavior.

Sequence diagram for Tree-Sitter syntactic validation in the double-lock harness

sequenceDiagram
    participant Harness as SafetyHarness
    participant SynLock as SyntacticLock
    participant Adapter as TreeSitterSyntacticLockAdapter
    participant TSLock as TreeSitterSyntacticLock

    Harness->>Harness: build VerificationContext from modified_files
    Harness->>SynLock: validate(context)
    activate SynLock

    Note over SynLock,Adapter: In this PR, SynLock is TreeSitterSyntacticLockAdapter

    SynLock->>Adapter: validate(context)
    activate Adapter
    Adapter->>Adapter: collect_failures(context)

    loop for each (path, content) in context.modified_files()
        Adapter->>TSLock: validate_file(path, content)
        alt Ok(file_failures)
            TSLock-->>Adapter: Vec_ValidationFailure
            Adapter->>Adapter: convert_failure(ValidationFailure) to VerificationFailure
        else Err(error)
            TSLock-->>Adapter: Error
            Adapter->>Adapter: push VerificationFailure for backend error
        end
    end

    Adapter-->>SynLock: SyntacticLockResult::Passed or SyntacticLockResult::Failed
    deactivate Adapter

    SynLock-->>Harness: SyntacticLockResult
    deactivate SynLock

    alt result.passed()
        Harness->>Harness: proceed to SemanticLock phase
    else
        Harness->>Harness: abort double_lock with syntactic failures
    end
Loading

Class diagram for TreeSitterSyntacticLockAdapter and related safety harness types

classDiagram
    class SyntacticLock {
        +validate(context: VerificationContext) SyntacticLockResult
    }

    class TreeSitterSyntacticLockAdapter {
        -inner: TreeSitterSyntacticLock
        +new() TreeSitterSyntacticLockAdapter
        +validate(context: VerificationContext) SyntacticLockResult
        +collect_failures(context: VerificationContext) Vec_VerificationFailure
    }

    class TreeSitterSyntacticLock {
        +new() TreeSitterSyntacticLock
        +validate_file(path: PathBuf, content: String) Result_Vec_ValidationFailure_Error
    }

    class VerificationContext {
        +new() VerificationContext
        +add_modified(path: PathBuf, content: String) void
        +modified_files() Iterator_PathBuf_String
    }

    class SyntacticLockResult {
        <<enum>>
        Passed
        Failed
        +passed() bool
        +failures() Option_Vec_VerificationFailure
    }

    class VerificationFailure {
        +new(path: PathBuf, message: String) VerificationFailure
        +at_location(line: usize, column: usize) VerificationFailure
        +file() PathBuf
        +line() Option_usize
        +column() Option_usize
    }

    class ValidationFailure {
        +path: PathBuf
        +message: String
        +line: usize
        +column: usize
    }

    SyntacticLock <|.. TreeSitterSyntacticLockAdapter
    TreeSitterSyntacticLockAdapter *-- TreeSitterSyntacticLock
    TreeSitterSyntacticLockAdapter --> VerificationContext
    TreeSitterSyntacticLockAdapter --> SyntacticLockResult
    TreeSitterSyntacticLockAdapter --> VerificationFailure
    TreeSitterSyntacticLock --> ValidationFailure
    ValidationFailure --> VerificationFailure
Loading

File-Level Changes

Change Details Files
Introduce TreeSitterSyntacticLockAdapter and integrate it with the SyntacticLock trait and verification flow.
  • Add TreeSitterSyntacticLockAdapter struct wrapping weaver_syntax::TreeSitterSyntacticLock and implementing SyntacticLock::validate
  • Translate weaver-syntax ValidationFailure instances into VerificationFailure with file, line, and column location data
  • Aggregate per-file Tree-Sitter validation failures and convert backend/parser errors into syntactic lock failures
  • Expose TreeSitterSyntacticLockAdapter from the safety_harness module and verification namespace
crates/weaverd/src/safety_harness/verification/syntactic.rs
crates/weaverd/src/safety_harness/verification.rs
crates/weaverd/src/safety_harness/mod.rs
Extend the safety harness BDD test world to support pluggable syntactic locks and track the current file for edits.
  • Introduce SyntacticLockVariant enum to switch between ConfigurableSyntacticLock and TreeSitterSyntacticLockAdapter in tests
  • Update SafetyHarnessWorld to store a SyntacticLockVariant, track current_file, and default edits to the most recently created source file
  • Add a Cucumber/Gherkin step to select the Tree-sitter syntactic lock and route validate calls through the selected variant
crates/weaverd/src/tests/safety_harness_behaviour.rs
Add end-to-end BDD scenarios for Tree-Sitter syntactic validation across Rust, Python, TypeScript, and unknown file types.
  • Extend safety_harness.feature with scenarios for valid/invalid Rust under Tree-Sitter syntactic validation
  • Add scenarios asserting that unknown extensions bypass Tree-Sitter validation while Python and TypeScript invalid code fails
  • Ensure scenarios exercise interactions with the semantic lock and the new syntactic lock selection step
crates/weaverd/tests/features/safety_harness.feature
Wire in the weaver-syntax dependency and update roadmap and execution plan documentation.
  • Add weaver-syntax as a dependency in weaverd/Cargo.toml so the adapter can use TreeSitterSyntacticLock
  • Mark the syntactic lock integration item as complete in docs/roadmap.md
  • Add an execution plan document describing the design decisions, implementation checklist, and testing for the syntactic lock integration
crates/weaverd/Cargo.toml
docs/roadmap.md
docs/execplans/phase-2-double-lock-on-syntactic-lock.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

@coderabbitai

coderabbitai Bot commented Dec 16, 2025 •

Copy link
Copy Markdown

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Integrates a Tree-sitter-based syntactic lock adapter into the weaverd safety harness module. Adds a new TreeSitterSyntacticLockAdapter that wraps the weaver-syntax crate's TreeSitterSyntacticLock implementation, enabling language-aware code validation for Rust, Python, and TypeScript through the existing harness verification interface.

Changes

Cohort / File(s) Summary
Dependency configuration
crates/weaverd/Cargo.toml
Added path-based dependency on weaver-syntax crate
Module exports
crates/weaverd/src/safety_harness/mod.rs, crates/weaverd/src/safety_harness/verification.rs
Introduced new syntactic module and publicly re-exported TreeSitterSyntacticLockAdapter through module hierarchy
Adapter implementation
crates/weaverd/src/safety_harness/verification/syntactic.rs
Implemented new TreeSitterSyntacticLockAdapter struct that wraps weaver_syntax::TreeSitterSyntacticLock, delegates per-file validation, converts syntax errors to VerificationFailure type, and includes comprehensive test coverage for Rust, Python, TypeScript, and edge cases
Test scaffolding
crates/weaverd/src/tests/safety_harness_behaviour.rs
Added SyntacticLockVariant enum to support both configurable and Tree-sitter syntactic locks; updated SafetyHarnessWorld with variant-aware locking and file tracking; extended step definitions to configure and utilise Tree-sitter validation
BDD feature scenarios
crates/weaverd/tests/features/safety_harness.feature
Added six new scenarios exercising Tree-sitter syntactic validation: valid/invalid Rust, Python, and TypeScript code paths; unknown file extension passthrough; verification outcomes
Documentation
docs/execplans/phase-2-double-lock-on-syntactic-lock.md, docs/roadmap.md
Added execution plan detailing adapter pattern, error handling, and implementation checklist; marked related roadmap items as completed

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~35 minutes

Focus review attention on:

  • Error handling and failure conversion logic in TreeSitterSyntacticLockAdapter::validate(), particularly location data capture
  • SyntacticLockVariant enum delegation correctness and exhaustiveness of trait implementation
  • Test coverage completeness across language-specific syntax validation paths
  • Proper initialisation and state management of the adapter within test scaffolding

Poem

🌳 Trees now whisper syntax truth,
Lock and key in parsed youth,
Rust and Python, TypeScript's dance—
Code flows through with confident glance,
Doubled safety, doubly blessed!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Title check ✅ Passed The title directly summarises the main change: integrating a Tree-Sitter syntactic lock adapter into the weaverd safety harness, which is the core objective of the PR.
Description check ✅ Passed The description provides comprehensive detail on all changeset areas: the adapter implementation, module exports, test infrastructure updates, BDD scenarios, documentation, and design rationale—all of which align directly with the changes shown in the raw summary.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch terragon/feature/double-lock-syntactic-lock-s4w3mu

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

@macroscopeapp

macroscopeapp Bot commented Dec 16, 2025

Copy link
Copy Markdown

Integrate Tree-Sitter syntactic lock into the Double-Lock harness by adding TreeSitterSyntacticLockAdapter in weaverd and validating Rust, Python, and TypeScript edits

Add weaver-syntax as a dependency and implement TreeSitterSyntacticLockAdapter that routes syntactic validation through Tree‑Sitter; update the safety harness to export the adapter and extend tests to run scenarios against the Tree‑Sitter variant.

📍Where to Start

Start with the adapter implementation in syntactic.rs, then see its re-exports in verification.rs and usage in tests in safety_harness_behaviour.rs.


Macroscope summarized 0a294e9.

@leynos
leynos marked this pull request as ready for review December 20, 2025 01:03
Add TreeSitterSyntacticLockAdapter in weaverd that wraps the weaver-syntax
TreeSitterSyntacticLock to implement the harness's SyntacticLock trait. This
provides real Tree-sitter-based syntactic validation for Rust, Python, and
TypeScript files during the safety harness verification phase.

Key changes:
- Add weaver-syntax dependency to weaverd
- Create TreeSitterSyntacticLockAdapter with convert_failure helper
- Add SyntacticLockVariant enum for pluggable locks in BDD tests
- Add 5 BDD scenarios testing Tree-sitter validation integration
- Add 11 unit tests covering adapter edge cases
- Update module exports to expose TreeSitterSyntacticLockAdapter

The adapter:
- Validates all modified files using Tree-sitter parsers
- Passes through files with unrecognised extensions (JSON, markdown, etc.)
- Converts weaver-syntax::ValidationFailure to weaverd::VerificationFailure
- Maps parser errors to SyntacticLockResult::Failed with error message

Design decisions documented in docs/execplans/phase-2-double-lock-on-syntactic-lock.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@leynos
leynos force-pushed the terragon/feature/double-lock-syntactic-lock-s4w3mu branch from 0a294e9 to f3c4798 Compare December 20, 2025 01:05
sourcery-ai[bot]

This comment was marked as resolved.

- Update DD-4 in execution plan to describe SyntacticLockVariant enum
  (not Box<dyn SyntacticLock> as originally written)
- Expand LSP and BDD acronyms on first use in execution plan
- Refactor unit tests to use rstest fixtures and parameterised cases
- Loosen test assertions to avoid tight coupling to parser failure
  granularity (assert "at least one failure" instead of exact counts)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@leynos

leynos commented Dec 20, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai Have the following now been resolved?

  • The execution plan doc (DD-4) describes SafetyHarnessWorld using Box<dyn SyntacticLock>, but the implementation uses a SyntacticLockVariant enum instead; consider updating the doc to match the actual design to avoid confusion for future maintainers.
  • Some adapter tests (e.g. mixed_valid_and_invalid_fails_with_invalid_only) assert an exact failure count and file name pattern, which tightly couples them to the current weaver-syntax failure granularity; consider loosening these to assert that at least one failure exists for the invalid file rather than enforcing len() == 1 and substring matches.

@coderabbitai

coderabbitai Bot commented Dec 20, 2025

Copy link
Copy Markdown

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash

# Read the execution plan document
echo "=== Execution Plan Document ==="
cat docs/execplans/phase-2-double-lock-on-syntactic-lock.md

echo -e "\n=== SafetyHarnessWorld Implementation ==="
# Find files containing SafetyHarnessWorld
fd -e rs | xargs rg -l "struct SafetyHarnessWorld" | head -5

echo -e "\n=== SafetyHarnessWorld Definition ==="
# Get the actual definition with context
rg -n -A 10 "struct SafetyHarnessWorld" --type rust

echo -e "\n=== Adapter Test File ==="
# Find the adapter test file
fd -e rs syntactic | xargs rg -l "mixed_valid_and_invalid_fails_with_invalid_only" 

echo -e "\n=== Test: mixed_valid_and_invalid_fails_with_invalid_only ==="
# Get the specific test mentioned
rg -n -A 30 "fn mixed_valid_and_invalid_fails_with_invalid_only" --type rust

Length of output: 6662


🏁 Script executed:

#!/bin/bash

# Find syntactic.rs files more broadly
echo "=== Finding syntactic.rs files ==="
fd syntactic.rs

echo -e "\n=== Searching for adapter tests in verification directory ==="
rg -n "mixed_valid_and_invalid" --type rust

echo -e "\n=== Searching for all test functions in syntactic adapter ==="
find crates/weaverd/src -name "syntactic.rs" -exec cat {} \; | head -300

echo -e "\n=== Check if tests are in a tests module under verification ==="
fd -e rs . crates/weaverd/src/safety_harness/verification/ -x cat {}

Length of output: 27931


@leynos: Yes, both issues have been resolved! ✅

Issue 1: Documentation vs Implementation Mismatch

The execution plan document (DD-4) now correctly describes the implementation:

"Modify SafetyHarnessWorld to use a SyntacticLockVariant enum that can hold either ConfigurableSyntacticLock or TreeSitterSyntacticLockAdapter"

This matches the actual implementation at line 46 of safety_harness_behaviour.rs:

syntactic_lock: SyntacticLockVariant,

Issue 2: Test Assertion Granularity

The mixed_valid_and_invalid_fails test (lines 220-237) now uses looser assertions that don't tightly couple to weaver-syntax failure granularity:

// At least one failure should exist for the invalid file
assert!(
    !failures.is_empty(),
    "should have at least one failure for invalid file"
);
// Verify the invalid file is represented in failures
let has_invalid_file = failures
    .iter()
    .any(|f| f.file().to_string_lossy().contains("invalid"));
assert!(has_invalid_file, "failures should include the invalid file");

Instead of enforcing len() == 1 and exact substring matches, the test now:

  • Checks that at least one failure exists
  • Verifies the invalid file is represented in the failures without assuming exact count

Both concerns have been addressed in the current PR state.

@leynos

leynos commented Dec 20, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Dec 20, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 7

📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d7187cd and a0fea76.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • crates/weaverd/Cargo.toml (1 hunks)
  • crates/weaverd/src/safety_harness/mod.rs (1 hunks)
  • crates/weaverd/src/safety_harness/verification.rs (1 hunks)
  • crates/weaverd/src/safety_harness/verification/syntactic.rs (1 hunks)
  • crates/weaverd/src/tests/safety_harness_behaviour.rs (5 hunks)
  • crates/weaverd/tests/features/safety_harness.feature (1 hunks)
  • docs/execplans/phase-2-double-lock-on-syntactic-lock.md (1 hunks)
  • docs/roadmap.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Run make check-fmt, make lint, and make test before committing, which execute cargo fmt --workspace -- --check, cargo clippy --workspace --all-targets --all-features -- -D warnings, and cargo test --workspace respectively.
Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error, consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality; run both before and after making any change.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments in Rust.
Do not use return in single-line functions in Rust.
Use predicate functions for conditional criteria with more than two branches in Rust.
Lints must not be silenced except as a last resort; lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow in Rust.
Use rstest fixtures for shared setup in Rust tests.
Replace duplicated tests with #[rstest(...)] parameterised cases in Rust.
Prefer mockall for mocks/stubs in Rust.
Prefer .expect() over .unwrap() in Rust.
Use concat!() to combine long string literals in Rust rather than escaping newlines with a backslash.
Prefer single-line function definitions in Rust where appropriate (e.g., `pub fn new(id: u64) -> Self { ...

Files:

  • crates/weaverd/src/safety_harness/verification.rs
  • crates/weaverd/src/safety_harness/mod.rs
  • crates/weaverd/src/safety_harness/verification/syntactic.rs
  • crates/weaverd/src/tests/safety_harness_behaviour.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cognitive complexity of functions no more than 9.

  • Adhere to single responsibility and CQRS
  • Place function attributes after doc comments.
  • Do not use return in single-line functions.
  • Move conditionals with >2 branches into a predicate function.
  • Avoid unsafe unless absolutely necessary.
  • Every module must begin with a //! doc comment that explains the module's purpose and utility.
  • Comments and docs must follow en-GB-oxendict (-ize / -yse / -our) spelling and grammar
  • Lints must not be silenced except as a last resort.
    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.
  • Replace duplicated tests with #[rstest(...)] parameterised cases.
  • Prefer mockall for mocks/stubs.
  • Prefer .expect() over .unwrap() in tests.
  • .expect() and .unwrap() are forbidden outside of tests. Errors must be propagated.
  • Ensure that any API or behavioural changes are reflected in the documentation in docs/
  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/
  • Files must not exceed 400 lines in length
    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such
    • For testing of functionality depending upon environment variables, dependency injection and...

Files:

  • crates/weaverd/src/safety_harness/verification.rs
  • crates/weaverd/src/safety_harness/mod.rs
  • crates/weaverd/src/safety_harness/verification/syntactic.rs
  • crates/weaverd/src/tests/safety_harness_behaviour.rs
docs/**/*.md

📄 CodeRabbit inference engine (AGENTS.md)

Documentation must use en-GB-oxendict ("-ize" / "-yse" / "-our") spelling and grammar, except for the "LICENSE" file which is left unchanged for community consistency.

docs/**/*.md: Use British English based on Oxford English Dictionary (en-GB-oxendict), including: -ize suffix (realize, organization), -lyse suffix (analyse, paralyse), -our suffix (colour, behaviour), -re suffix (calibre, centre), double 'l' (cancelled, counsellor), maintain 'e' (likeable, liveable), -ogue suffix (analogue, catalogue)
Use US spelling when used in an API, for example color
Use the Oxford comma in documentation: 'ships, planes, and hovercraft' where it aids comprehension
Treat company names as collective nouns in documentation, for example: 'Lille Industries are expanding'
Write headings in sentence case using Markdown headings (#, ##, ###) in order without skipping levels
Follow markdownlint recommendations for Markdown consistency
Provide code blocks and lists using standard Markdown syntax, always providing a language identifier for fenced code blocks (use plaintext for non-code text)
Use - as the first level bullet and renumber lists when items change in documentation
Prefer inline links using [text](url) or angle brackets around the URL in documentation
Ensure blank lines before and after bulleted lists and fenced blocks in documentation
Ensure tables have a delimiter line below the header row in documentation
Expand any uncommon acronym on first use in documentation, for example, Continuous Integration (CI)
Wrap paragraphs at 80 columns in documentation
Wrap code at 120 columns in documentation
Do not wrap tables in documentation
Use footnotes referenced with [^label] in documentation
Include Mermaid diagrams where they add clarity to documentation
When embedding figures in documentation, use ![alt text](path/to/image) and provide brief alt text describing the content
Add a short description before each Mermaid diagram so screen readers can understand it
Define roa...

Files:

  • docs/execplans/phase-2-double-lock-on-syntactic-lock.md
  • docs/roadmap.md
**/*.md

📄 CodeRabbit inference engine (AGENTS.md)

**/*.md: Validate Markdown files using make markdownlint.
Run make fmt after any documentation changes to format all Markdown files and fix table markup.
Validate Mermaid diagrams in Markdown files by running make nixie.
Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks in Markdown must be wrapped at 120 columns.
Tables and headings in Markdown must not be wrapped.
Use dashes (-) for list bullets in Markdown.
Use GitHub-flavoured Markdown footnotes ([^1]) for references and footnotes.

Files:

  • docs/execplans/phase-2-double-lock-on-syntactic-lock.md
  • docs/roadmap.md

⚙️ CodeRabbit configuration file

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -yse / -our) spelling and grammar
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • docs/execplans/phase-2-double-lock-on-syntactic-lock.md
  • docs/roadmap.md
🧠 Learnings (1)
📚 Learning: 2025-12-14T19:21:48.532Z
Learnt from: leynos
Repo: leynos/weaver PR: 38
File: crates/weaverd/src/tests/safety_harness_behaviour.rs:0-0
Timestamp: 2025-12-14T19:21:48.532Z
Learning: In rstest-bdd step definitions, underscore-prefixed parameters like _world can trigger non_snake_case lints via generated guard symbols, and patterns like _: T are rejected by the framework. For intentionally unused parameters in rstest-bdd steps, use a named parameter with #[expect(unused_variables, reason = "...")] instead. This guideline applies to Rust test files under crates/weaverd/src/tests (and similarly structured test files using rstest-bdd).

Applied to files:

  • crates/weaverd/src/tests/safety_harness_behaviour.rs
🧬 Code graph analysis (1)
crates/weaverd/src/tests/safety_harness_behaviour.rs (2)
crates/weaverd/src/safety_harness/verification/syntactic.rs (3)
  • validate (63-71)
  • lock (113-115)
  • new (49-53)
crates/weaverd/src/safety_harness/verification/test_doubles.rs (6)
  • validate (34-42)
  • validate (84-101)
  • passing (22-24)
  • passing (57-62)
  • failing (28-30)
  • failing (66-71)
🪛 LanguageTool
docs/execplans/phase-2-double-lock-on-syntactic-lock.md

[typographical] ~4-~4: To join two clauses or introduce examples, consider using an em dash.
Context: ...rness Status: Complete Phase: 2 - Syntactic & Relational Intelligence **La...

(DASH_RULE)


[style] ~54-~54: Would you like to use the Oxford spelling “Organization”? The spelling ‘Organisation’ is also correct.
Context: ...messages to operators ### DD-3: Module Organisation Decision: Place the adapter in a n...

(OXFORD_SPELLING_Z_NOT_S)


[style] ~129-~129: Would you like to use the Oxford spelling “initialization”? The spelling ‘initialisation’ is also correct.
Context: ...|------|--------|------------| | Parser initialisation failure | Medium | Map to backend error...

(OXFORD_SPELLING_Z_NOT_S)


[typographical] ~135-~135: To join two clauses or introduce examples, consider using an em dash.
Context: ...## References - docs/weaver-design.md - Section 4.2 "Double-Lock Safety Harness"...

(DASH_RULE)


[typographical] ~136-~136: To join two clauses or introduce examples, consider using an em dash.
Context: ...tes/weaver-syntax/src/syntactic_lock.rs- Source implementation -crates/weaverd/...

(DASH_RULE)


[typographical] ~137-~137: To join two clauses or introduce examples, consider using an em dash.
Context: ...verd/src/safety_harness/verification.rs` - Target trait

(DASH_RULE)

🔍 Remote MCP

Since the repositories aren't indexed in Deepwiki, let me search for general information about Tree-Sitter and the validation patterns being used:Based on my search results, I've gathered relevant context about Tree-Sitter and the patterns used in this PR. Here's the summary:

Key Context for PR Review

Tree-Sitter Fundamentals

Tree-Sitter is a parser generator tool and an incremental parsing library that can build a concrete syntax tree for a source file and efficiently update the syntax tree as the source file is edited. This is particularly relevant since the PR integrates Tree-Sitter syntax validation into the weaverd double-lock safety harness.

Multi-Language Support

The TreeSitterSyntacticLockAdapter's support for Rust, Python, and TypeScript aligns with Tree-Sitter's design capabilities. Tree-sitter-javascript serves as a complete parsing solution that transforms source code into abstract syntax trees (ASTs) and provides language-aware analysis capabilities through query systems, encompassing the core grammar definition, generated parser components, multi-language bindings, and comprehensive tooling. Tree-Sitter natively supports multiple programming languages with similar architecture.

Validation Strategy: Unknown Extensions

The PR's design choice to pass through unknown file extensions without validation is sound. This follows pragmatic parsing patterns where file type detection determines validation scope, rather than attempting universal syntax checking.

Potential Performance Considerations

Parser incremental changes to the tree are necessary so it doesn't have to redo the whole thing on every keystroke. The PR notes "potential minor runtime overhead from Tree-Sitter parsing"—this is expected since Tree-Sitter performs full syntax tree generation rather than lightweight incremental updates in an editor context.

Test Coverage Strategy

The BDD scenarios covering valid/invalid code, multi-file aggregation, and language-specific edge cases align with best practices for validating multi-language parser integration. The adapter pattern wrapping weaver_syntax::TreeSitterSyntacticLock allows clear separation of concerns.

[::web_search::]

⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (15)
docs/roadmap.md (1)

85-86: LGTM!

Roadmap item correctly marked as complete, reflecting the integration work in this PR.

crates/weaverd/Cargo.toml (1)

19-19: LGTM!

Path dependency correctly added for the internal weaver-syntax crate, enabling the Tree-Sitter adapter integration.

crates/weaverd/src/safety_harness/verification.rs (1)

8-8: LGTM!

Module declaration and public re-export follow the existing patterns and maintain alphabetical ordering.

Also applies to: 15-15

crates/weaverd/src/safety_harness/mod.rs (1)

39-43: LGTM!

Public exports correctly updated to include TreeSitterSyntacticLockAdapter, maintaining alphabetical ordering.

crates/weaverd/tests/features/safety_harness.feature (1)

74-110: LGTM!

Tree-sitter integration scenarios comprehensively cover the key validation paths: successful Rust validation, failure detection for Rust/Python/TypeScript, and pass-through for unknown extensions. Valid code paths for Python and TypeScript are covered by the parameterised unit tests in syntactic.rs.

crates/weaverd/src/safety_harness/verification/syntactic.rs (4)

1-6: LGTM!

Module documentation clearly explains the adapter's purpose and boundary responsibilities.


62-72: LGTM!

Clean delegation pattern with appropriate result construction.


98-101: LGTM!

Conversion function cleanly maps between crate boundaries, preserving location information.


103-255: LGTM!

Excellent test coverage using rstest fixtures and parameterised cases. The loosened assertions (e.g., failures.len() >= 2) correctly avoid coupling to parser-specific failure granularity.

crates/weaverd/src/tests/safety_harness_behaviour.rs (6)

14-18: LGTM!

The imports are correctly extended to include the new SyntacticLock trait, SyntacticLockResult, and TreeSitterSyntacticLockAdapter required for the pluggable lock pattern.


20-36: LGTM!

Clean delegation pattern. The SyntacticLockVariant enum correctly wraps both lock types and the SyntacticLock trait implementation properly delegates to the underlying variant.


44-46: LGTM!

The current_file field appropriately tracks the most recently created source file, enabling edit steps to target it by default. The SyntacticLockVariant type enables pluggable lock selection.


59-60: LGTM!

Correct initialisation: current_file starts as None, and the syntactic lock defaults to a passing configurable lock wrapped in the new variant.


75-82: LGTM!

The current_file tracking and current_file_name() helper correctly maintain backward compatibility by falling back to "test.txt" when no file has been explicitly created in the scenario.


171-188: LGTM!

The given steps correctly wrap configurable locks in SyntacticLockVariant::Configurable and introduce the new Tree-sitter step cleanly. The pattern is consistent with the semantic lock steps.

- Use Oxford English spelling (-ize suffix) per coding guidelines:
  - unrecognised → unrecognized (syntactic.rs)
  - initialised → initialized (syntactic.rs)
  - initialisation → initialization (syntactic.rs, exec plan)
  - Organisation → Organization (exec plan)

- Update BDD step definitions for consistency:
  - then_file_contains now uses current_file_name()
  - then_file_unchanged now uses current_file_name() and original_content()

This ensures unnamed "then" steps target the same file as preceding
"given" and "when" steps, preventing future scenarios from inadvertently
checking the wrong file.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@leynos leynos changed the title Integrate Tree-Sitter syntactic lock into weaverd double-lock Add Tree-Sitter syntactic lock adapter to weaverd safety harness Dec 20, 2025
Adds a Mermaid sequence diagram to the execution plan document showing
the interaction between SafetyHarness, SyntacticLock trait,
TreeSitterSyntacticLockAdapter, and TreeSitterSyntacticLock during
validation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@leynos leynos changed the title Add Tree-Sitter syntactic lock adapter to weaverd safety harness Integrate Tree-Sitter syntactic lock into weaverd safety harness Dec 20, 2025
@leynos
leynos merged commit c15f792 into main Dec 20, 2025
@leynos
leynos deleted the terragon/feature/double-lock-syntactic-lock-s4w3mu branch December 20, 2025 21:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant