Skip to content

fix(query): tighten message and cwd filters - #692

Merged
Sinity merged 2 commits into
masterfrom
feature/fix/query-read-semantics
May 2, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/fix/query-read-semantics

Conversation

@Sinity

@Sinity Sinity commented May 2, 2026 •

Copy link
Copy Markdown
Owner

Summary

Tightens the query/read filter contract for message types and cwd-scoped session filters.

Problem

#621 tracks several query/read correctness gaps. This slice addresses the executable filter bugs: invalid message_type values were accepted at user/API/MCP boundaries and normalized to normal messages; unknown since_session references broadened to the full result set; since_session included no-cwd candidates even when the reference session had cwd evidence; and cwd_prefix used plain prefix matching that could include sibling repositories such as /repo/foo2 when filtering /repo/foo.

Solution

Add strict message-type filter validation while preserving forgiving parser/provider normalization. ConversationQuerySpec.from_params(), MCP query requests, MCP get_messages, storage message reads, SQL conversation filters, and runtime filters now reject unknown message-type filters instead of collapsing them to message.

Add a shared path-component bounded cwd prefix helper and use it in both runtime filters and SQL pushdown. cwd_prefix now matches exact paths and child paths only, and since_session cwd matching uses the same semantics. Unknown since_session references now return no runtime-filter matches, and unknown-cwd candidates are excluded when the reference session has cwd evidence.

The CLI message-type choice and generated CLI docs now include message, since normal-message filtering is now a supported strict filter value.

Verification

  • pytest -q tests/unit/core/test_query_fields.py tests/unit/core/test_cwd_prefix_filter.py tests/unit/archive/test_query_runtime_filters.py tests/unit/core/test_message_types.py tests/unit/storage/test_message_query_reads.py tests/unit/core/test_facade_api.py tests/unit/mcp/test_tool_contracts.py (119 passed)
  • ruff check on changed query/storage/MCP/API test files
  • mypy polylogue/archive/query/spec.py polylogue/archive/message/types.py polylogue/archive/query/path_prefix.py polylogue/archive/query/runtime_filters.py polylogue/storage/backends/queries/filter_builder.py polylogue/storage/backends/queries/message_query_reads.py polylogue/mcp/query_contracts.py polylogue/mcp/server_tools.py
  • devtools render-all --check
  • devtools verify-topology && devtools verify-layering && devtools verify-test-ownership
  • devtools verify --quick
  • devtools verify --quick again via pre-push hook

Ref #621

Summary by CodeRabbit

  • New Features

    • Added "message" as a new message-type filter option alongside existing types.
    • Enhanced working directory prefix filtering with more precise path-component-bounded matching.
  • Bug Fixes

    • Improved message-type validation with clearer error messages for invalid inputs.
    • Fixed working directory path matching behavior for more accurate filtering.
  • Tests

    • Added comprehensive test coverage for message-type validation and path-prefix filtering.

Sinity added 2 commits May 2, 2026 08:07
Problem: query/read filters still used forgiving provider coercion and plain string prefix matching at user-facing boundaries. Unknown since-session IDs broadened to every conversation, unknown-cwd candidates stayed in same-cwd recall, message_type typos collapsed to normal messages, and cwd_prefix matched sibling repositories.\n\nWhat changed: add strict message-type filter validation for query/API/MCP/storage paths while preserving forgiving parser normalization, add a path-component bounded cwd prefix primitive, use it in runtime and SQL filters, make unknown since-session references return no results, and exclude unknown-cwd candidates when a reference session has cwd evidence.\n\nVerification: pytest focused query/storage/API/MCP suite, ruff, mypy on changed source files, devtools render-all --check, topology/layering/test-ownership checks, and devtools verify --quick.\n\nRef #621\n\nCo-Authored-By: Claude <[email protected]>
Problem: ConversationQuerySpec.from_params still accepted invalid message_type values and deferred failure until storage or runtime filtering. MCP query requests already flow through the spec layer, so the boundary should be strict there too.\n\nWhat changed: add optional_message_type normalization that validates user-supplied values through the strict message-type filter validator and raises QuerySpecError for invalid tokens. Extend query-field tests to cover valid hyphenated input, normal message filters, and invalid spec construction.\n\nVerification: focused query/API/MCP/storage tests, ruff, and mypy on changed query source files.\n\nRef #621\n\nCo-Authored-By: Claude <[email protected]>
Copilot AI review requested due to automatic review settings May 2, 2026 10:24
@coderabbitai

coderabbitai Bot commented May 2, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR adds stricter validation for message-type filters and introduces path-prefix filtering for conversations. Message types are now validated at parse time to catch invalid inputs, and a new "message" content type is added. Path-prefix matching uses component-bounded semantics to prevent partial substring matches. These changes are integrated across query planning, CLI, MCP, storage, and test suites.

Changes

Message Type Validation & Path-Prefix Filtering

