Skip to content

Document milestone 4.1.5 Formula model and normalisation pipeline in developers-guide.md #111

Open

Description

@coderabbitai

Background

PR #104 (#104) completed milestone 4.1.5, introducing the canonical Formula enum, the Decorated<T> wrapper, normalize.rs, and semantic_check.rs. These are absent from docs/developers-guide.md.

Requested by @leynos in the review of PR #104.

Work required

Add a Milestone 4.1.5 section to docs/developers-guide.md covering:

  • The Formula enum and Atom variants in sempai_core::formula.
  • The Decorated<T> wrapper and its metadata fields.
  • The normalisation pipeline in crates/sempai/src/normalize.rs (legacy and v2 paths).
  • The semantic validation rules in crates/sempai/src/semantic_check.rs.
  • How Engine::compile_yaml wires normalisation and validation together.

Acceptance criteria

Activity

  1. leynos commented on May 1, 2026

    @leynos
    Owner
  2. coderabbitai commented on May 1, 2026

    @coderabbitai
    Author

    Coding Plan

    Summary

    • Treat PR #104's merge as a prerequisite; verify code existence before documenting.
    • Structure the new section with one H2 and six H3 subsections covering the formula model, wrapper, normalisation algorithm, semantic constraints, and engine integration.
    • Follow existing developers-guide.md conventions: numbered step lists for pipelines, bulleted catalogues for APIs, minimal Rust code blocks for type definitions.
    • Cross-check all documented artefacts against the actual implementation to satisfy the acceptance criterion of consistency with the merged PR.
    Design Choices
    Design Choice 1: PR `#104` has been merged and the referenced code exists

    Options Considered:

    1. Proceed with documentation based on design specifications in docs/sempai-query-language-design.md.
    2. Block until PR #104 is confirmed merged and code is available.

    Chosen Option: 1

    Rationale: The codebase exploration found no normalize.rs, semantic_check.rs, or sempai_core::formula module. Engine::compile_yaml returns a not_implemented stub. Either PR #104 has not been merged to the explored branch, or the ticket was created prematurely. The design documentation provides complete specifications for the types and algorithms; proceed by documenting the designed behaviour, verifying against actual implementation before finalising.

    💡 User Tips

    Regenerate the plan with different choices with @coderabbitai <feedback>.

    Implementation Steps

    Phase 1: Verify Prerequisite State

    Confirm that milestone 4.1.5 code has landed before writing documentation that references it.

    Confirm PR `#104` Merge Status

    Verify that the implementation exists in the working branch before proceeding.

    • Check that crates/sempai-core/src/formula.rs (or formula/mod.rs) exists and exports Formula, Atom, and Decorated<T>.
    • Check that crates/sempai/src/normalize.rs exists with normalize_legacy and normalize_match functions.
    • Check that crates/sempai/src/semantic_check.rs exists with check function.
    • Confirm Engine::compile_yaml no longer returns not_implemented for normalisation.
    • If any prerequisite is missing, halt and report the blocker; do not proceed with documentation.
    🤖 Prompt for AI agents
    Verify that all prerequisite implementation artefacts from PR `#104` are present
    before any documentation is written.
    
    - Check for the existence of `crates/sempai-core/src/formula.rs` (or
    `formula/mod.rs`) and confirm it exports `Formula`, `Atom`, and `Decorated<T>`.
    - Check for `crates/sempai/src/normalize.rs` and confirm it contains
    `normalize_legacy` and `normalize_match` functions.
    - Check for `crates/sempai/src/semantic_check.rs` and confirm it contains a
    `check` function.
    - Confirm that `Engine::compile_yaml` no longer returns a `not_implemented` stub
    for the normalisation step.
    - If any of the above are absent, halt immediately and report the specific
    missing artefact as a blocker; do not proceed to Phase 2.
    

    Phase 2: Draft the Milestone 4.1.5 Documentation Section

    Add the new section to docs/developers-guide.md following existing formatting conventions.

    Task 1: Create Section Scaffold

    Add the H2 section heading and introductory prose after the existing final section.

    • Insert ## Milestone 4.1.5 – Formula normalisation and semantic validation after line 558 (end of current file).
    • Write an introductory paragraph explaining the purpose: lowering LegacyFormula and MatchFormula (from sempai_yaml) into a single canonical Formula representation, then enforcing structural semantic constraints before plan compilation.
    • Reference the source location crates/sempai-core/src/formula.rs and crates/sempai/src/.
    Task 2: Document the Formula Enum and Atom Variants

    Describe the canonical formula model that both legacy and v2 syntaxes normalise into.

    • Add H3 subsection ### Formula enum (sempai_core::formula).
    • List each variant (Atom, Not, Inside, Anywhere, And, Or) with a one-sentence description of its semantic role.
    • Explain that Not, Inside, and Anywhere are constraint forms (do not produce anchors), whilst Atom, And, and Or can produce match candidates.
    • Add a sub-heading or inline explanation for Atom variants: Pattern(PatternAtom), Regex(RegexAtom), TreeSitterQuery(TreeSitterQueryAtom).
    • Include a minimal fenced Rust code block showing the enum definition (copied from the implementation, not invented).
    Task 3: Document the Decorated Wrapper

    Explain the metadata wrapper that annotates every formula node.

    • Add H3 subsection ### Decorated<T> wrapper.
    • List the five fields (node, where_, as_, fix, span) with their types and purposes.
    • Explain that where_ carries Vec<WhereClause> constraint entries, as_ binds the match to a named capture, fix surfaces an autofix hint (not applied by Sempai), and span preserves source location for diagnostics.
    • Note that every element in And and Or vectors, and the inner node of Not/Inside/Anywhere, is a Decorated<Formula>.
    Task 4: Document the Normalisation Pipeline

    Describe how normalize.rs transforms parsed formulas into the canonical model.

    • Add H3 subsection ### Normalisation pipeline (normalize.rs).
    • Explain the two entry paths: normalize_legacy(LegacyFormula) -> Formula and normalize_match(MatchFormula) -> Formula.
    • Use a numbered step list (Pattern A from existing guide) to describe the algorithm:
      1. Dispatch on principal variant (SearchQueryPrincipal::Legacy or ::Match).
      2. Recursively map each source variant to its canonical Formula constructor.
      3. Parse raw where_clauses: Vec<Value> into typed WhereClause entries during the v2 path.
      4. Thread SourceSpan from parsed nodes into each Decorated wrapper.
      5. Return the normalised Formula tree (or propagate DiagnosticReport on malformed input).
    • Include a brief mapping table showing legacy-to-canonical correspondences (e.g., patterns → And, pattern-either → Or, pattern-not-inside → Not(Inside(…))).
    Task 5: Document Semantic Validation Rules

    Describe the constraints enforced by semantic_check.rs.

    • Add H3 subsection ### Semantic validation (semantic_check.rs).
    • Explain the two structural constraints:
      • InvalidNotInOr — direct Not children inside an Or are rejected; rationale: negations require a conjunction anchor.
      • MissingPositiveTermInAnd — every And must contain at least one positive term (Atom, Or, or nested And that itself passes); exception: metavariable-pattern contexts are exempt.
    • State the corresponding diagnostic codes (E_SEMPAI_INVALID_NOT_IN_OR, E_SEMPAI_MISSING_POSITIVE_TERM_IN_AND).
    • Include a short fenced Rust example showing a rejected formula and the expected diagnostic message.
    Task 6: Document Engine::compile_yaml Integration

    Explain how the engine wires parsing, normalisation, and validation together.

    • Add H3 subsection ### Engine wiring.
    • Use a numbered step list to describe the pipeline executed by Engine::compile_yaml:
      1. Parse YAML via sempai_yaml::parse_rule_file → RuleFile.
      2. Validate supported modes via validate_supported_modes (rejects non-Search modes).
      3. Normalise each rule's SearchQueryPrincipal via normalize → Formula.
      4. Run semantic checks via check → reject invalid structures.
      5. Return Vec<QueryPlan> on success, or DiagnosticReport on any failure.
    • Reference the QueryPlan struct and note that the _plan field now holds the validated Formula (no longer a unit placeholder).
    🤖 Prompt for AI agents
    Draft the new milestone 4.1.5 section in `docs/developers-guide.md`, appending
    it after line 558 and comprising one H2 heading and six H3 subsections.
    
    **Section scaffold (Task 2.1)**
    - Append `## Milestone 4.1.5 – Formula normalisation and semantic validation` at
    end of file.
    - Write an introductory paragraph covering: lowering `LegacyFormula` and
    `MatchFormula` (from `sempai_yaml`) into a canonical `Formula`, then enforcing
    structural semantic constraints before plan compilation.
    - Reference source locations `crates/sempai-core/src/formula.rs` and
    `crates/sempai/src/`.
    
    **Formula enum subsection (Task 2.2)**
    - Add `### Formula enum (`sempai_core::formula`)`.
    - List each variant (`Atom`, `Not`, `Inside`, `Anywhere`, `And`, `Or`) with a
    one-sentence semantic description.
    - Distinguish constraint forms (`Not`, `Inside`, `Anywhere`) from
    match-candidate forms (`Atom`, `And`, `Or`).
    - Explain `Atom` sub-variants: `Pattern(PatternAtom)`, `Regex(RegexAtom)`,
    `TreeSitterQuery(TreeSitterQueryAtom)`.
    - Include a minimal fenced ~~~rust~~~ code block with the enum definition copied
    verbatim from the implementation.
    
    **`Decorated<T>` wrapper subsection (Task 2.3)**
    - Add `### Decorated<T> wrapper`.
    - List all five fields (`node`, `where_`, `as_`, `fix`, `span`) with types and
    purposes.
    - Explain `where_` (`Vec<WhereClause>`), `as_` (named capture), `fix` (autofix
    hint, not applied by Sempai), and `span` (source location for diagnostics).
    - Note that `And`/`Or` vector elements and inner nodes of
    `Not`/`Inside`/`Anywhere` are all `Decorated<Formula>`.
    
    **Normalisation pipeline subsection (Task 2.4)**
    - Add `### Normalisation pipeline (`normalize.rs`)`.
    - State the two entry points: `normalize_legacy(LegacyFormula) -> Formula` and
    `normalize_match(MatchFormula) -> Formula`.
    - Write a numbered step list matching the five algorithm steps: dispatch on
    principal variant, recursively map to canonical constructors, parse
    `where_clauses`, thread `SourceSpan`, return or propagate `DiagnosticReport`.
    - Include a mapping table of legacy-to-canonical correspondences (`patterns` →
    `And`, `pattern-either` → `Or`, `pattern-not-inside` → `Not(Inside(…))`).
    
    **Semantic validation subsection (Task 2.5)**
    - Add `### Semantic validation (`semantic_check.rs`)`.
    - Document `InvalidNotInOr` and `MissingPositiveTermInAnd` with rationale and
    the metavariable-pattern exemption.
    - State diagnostic codes `E_SEMPAI_INVALID_NOT_IN_OR` and
    `E_SEMPAI_MISSING_POSITIVE_TERM_IN_AND`.
    - Include a short fenced ~~~rust~~~ example of a rejected formula and its
    expected diagnostic message.
    
    **Engine wiring subsection (Task 2.6)**
    - Add `### Engine wiring`.
    - Write a five-step numbered list for `Engine::compile_yaml`: parse YAML →
    validate modes → normalise → semantic check → return `Vec<QueryPlan>` or
    `DiagnosticReport`.
    - Reference the `QueryPlan` struct and note the `_plan` field now holds the
    validated `Formula`.
    
    **Formatting rules to enforce throughout**
    - Wrap prose at 80 columns.
    - Use sentence-case headings.
    - Fence all code blocks with ~~~rust~~~ or ~~~toml~~~ language identifiers.
    - Use `-` bullets with em-dash separators for function catalogues.
    - Maintain impersonal technical tone; avoid personal pronouns.
    

    Phase 3: Review and Finalise

    Ensure the new section matches implementation and existing guide conventions.

    Task 1: Cross-Check Against Implementation

    Verify documentation accuracy against the merged code.

    • Compare documented type signatures with actual definitions in crates/sempai-core/src/formula.rs.
    • Confirm function names in normalize.rs and semantic_check.rs match the documented catalogue.
    • Verify diagnostic codes are spelled correctly.
    Task 2: Apply Formatting Conventions

    Ensure consistency with existing developers-guide.md style.

    • Wrap prose at 80 columns.
    • Use sentence-case headings.
    • Fence all code blocks with ```rust or ```toml language identifiers.
    • Use - bullets with em-dash separators for function catalogues.
    • Avoid personal pronouns and maintain impersonal technical tone.
    🤖 Prompt for AI agents
    Review and finalise the drafted section to ensure accuracy and stylistic
    consistency.
    
    - Compare every documented type signature against the actual definitions in
    `crates/sempai-core/src/formula.rs`; correct any discrepancies.
    - Confirm that all function names documented for `normalize.rs` and
    `semantic_check.rs` match those in the merged implementation exactly.
    - Verify that diagnostic codes `E_SEMPAI_INVALID_NOT_IN_OR` and
    `E_SEMPAI_MISSING_POSITIVE_TERM_IN_AND` are spelled correctly throughout.
    - Enforce formatting rules across the entire new section:
      - Prose wrapped at 80 columns.
      - Sentence-case headings.
      - All code blocks fenced with ~~~rust~~~ or ~~~toml~~~.
      - `-` bullets with em-dash separators for function catalogues.
      - No personal pronouns; impersonal technical tone throughout.
    
    Research

    The docs/developers-guide.md file is a 558-line developer reference using H2 sections for major features and H3 subsections for specific components. It follows consistent conventions: prose introductions, numbered step lists for pipelines, bulleted function catalogues, and fenced Rust code blocks with crate-path references. The sempai crate family (sempai, sempai-core, sempai-yaml) currently contains parsed formula types (LegacyFormula, MatchFormula) but the canonical normalised Formula model exists only in design documentation (docs/sempai-query-language-design.md).


    🚀 Next Steps

    🤖 All AI agent prompts combined
    Task: 1
    
    Verify that all prerequisite implementation artefacts from PR `#104` are present
    before any documentation is written.
    
    - Check for the existence of `crates/sempai-core/src/formula.rs` (or
    `formula/mod.rs`) and confirm it exports `Formula`, `Atom`, and `Decorated<T>`.
    - Check for `crates/sempai/src/normalize.rs` and confirm it contains
    `normalize_legacy` and `normalize_match` functions.
    - Check for `crates/sempai/src/semantic_check.rs` and confirm it contains a
    `check` function.
    - Confirm that `Engine::compile_yaml` no longer returns a `not_implemented` stub
    for the normalisation step.
    - If any of the above are absent, halt immediately and report the specific
    missing artefact as a blocker; do not proceed to Phase 2.
    ===============================================================================
    
    Task: 2
    
    Draft the new milestone 4.1.5 section in `docs/developers-guide.md`, appending
    it after line 558 and comprising one H2 heading and six H3 subsections.
    
    **Section scaffold (Task 2.1)**
    - Append `## Milestone 4.1.5 – Formula normalisation and semantic validation` at
    end of file.
    - Write an introductory paragraph covering: lowering `LegacyFormula` and
    `MatchFormula` (from `sempai_yaml`) into a canonical `Formula`, then enforcing
    structural semantic constraints before plan compilation.
    - Reference source locations `crates/sempai-core/src/formula.rs` and
    `crates/sempai/src/`.
    
    **Formula enum subsection (Task 2.2)**
    - Add `### Formula enum (`sempai_core::formula`)`.
    - List each variant (`Atom`, `Not`, `Inside`, `Anywhere`, `And`, `Or`) with a
    one-sentence semantic description.
    - Distinguish constraint forms (`Not`, `Inside`, `Anywhere`) from
    match-candidate forms (`Atom`, `And`, `Or`).
    - Explain `Atom` sub-variants: `Pattern(PatternAtom)`, `Regex(RegexAtom)`,
    `TreeSitterQuery(TreeSitterQueryAtom)`.
    - Include a minimal fenced ~~~rust~~~ code block with the enum definition copied
    verbatim from the implementation.
    
    **`Decorated<T>` wrapper subsection (Task 2.3)**
    - Add `### Decorated<T> wrapper`.
    - List all five fields (`node`, `where_`, `as_`, `fix`, `span`) with types and
    purposes.
    - Explain `where_` (`Vec<WhereClause>`), `as_` (named capture), `fix` (autofix
    hint, not applied by Sempai), and `span` (source location for diagnostics).
    - Note that `And`/`Or` vector elements and inner nodes of
    `Not`/`Inside`/`Anywhere` are all `Decorated<Formula>`.
    
    **Normalisation pipeline subsection (Task 2.4)**
    - Add `### Normalisation pipeline (`normalize.rs`)`.
    - State the two entry points: `normalize_legacy(LegacyFormula) -> Formula` and
    `normalize_match(MatchFormula) -> Formula`.
    - Write a numbered step list matching the five algorithm steps: dispatch on
    principal variant, recursively map to canonical constructors, parse
    `where_clauses`, thread `SourceSpan`, return or propagate `DiagnosticReport`.
    - Include a mapping table of legacy-to-canonical correspondences (`patterns` →
    `And`, `pattern-either` → `Or`, `pattern-not-inside` → `Not(Inside(…))`).
    
    **Semantic validation subsection (Task 2.5)**
    - Add `### Semantic validation (`semantic_check.rs`)`.
    - Document `InvalidNotInOr` and `MissingPositiveTermInAnd` with rationale and
    the metavariable-pattern exemption.
    - State diagnostic codes `E_SEMPAI_INVALID_NOT_IN_OR` and
    `E_SEMPAI_MISSING_POSITIVE_TERM_IN_AND`.
    - Include a short fenced ~~~rust~~~ example of a rejected formula and its
    expected diagnostic message.
    
    **Engine wiring subsection (Task 2.6)**
    - Add `### Engine wiring`.
    - Write a five-step numbered list for `Engine::compile_yaml`: parse YAML →
    validate modes → normalise → semantic check → return `Vec<QueryPlan>` or
    `DiagnosticReport`.
    - Reference the `QueryPlan` struct and note the `_plan` field now holds the
    validated `Formula`.
    
    **Formatting rules to enforce throughout**
    - Wrap prose at 80 columns.
    - Use sentence-case headings.
    - Fence all code blocks with ~~~rust~~~ or ~~~toml~~~ language identifiers.
    - Use `-` bullets with em-dash separators for function catalogues.
    - Maintain impersonal technical tone; avoid personal pronouns.
    ===============================================================================
    
    Task: 3
    
    Review and finalise the drafted section to ensure accuracy and stylistic
    consistency.
    
    - Compare every documented type signature against the actual definitions in
    `crates/sempai-core/src/formula.rs`; correct any discrepancies.
    - Confirm that all function names documented for `normalize.rs` and
    `semantic_check.rs` match those in the merged implementation exactly.
    - Verify that diagnostic codes `E_SEMPAI_INVALID_NOT_IN_OR` and
    `E_SEMPAI_MISSING_POSITIVE_TERM_IN_AND` are spelled correctly throughout.
    - Enforce formatting rules across the entire new section:
      - Prose wrapped at 80 columns.
      - Sentence-case headings.
      - All code blocks fenced with ~~~rust~~~ or ~~~toml~~~.
      - `-` bullets with em-dash separators for function catalogues.
      - No personal pronouns; impersonal technical tone throughout.
    
    💡 Iterate on the plan with: @coderabbitai <feedback>
    Example Feedback
    - `@coderabbitai` You can skip phase 3. Add a simple unit test case for phase 2.
    - `@coderabbitai` For design choice 1 go ahead with option 3 and replan.
    

    💬 Have feedback or questions? Drop into our discord!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions