Skip to content

refactor(cli): generalize message role filtering - #320

Merged
Sinity merged 3 commits into
masterfrom
feature/refactor/message-role-output-filter
Apr 21, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/refactor/message-role-output-filter

Conversation

@Sinity

@Sinity Sinity commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes #318.
Closes #319.

Replaces the bespoke user-only output idea with a composable message-role projection that works across CLI parsing, in-memory conversation projection, streaming storage reads, stream headers, and semantic facts. Also removes the unrelated local full-verification blocker that surfaced while validating this PR.

Problem

--user-only made one role projection special even though the model already has canonical roles and provider role normalization. That left an arbitrary surface where user, assistant, tool, system, and unknown should all be expressible through the same mechanism.

Full local verification was also not actually usable: tests/unit/storage/test_repository_state_machine.py::TestArchiveLifecycle::runTest spent most of its runtime recreating file-backed SQLite schemas for Hypothesis examples and could exceed practical local budgets.

Solution

  • Add --message-role, accepting repeated or comma-separated canonical roles with provider aliases normalized through the shared role model.
  • Keep --dialogue-only as a shorthand for user,assistant, while explicit --message-role wins when both are supplied.
  • Add shared polylogue.lib.message_roles helpers for canonical role filters, SQL aliases, labels, and stats keys.
  • Push role filtering into streaming SQL reads and expose canonical role counts from conversation stats.
  • Replace arbitrary Conversation.user_only() / assistant_only() helpers with generic Conversation.with_roles(...); dialogue_only() now delegates to that generic projection.
  • Carry effective role filters through stream semantic facts and generated CLI docs.
  • Switch the archive lifecycle state-machine test to in-memory SQLite so it keeps the same lifecycle model coverage without paying multi-second file-backed schema setup per example.
  • Refresh terminal and showcase help baselines for the new CLI option.

Verification

uv run ruff check docs/cli-reference.md polylogue/cli/click_app.py polylogue/cli/click_option_groups.py polylogue/cli/query.py polylogue/cli/query_contracts.py polylogue/cli/query_output.py polylogue/cli/root_request.py polylogue/lib/conversation_runtime.py polylogue/lib/message_roles.py polylogue/lib/semantic_fact_models.py polylogue/lib/semantic_facts.py polylogue/protocols.py polylogue/storage/backends/async_sqlite_archive.py polylogue/storage/backends/queries/message_query_reads.py polylogue/storage/backends/queries/message_query_stats.py polylogue/storage/backends/query_store_archive.py polylogue/storage/repository_archive_conversations.py tests/unit/cli/test_click_app.py tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py tests/unit/core/test_conversation_semantics.py tests/unit/core/test_message_laws.py tests/unit/storage/test_backend.py
uv run mypy polylogue/cli/click_app.py polylogue/cli/click_option_groups.py polylogue/cli/query.py polylogue/cli/query_contracts.py polylogue/cli/query_output.py polylogue/cli/root_request.py polylogue/lib/conversation_runtime.py polylogue/lib/message_roles.py polylogue/lib/semantic_fact_models.py polylogue/lib/semantic_facts.py polylogue/protocols.py polylogue/storage/backends/async_sqlite_archive.py polylogue/storage/backends/queries/message_query_reads.py polylogue/storage/backends/queries/message_query_stats.py polylogue/storage/backends/query_store_archive.py polylogue/storage/repository_archive_conversations.py tests/unit/cli/test_click_app.py tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py tests/unit/core/test_conversation_semantics.py tests/unit/core/test_message_laws.py tests/unit/storage/test_backend.py
uv run pytest -q tests/unit/cli/test_click_app.py tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py tests/unit/core/test_conversation_semantics.py tests/unit/core/test_message_laws.py tests/unit/storage/test_backend.py
uv run devtools render-all --check
uv run devtools verify --quick
timeout 90s uv run pytest -q -n0 tests/unit/storage/test_repository_state_machine.py::TestArchiveLifecycle::runTest
uv run pytest -q tests/unit/cli/test_terminal_snapshots.py --snapshot-update
uv run devtools verify
uv run devtools verify-showcase --update
uv run devtools verify-showcase
git push

@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This change introduces role-based message filtering throughout the CLI and storage stack, replacing special-case handling with a generalized --message-role option that filters conversation output by message role. The parameter threads through query contracts, execution, storage backends, and rendering functions while preserving the --dialogue-only shorthand.

Changes

