Repository navigation
refactor(cli): generalize message role filtering - #320
Conversation
📝 WalkthroughWalkthroughThis change introduces role-based message filtering throughout the CLI and storage stack, replacing special-case handling with a generalized Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
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 | 🔵 TrivialMinor:
dialogue_onlyis redundant whenmessage_rolesis also passed.
effective_message_roles()already foldsdialogue_onlyinto(Role.USER, Role.ASSISTANT)when no explicit roles are set, and downstreamiter_messagesusesmessage_roles or ((USER, ASSISTANT) if dialogue_only else ())— somessage_roleswins either way. Passing both works correctly today but couples the call site to two sources of truth; consider passing onlymessage_roles=plan.output.effective_message_roles()and letting the stream-header/facts layer derive thedialogue_onlyflag from the role set (or fromplan.output) for consistency withproject_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 | 🟡 MinorMake the stream test exercise the role-filter plumbing.
The user-only case currently passes because
limit=1returns the first message;_iter_messagesignores the receivedmessage_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 | 🟠 MajorUse the shared role aliases for dialogue stats too.
dialogue_messagesstill excludes assistant aliases likemodelandai, while the streaming SQL filter now includes them viamessage_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
📒 Files selected for processing (25)
docs/cli-reference.mdpolylogue/cli/click_app.pypolylogue/cli/click_option_groups.pypolylogue/cli/query.pypolylogue/cli/query_contracts.pypolylogue/cli/query_output.pypolylogue/cli/root_request.pypolylogue/lib/conversation_runtime.pypolylogue/lib/message_roles.pypolylogue/lib/semantic_fact_models.pypolylogue/lib/semantic_facts.pypolylogue/protocols.pypolylogue/storage/backends/async_sqlite_archive.pypolylogue/storage/backends/queries/message_query_reads.pypolylogue/storage/backends/queries/message_query_stats.pypolylogue/storage/backends/query_store_archive.pypolylogue/storage/repository_archive_conversations.pytests/unit/cli/__snapshots__/test_terminal_snapshots.ambrtests/unit/cli/test_click_app.pytests/unit/cli/test_query_exec.pytests/unit/cli/test_query_exec_laws.pytests/unit/core/test_conversation_semantics.pytests/unit/core/test_message_laws.pytests/unit/storage/test_backend.pytests/unit/storage/test_repository_state_machine.py
| 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] |
There was a problem hiding this comment.
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.
| 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.
| 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)) |
There was a problem hiding this comment.
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)).
| 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 |
There was a problem hiding this comment.
Consider tightening error surface for empty/non-string inputs.
Two minor behavioral edges worth noting:
Role.normalize("")raisesValueError("Role cannot be empty...")rather than the more informative "Unknown message role ..." message crafted here. In practice_split_role_tokensfilters empties so this is only reachable whennormalize_message_role_tokenis called directly with a blank string, but a consistent error would be friendlier.- 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.
| 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) |
There was a problem hiding this comment.
🧹 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": (), |
There was a problem hiding this comment.
🧹 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.
| 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() |
There was a problem hiding this comment.
🧹 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.
## 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 ```
`--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
`--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
`--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
|
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. |
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-onlymade one role projection special even though the model already has canonical roles and provider role normalization. That left an arbitrary surface whereuser,assistant,tool,system, andunknownshould all be expressible through the same mechanism.Full local verification was also not actually usable:
tests/unit/storage/test_repository_state_machine.py::TestArchiveLifecycle::runTestspent most of its runtime recreating file-backed SQLite schemas for Hypothesis examples and could exceed practical local budgets.Solution
--message-role, accepting repeated or comma-separated canonical roles with provider aliases normalized through the shared role model.--dialogue-onlyas a shorthand foruser,assistant, while explicit--message-rolewins when both are supplied.polylogue.lib.message_roleshelpers for canonical role filters, SQL aliases, labels, and stats keys.Conversation.user_only()/assistant_only()helpers with genericConversation.with_roles(...);dialogue_only()now delegates to that generic projection.Verification