Layer / File(s) Summary
Data Types & Validation
polylogue/archive/message/types.py, polylogue/archive/query/path_prefix.py
MessageType adds a strict validate_filter_token validator for user inputs (replacing lenient normalize), and __all__ now exports validate_message_type_filter. New module introduces normalize_path_prefix, path_matches_prefix (component-bounded matching), and escaped_sql_path_prefix_patterns for SQL generation with wildcard escaping.
Query Planning
polylogue/archive/query/runtime_filters.py, polylogue/archive/query/spec.py
apply_full_filters switches to validate_message_type_filter and adds cwd_prefix filtering via path_matches_prefix. New optional_message_type in spec.py wraps validation failures as QuerySpecError.
CLI & MCP Integration
polylogue/cli/click_option_groups.py, polylogue/mcp/query_contracts.py, polylogue/mcp/server_tools.py
CLI derives --message-type choices from MessageType enum. MCP query_contracts and server_tools validate message_type via validate_message_type_filter before constructing query specs.
Storage Implementation
polylogue/storage/backends/queries/filter_builder.py, polylogue/storage/backends/queries/message_query_reads.py
Filter builder uses escaped_sql_path_prefix_patterns for component-bounded cwd_prefix SQL generation. Both files switch from MessageType.normalize to validate_message_type_filter. MessageTypeName type alias expanded to include "message".
Tests & Documentation
docs/cli-reference.md, docs/topology-status.md, docs/plans/topology-target.yaml, tests/unit/archive/test_query_runtime_filters.py, tests/unit/core/test_*.py, tests/unit/mcp/test_tool_contracts.py, tests/unit/storage/test_message_query_reads.py
CLI docs updated to list message as valid filter value. Topology files reflect new module and loc changes. Tests validate rejection of invalid message types, path-component-bounded prefix matching (including Windows paths), and SQL generation correctness.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

area:cli, area:storage, area:query, type:feature

Poem

🐰 Filters now talk in clearer tongue,
No typos slip through unsung,
Paths match bounds, not just strings—
Component-wise, the query sings.
Message flows where once none dwelt,
Validation's touch is gently felt. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(query): tighten message and cwd filters' accurately summarizes the main changes—stricter validation of message-type and cwd filters across the codebase.
Description check ✅ Passed The description covers all required template sections: Summary (what changed), Problem (why needed), Solution (what was done), Verification (test commands run), and Risks (none noted, section omitted appropriately).
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 feature/fix/query-read-semantics

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

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

@github-actions

github-actions Bot commented May 2, 2026

Copy link
Copy Markdown
Contributor

Polylogue Proof Pack

Refs: origin/master..HEAD
Changed paths: 19

Affected Domains

  • architecture_discipline — 2 claim(s), maturity growing
  • spec_completeness — 1 claim(s), maturity seed
  • unclassified — 4 claim(s), maturity seed
Additional routed domains with zero affected claims
  • docs_media — maturity seed

Focused Gates

  • devtools render-all --check — generated surface or renderer changed
  • devtools verify-manifests — structural manifest changed
  • devtools affected-obligations --path docs/plans/topology-target.yaml — refresh structural obligation routing
  • devtools verify-topology — topology projection changed
  • devtools affected-obligations --path docs/topology-status.md — refresh structural obligation routing
  • pytest tests/unit/cli — CLI command surface changed
  • pytest tests/unit/proof/test_evidence_runners.py — CLI proof runners exercise command output
  • devtools render-cli-reference --check — CLI reference is generated from command help

Required PR Gates

  • devtools verify --quick — full PR gate remains explicit
  • devtools verify — full PR gate remains explicit

Optional Confidence Gates

  • devtools build-package — deployment readiness gate; run when packaging or release confidence matters
  • nix flake check — deployment readiness gate; run when packaging or release confidence matters

Known Gaps

  • none for domains with affected claims
Additional gaps in zero-claim routed domains
  • docs_media: docs_media: No scenario for documentation freshness verification [owner: scenario-coverage; next: Add scenario family or generated projection for this subject], docs_media: README examples and media are not yet generated from executable scenario projections. [owner: docs-media; next: Add executable scenario projection or media integrity gate], docs_media: Screenshots and VHS media have no committed nonblank/readability verification. [owner: docs-media; next: Add executable scenario projection or media integrity gate]

Oracle / Cost

  • oracle mix: {"construction_sanity": 169, "drift_check": 2}
  • cost tier: {"static": 166, "unit": 5}
  • stable affected obligations: 171
  • agent judgment cells: 0

@Sinity
Sinity merged commit fd56afb into master May 2, 2026
12 of 17 checks passed
@Sinity
Sinity deleted the feature/fix/query-read-semantics branch May 2, 2026 10:26

Copilot AI 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.

Pull request overview

