Repository navigation
Integrate Tree-Sitter syntactic lock into weaverd safety harness - #39
Conversation
Reviewer's GuideIntegrates 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 harnesssequenceDiagram
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
Class diagram for TreeSitterSyntacticLockAdapter and related safety harness typesclassDiagram
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
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughIntegrates a Tree-sitter-based syntactic lock adapter into the weaverd safety harness module. Adds a new Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~35 minutes Focus review attention on:
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
Integrate Tree-Sitter syntactic lock into the Double-Lock harness by adding
|
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>
0a294e9 to
f3c4798
Compare
- 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>
|
@coderabbitai Have the following now been resolved?
|
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 6662 🏁 Script executed: 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:
This matches the actual implementation at line 46 of syntactic_lock: SyntacticLockVariant,Issue 2: Test Assertion Granularity The // 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
Both concerns have been addressed in the current PR state. |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 7
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
⛔ Files ignored due to path filters (1)
Cargo.lockis 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: Runmake check-fmt,make lint, andmake testbefore committing, which executecargo fmt --workspace -- --check,cargo clippy --workspace --all-targets --all-features -- -D warnings, andcargo test --workspacerespectively.
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 usingArcto 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 withcargo doc.
Prefer immutable data and avoid unnecessarymutbindings.
Handle errors with theResulttype instead of panicking where feasible.
Avoidunsafecode unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments in Rust.
Do not usereturnin 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.
Preferexpectoverallowin Rust.
Userstestfixtures for shared setup in Rust tests.
Replace duplicated tests with#[rstest(...)]parameterised cases in Rust.
Prefermockallfor mocks/stubs in Rust.
Prefer.expect()over.unwrap()in Rust.
Useconcat!()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.rscrates/weaverd/src/safety_harness/mod.rscrates/weaverd/src/safety_harness/verification/syntactic.rscrates/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
returnin single-line functions.- Move conditionals with >2 branches into a predicate function.
- Avoid
unsafeunless 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
rstestfixtures for shared setup and to avoid repetition between tests.- Replace duplicated tests with
#[rstest(...)]parameterised cases.- Prefer
mockallfor 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.rscrates/weaverd/src/safety_harness/mod.rscrates/weaverd/src/safety_harness/verification/syntactic.rscrates/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 examplecolor
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 (useplaintextfor 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, useand 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.mddocs/roadmap.md
**/*.md
📄 CodeRabbit inference engine (AGENTS.md)
**/*.md: Validate Markdown files usingmake markdownlint.
Runmake fmtafter any documentation changes to format all Markdown files and fix table markup.
Validate Mermaid diagrams in Markdown files by runningmake 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.mddocs/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.mddocs/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-syntaxcrate, 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
rstestfixtures 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
SyntacticLocktrait,SyntacticLockResult, andTreeSitterSyntacticLockAdapterrequired for the pluggable lock pattern.
20-36: LGTM!Clean delegation pattern. The
SyntacticLockVariantenum correctly wraps both lock types and theSyntacticLocktrait implementation properly delegates to the underlying variant.
44-46: LGTM!The
current_filefield appropriately tracks the most recently created source file, enabling edit steps to target it by default. TheSyntacticLockVarianttype enables pluggable lock selection.
59-60: LGTM!Correct initialisation:
current_filestarts asNone, and the syntactic lock defaults to a passing configurable lock wrapped in the new variant.
75-82: LGTM!The
current_filetracking andcurrent_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::Configurableand 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>
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>
Summary
Changes
Core functionality
TreeSitterSyntacticLockAdapterthat wrapsweaver_syntax::TreeSitterSyntacticLockand implements the harness'sSyntacticLocktraitModule exports & wiring
TreeSitterSyntacticLockAdapterSafety harness tests & BDD integration
ConfigurableSyntacticLockorTreeSitterSyntacticLockAdapterExecution plan & roadmap
Tests & test plans
Documentation
Why this change
Potential impact & risk
How to run & verify
Related notes
🌿 Generated by Terry
ℹ️ Tag @terragon-labs to ask questions and address PR feedback
📎 Task: https://www.terragonlabs.com/task/98fd43dc-524a-464a-a0e9-f134a9c2c0ff