Cohort / File(s) Summary
CLI Options & Contracts
polylogue/cli/click_option_groups.py, polylogue/cli/query_contracts.py, polylogue/cli/click_app.py
Added repeatable --message-role CLI option with validation callback. Extended QueryOutputSpec with message_roles field and effective_message_roles() method to compute active roles (explicit filter, or dialogue preset, or none). Integrated into cli(...) function signature.
Query Execution & Output
polylogue/cli/query.py, polylogue/cli/query_output.py, polylogue/cli/root_request.py
Updated message projection to use with_roles(message_roles) instead of dialogue_only(). Modified stream_conversation, render_stream_header, and render_stream_transcript to accept and apply role filtering; headers now display role-specific message counts. Added message_role as output-mode-activating parameter in RootModeRequest.
Core Message Role Library
polylogue/lib/message_roles.py
New module providing MessageRoleFilter type, ROLE_SQL_VALUES mapping, and normalization utilities (normalize_message_role_token, normalize_message_roles). Includes helpers for role labels and per-role count keys.
Conversation Projection
polylogue/lib/conversation_runtime.py
Replaced user_only() and assistant_only() methods with generalized with_roles(roles) method. Updated dialogue_only() to delegate to with_roles((Role.USER, Role.ASSISTANT)).
Semantic Facts & Models
polylogue/lib/semantic_facts.py, polylogue/lib/semantic_fact_models.py
Added message_roles parameter to build_stream_semantic_facts() for role-based message filtering. Extended StreamSemanticFacts with message_roles field and updated serialization in to_proof_input().
Storage & Query Protocol
polylogue/protocols.py, polylogue/storage/repository_archive_conversations.py, polylogue/storage/backends/async_sqlite_archive.py, polylogue/storage/backends/query_store_archive.py
Extended ConversationReader.iter_messages protocol signature to accept message_roles: MessageRoleFilter = () parameter across all implementing layers.
Storage Backend Query Logic
polylogue/storage/backends/queries/message_query_reads.py, polylogue/storage/backends/queries/message_query_stats.py
Updated SQL message filtering to compute effective_roles from message_roles parameter and use message_role_sql_values() for dynamic role-based WHERE clauses. Extended stats query to compute per-role message counts via GROUP BY role.
Documentation & Snapshots
docs/cli-reference.md, tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
Added --message-role TEXT CLI option documentation and updated help text snapshots for terminal output width variations.
Unit Tests — CLI & Query
tests/unit/cli/test_click_app.py, tests/unit/cli/test_query_exec.py, tests/unit/cli/test_query_exec_laws.py
Updated test helpers with message_role: () default parameter. Extended test parametrization to cover role-filtering cases (e.g., message_roles=("user",)) with assertion of expected output labels. Added contract tests validating message_roles overrides dialogue_only.
Unit Tests — Core & Storage
tests/unit/core/test_conversation_semantics.py, tests/unit/core/test_message_laws.py, tests/unit/storage/test_backend.py, tests/unit/storage/test_repository_state_machine.py
Refactored projection tests to use with_roles() instead of removed user_only() method. Added test_backend_stream_messages_accepts_generic_role_filter to validate role-filtering and per-role stats. Switched state-machine test from on-disk to in-memory SQLite for bounded lifecycle verification.

Sequence Diagram

sequenceDiagram
    actor User
    participant CLI as CLI Parser
    participant Contracts as QueryOutputSpec
    participant Executor as Query Executor
    participant Repo as Message Repository
    participant Storage as SQLite Backend
    participant Render as Output Renderer

    User->>CLI: --message-role user,assistant
    CLI->>CLI: Validate & normalize roles
    CLI->>Contracts: Create QueryOutputSpec(message_roles=...)
    Contracts->>Contracts: Compute effective_message_roles()
    
    rect rgba(100, 150, 200, 0.5)
    Note over Contracts,Executor: Query Execution Phase
    Executor->>Repo: with_roles(effective_message_roles)
    Executor->>Executor: Build semantic facts with message_roles
    end
    
    rect rgba(200, 100, 100, 0.5)
    Note over Repo,Storage: Storage Filtering Phase
    Repo->>Storage: iter_messages(message_roles=...)
    Storage->>Storage: Compute message_role_sql_values()
    Storage->>Storage: Add WHERE role IN (...) to SQL
    Storage-->>Repo: Filtered messages
    end
    
    rect rgba(100, 200, 100, 0.5)
    Note over Render,User: Output Phase
    Repo->>Render: stream_conversation(message_roles=...)
    Render->>Render: Compute effective_roles & filter messages
    Render->>Render: Render header with role labels
    Render->>Render: Output filtered messages
    Render-->>User: Filtered conversation output
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • PR #277: Extends CLI query contracts and plumbing with message-role filtering; directly builds on the same query-contracts/CLI surface being modified here.
  • PR #276: Modifies StreamSemanticFacts data and serialization methods that are extended in this change to include message_roles fields.
  • PR #247: Refactors protocols and query/runtime store interfaces that now accept the new message_roles parameter.

Poem

🐇 Roles now flow like burrows wide,
From CLI down to SQL's hide,
User, assistant, tool aligned—
No more user-only confined!
Generic filters, freely twined!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.65% 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 'refactor(cli): generalize message role filtering' directly and accurately summarizes the main change: replacing bespoke user-only output with a composable message-role projection across the CLI.
Linked Issues check ✅ Passed The PR fully addresses both linked issues: #318 replaces --user-only with --message-role with shared role normalization and streaming SQL integration; #319 bounds the state-machine test using in-memory SQLite, enabling faster local verification.
Out of Scope Changes check ✅ Passed All changes are scoped to message-role filtering implementation (CLI, in-memory projection, storage streaming, semantic facts, helpers) and resolving the state-machine test performance issue; no unrelated modifications detected.
Description check ✅ Passed The PR description comprehensively covers all required sections: Summary (with issue references), Problem, Solution, and Verification with explicit commands.

✏️ 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/refactor/message-role-output-filter

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

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

@Sinity
Sinity marked this pull request as ready for review April 21, 2026 21:36

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8ad51ed2cb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@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: 6

Caution

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

⚠️ Outside diff range comments (3)
polylogue/cli/query.py (1)

398-406: 🧹 Nitpick | 🔵 Trivial

Minor: dialogue_only is redundant when message_roles is also passed.

effective_message_roles() already folds dialogue_only into (Role.USER, Role.ASSISTANT) when no explicit roles are set, and downstream iter_messages uses message_roles or ((USER, ASSISTANT) if dialogue_only else ()) — so message_roles wins either way. Passing both works correctly today but couples the call site to two sources of truth; consider passing only message_roles=plan.output.effective_message_roles() and letting the stream-header/facts layer derive the dialogue_only flag from the role set (or from plan.output) for consistency with project_query_results.

Non-blocking; behavior is correct.

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

In `@polylogue/cli/query.py` around lines 398 - 406, Remove the redundant
dialogue_only argument when calling _query_output.stream_conversation: stop
passing plan.output.dialogue_only and only pass
message_roles=plan.output.effective_message_roles(); update any
stream-header/facts logic (the code that derives dialogue-only behavior, e.g.,
iter_messages or the stream layer) to infer dialogue_only from the message_roles
(or from plan.output) as needed so behavior remains unchanged while avoiding two
sources of truth.
tests/unit/cli/test_query_exec.py (1)

741-823: ⚠️ Potential issue | 🟡 Minor

Make the stream test exercise the role-filter plumbing.

The user-only case currently passes because limit=1 returns the first message; _iter_messages ignores the received message_roles, so this would not catch a broken forwarder.

🧪 Proposed test tightening
 async def test_stream_conversation_output_contract(
@@
 ) -> None:
     from polylogue.cli.query_output import stream_conversation
     from polylogue.lib.message_roles import normalize_message_roles
+    from polylogue.lib.roles import Role
@@
-    async def _iter_messages(*_args: object, **_kwargs: object) -> AsyncIterator[MessageModel]:
+    observed_iter_kwargs: list[dict[str, object]] = []
+    expected_effective_roles = normalize_message_roles(message_roles) or (
+        (Role.USER, Role.ASSISTANT) if dialogue_only else ()
+    )
+
+    async def _iter_messages(*_args: object, **_kwargs: object) -> AsyncIterator[MessageModel]:
+        observed_iter_kwargs.append(_kwargs)
         messages = [_make_msg("m1", "user", "Hello"), _make_msg("m2", "assistant", "Hi")]
-        if limit is not None:
-            messages[:] = messages[:limit]
+        requested_roles = _kwargs.get("message_roles", ())
+        if requested_roles:
+            messages = [message for message in messages if Role.normalize(str(message.role)) in requested_roles]
+        requested_limit = _kwargs.get("limit")
+        if requested_limit is not None:
+            messages = messages[: int(requested_limit)]
         for message in messages:
             yield message
@@
     output = stdout.getvalue()
     assert count == (1 if limit == 1 else 2)
+    assert observed_iter_kwargs
+    assert observed_iter_kwargs[0].get("message_roles") == expected_effective_roles
+    assert observed_iter_kwargs[0].get("limit") == limit
     for fragment in expected_fragments:
         assert fragment in output
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/cli/test_query_exec.py` around lines 741 - 823, The test's
_iter_messages helper currently ignores the message_roles argument so the
"user-only" case passes spuriously; update _iter_messages (the function assigned
to repo.iter_messages used by stream_conversation) to accept the message_roles
parameter from the caller and filter the yielded messages by role (compare
against the normalized roles from normalize_message_roles/message_roles), so the
test actually exercises the role-filter plumbing when stream_conversation
forwards message_roles to repo.iter_messages.
polylogue/storage/backends/queries/message_query_stats.py (1)

23-46: ⚠️ Potential issue | 🟠 Major

Use the shared role aliases for dialogue stats too.

dialogue_messages still excludes assistant aliases like model and ai, while the streaming SQL filter now includes them via message_role_sql_values. Those messages will be streamed as dialogue but counted as non-dialogue/tool in stats.

🐛 Proposed fix
+    dialogue_role_values = message_role_sql_values((Role.USER, Role.ASSISTANT))
+    dialogue_placeholders = ",".join("?" for _ in dialogue_role_values)
     cursor = await conn.execute(
-        "SELECT COUNT(*) as cnt FROM messages WHERE conversation_id = ? AND role IN ('user', 'assistant', 'human')",
-        (conversation_id,),
+        f"""
+        SELECT COUNT(*) as cnt
+        FROM messages
+        WHERE conversation_id = ? AND role IN ({dialogue_placeholders})
+        """,
+        (conversation_id, *dialogue_role_values),
     )
     row = await cursor.fetchone()
     dialogue = int(row["cnt"]) if row else 0
 
@@
     )
     role_counts = {str(row["role"]): int(row["cnt"]) for row in await cursor.fetchall()}
     canonical_role_counts = {message_role_count_key(role): _role_count(role_counts, role) for role in Role}
+    tool = canonical_role_counts[message_role_count_key(Role.TOOL)]
 
     return {
         "total_messages": total,
         "dialogue_messages": dialogue,
-        "tool_messages": total - dialogue,
+        "tool_messages": tool,
         **canonical_role_counts,
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/backends/queries/message_query_stats.py` around lines 23 -
46, dialogue_messages is computed with a hardcoded role list
('user','assistant','human') which diverges from the streaming filter; update
the query that sets dialogue_messages to use the shared alias set used elsewhere
(message_role_sql_values / the same role aliases used by
message_role_count_key/_role_count) so the SQL and in-memory role counting
align; locate the dialogue_messages calculation and replace the hardcoded IN
clause with the shared role alias values (or construct the parameter tuple from
message_role_sql_values/Role aliases), and ensure tool_messages continues to be
computed as total - dialogue after this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/cli/query_output.py`:
- Around line 560-561: The in-memory filter uses effective_roles (computed from
message_roles or DIALOGUE_MESSAGE_ROLES) but compares only canonical roles,
dropping hydrated messages with provider aliases (e.g., "human" / "model");
update the filter to be alias-aware by expanding effective_roles into the full
set of allowed role strings (canonical + provider aliases) before filtering —
e.g., compute allowed_roles = set(message_role_sql_values(effective_roles)) or
use the same alias-expansion utility the SQL path uses, then change the list
comprehension in filtered_messages to check message.role in allowed_roles so
render_stream_transcript() and repo.iter_messages(...) yield consistent results.

In `@polylogue/lib/conversation_runtime.py`:
- Around line 89-94: The with_roles method currently treats empty or None input
as a selector that matches nothing (because normalize_message_roles returns ()
and message.role in () is always false), silently dropping all messages; change
with_roles in ConversationRuntimeMixin so it checks the normalized result from
normalize_message_roles (selected_roles) and if it's empty/falsy returns self
(no-op) instead of filtering away everything (i.e., add an early "if not
selected_roles: return self" before calling self.filter), and keep dialogue_only
as-is to continue calling with_roles((Role.USER, Role.ASSISTANT)).

In `@polylogue/lib/message_roles.py`:
- Around line 50-62: The outer split of string tokens in normalize_message_roles
is redundant because _iter_role_values already comma-splits some inputs; fix by
moving comma-splitting responsibility into _iter_role_values (make it
recursively split strings and iterables so it yields individual role token
strings) and then simplify normalize_message_roles to treat each raw from
_iter_role_values as a single candidate (remove the isinstance(raw, str) branch
and calls to _split_role_tokens), still passing each raw to
normalize_message_role_token and deduplicating into roles.
- Around line 37-47: normalize_message_role_token should tighten error handling
for empty and non-string inputs and avoid shadowing the local variable; change
logic so that if value is a Role return it, if it's not a str raise a TypeError
(so things like dict/list/123 produce a clear type error instead of a confusing
str(value)), if it is a str strip it and if token is empty or
Role.normalize(token) == Role.UNKNOWN raise the same ValueError("Unknown message
role ...") using the token (so blank strings get the consistent "Unknown message
role" message), and when building the valid roles list use a different generator
variable name (e.g., r) instead of reusing role to avoid shadowing the local
variable.

In `@tests/unit/cli/test_click_app.py`:
- Line 56: Update the parametrized output-mode tests to explicitly assert that
an empty tuple for message_role does not activate output mode: modify the
parametrization near test_no_args_shows_stats (and the similar block around line
147) to include a negative case where "message_role": () is expected to NOT
trigger query execution, and add an assertion in the test function (e.g.,
test_no_args_shows_stats or the parametrized test that checks has_output_mode)
that when message_role == () the CLI does not run the query/path that indicates
output-mode activation; ensure the test uses the same has_output_mode semantics
used elsewhere so the falsy-tuple behavior is pinned down.

In `@tests/unit/storage/test_backend.py`:
- Around line 1003-1028: Add a small assertion in
test_backend_stream_messages_accepts_generic_role_filter to cover the contract
that explicit message_roles supersede dialogue_only: after saving messages and
before closing the backend, call backend.iter_messages("conv-role-filter",
dialogue_only=True, message_roles=(Role.TOOL,)) and assert it yields only the
tool message_id ["msg-tool"]; reference the test function name
test_backend_stream_messages_accepts_generic_role_filter, the
backend.iter_messages method, and the existing message IDs to locate where to
insert this check.

---

Outside diff comments:
In `@polylogue/cli/query.py`:
- Around line 398-406: Remove the redundant dialogue_only argument when calling
_query_output.stream_conversation: stop passing plan.output.dialogue_only and
only pass message_roles=plan.output.effective_message_roles(); update any
stream-header/facts logic (the code that derives dialogue-only behavior, e.g.,
iter_messages or the stream layer) to infer dialogue_only from the message_roles
(or from plan.output) as needed so behavior remains unchanged while avoiding two
sources of truth.

In `@polylogue/storage/backends/queries/message_query_stats.py`:
- Around line 23-46: dialogue_messages is computed with a hardcoded role list
('user','assistant','human') which diverges from the streaming filter; update
the query that sets dialogue_messages to use the shared alias set used elsewhere
(message_role_sql_values / the same role aliases used by
message_role_count_key/_role_count) so the SQL and in-memory role counting
align; locate the dialogue_messages calculation and replace the hardcoded IN
clause with the shared role alias values (or construct the parameter tuple from
message_role_sql_values/Role aliases), and ensure tool_messages continues to be
computed as total - dialogue after this change.

In `@tests/unit/cli/test_query_exec.py`:
- Around line 741-823: The test's _iter_messages helper currently ignores the
message_roles argument so the "user-only" case passes spuriously; update
_iter_messages (the function assigned to repo.iter_messages used by
stream_conversation) to accept the message_roles parameter from the caller and
filter the yielded messages by role (compare against the normalized roles from
normalize_message_roles/message_roles), so the test actually exercises the
role-filter plumbing when stream_conversation forwards message_roles to
repo.iter_messages.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9ddf7241-3738-43f9-b142-320d0d06c491

📥 Commits

Reviewing files that changed from the base of the PR and between dc0319e and 8ad51ed.

📒 Files selected for processing (25)
  • docs/cli-reference.md
  • polylogue/cli/click_app.py
  • polylogue/cli/click_option_groups.py
  • polylogue/cli/query.py
  • polylogue/cli/query_contracts.py
  • polylogue/cli/query_output.py
  • polylogue/cli/root_request.py
  • polylogue/lib/conversation_runtime.py
  • polylogue/lib/message_roles.py
  • polylogue/lib/semantic_fact_models.py
  • polylogue/lib/semantic_facts.py
  • polylogue/protocols.py
  • polylogue/storage/backends/async_sqlite_archive.py
  • polylogue/storage/backends/queries/message_query_reads.py
  • polylogue/storage/backends/queries/message_query_stats.py
  • polylogue/storage/backends/query_store_archive.py
  • polylogue/storage/repository_archive_conversations.py
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/cli/test_click_app.py
  • tests/unit/cli/test_query_exec.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/core/test_conversation_semantics.py
  • tests/unit/core/test_message_laws.py
  • tests/unit/storage/test_backend.py
  • tests/unit/storage/test_repository_state_machine.py

Comment on lines +560 to +561
effective_roles = message_roles or (DIALOGUE_MESSAGE_ROLES if dialogue_only else ())
filtered_messages = [message for message in messages if not effective_roles or message.role in effective_roles]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Use alias-aware role matching for in-memory filtering.

Line 561 only matches canonical roles, so hydrated messages with provider aliases like human or model are dropped here, while the SQL streaming path includes them via message_role_sql_values(). This makes render_stream_transcript() disagree with repo.iter_messages(..., message_roles=...).

🐛 Proposed fix
-from polylogue.lib.message_roles import MessageRoleFilter, message_role_count_key, message_role_labels
+from polylogue.lib.message_roles import (
+    MessageRoleFilter,
+    message_role_count_key,
+    message_role_labels,
+    message_role_sql_values,
+)
@@
-    effective_roles = message_roles or (DIALOGUE_MESSAGE_ROLES if dialogue_only else ())
-    filtered_messages = [message for message in messages if not effective_roles or message.role in effective_roles]
+    effective_roles = message_roles or (DIALOGUE_MESSAGE_ROLES if dialogue_only else ())
+    role_values = set(message_role_sql_values(effective_roles))
+    filtered_messages = [
+        message
+        for message in messages
+        if not role_values
+        or str(getattr(message.role, "value", message.role) or "unknown").strip().lower() in role_values
+    ]
📝 Committable suggestion

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

Suggested change
effective_roles = message_roles or (DIALOGUE_MESSAGE_ROLES if dialogue_only else ())
filtered_messages = [message for message in messages if not effective_roles or message.role in effective_roles]
effective_roles = message_roles or (DIALOGUE_MESSAGE_ROLES if dialogue_only else ())
role_values = set(message_role_sql_values(effective_roles))
filtered_messages = [
message
for message in messages
if not role_values
or str(getattr(message.role, "value", message.role) or "unknown").strip().lower() in role_values
]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/query_output.py` around lines 560 - 561, The in-memory filter
uses effective_roles (computed from message_roles or DIALOGUE_MESSAGE_ROLES) but
compares only canonical roles, dropping hydrated messages with provider aliases
(e.g., "human" / "model"); update the filter to be alias-aware by expanding
effective_roles into the full set of allowed role strings (canonical + provider
aliases) before filtering — e.g., compute allowed_roles =
set(message_role_sql_values(effective_roles)) or use the same alias-expansion
utility the SQL path uses, then change the list comprehension in
filtered_messages to check message.role in allowed_roles so
render_stream_transcript() and repo.iter_messages(...) yield consistent results.

Comment on lines +89 to +94
def with_roles(self, roles: object) -> Self:
selected_roles = normalize_message_roles(roles)
return self.filter(lambda message: message.role in selected_roles)

def dialogue_only(self) -> Self:
return self.filter(lambda message: message.is_dialogue)
return self.with_roles((Role.USER, Role.ASSISTANT))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

with_roles(()) silently drops every message — worth documenting.

With an empty/None roles argument, normalize_message_roles returns () and the predicate message.role in () is always false, so the result is a conversation with zero messages. CLI callers guard with if message_roles: before invoking (see polylogue/cli/query.py:253-255), but as a public API on ConversationRuntimeMixin this edge is easy to misuse. Either document it or treat empty input as a no-op / raise:

 def with_roles(self, roles: object) -> Self:
+    """Return a copy retaining only messages whose role is in ``roles``.
+
+    An empty/``None`` selection yields an empty conversation; pass explicit
+    roles (e.g., ``(Role.USER, Role.ASSISTANT)``) to filter.
+    """
     selected_roles = normalize_message_roles(roles)
     return self.filter(lambda message: message.role in selected_roles)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/lib/conversation_runtime.py` around lines 89 - 94, The with_roles
method currently treats empty or None input as a selector that matches nothing
(because normalize_message_roles returns () and message.role in () is always
false), silently dropping all messages; change with_roles in
ConversationRuntimeMixin so it checks the normalized result from
normalize_message_roles (selected_roles) and if it's empty/falsy returns self
(no-op) instead of filtering away everything (i.e., add an early "if not
selected_roles: return self" before calling self.filter), and keep dialogue_only
as-is to continue calling with_roles((Role.USER, Role.ASSISTANT)).

Comment on lines +37 to +47
def normalize_message_role_token(value: object) -> Role:
"""Normalize one user-supplied message role token."""
if isinstance(value, Role):
return value
token = str(value).strip()
role = Role.normalize(token)
if role == Role.UNKNOWN and token.lower() != Role.UNKNOWN.value:
valid = ", ".join(role.value for role in Role)
msg = f"Unknown message role {token!r}. Valid roles: {valid}"
raise ValueError(msg)
return role

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Consider tightening error surface for empty/non-string inputs.

Two minor behavioral edges worth noting:

  1. Role.normalize("") raises ValueError("Role cannot be empty...") rather than the more informative "Unknown message role ..." message crafted here. In practice _split_role_tokens filters empties so this is only reachable when normalize_message_role_token is called directly with a blank string, but a consistent error would be friendlier.
  2. For non-str / non-Role / non-iterable objects, str(value) is used — e.g., normalize_message_role_token(123) produces an error message with '123', which is fine, but passing a dict/list would produce a confusing stringified repr. Low-impact since the CLI only feeds Click-parsed strings.

Also a readability nit: the generator ", ".join(role.value for role in Role) reuses the name role that's bound on line 42; harmless in Py3 but renaming (e.g., r) avoids the shadowing.

Proposed tweak
-    token = str(value).strip()
-    role = Role.normalize(token)
-    if role == Role.UNKNOWN and token.lower() != Role.UNKNOWN.value:
-        valid = ", ".join(role.value for role in Role)
-        msg = f"Unknown message role {token!r}. Valid roles: {valid}"
-        raise ValueError(msg)
-    return role
+    token = str(value).strip()
+    if not token:
+        valid = ", ".join(r.value for r in Role)
+        raise ValueError(f"Empty message role. Valid roles: {valid}")
+    role = Role.normalize(token)
+    if role == Role.UNKNOWN and token.lower() != Role.UNKNOWN.value:
+        valid = ", ".join(r.value for r in Role)
+        raise ValueError(f"Unknown message role {token!r}. Valid roles: {valid}")
+    return role
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/lib/message_roles.py` around lines 37 - 47,
normalize_message_role_token should tighten error handling for empty and
non-string inputs and avoid shadowing the local variable; change logic so that
if value is a Role return it, if it's not a str raise a TypeError (so things
like dict/list/123 produce a clear type error instead of a confusing
str(value)), if it is a str strip it and if token is empty or
Role.normalize(token) == Role.UNKNOWN raise the same ValueError("Unknown message
role ...") using the token (so blank strings get the consistent "Unknown message
role" message), and when building the valid roles list use a different generator
variable name (e.g., r) instead of reusing role to avoid shadowing the local
variable.

Comment on lines +50 to +62
def normalize_message_roles(value: object) -> MessageRoleFilter:
"""Normalize repeated or comma-separated role values to canonical roles."""
roles: list[Role] = []
for raw in _iter_role_values(value):
if isinstance(raw, str):
candidates: Sequence[object] = _split_role_tokens(raw)
else:
candidates = (raw,)
for candidate in candidates:
role = normalize_message_role_token(candidate)
if role not in roles:
roles.append(role)
return tuple(roles)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Redundant (but safe) comma-split on string inputs.

When value is a plain string like "user,assistant", _iter_role_values already comma-splits it, and then the isinstance(raw, str) branch in the outer loop splits each already-stripped token again. It's idempotent, but the inner branch really only matters for iterables that contain comma-separated strings (e.g., Click's repeatable tuple[str, ...] where a user wrote --message-role user,assistant). You could drop the double-split by moving the split entirely into one place — either always in _iter_role_values (and make it recursive for iterables) or only here. Optional cleanup; current behavior is correct.

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

In `@polylogue/lib/message_roles.py` around lines 50 - 62, The outer split of
string tokens in normalize_message_roles is redundant because _iter_role_values
already comma-splits some inputs; fix by moving comma-splitting responsibility
into _iter_role_values (make it recursively split strings and iterables so it
yields individual role token strings) and then simplify normalize_message_roles
to treat each raw from _iter_role_values as a single candidate (remove the
isinstance(raw, str) branch and calls to _split_role_tokens), still passing each
raw to normalize_message_role_token and deduplicating into roles.

"transform": None,
"stream": False,
"dialogue_only": False,
"message_role": (),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Coverage matches the new has_output_mode semantics.

Adding message_role=("user",) to the output-mode trigger parametrization aligns with RootModeRequest.has_output_mode() now treating message_role as output-activating. Consider also asserting that message_role=() does not trigger query execution — currently test_no_args_shows_stats covers the default-empty case implicitly, but an explicit negative case would pin the falsy-tuple behavior.

Also applies to: 147-147

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

In `@tests/unit/cli/test_click_app.py` at line 56, Update the parametrized
output-mode tests to explicitly assert that an empty tuple for message_role does
not activate output mode: modify the parametrization near
test_no_args_shows_stats (and the similar block around line 147) to include a
negative case where "message_role": () is expected to NOT trigger query
execution, and add an assertion in the test function (e.g.,
test_no_args_shows_stats or the parametrized test that checks has_output_mode)
that when message_role == () the CLI does not run the query/path that indicates
output-mode activation; ensure the test uses the same has_output_mode semantics
used elsewhere so the falsy-tuple behavior is pinned down.

Comment on lines +1003 to +1028
async def test_backend_stream_messages_accepts_generic_role_filter(tmp_path: Path) -> None:
backend = SQLiteBackend(db_path=tmp_path / "role-filter.db")
conv = make_conversation("conv-role-filter", title="Role Filter")
messages = [
make_message("msg-user", "conv-role-filter", role="user", text="User text"),
make_message("msg-assistant", "conv-role-filter", role="assistant", text="Assistant text"),
make_message("msg-tool", "conv-role-filter", role="tool", text="Tool text"),
make_message("msg-system", "conv-role-filter", role="system", text="System text"),
]

async with backend.transaction():
await backend.save_conversation_record(conv)
await backend.save_messages(messages)

user_messages = [message async for message in backend.iter_messages("conv-role-filter", message_roles=(Role.USER,))]
dialogue_messages = [message async for message in backend.iter_messages("conv-role-filter", dialogue_only=True)]
stats = await backend.get_conversation_stats("conv-role-filter")

assert [message.message_id for message in user_messages] == ["msg-user"]
assert [message.message_id for message in dialogue_messages] == ["msg-user", "msg-assistant"]
assert stats["role_user_messages"] == 1
assert stats["role_assistant_messages"] == 1
assert stats["role_tool_messages"] == 1
assert stats["role_system_messages"] == 1

await backend.close()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Good coverage for the new role filter and role-count stats.

Exercises three contracts in one test: (1) message_roles=(Role.USER,) yields only user rows, (2) dialogue_only=True yields user+assistant in order, and (3) get_conversation_stats exposes canonical role_<name>_messages keys. Consider adding a case mixing dialogue_only=True with an explicit message_roles=(Role.TOOL,) to lock in the "explicit roles supersede dialogue_only" contract asserted by the PR objective — cheap to add next to this test.

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

In `@tests/unit/storage/test_backend.py` around lines 1003 - 1028, Add a small
assertion in test_backend_stream_messages_accepts_generic_role_filter to cover
the contract that explicit message_roles supersede dialogue_only: after saving
messages and before closing the backend, call
backend.iter_messages("conv-role-filter", dialogue_only=True,
message_roles=(Role.TOOL,)) and assert it yields only the tool message_id
["msg-tool"]; reference the test function name
test_backend_stream_messages_accepts_generic_role_filter, the
backend.iter_messages method, and the existing message IDs to locate where to
insert this check.

@Sinity
Sinity merged commit 30162e6 into master Apr 21, 2026
14 checks passed
@Sinity
Sinity deleted the feature/refactor/message-role-output-filter branch April 21, 2026 22:00
Sinity added a commit that referenced this pull request Apr 22, 2026
## Summary

Closes #318.
Closes #319.

Replaces the bespoke user-only output idea with a composable message-role projection that works across CLI parsing, in-memory conversation projection, streaming storage reads, stream headers, and semantic facts. Also removes the unrelated local full-verification blocker that surfaced while validating this PR.

## Problem

`--user-only` made one role projection special even though the model already has canonical roles and provider role normalization. That left an arbitrary surface where `user`, `assistant`, `tool`, `system`, and `unknown` should all be expressible through the same mechanism.

Full local verification was also not actually usable: `tests/unit/storage/test_repository_state_machine.py::TestArchiveLifecycle::runTest` spent most of its runtime recreating file-backed SQLite schemas for Hypothesis examples and could exceed practical local budgets.

## Solution

- Add `--message-role`, accepting repeated or comma-separated canonical roles with provider aliases normalized through the shared role model.
- Keep `--dialogue-only` as a shorthand for `user,assistant`, while explicit `--message-role` wins when both are supplied.
- Add shared `polylogue.lib.message_roles` helpers for canonical role filters, SQL aliases, labels, and stats keys.
- Push role filtering into streaming SQL reads and expose canonical role counts from conversation stats.
- Replace arbitrary `Conversation.user_only()` / `assistant_only()` helpers with generic `Conversation.with_roles(...)`; `dialogue_only()` now delegates to that generic projection.
- Carry effective role filters through stream semantic facts and generated CLI docs.
- Switch the archive lifecycle state-machine test to in-memory SQLite so it keeps the same lifecycle model coverage without paying multi-second file-backed schema setup per example.
- Refresh terminal and showcase help baselines for the new CLI option.

## Verification

```bash
uv run ruff check docs/cli-reference.md polylogue/cli/click_app.py polylogue/cli/click_option_groups.py polylogue/cli/query.py polylogue/cli/query_contracts.py polylogue/cli/query_output.py polylogue/cli/root_request.py polylogue/lib/conversation_runtime.py polylogue/lib/message_roles.py polylogue/lib/semantic_fact_models.py polylogue/lib/semantic_facts.py polylogue/protocols.py polylogue/storage/backends/async_sqlite_archive.py polylogue/storage/backends/queries/message_query_reads.py polylogue/storage/backends/queries/message_query_stats.py polylogue/storage/backends/query_store_archive.py polylogue/storage/repository_archive_conversations.py tests/unit/cli/test_click_app.py tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py tests/unit/core/test_conversation_semantics.py tests/unit/core/test_message_laws.py tests/unit/storage/test_backend.py
uv run mypy polylogue/cli/click_app.py polylogue/cli/click_option_groups.py polylogue/cli/query.py polylogue/cli/query_contracts.py polylogue/cli/query_output.py polylogue/cli/root_request.py polylogue/lib/conversation_runtime.py polylogue/lib/message_roles.py polylogue/lib/semantic_fact_models.py polylogue/lib/semantic_facts.py polylogue/protocols.py polylogue/storage/backends/async_sqlite_archive.py polylogue/storage/backends/queries/message_query_reads.py polylogue/storage/backends/queries/message_query_stats.py polylogue/storage/backends/query_store_archive.py polylogue/storage/repository_archive_conversations.py tests/unit/cli/test_click_app.py tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py tests/unit/core/test_conversation_semantics.py tests/unit/core/test_message_laws.py tests/unit/storage/test_backend.py
uv run pytest -q tests/unit/cli/test_click_app.py tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py tests/unit/core/test_conversation_semantics.py tests/unit/core/test_message_laws.py tests/unit/storage/test_backend.py
uv run devtools render-all --check
uv run devtools verify --quick
timeout 90s uv run pytest -q -n0 tests/unit/storage/test_repository_state_machine.py::TestArchiveLifecycle::runTest
uv run pytest -q tests/unit/cli/test_terminal_snapshots.py --snapshot-update
uv run devtools verify
uv run devtools verify-showcase --update
uv run devtools verify-showcase
git push
```
Sinity added a commit that referenced this pull request Apr 22, 2026
`--user-only` made one role projection special even though the
model already has canonical roles and provider role normalization.
That left an arbitrary surface where `user`, `assistant`, `tool`,
`system`, and `unknown` should all be expressible through the same
mechanism. Full local verification was also not usable: the archive
lifecycle state-machine test spent most of its runtime recreating
file-backed SQLite schemas for Hypothesis examples and could exceed
practical local budgets.

Replaces the bespoke user-only output idea with a composable
message-role projection that works across CLI parsing, in-memory
conversation projection, streaming storage reads, stream headers,
and semantic facts. Adds `--message-role`, accepting repeated or
comma-separated canonical roles with provider aliases normalized
through the shared role model. Keeps `--dialogue-only` as a
shorthand for `user,assistant`; explicit `--message-role` wins when
both are supplied. Adds shared `lib/message_roles.py` helpers for
canonical role filters, SQL aliases, labels, and stats keys. Pushes
role filtering into streaming SQL reads; exposes canonical role
counts from conversation stats. Replaces arbitrary
`Conversation.user_only()` / `assistant_only()` helpers with generic
`Conversation.with_roles(...)`; `dialogue_only()` delegates.
Carries effective role filters through stream semantic facts and
generated CLI docs.

Switches the archive lifecycle state-machine test to in-memory
SQLite so it keeps the same lifecycle model coverage without paying
multi-second file-backed schema setup per example. Refreshes
terminal and showcase help baselines for the new CLI option.

Verification: ruff + mypy + pytest over CLI / conversation-semantics
/ message-laws / storage-backend; devtools render-all --check,
verify --quick, and verify green; showcase verify-showcase refreshed
and re-verified.

Closes #318
Closes #319
Sinity added a commit that referenced this pull request Apr 22, 2026
`--user-only` made one role projection special even though the
model already has canonical roles and provider role normalization.
That left an arbitrary surface where `user`, `assistant`, `tool`,
`system`, and `unknown` should all be expressible through the same
mechanism. Full local verification was also not usable: the archive
lifecycle state-machine test spent most of its runtime recreating
file-backed SQLite schemas for Hypothesis examples and could exceed
practical local budgets.

Replaces the bespoke user-only output idea with a composable
message-role projection that works across CLI parsing, in-memory
conversation projection, streaming storage reads, stream headers,
and semantic facts. Adds `--message-role`, accepting repeated or
comma-separated canonical roles with provider aliases normalized
through the shared role model. Keeps `--dialogue-only` as a
shorthand for `user,assistant`; explicit `--message-role` wins when
both are supplied. Adds shared `lib/message_roles.py` helpers for
canonical role filters, SQL aliases, labels, and stats keys. Pushes
role filtering into streaming SQL reads; exposes canonical role
counts from conversation stats. Replaces arbitrary
`Conversation.user_only()` / `assistant_only()` helpers with generic
`Conversation.with_roles(...)`; `dialogue_only()` delegates.
Carries effective role filters through stream semantic facts and
generated CLI docs.

Switches the archive lifecycle state-machine test to in-memory
SQLite so it keeps the same lifecycle model coverage without paying
multi-second file-backed schema setup per example. Refreshes
terminal and showcase help baselines for the new CLI option.

Verification: ruff + mypy + pytest over CLI / conversation-semantics
/ message-laws / storage-backend; devtools render-all --check,
verify --quick, and verify green; showcase verify-showcase refreshed
and re-verified.

Closes #318
Closes #319
Sinity added a commit that referenced this pull request Apr 22, 2026
`--user-only` made one role projection special even though the
model already has canonical roles and provider role normalization.
That left an arbitrary surface where `user`, `assistant`, `tool`,
`system`, and `unknown` should all be expressible through the same
mechanism. Full local verification was also not usable: the archive
lifecycle state-machine test spent most of its runtime recreating
file-backed SQLite schemas for Hypothesis examples and could exceed
practical local budgets.

Replaces the bespoke user-only output idea with a composable
message-role projection that works across CLI parsing, in-memory
conversation projection, streaming storage reads, stream headers,
and semantic facts. Adds `--message-role`, accepting repeated or
comma-separated canonical roles with provider aliases normalized
through the shared role model. Keeps `--dialogue-only` as a
shorthand for `user,assistant`; explicit `--message-role` wins when
both are supplied. Adds shared `lib/message_roles.py` helpers for
canonical role filters, SQL aliases, labels, and stats keys. Pushes
role filtering into streaming SQL reads; exposes canonical role
counts from conversation stats. Replaces arbitrary
`Conversation.user_only()` / `assistant_only()` helpers with generic
`Conversation.with_roles(...)`; `dialogue_only()` delegates.
Carries effective role filters through stream semantic facts and
generated CLI docs.

Switches the archive lifecycle state-machine test to in-memory
SQLite so it keeps the same lifecycle model coverage without paying
multi-second file-backed schema setup per example. Refreshes
terminal and showcase help baselines for the new CLI option.

Verification: ruff + mypy + pytest over CLI / conversation-semantics
/ message-laws / storage-backend; devtools render-all --check,
verify --quick, and verify green; showcase verify-showcase refreshed
and re-verified.

Closes #318
Closes #319
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 2 finding(s) confirmed still present → tracked in #550.

@Sinity
Sinity requested review from Copilot and removed request for Copilot May 1, 2026 00:43
@Sinity
Sinity removed the request for review from Copilot May 1, 2026 02:15
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test: bound archive lifecycle state-machine verification refactor(cli): generalize message role output filtering

1 participant