This PR tightens archive query/read filtering so user-facing message-type filters are validated strictly and cwd-based filters use path-component-bounded matching across runtime and SQL paths. It fits into the archive query stack by aligning CLI/MCP/API/spec/storage behavior around the canonical query contract tracked in #621.

Changes:

  • Added strict validation for message_type filters across query spec construction, MCP query/read surfaces, runtime filtering, and SQL/message reads.
  • Introduced shared cwd path-prefix matching helpers and applied them to runtime filters and SQL pushdown to avoid sibling-path false positives.
  • Expanded unit coverage and regenerated CLI/topology docs to reflect the tightened filter contract.

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/unit/storage/test_message_query_reads.py Adds storage-level tests for strict message-type filtering and message support.
tests/unit/mcp/test_tool_contracts.py Adds MCP tool tests for rejecting unknown message_type values.
tests/unit/core/test_query_fields.py Covers strict query-spec normalization for message_type.
tests/unit/core/test_message_types.py Tests the new strict message-type validation helper.
tests/unit/core/test_facade_api.py Verifies facade read API rejects invalid message-type filters.
tests/unit/core/test_cwd_prefix_filter.py Adds SQL cwd-prefix behavior tests and updates expected SQL patterns.
tests/unit/archive/test_query_runtime_filters.py Expands runtime-filter coverage for strict message types and bounded cwd/since-session behavior.
polylogue/storage/backends/queries/message_query_reads.py Switches message reads to strict message_type validation and adds message to the accepted literal set.
polylogue/storage/backends/queries/filter_builder.py Applies strict message-type validation and bounded cwd SQL matching.
polylogue/mcp/server_tools.py Validates get_messages MCP message_type input before dispatching reads.
polylogue/mcp/query_contracts.py Validates MCP query message_type inputs before building query specs.
polylogue/cli/click_option_groups.py Updates root query CLI option choices/docs to include message.
polylogue/archive/query/spec.py Adds strict optional message_type normalization for query-spec params.
polylogue/archive/query/runtime_filters.py Enforces strict runtime message-type validation and bounded cwd/since-session filtering.
polylogue/archive/query/path_prefix.py Introduces shared path-prefix normalization/matching helpers for cwd filters.
polylogue/archive/message/types.py Separates forgiving provider normalization from strict user-filter validation.
docs/topology-status.md Regenerated topology status counts for the new query helper file.
docs/plans/topology-target.yaml Registers the new query helper and updates generated LOC metadata.
docs/cli-reference.md Regenerates CLI docs to show message as an allowed root query filter value.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +5 to +10

def normalize_path_prefix(value: object) -> str:
"""Normalize a user path prefix for component-bounded comparison."""
raw = str(value).strip().replace("\\", "/")
while "//" in raw:
raw = raw.replace("//", "/")
Comment on lines 183 to +186
"--message-type",
"message_type",
type=click.Choice(["summary", "tool_use", "tool_result", "thinking"]),
help="Filter by message content type (summary, tool_use, tool_result, thinking)",
type=click.Choice([message_type.value for message_type in MessageType]),
help="Filter by message content type (message, summary, tool_use, tool_result, thinking)",
Sinity added a commit that referenced this pull request May 7, 2026
Summary

Tighten query/read message-type and cwd-scoped filter semantics.

Problem

Invalid message_type values were accepted at user/API/MCP boundaries and could collapse to normal messages. Unknown since_session references broadened runtime results, same-cwd recall included unknown-cwd candidates, and cwd_prefix used string-prefix semantics that could include sibling repositories.

Solution

Add strict message-type filter validation while preserving forgiving parser normalization. Validate message_type in query specs, MCP query contracts, MCP get_messages, storage message reads, SQL filters, and runtime filters. Add path-component bounded cwd matching and use it for runtime since_session, runtime cwd_prefix, and SQL cwd_prefix pushdown. Unknown since_session references now produce no runtime-filter matches, and unknown-cwd candidates are excluded when the reference session has cwd evidence.

Verification

pytest -q tests/unit/core/test_query_fields.py tests/unit/core/test_cwd_prefix_filter.py tests/unit/archive/test_query_runtime_filters.py tests/unit/core/test_message_types.py tests/unit/storage/test_message_query_reads.py tests/unit/core/test_facade_api.py tests/unit/mcp/test_tool_contracts.py
ruff check on changed query/storage/MCP/test files
mypy polylogue/archive/query/spec.py polylogue/archive/message/types.py polylogue/archive/query/path_prefix.py polylogue/archive/query/runtime_filters.py polylogue/storage/backends/queries/filter_builder.py polylogue/storage/backends/queries/message_query_reads.py polylogue/mcp/query_contracts.py polylogue/mcp/server_tools.py
devtools render-all --check
devtools verify-topology && devtools verify-layering && devtools verify-test-ownership
devtools verify --quick

CI note: showcase-verify failed in GitHub Actions and was explicitly ignored per user instruction on 2026-05-02; local quick verification and focused tests passed.

Ref #621
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.

2 participants