Repository navigation
feat(cli): unify read surface under single read verb (#1813) - #1863
Conversation
|
Warning Review limit reached
More reviews will be available in 49 minutes and 18 seconds. Learn how PR review limits work. Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file). ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (33)
📝 WalkthroughWalkthroughThis PR implements unified query verb consolidation by introducing a new ChangesQuery Verb Consolidation to Unified Read Action
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels
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 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: dd79abde8a
ℹ️ 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: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@polylogue/cli/query_group.py`:
- Around line 41-45: Add unit tests exercising the query-first parser's optional
"then" connector behaviour so the logic in polylogue/cli/query_group.py (the
branch that checks if arg == "then" and uses VERB_NAMES) is covered; add tests
that call the CLI parser (or the query-first parsing function) for these inputs
and assert the parsed query terms and verb: "polylogue foo then read" (connector
before verb yields query="foo", verb="read"), "polylogue then read" (no query
terms, verb="read"), "polylogue foo then" (connector at end treated as literal
or no verb per current spec—assert expected no-verb result), "polylogue foo then
bar then read" (only the "then" immediately before the verb is treated as
connector so query="foo bar", verb="read"), and "polylogue foo -- then read"
(the "then" after "--" must be treated as a query term, not a connector); make
assertions against the parser output (query tokens and verb) and include any
needed setup/teardown to invoke the same parsing function used by the CLI tests
so VERB_NAMES and the connector branch are exercised.
In `@polylogue/cli/query_verbs.py`:
- Around line 153-159: The CLI currently accepts the --to / destination option
(choice _READ_DESTINATIONS) but several handlers silently ignore it; add an
explicit compatibility check and fail fast or implement routing: create/inline a
validator (e.g. validate_destination_for_read(destination, mode_or_view)) and
call it at the start of each affected branch so unsupported combos raise
click.UsageError with a clear message, or replace the silent terminal-only
output with explicit routing to the chosen destination (call appropriate output
functions like write_to_terminal, write_to_browser, write_to_clipboard). Apply
this change at polylogue/cli/query_verbs.py:153-159 (ensure the option is
validated/consumed), and add the validator call or routing in each branch at
228-295, 422-437, 440-456, and 458-494 (if a site is corrected by the root
validator note that no direct change is needed there). Ensure messages reference
the --to/destination value and the current read mode so users know which
combinations are invalid.
- Around line 310-326: In _find_first, avoid materializing all results with
list(...) when you only need the first match: replace the list(...) calls on
filter_chain.list_summaries() and filter_chain.list() with a bounded query or
one-result iteration (e.g., call a list_summaries(limit=1)/list(limit=1) variant
if supported, or iterate the async generator with "async for item in ..." and
break after the first item) and then set first_id from that single item; keep
the existing branch logic using filter_chain.can_use_summaries() and update only
the calls to filter_chain.list_summaries and filter_chain.list to fetch a single
result.
In `@tests/unit/cli/test_query_verbs_runtime.py`:
- Around line 101-161: Add runtime tests that exercise the new
destination-routing matrix for the read verb: create tests that call the wrapped
read_verb.callback (use getattr(..., "__wrapped__")) with destinations
"terminal", "file", "clipboard", and "browser" for both summary and --all
(export_all=True) paths and assert correct dispatch to
polylogue.cli.query_verbs._execute_query_verb or
polylogue.cli.bulk_export.run_bulk_export as appropriate; also add cases
asserting a UsageError is raised for unsupported destination/output_format
combinations (e.g., --to=clipboard with output_format that isn't allowed) by
catching the UsageError type and verifying the message. Reference the existing
test helpers _context_pair and reuse the same argument shape as
test_read_verb_summary_dispatches_to_execute_query_verb and
test_read_verb_all_invokes_run_bulk_export when constructing these new tests so
the coverage locks the complex routing behavior.
🪄 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: 55cfb9c0-74db-4287-8c35-f204fed37efb
📒 Files selected for processing (21)
devtools/render_cli_reference.pydocs/cli-reference.mddocs/plans/topology-target.yamldocs/test-quality-workflows.mdpolylogue/cli/click_app.pypolylogue/cli/click_command_registration.pypolylogue/cli/commands/commands.pypolylogue/cli/output_assurance.pypolylogue/cli/query_group.pypolylogue/cli/query_verbs.pypolylogue/cli/shell_completion_values.pypolylogue/cli/verb_names.pytests/unit/cli/test_bulk_export.pytests/unit/cli/test_cli_error_boundaries.pytests/unit/cli/test_click_app.pytests/unit/cli/test_command_aux_runtime.pytests/unit/cli/test_deterministic_output.pytests/unit/cli/test_export.pytests/unit/cli/test_json_output.pytests/unit/cli/test_query_verbs_runtime.pytests/unit/cli/test_stdout_stderr_split.py
💤 Files with no reviewable changes (4)
- polylogue/cli/shell_completion_values.py
- tests/unit/cli/test_command_aux_runtime.py
- tests/unit/cli/test_export.py
- polylogue/cli/click_command_registration.py
| async def _find_first() -> str | None: | ||
| plan = build_query_execution_plan(request.query_params()) | ||
| archive_root = archive_file_set_root_for_paths( | ||
| archive_root_path=config.archive_root, | ||
| db_anchor=config.db_path, | ||
| ) | ||
| vector_provider = _create_query_vector_provider(config, db_path=archive_root / "embeddings.db") | ||
| filter_chain = plan.selection.build_filter(config, vector_provider=vector_provider) | ||
| first_id: str | None = None | ||
| if filter_chain.can_use_summaries(): | ||
| summaries: list[SessionSummary] = list(await filter_chain.list_summaries()) | ||
| if summaries: | ||
| first_id = str(summaries[0].id) | ||
| else: | ||
| sessions: list[Session] = list(await filter_chain.list()) | ||
| if sessions: | ||
| first_id = str(sessions[0].id) |
There was a problem hiding this comment.
Avoid full materialization when only the first browser match is needed.
The browser path builds list(...) of all summaries/sessions and then reads index 0. On large archives this is unnecessary I/O and memory overhead. Constrain the query to one result before execution (or use an iterator/first-item path) so opening a single session stays bounded.
Proposed fix sketch
async def _find_first() -> str | None:
- plan = build_query_execution_plan(request.query_params())
+ params = dict(request.query_params())
+ params["limit"] = 1
+ plan = build_query_execution_plan(params)
...
- if filter_chain.can_use_summaries():
- summaries: list[SessionSummary] = list(await filter_chain.list_summaries())
+ if filter_chain.can_use_summaries():
+ summaries: list[SessionSummary] = list(await filter_chain.list_summaries())
if summaries:
first_id = str(summaries[0].id)📝 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.
| async def _find_first() -> str | None: | |
| plan = build_query_execution_plan(request.query_params()) | |
| archive_root = archive_file_set_root_for_paths( | |
| archive_root_path=config.archive_root, | |
| db_anchor=config.db_path, | |
| ) | |
| vector_provider = _create_query_vector_provider(config, db_path=archive_root / "embeddings.db") | |
| filter_chain = plan.selection.build_filter(config, vector_provider=vector_provider) | |
| first_id: str | None = None | |
| if filter_chain.can_use_summaries(): | |
| summaries: list[SessionSummary] = list(await filter_chain.list_summaries()) | |
| if summaries: | |
| first_id = str(summaries[0].id) | |
| else: | |
| sessions: list[Session] = list(await filter_chain.list()) | |
| if sessions: | |
| first_id = str(sessions[0].id) | |
| async def _find_first() -> str | None: | |
| params = dict(request.query_params()) | |
| params["limit"] = 1 | |
| plan = build_query_execution_plan(params) | |
| archive_root = archive_file_set_root_for_paths( | |
| archive_root_path=config.archive_root, | |
| db_anchor=config.db_path, | |
| ) | |
| vector_provider = _create_query_vector_provider(config, db_path=archive_root / "embeddings.db") | |
| filter_chain = plan.selection.build_filter(config, vector_provider=vector_provider) | |
| first_id: str | None = None | |
| if filter_chain.can_use_summaries(): | |
| summaries: list[SessionSummary] = list(await filter_chain.list_summaries()) | |
| if summaries: | |
| first_id = str(summaries[0].id) | |
| else: | |
| sessions: list[Session] = list(await filter_chain.list()) | |
| if sessions: | |
| first_id = str(sessions[0].id) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@polylogue/cli/query_verbs.py` around lines 310 - 326, In _find_first, avoid
materializing all results with list(...) when you only need the first match:
replace the list(...) calls on filter_chain.list_summaries() and
filter_chain.list() with a bounded query or one-result iteration (e.g., call a
list_summaries(limit=1)/list(limit=1) variant if supported, or iterate the async
generator with "async for item in ..." and break after the first item) and then
set first_id from that single item; keep the existing branch logic using
filter_chain.can_use_summaries() and update only the calls to
filter_chain.list_summaries and filter_chain.list to fetch a single result.
| def test_read_verb_summary_dispatches_to_execute_query_verb() -> None: | ||
| """read --view summary (default) routes to _execute_query_verb.""" | ||
| _, child = _context_pair(params={"origin": "chatgpt-export"}, query_terms=("alpha",)) | ||
| wrapped = getattr(query_verbs.read_verb.callback, "__wrapped__", None) | ||
| assert callable(wrapped) | ||
|
|
||
| with patch("polylogue.cli.query_verbs._execute_query_verb") as execute: | ||
| wrapped(child, ("regression",)) | ||
|
|
||
| wrapped( | ||
| child, | ||
| "summary", # view | ||
| "terminal", # destination | ||
| None, # output_format | ||
| None, # out_path | ||
| False, # export_all | ||
| (), # message_role | ||
| None, # message_type | ||
| None, # limit | ||
| 0, # offset | ||
| False, # no_code_blocks | ||
| False, # no_tool_calls | ||
| False, # no_tool_outputs | ||
| False, # no_file_reads | ||
| False, # prose_only | ||
| None, # fields | ||
| ) | ||
|
|
||
| execute.assert_called_once() | ||
| request = execute.call_args.args[1] | ||
| assert isinstance(request, RootModeRequest) | ||
| assert "conv_id" not in request.query_params() or not request.query_params().get("conv_id") | ||
| assert request.query_params()["query"] == ("error", "regression") | ||
| assert request.query_params()["origin"] == "chatgpt-export" | ||
|
|
||
|
|
||
| def test_bulk_export_verb_invokes_run_bulk_export_with_parent_request() -> None: | ||
| _, child = _context_pair( | ||
| params={"origin": "claude-code-session", "limit": 5}, | ||
| query_terms=("alpha",), | ||
| ) | ||
| wrapped = getattr(query_verbs.bulk_export_verb.callback, "__wrapped__", None) | ||
| def test_read_verb_all_invokes_run_bulk_export() -> None: | ||
| """read --all routes to run_bulk_export.""" | ||
| _, child = _context_pair(params={"origin": "claude-code-session"}, query_terms=("alpha",)) | ||
| wrapped = getattr(query_verbs.read_verb.callback, "__wrapped__", None) | ||
| assert callable(wrapped) | ||
|
|
||
| with patch("polylogue.cli.bulk_export.run_bulk_export") as run_export: | ||
| wrapped(child, "jsonl", None) | ||
|
|
||
| assert run_export.call_count == 1 | ||
| args, kwargs = run_export.call_args | ||
| env_arg, request_arg = args | ||
| assert env_arg is child.obj | ||
| assert isinstance(request_arg, RootModeRequest) | ||
| assert request_arg.query_params()["origin"] == "claude-code-session" | ||
| assert request_arg.query_params()["query"] == ("alpha",) | ||
| assert kwargs == {"output_format": "jsonl", "fields": None} | ||
| wrapped( | ||
| child, | ||
| "summary", # view | ||
| "terminal", # destination | ||
| "json", # output_format | ||
| None, # out_path | ||
| True, # export_all | ||
| (), # message_role | ||
| None, # message_type | ||
| None, # limit | ||
| 0, # offset | ||
| False, # no_code_blocks | ||
| False, # no_tool_calls | ||
| False, # no_tool_outputs | ||
| False, # no_file_reads | ||
| False, # prose_only | ||
| None, # fields | ||
| ) | ||
|
|
||
| run_export.assert_called_once() | ||
| assert run_export.call_args.kwargs["output_format"] == "json" | ||
|
|
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
Add runtime coverage for read destination-routing branches.
These tests validate summary and --all dispatch, but they do not lock behavior for the new destination matrix (--to file/clipboard/browser) where branch logic is now complex. Add focused cases for supported/unsupported combinations (including expected UsageError) to prevent silent routing regressions.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/cli/test_query_verbs_runtime.py` around lines 101 - 161, Add
runtime tests that exercise the new destination-routing matrix for the read
verb: create tests that call the wrapped read_verb.callback (use getattr(...,
"__wrapped__")) with destinations "terminal", "file", "clipboard", and "browser"
for both summary and --all (export_all=True) paths and assert correct dispatch
to polylogue.cli.query_verbs._execute_query_verb or
polylogue.cli.bulk_export.run_bulk_export as appropriate; also add cases
asserting a UsageError is raised for unsupported destination/output_format
combinations (e.g., --to=clipboard with output_format that isn't allowed) by
catching the UsageError type and verifying the message. Reference the existing
test helpers _context_pair and reuse the same argument shape as
test_read_verb_summary_dispatches_to_execute_query_verb and
test_read_verb_all_invokes_run_bulk_export when constructing these new tests so
the coverage locks the complex routing behavior.
|
Scope (v8 overlay review): this PR closes #1813 (read-surface unification) only — it is not #1842. It removes show/open/messages/raw/bulk-export/select/export, but Follow-up noted (Ref #1842): destination capture currently intercepts |
14b273b to
1384059
Compare
Replace the scattered show/open/bulk-export/messages/raw/select verbs
with a single `read` router verb that dispatches to existing renderers.
Remove the `export` root command entirely.
The new grammar is:
polylogue QUERY read [--view V] [--to D] [--format F] [--out PATH]
polylogue QUERY then read ... # optional `then` connector
Kept verbs: list, count, stats, recent, delete.
Removed verbs: show, open, bulk-export, messages, raw, select, export.
Changes:
- verb_names.py: VERB_NAMES updated to {list,count,stats,delete,recent,read}
- query_group.py: optional `then` connector in _split_query_mode_args
- query_verbs.py: complete rewrite — read_verb with --view/--to/--format/--out
dispatches to run_messages, run_raw, run_bulk_export, execute_query_request;
destination capture uses click.echo interception, no env.ui patching
- click_app.py: _QUERY_VERB_HELP updated; docstring examples updated
- click_command_registration.py: export root command removed
- shell_completion_values.py: complete_open_targets removed
- output_assurance.py: matrix updated to read verb only
- commands/commands.py: _COMMAND_CATEGORIES updated
- devtools/render_cli_reference.py: SECTIONS updated (open→read)
- Generated surfaces regenerated: cli-reference.md, topology-target.yaml,
AGENTS.md, docs/devtools.md, docs/openapi/search.yaml
Tests:
- test_export.py: deleted (export command removed)
- test_bulk_export.py: updated for read --all routing
- test_click_app.py: updated; read --view messages/raw tests added
- test_query_verbs_runtime.py: open/show/bulk_export tests replaced with read tests
- Other CLI test files updated to match new verb surface
Co-Authored-By: Claude <[email protected]>
docs/test-quality-workflows.md was out of sync after removing the export/show/open verbs from the CLI surface. Co-Authored-By: Claude <[email protected]>
…ead surface The read-action consolidation removed show/open/messages/raw/select/bulk-export/ export but left three generated/derived CLI surfaces stale, failing showcase-verify and test×3: - showcase help baselines: regenerate help-main.txt, add help-read.txt, drop the seven orphaned help-<removed>.txt baselines. - syrupy help/terminal snapshots: the help epilog examples now show `read` not `open`; regenerate test_help_snapshots/test_terminal_snapshots .ambr. - ASSURANCE_REGISTRY: drop the dead `export` OutputAssurance entry. test_json_status_snapshot is a pre-existing env-sensitive drift (fails on master too; method count is environment-dependent) and is intentionally not touched. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Problem: #1813 folded `open --print-url` into `read --to browser`, but the new browser route emitted human text ("✗ No sessions matched.") and exit 0 even for machine consumers. The integration test pinning the old contract (JSON no-results envelope + exit 2) failed, and the regression was real: a `--format json` request that matched nothing no longer returned a structured error. What changed: - `_run_read_browser` now emits the canonical `no_results` error envelope and exits 2 when JSON output is requested (on the verb via `read -f json` or on the root via `--format json … read`), mirroring the removed `_emit_open_no_results` json branch. - Migrated the integration test to the `read --to browser` grammar and renamed it accordingly. - Flagged the remaining pre-#1813 verb grammar in the #847-skipped tests so the daemon-fixture rewrite migrates rather than resurrects the removed verbs. Ref #1813
1384059 to
d3bdf88
Compare
#1867) ## Summary Rename the `read --view conversation` token to `transcript` to remove stale "conversation" vocabulary that #1863 reintroduced on public CLI surfaces, restoring the session/origin vocabulary policy from the #1810/#1852 sweep. ## Problem #1863 shipped `read --view conversation`. The public-surface audit (`tools/cleanup/polylogue_public_surface_audit.sh`, #1852) flags `conversation` as stale schema-v1 vocabulary on both `polylogue/cli/query_verbs.py` and the generated `docs/cli-reference.md`. The audit **false-passed in CI** — the Ubuntu-image ripgrep silently mishandles the audit's `rg` invocation (the #1854/#1855 shelled-binary-in-CI fragility) — so the violation landed on master uncaught. It deterministically fails the local pre-push gate (nix ripgrep), blocking every subsequent push. ## Solution - Rename the read view token `conversation` → `transcript` in `query_verbs.py` (`_READ_VIEWS`, help text, comment). The view has no distinct dispatch branch — it shares the summary fallthrough render path — so this is a pure token rename, no behavior change. - Regenerate `docs/cli-reference.md` and the `help-read.txt` showcase baseline. ## Verification - `tools/cleanup/polylogue_public_surface_audit.sh` → exit 0 (`clean (no stale schema-v1 vocabulary on public surfaces)`) - `mypy --strict polylogue/cli/query_verbs.py` → clean - `ruff check` → clean - `pytest tests/unit/cli -k "help or read or view"` → 433 passed, 4 snapshots passed ## Follow-up The CI audit's ripgrep false-pass is a real gap (CI did not catch this violation). The lint job's `rg` invocation hardening against the runner image is tracked separately (#1855 class).
|
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
Replaces the scattered
show/open/bulk-export/messages/raw/selectquery verbs and theexportroot command with a singlereadrouter verb. The verb dispatches to the existing renderers — nothing was rewritten, only routed.Problem
Six overlapping verbs (
show,open,messages,raw,bulk-export,select) and a separateexportroot command all did variations of "render a session". Each had its own option set, help text, and OutputAssurance entry. A new user had no obvious entry point and no way to do "read a session then send it to a file". The grammar was additive rather than composable.Solution
New grammar:
--viewselects the renderer:summary(default),conversation,messages,raw,context.--toselects the destination:terminal(default),stdout,browser,clipboard,file.Files changed:
polylogue/cli/verb_names.py— VERB_NAMES reduced to{list,count,stats,delete,recent,read}polylogue/cli/query_group.py— optionalthenconnector in_split_query_mode_argspolylogue/cli/query_verbs.py— complete replacement:read_verbrouting torun_messages,run_raw,run_bulk_export,execute_query_request; destination capture viaclick.echointerceptionpolylogue/cli/click_app.py—_QUERY_VERB_HELPupdated; docstring examples updatedpolylogue/cli/click_command_registration.py—exportroot command removedpolylogue/cli/shell_completion_values.py—complete_open_targetsremovedpolylogue/cli/output_assurance.py— matrix collapsed toreadentry onlypolylogue/cli/commands/commands.py—_COMMAND_CATEGORIESupdateddevtools/render_cli_reference.py— SECTIONS updated (open→read)tests/unit/cli/test_export.py— deleted (export command gone)Verification
Closes #1813
Co-Authored-By: Claude [email protected]
Summary by CodeRabbit
New Features
readcommand with configurable views and output routing via--to/--outoptions.thenconnector syntax in query commands (e.g.,find ... then read).Documentation