Skip to content

refactor: contract CLI, MCP, and UI surfaces over renewed substrate - #277

Merged
Sinity merged 5 commits into
masterfrom
feature/refactor/cli-mcp-ui-surface-contraction
Apr 20, 2026
Merged

Sinity merged 5 commits into
masterfrom
feature/refactor/cli-mcp-ui-surface-contraction

Conversation

@Sinity

@Sinity Sinity commented Apr 20, 2026 •

Copy link
Copy Markdown
Owner

Summary

Contract the CLI, MCP, and UI layers around typed request/output surfaces instead of raw dict envelopes and duplicated presentation glue.

Ref #273

Problem

After the substrate renewals, several surface paths still rebuilt semantics ad hoc:

  • query execution mixed raw param dicts, action routing, output destinations, and mutation flags without a stable contract
  • MCP/server helpers repeated their own query normalization and product-tool argument coercion
  • UI/rendering/check/schema helpers still carried presentation-side coercion and fallback logic that belonged in shared surface contracts
  • tests still targeted the older execute_query/raw-param seams, so the surface contraction work left stale routing assumptions behind

Solution

Introduce and propagate typed surface contracts across the query-first entrypoints and adjacent helpers:

  • add explicit CLI query contracts in polylogue/cli/query_contracts.py, polylogue/cli/query_feedback.py, and polylogue/cli/product_command_contracts.py
  • route polylogue/cli/query.py, query_actions.py, query_output.py, query_stats.py, query_semantic.py, query_verbs.py, and root_request.py through RootModeRequest, QueryExecutionPlan, QueryOutputSpec, QueryMutationSpec, and parsed delivery targets
  • simplify schema/check/helper/run support surfaces in polylogue/cli/check_options.py, check_rendering_plain.py, schema_command_support.py, schema_rendering_explain.py, schema_rendering_results.py, helper_summary.py, helpers.py, run_display_workflow.py, run_watch_workflow.py, and run_workflow.py
  • contract MCP/UI/rendering helpers in polylogue/mcp/query_contracts.py, product_tool_contracts.py, server_tools.py, server_prompts.py, server_resources.py, server_product_tools.py, polylogue/ui/facade.py, facade_console.py, facade_rendering.py, polylogue/rendering/blocks.py, core_messages.py, core_markdown.py, and renderers/html_messages.py
  • align CLI routing/query execution tests with the new typed request seam in tests/unit/cli/test_click_app.py, test_query_exec.py, and test_query_exec_laws.py

Verification

devtools verify
mypy tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py
pytest -q tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py
mypy tests/unit/cli/test_click_app.py
pytest -q tests/unit/cli/test_click_app.py
pytest -q tests/unit/cli/test_run.py tests/unit/cli/test_run_laws.py tests/unit/cli/test_source_selection_helpers.py tests/unit/ui/test_ui.py
pytest -q tests/unit/cli/test_check.py tests/unit/cli/test_cli_error_boundaries.py
pytest -q tests/unit/ui/test_ui.py tests/unit/mcp/test_server_surfaces.py tests/unit/rendering/test_rendering.py

@coderabbitai

coderabbitai Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces structured typed contracts throughout the CLI, MCP, and rendering layers, replacing loosely-typed dictionary-based parameter passing with strongly-typed dataclasses. It moves core query, product, and rendering definitions into dedicated contract modules and refactors call sites to use these new typed objects while tightening existing type annotations.

Changes

Cohort / File(s) Summary
Type Annotation Tightening
polylogue/cli/check_options.py, polylogue/cli/helpers.py, polylogue/cli/run_display_workflow.py, polylogue/cli/run_watch_workflow.py, polylogue/cli/run_workflow.py
Replaced Any types with concrete types (AppEnv, Config, RunResult, CheckCommandDecorator) in function parameters and annotations. No functional logic changes.
Query Contracts & Execution
polylogue/cli/query_contracts.py, polylogue/cli/query.py, polylogue/cli/query_feedback.py, polylogue/cli/query_actions.py, polylogue/cli/query_output.py, polylogue/cli/query_stats.py, polylogue/cli/query_semantic.py, polylogue/cli/query_verbs.py, polylogue/cli/root_request.py
Introduced new query_contracts module with typed dataclasses (QueryExecutionPlan, QueryOutputSpec, QueryMutationSpec, QueryAction, QueryRoute, etc.). Refactored query modules to use these contracts instead of dict-based parameters; updated RootModeRequest with transformation helpers.
Product Command Contracts
polylogue/cli/product_command_contracts.py, polylogue/cli/commands/products.py, polylogue/cli/products_rendering.py
Added new product_command_contracts module with ProductCommandRequest and helper functions. Updated products command and rendering to use typed request objects instead of manual context traversal.
Schema & Check Commands
polylogue/cli/commands/schema.py, polylogue/cli/check_rendering_plain.py, polylogue/cli/schema_command_support.py, polylogue/cli/schema_rendering_explain.py, polylogue/cli/schema_rendering_results.py
Refactored schema command helpers with centralized error handling and stronger type contracts. Updated rendering to use typed result objects (SchemaExplainResult, SchemaInferResult, etc.) instead of Any. Improved proof report access via typed attributes.
Helper Summary & Output
polylogue/cli/helper_summary.py
Replaced loose callback types with explicit typing.Protocol-based signatures. Added domain types (Config, Source, ReadinessReport, RuntimeServices, SQLiteBackend) to callback parameter annotations.
MCP Contracts & Tools
polylogue/mcp/query_contracts.py, polylogue/mcp/product_tool_contracts.py, polylogue/mcp/server_tools.py, polylogue/mcp/server_prompts.py, polylogue/mcp/server_resources.py, polylogue/mcp/server_product_tools.py
Introduced MCPConversationQueryRequest and ProductListToolSpec dataclasses for query/product tool contracts. Removed local helpers and replaced query spec building to use new typed request objects.
Rendering Core & Dispatch
polylogue/rendering/blocks.py, polylogue/rendering/core_messages.py, polylogue/rendering/core_markdown.py, polylogue/rendering/renderers/html_messages.py
Refactored rendering to use dispatch tables (dict-based router functions) instead of if/elif chains. Extracted timestamp/branch-index normalization and role CSS class generation into public functions. Replaced post-processing helpers with shared utilities.
UI/Console Facade
polylogue/ui/facade.py, polylogue/ui/facade_console.py, polylogue/ui/facade_rendering.py
Tightened console protocol types from Any to object. Added helpers (_render_plain_object, _render_panel, _print_plain_section) to consolidate rendering logic and reduce duplication.
Shell Completion
polylogue/cli/shell_completion_values.py
Introduced _rows_to_completion_items helper to centralize CompletionItem construction from database rows.
Tests
tests/unit/cli/test_click_app.py, tests/unit/cli/test_query_exec.py, tests/unit/cli/test_query_exec_laws.py
Updated test patching/assertions to use new typed request/spec objects. Added helper builders (_delivery_targets, _output_spec, _mutation_spec) for constructing typed contract instances in tests.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested labels

area:cli, type:refactor, type:typing

Poem

🐰 Contracts bind the chaotic flow,
Types replace the dicts below,
Dataclasses dance where params flowed,
Rendering roads now dispatch-bestowed!
Query plans emerge so bright and clear,
Typed contracts bring us good cheer! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main refactoring work: contracting CLI, MCP, and UI surfaces with typed request objects.
Description check ✅ Passed The description includes all required sections: Summary, Problem, Solution, and Verification with specific test commands. It comprehensively outlines the scope and rationale.

✏️ 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/cli-mcp-ui-surface-contraction

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.

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

Caution

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

⚠️ Outside diff range comments (2)
polylogue/rendering/core_messages.py (1)

41-45: ⚠️ Potential issue | 🟡 Minor

Catch OverflowError for invalid numeric timestamps.

datetime.fromtimestamp(...) raises OverflowError for out-of-range values, causing rendering to crash instead of returning None.

🛡️ Proposed fix
     if isinstance(timestamp, int | float):
         try:
             return datetime.fromtimestamp(float(timestamp), tz=timezone.utc).isoformat().replace("+00:00", "Z")
-        except (ValueError, OSError):
+        except (OverflowError, ValueError, OSError):
             return None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/rendering/core_messages.py` around lines 41 - 45, The except block
that currently catches (ValueError, OSError) around
datetime.fromtimestamp(float(timestamp), tz=timezone.utc) must also catch
OverflowError so out-of-range numeric timestamps return None instead of
crashing; update the exception tuple to include OverflowError in the try/except
that wraps datetime.fromtimestamp (the block handling the timestamp variable) so
the function returns None for invalid numeric timestamps.
polylogue/cli/query.py (1)

329-334: ⚠️ Potential issue | 🟡 Minor

Add an explicit return after no_results(env, params) in the SUMMARY_LIST branch.

no_results is only guaranteed to terminate via SystemExit when exit_code is non-None (the default is 2, so today this works). However, the signature explicitly permits exit_code=None:

def no_results(
    env: AppEnv,
    params: QueryParams,
    *,
    exit_code: int | None = 2,
) -> None:

If the default ever changes, a caller passes exit_code=None, or emit_no_results is later refactored, control falls through to _output_summary_list(env, [], plan.output, repo) and silently renders an empty summary list instead of surfacing the no-results condition. Every other route in this function exits or returns immediately after no_results/terminal actions — SUMMARY_LIST is the outlier.

🔧 Proposed defensive fix
     if route == QueryRoute.SUMMARY_LIST:
         summary_results = await filter_chain.list_summaries()
         if not summary_results:
             no_results(env, params)
+            return
         await _query_output._output_summary_list(env, summary_results, plan.output, repo)
         return
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/query.py` around lines 329 - 334, The SUMMARY_LIST branch can
fall through after calling no_results(env, params) if no_results doesn't exit;
update the QueryRoute.SUMMARY_LIST handling so that immediately after calling
no_results(env, params) you perform an explicit return to avoid calling
_query_output._output_summary_list with empty results; change the block around
QueryRoute.SUMMARY_LIST (where summary_results is set and no_results is invoked)
to return right after no_results to prevent further execution (affecting
symbols: route/QueryRoute.SUMMARY_LIST, summary_results, no_results,
_query_output._output_summary_list, plan.output, repo, env, params).
🤖 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/check_options.py`:
- Line 13: Add the new type alias CheckCommandDecorator to the module's public
exports by including "CheckCommandDecorator" in the __all__ list; locate the
__all__ declaration in the same module (around where CheckCommandDecorator =
Callable[[Callable[..., object]], Callable[..., object]] is defined) and append
the string name "CheckCommandDecorator" so the alias is exported.

In `@polylogue/cli/product_command_contracts.py`:
- Around line 39-73: The method ProductCommandRequest.from_context redundantly
re-checks inherited_root_keys against query_model_field_names
(accepted_root_keys) even though the caller already pre-filters those keys;
remove the duplicate guard in from_context by deleting the "if key not in
accepted_root_keys: continue" check and let the caller-provided
inherited_root_keys be trusted, keeping the rest of the loop (the existing
checks for existing normalized_kwargs values and inheriting root_params) intact;
update any local comment/docstring for from_context to note that
inherited_root_keys should already be filtered by query_model_field_names and
reference the query_model_field_names helper in the comment for clarity.
- Around line 31-37: ProductCommandRequest declares a mutable dict for
query_kwargs which breaks the frozen immutability guarantee; change the type
annotation from dict[str, object] to Mapping[str, object] and ensure the
instance holds an immutable mapping by wrapping any provided dict in
types.MappingProxyType inside ProductCommandRequest.__post_init__ (use
object.__setattr__ because the dataclass is frozen/slots). This preserves the
public API (accept dict inputs) but guarantees immutability for the stored
query_kwargs.

In `@polylogue/cli/query_feedback.py`:
- Around line 26-28: The JSON branch currently coerces exit_code with "exit_code
or 2" and always calls error_no_results(...).emit(), which both forces None/0 to
2 and always raises SystemExit; fix by only calling .emit() when you have an
actual integer exit code and returning early when exit_code is None. In the
block guarded by output_format == "json", replace the coercion with an explicit
None check: if exit_code is None then handle/return the resolved_message/filters
without calling .emit(), else call error_no_results(resolved_message,
filters=filters or None).emit(exit_code) using the integer exit_code; ensure you
reference the same resolved_message, filters and output_format symbols and do
not use "or" coercion on exit_code.

In `@polylogue/cli/query_stats.py`:
- Around line 104-134: The no-results path currently only emits structured
output for JSON; update emit_no_results so it accepts output_format and emits a
machine-parseable empty stats payload for JSON, YAML and CSV (not just human
text), and set exit_code=2 for these machine formats; then call emit_no_results
from output_stats_sql (and the other no-results call sites that pass
selection/output_format) without special-casing JSON so YAML/CSV also return
structured empty output and an exit code of 2 when no rows match. Ensure
references to emit_no_results, output_stats_sql, filter_chain.count, and
repo.get_archive_stats are updated accordingly.

In `@polylogue/cli/query_verbs.py`:
- Around line 82-86: The open-shortcut uses _parent_query_terms(ctx) which only
checks ctx.meta, causing a fallback to treat a colon-containing target term as
conv_id even when the typed RootModeRequest (request) already has query_terms;
change the check to use the typed request's query_terms (request.query_terms)
instead of calling _parent_query_terms(ctx) so the branch that calls
_execute_query_verb(request.with_param_updates(conv_id=...)) only triggers when
request.query_terms is empty; update the conditional around request =
_parent_request(ctx)... to reference request.query_terms and keep the subsequent
call sites to _execute_query_verb and append_query_terms unchanged.

In `@polylogue/cli/root_request.py`:
- Around line 70-74: The helpers with_query_terms and append_query_terms
incorrectly iterate strings (so with_query_terms("bug") -> ("b","u","g"));
update both to use the existing coerce_query_terms helper the same way
from_context/from_params do: in with_query_terms call replace(self,
query_terms=tuple(coerce_query_terms(query_terms))) and in append_query_terms
call self.with_query_terms(self.query_terms +
tuple(coerce_query_terms(extra_terms))) so single-string inputs are treated as
one term and other coercions are preserved.

In `@polylogue/cli/schema_rendering_explain.py`:
- Around line 21-27: _json_values and _json_entries are duplicate helpers that
both return the input if it's a list else an empty list; collapse them into a
single helper (e.g. _as_list) and update callers to use that helper (replace
references to _json_values and _json_entries with _as_list). Implement
_as_list(value: object) -> list[object] with the same behavior, remove the
redundant function, and adjust any imports/uses throughout the module so call
sites (places that invoked _json_values or _json_entries) now call _as_list.

In `@polylogue/cli/schema_rendering_results.py`:
- Around line 125-129: The code duplicates SchemaListResult serialization by
constructing a fallback payload instead of reusing the model's serializer;
change the branch that handles provider+json_output to call result.to_dict() and
pass that into emit_success (i.e., replace the conditional
emit_success(selected.to_dict() if selected is not None else {"provider":
provider, "versions": []}) with emit_success(result.to_dict())), keeping the
rest of the logic (provider check, return) intact; reference: result, selected,
SchemaListResult.to_dict(), emit_success, json_output, provider.

In `@polylogue/mcp/product_tool_contracts.py`:
- Around line 12-17: _sanitize_offset currently calls int(value) for
str/bytes/bytearray and will raise ValueError for non-numeric inputs, escaping
the intended safe fallback; update _sanitize_offset to keep the existing bool
check but wrap the int(value) conversion in a try/except (catching ValueError
and TypeError) and on exception return 0, otherwise return max(0,
int_converted); mention _sanitize_offset and normalize_kwargs so the sanitizer
is fixed where normalize_kwargs relies on it.
- Around line 66-73: The current creation of inspect.Parameter in
product_tool_contracts.py always sets default=None which silently makes required
fields optional; change the default logic to use inspect.Parameter.empty when
field_info.is_required() is True (i.e., set default=inspect.Parameter.empty if
field_info.is_required(), otherwise keep field_info.get_default(...)), and
ensure the annotation still uses field_info.annotation or object; alternatively,
if you prefer strictness, replace that branch with a guard that raises a clear
exception when field_info.is_required() is True to prevent silently converting
required fields to optional—update the code around parameters.append(...) where
inspect.Parameter is constructed to implement one of these behaviors.

In `@polylogue/mcp/query_contracts.py`:
- Line 54: The parameter type for build_spec's clamp_limit is currently declared
as Callable[[int | object], int], which collapses to object; change the
annotation to reflect intended input type—either Callable[[int], int] if
clamp_limit should accept ints only, or Callable[[object], int] if it
intentionally accepts arbitrary values to coerce; update the build_spec
signature accordingly (refer to the build_spec method) and adjust any
callers/tests if needed to match the chosen tighter or looser type.

In `@polylogue/rendering/blocks.py`:
- Around line 236-260: _MEDIA_BLOCK_TYPES are treated as structured-excluded and
HTML dispatch maps them to _noop_renderer, causing media-only blocks to be
dropped; update the code so media block types are included in
_STRUCTURED_BLOCK_TYPES where appropriate and replace the HTML renderer mapping
that uses _noop_renderer for _MEDIA_BLOCK_TYPES with the proper media HTML
renderer (e.g., _render_media_html) so that both _MARKDOWN_BLOCK_RENDERERS and
_HTML_BLOCK_RENDERERS handle media via _render_media_markdown/_render_media_html
and has_structured_blocks(...) will not omit media-only messages.

In `@polylogue/rendering/core_messages.py`:
- Around line 82-87: The current filtering builds mainline by excluding any
message where _mapping_branch_index(message) is truthy, which also drops branch
messages whose parent_message_id is None (root-level alternatives); instead,
adjust the logic that constructs mainline and mainline_by_parent so root-level
branch messages are preserved: when computing mainline from copied_messages keep
messages either with _mapping_branch_index(message) == 0 or with a non-None
parent (i.e., only exclude non-root branch messages that should not be
mainline), and when building mainline_by_parent (and the similar mappings around
lines 89-97 and 125-136) ensure you attach branch messages whose
parent_message_id is None into a separate root-level branch bucket rather than
dropping them, using the same helpers (_mapping_branch_index,
_mapping_parent_message_id) to identify and correctly classify root-level
branches.

In `@polylogue/ui/facade_console.py`:
- Around line 28-38: The plain-text renderer _render_plain_object() is treating
all strings as Rich markup which corrupts raw user content (used by
render_code()/render_markdown()); change it so that when obj is an instance of
str or when falling back to raw = str(obj) it returns the string directly (or
buf.getvalue().rstrip() for Table) without calling Text.from_markup(); only call
Text.from_markup() (or equivalent markup parsing) when the incoming object is
already a Rich Text instance or when an explicit markup flag/value indicates
markup should be parsed. Ensure references: _render_plain_object(),
render_code(), render_markdown(), and any use of Text.from_markup() are updated
accordingly.

---

Outside diff comments:
In `@polylogue/cli/query.py`:
- Around line 329-334: The SUMMARY_LIST branch can fall through after calling
no_results(env, params) if no_results doesn't exit; update the
QueryRoute.SUMMARY_LIST handling so that immediately after calling
no_results(env, params) you perform an explicit return to avoid calling
_query_output._output_summary_list with empty results; change the block around
QueryRoute.SUMMARY_LIST (where summary_results is set and no_results is invoked)
to return right after no_results to prevent further execution (affecting
symbols: route/QueryRoute.SUMMARY_LIST, summary_results, no_results,
_query_output._output_summary_list, plan.output, repo, env, params).

In `@polylogue/rendering/core_messages.py`:
- Around line 41-45: The except block that currently catches (ValueError,
OSError) around datetime.fromtimestamp(float(timestamp), tz=timezone.utc) must
also catch OverflowError so out-of-range numeric timestamps return None instead
of crashing; update the exception tuple to include OverflowError in the
try/except that wraps datetime.fromtimestamp (the block handling the timestamp
variable) so the function returns None for invalid numeric timestamps.
🪄 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: fa35b04c-97c1-4500-8dbd-b68ce43ad820

📥 Commits

Reviewing files that changed from the base of the PR and between 973c15a and 14ce089.

📒 Files selected for processing (40)
  • polylogue/cli/check_options.py
  • polylogue/cli/check_rendering_plain.py
  • polylogue/cli/commands/products.py
  • polylogue/cli/commands/schema.py
  • polylogue/cli/helper_summary.py
  • polylogue/cli/helpers.py
  • polylogue/cli/product_command_contracts.py
  • polylogue/cli/products_rendering.py
  • polylogue/cli/query.py
  • polylogue/cli/query_actions.py
  • polylogue/cli/query_contracts.py
  • polylogue/cli/query_feedback.py
  • polylogue/cli/query_output.py
  • polylogue/cli/query_semantic.py
  • polylogue/cli/query_stats.py
  • polylogue/cli/query_verbs.py
  • polylogue/cli/root_request.py
  • polylogue/cli/run_display_workflow.py
  • polylogue/cli/run_watch_workflow.py
  • polylogue/cli/run_workflow.py
  • polylogue/cli/schema_command_support.py
  • polylogue/cli/schema_rendering_explain.py
  • polylogue/cli/schema_rendering_results.py
  • polylogue/cli/shell_completion_values.py
  • polylogue/mcp/product_tool_contracts.py
  • polylogue/mcp/query_contracts.py
  • polylogue/mcp/server_product_tools.py
  • polylogue/mcp/server_prompts.py
  • polylogue/mcp/server_resources.py
  • polylogue/mcp/server_tools.py
  • polylogue/rendering/blocks.py
  • polylogue/rendering/core_markdown.py
  • polylogue/rendering/core_messages.py
  • polylogue/rendering/renderers/html_messages.py
  • polylogue/ui/facade.py
  • polylogue/ui/facade_console.py
  • polylogue/ui/facade_rendering.py
  • tests/unit/cli/test_click_app.py
  • tests/unit/cli/test_query_exec.py
  • tests/unit/cli/test_query_exec_laws.py

_MAINTENANCE_TARGET_HELP = build_maintenance_target_catalog().help_text()

CHECK_COMMAND_OPTION_DECORATORS: tuple[Callable[[Callable[..., Any]], Callable[..., Any]], ...] = (
CheckCommandDecorator = Callable[[Callable[..., object]], Callable[..., object]]

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

Export CheckCommandDecorator in __all__.

The new type alias is described as exported but is missing from __all__.

Proposed change
-__all__ = ["CHECK_COMMAND_OPTION_DECORATORS", "apply_check_command_options"]
+__all__ = ["CHECK_COMMAND_OPTION_DECORATORS", "CheckCommandDecorator", "apply_check_command_options"]

Also applies to: 113-113

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

In `@polylogue/cli/check_options.py` at line 13, Add the new type alias
CheckCommandDecorator to the module's public exports by including
"CheckCommandDecorator" in the __all__ list; locate the __all__ declaration in
the same module (around where CheckCommandDecorator = Callable[[Callable[...,
object]], Callable[..., object]] is defined) and append the string name
"CheckCommandDecorator" so the alias is exported.

Comment on lines +31 to +37
@dataclass(frozen=True, slots=True)
class ProductCommandRequest:
"""Normalized product command request shared by all product subcommands."""

query_kwargs: dict[str, object]
output_format: str | None
json_mode: bool

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

Minor: mutable dict on a frozen/slots dataclass.

query_kwargs: dict[str, object] is mutable and shared by reference — callers can mutate a ProductCommandRequest in-place despite frozen=True. Consider exposing it as Mapping[str, object] (or freezing to a MappingProxyType) to make the immutability contract real.

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

In `@polylogue/cli/product_command_contracts.py` around lines 31 - 37,
ProductCommandRequest declares a mutable dict for query_kwargs which breaks the
frozen immutability guarantee; change the type annotation from dict[str, object]
to Mapping[str, object] and ensure the instance holds an immutable mapping by
wrapping any provided dict in types.MappingProxyType inside
ProductCommandRequest.__post_init__ (use object.__setattr__ because the
dataclass is frozen/slots). This preserves the public API (accept dict inputs)
but guarantees immutability for the stored query_kwargs.

Comment on lines +39 to +73
@classmethod
def from_context(
cls,
ctx: click.Context,
product_type: ProductType,
*,
json_mode: bool,
output_format: str | None,
kwargs: Mapping[str, object],
inherited_root_keys: tuple[str, ...],
) -> ProductCommandRequest:
root_params = find_root_params(ctx)
accepted_root_keys = query_model_field_names(product_type)
normalized_kwargs = dict(kwargs)

for key in inherited_root_keys:
if key not in accepted_root_keys:
continue
if normalized_kwargs.get(key) is not None:
continue
inherited_value = root_params.get(key)
if inherited_value is not None:
normalized_kwargs[key] = inherited_value

resolved_output_format = output_format
if resolved_output_format is None:
root_output_format = root_params.get("output_format")
if isinstance(root_output_format, str):
resolved_output_format = root_output_format

return cls(
query_kwargs=normalized_kwargs,
output_format=resolved_output_format,
json_mode=json_mode,
)

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 filtering vs. caller — intentional?

inherited_root_keys is already filtered by query_model_field_names(pt) at the call site in commands/products.py (Line 90), and from_context filters again via accepted_root_keys. Not a bug, but one of the two filters is dead weight; consider either dropping the pre-filter at the call site (let from_context own the policy) or trusting the caller here and removing the if key not in accepted_root_keys: continue guard.

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

In `@polylogue/cli/product_command_contracts.py` around lines 39 - 73, The method
ProductCommandRequest.from_context redundantly re-checks inherited_root_keys
against query_model_field_names (accepted_root_keys) even though the caller
already pre-filters those keys; remove the duplicate guard in from_context by
deleting the "if key not in accepted_root_keys: continue" check and let the
caller-provided inherited_root_keys be trusted, keeping the rest of the loop
(the existing checks for existing normalized_kwargs values and inheriting
root_params) intact; update any local comment/docstring for from_context to note
that inherited_root_keys should already be filtered by query_model_field_names
and reference the query_model_field_names helper in the comment for clarity.

Comment on lines +26 to +28
if output_format == "json":
error_no_results(resolved_message, filters=filters or None).emit(exit_code=exit_code or 2)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect MachineError.emit behavior without modifying files.
rg -n -C 8 'class MachineError|def emit\s*\('

Repository: Sinity/polylogue

Length of output: 6550


Fix exit code coercion and proper termination for JSON output.

exit_code or 2 coerces both None and 0 to 2, preventing the advertised non-terminating behavior when exit_code=None. However, .emit() always raises SystemExit(exit_code) and does not return, so code cannot fall through. The solution is to only call .emit() with a valid integer exit code, or return early when exit_code is None:

🐛 Proposed fix
     if output_format == "json":
-        error_no_results(resolved_message, filters=filters or None).emit(exit_code=exit_code or 2)
+        if exit_code is None:
+            return
+        error_no_results(resolved_message, filters=filters or None).emit(exit_code=exit_code)
📝 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
if output_format == "json":
error_no_results(resolved_message, filters=filters or None).emit(exit_code=exit_code or 2)
if output_format == "json":
if exit_code is None:
return
error_no_results(resolved_message, filters=filters or None).emit(exit_code=exit_code)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/query_feedback.py` around lines 26 - 28, The JSON branch
currently coerces exit_code with "exit_code or 2" and always calls
error_no_results(...).emit(), which both forces None/0 to 2 and always raises
SystemExit; fix by only calling .emit() when you have an actual integer exit
code and returning early when exit_code is None. In the block guarded by
output_format == "json", replace the coercion with an explicit None check: if
exit_code is None then handle/return the resolved_message/filters without
calling .emit(), else call error_no_results(resolved_message, filters=filters or
None).emit(exit_code) using the integer exit_code; ensure you reference the same
resolved_message, filters and output_format symbols and do not use "or" coercion
on exit_code.

Comment on lines +104 to +134
emit_no_results(
env,
selection=selection,
output_format=output_format,
exit_code=2 if output_format == "json" else None,
)
return
conv_ids = [str(summary.id) for summary in summaries]
conv_count = len(conv_ids)
else:
conv_count = await filter_chain.count()
if conv_count == 0:
if output_format == "json":
error_no_results("No conversations matched.", filters=described_filters).emit(exit_code=2)
env.ui.console.print("No conversations matched.")
emit_no_results(
env,
selection=selection,
output_format=output_format,
exit_code=2 if output_format == "json" else None,
)
return
conv_ids = None
else:
conv_ids = None
archive_stats = await repo.get_archive_stats()
conv_count = archive_stats.total_conversations
if conv_count == 0:
if output_format == "json":
error_no_results("No conversations in archive.").emit(exit_code=2)
env.ui.console.print("No conversations in archive.")
emit_no_results(
env,
output_format=output_format,
message="No conversations in archive.",
exit_code=2 if output_format == "json" else None,
)

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

Keep YAML/CSV no-result stats responses machine-parseable.

emit_no_results only emits structured output for JSON; for YAML/CSV it prints human text. In output_stats_sql, those non-JSON machine formats also return with exit_code=None, so polylogue stats --format yaml|csv can produce non-parseable text with a success status when no rows match. Use a format-aware empty structured stats payload or extend the no-results helper for all machine formats.

Also applies to: 241-242, 573-574, 656-657

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

In `@polylogue/cli/query_stats.py` around lines 104 - 134, The no-results path
currently only emits structured output for JSON; update emit_no_results so it
accepts output_format and emits a machine-parseable empty stats payload for
JSON, YAML and CSV (not just human text), and set exit_code=2 for these machine
formats; then call emit_no_results from output_stats_sql (and the other
no-results call sites that pass selection/output_format) without special-casing
JSON so YAML/CSV also return structured empty output and an exit code of 2 when
no rows match. Ensure references to emit_no_results, output_stats_sql,
filter_chain.count, and repo.get_archive_stats are updated accordingly.

Comment on lines +66 to +73
parameters.append(
inspect.Parameter(
field_name,
inspect.Parameter.KEYWORD_ONLY,
default=None if field_info.is_required() else field_info.get_default(call_default_factory=True),
annotation=field_info.annotation if field_info.annotation is not None else object,
)
)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Enumerate query_model classes registered in PRODUCT_REGISTRY and flag required fields.
rg -nP --type=py -C3 'query_model\s*=' 
rg -nP --type=py -C2 'class\s+\w+\(ArchiveProductModel\)'

Repository: Sinity/polylogue

Length of output: 14213


🏁 Script executed:

#!/bin/bash
# Find where query model classes are defined
fd -t py . | xargs grep -l "class SessionProfileProductQuery\|class SessionEnrichmentProductQuery\|class SessionWorkEventProductQuery\|class SessionPhaseProductQuery\|class WorkThreadProductQuery\|class SessionTagRollupQuery\|class DaySessionSummaryProductQuery\|class WeekSessionSummaryProductQuery\|class ProviderAnalyticsProductQuery"

Repository: Sinity/polylogue

Length of output: 231


🏁 Script executed:

#!/bin/bash
# Find query model class definitions - search all Python files
rg -n "^class (SessionProfileProductQuery|SessionEnrichmentProductQuery|SessionWorkEventProductQuery|SessionPhaseProductQuery|WorkThreadProductQuery|SessionTagRollupQuery|DaySessionSummaryProductQuery|WeekSessionSummaryProductQuery|ProviderAnalyticsProductQuery)" --type py -A 20

Repository: Sinity/polylogue

Length of output: 3117


🏁 Script executed:

#!/bin/bash
# Find parent class definitions for query models
rg -n "^class (SessionWindowProductQuery|SearchableConversationTimelineProductQuery|ConversationTimelineWindowProductQuery|SearchableTimeWindowProductQuery|ProviderSearchProductQuery|ProviderTimeWindowProductQuery|PaginatedProductQuery)" --type py -A 15

Repository: Sinity/polylogue

Length of output: 3176


🏁 Script executed:

#!/bin/bash
# Check ArchiveProductModel definition
rg -n "^class ArchiveProductModel" --type py -A 10

Repository: Sinity/polylogue

Length of output: 940


No required fields found in registered query models.

All registered product query models define only optional fields (all with explicit defaults: None, numeric values, or strings). The code pattern at lines 66-73 that assigns default=None for required fields is not currently problematic because no query models declare required fields. However, the pattern itself remains fragile—if a query model with required fields were registered, this code would silently convert them to optional parameters in the MCP schema, masking the intent. Consider either:

  • Using inspect.Parameter.empty for truly required fields (no default) so the MCP schema enforces them at call time, or
  • Adding a safeguard that raises an error if a required field is encountered.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/mcp/product_tool_contracts.py` around lines 66 - 73, The current
creation of inspect.Parameter in product_tool_contracts.py always sets
default=None which silently makes required fields optional; change the default
logic to use inspect.Parameter.empty when field_info.is_required() is True
(i.e., set default=inspect.Parameter.empty if field_info.is_required(),
otherwise keep field_info.get_default(...)), and ensure the annotation still
uses field_info.annotation or object; alternatively, if you prefer strictness,
replace that branch with a guard that raises a clear exception when
field_info.is_required() is True to prevent silently converting required fields
to optional—update the code around parameters.append(...) where
inspect.Parameter is constructed to implement one of these behaviors.

min_words: int | None = None
limit: int = 10

def build_spec(self, clamp_limit: Callable[[int | object], int]) -> ConversationQuerySpec:

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

Nit: int | object collapses to object.

Callable[[int | object], int] is equivalent to Callable[[object], int] under PEP 604 union semantics — the int arm adds no information. If the intent is "accepts int but tolerates other types that clamp_limit will coerce," either narrow to Callable[[int], int] or make the looseness explicit with Callable[[object], int].

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

In `@polylogue/mcp/query_contracts.py` at line 54, The parameter type for
build_spec's clamp_limit is currently declared as Callable[[int | object], int],
which collapses to object; change the annotation to reflect intended input
type—either Callable[[int], int] if clamp_limit should accept ints only, or
Callable[[object], int] if it intentionally accepts arbitrary values to coerce;
update the build_spec signature accordingly (refer to the build_spec method) and
adjust any callers/tests if needed to match the chosen tighter or looser type.

Comment on lines +236 to +260
_MEDIA_BLOCK_TYPES = frozenset(
{
ContentBlockType.IMAGE.value,
ContentBlockType.DOCUMENT.value,
"file",
}
)


_MARKDOWN_BLOCK_RENDERERS: dict[str, Callable[[RenderableBlock], str]] = {
ContentBlockType.THINKING.value: _render_thinking_markdown,
ContentBlockType.TOOL_USE.value: _render_tool_use_markdown,
ContentBlockType.TOOL_RESULT.value: _render_tool_result_markdown,
ContentBlockType.CODE.value: _render_code_markdown,
**dict.fromkeys(_MEDIA_BLOCK_TYPES, _render_media_markdown),
}


_HTML_BLOCK_RENDERERS: dict[str, Callable[[RenderableBlock], str]] = {
ContentBlockType.THINKING.value: _render_thinking_html,
ContentBlockType.TOOL_USE.value: _render_tool_use_html,
ContentBlockType.TOOL_RESULT.value: _render_tool_result_html,
ContentBlockType.CODE.value: _render_code_html,
**dict.fromkeys(_MEDIA_BLOCK_TYPES, _noop_renderer),
}

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

Do not drop media-only content blocks.

image/document/file blocks are excluded from _STRUCTURED_BLOCK_TYPES, and HTML dispatch maps them to _noop_renderer. Surfaces gated by has_structured_blocks(...) can therefore omit media-only messages entirely.

🐛 Proposed fix
+def _render_media_html(block: RenderableBlock) -> str:
+    url = block.url or ""
+    mime = block.mime_type or ""
+    name = escape(block.name or block.type)
+    label = f'<a href="{escape(url, quote=True)}">{name}</a>' if url else name
+    meta = f' <span class="media-mime">({escape(mime)})</span>' if mime else ""
+    return f'<div class="media-block">{label}{meta}</div>'
+
+
 _HTML_BLOCK_RENDERERS: dict[str, Callable[[RenderableBlock], str]] = {
     ContentBlockType.THINKING.value: _render_thinking_html,
     ContentBlockType.TOOL_USE.value: _render_tool_use_html,
     ContentBlockType.TOOL_RESULT.value: _render_tool_result_html,
     ContentBlockType.CODE.value: _render_code_html,
-    **dict.fromkeys(_MEDIA_BLOCK_TYPES, _noop_renderer),
+    **dict.fromkeys(_MEDIA_BLOCK_TYPES, _render_media_html),
 }
-_STRUCTURED_BLOCK_TYPES = {
+_STRUCTURED_BLOCK_TYPES = {
     ContentBlockType.THINKING.value,
     ContentBlockType.TOOL_USE.value,
     ContentBlockType.TOOL_RESULT.value,
     ContentBlockType.CODE.value,
-}
+} | _MEDIA_BLOCK_TYPES

Also applies to: 291-296

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

In `@polylogue/rendering/blocks.py` around lines 236 - 260, _MEDIA_BLOCK_TYPES are
treated as structured-excluded and HTML dispatch maps them to _noop_renderer,
causing media-only blocks to be dropped; update the code so media block types
are included in _STRUCTURED_BLOCK_TYPES where appropriate and replace the HTML
renderer mapping that uses _noop_renderer for _MEDIA_BLOCK_TYPES with the proper
media HTML renderer (e.g., _render_media_html) so that both
_MARKDOWN_BLOCK_RENDERERS and _HTML_BLOCK_RENDERERS handle media via
_render_media_markdown/_render_media_html and has_structured_blocks(...) will
not omit media-only messages.

Comment on lines +82 to +87
mainline = [message for message in copied_messages if not _mapping_branch_index(message)]
mainline_by_parent = {
parent_message_id: message
for message in mainline
if (parent_message_id := _mapping_parent_message_id(message)) is not None
}

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

Preserve root-level branch messages instead of dropping them.

A branch with branch_index != 0 and parent_message_id is None is neither included in mainline nor attached, so root-level alternatives disappear from the rendered output.

🐛 Proposed fix
-    mainline_by_parent = {
-        parent_message_id: message
-        for message in mainline
-        if (parent_message_id := _mapping_parent_message_id(message)) is not None
-    }
+    mainline_by_parent = {_mapping_parent_message_id(message): message for message in mainline}
 
     for message in copied_messages:
         branch_index = _mapping_branch_index(message)
         parent_message_id = _mapping_parent_message_id(message)
-        if not branch_index or parent_message_id is None:
+        if not branch_index:
             continue
         sibling = mainline_by_parent.get(parent_message_id)
         if sibling is None:
             mainline.append(message)
             continue
-        mainline_by_parent = {
-            message.parent_message_id: message for message in mainline if message.parent_message_id is not None
-        }
+        mainline_by_parent = {message.parent_message_id: message for message in mainline}
 
         for message in typed_messages:
-            if not message.branch_index or message.parent_message_id is None:
+            if not message.branch_index:
                 continue
             sibling = mainline_by_parent.get(message.parent_message_id)
             if sibling is None:
                 mainline.append(message)
                 continue

Also applies to: 89-97, 125-136

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

In `@polylogue/rendering/core_messages.py` around lines 82 - 87, The current
filtering builds mainline by excluding any message where
_mapping_branch_index(message) is truthy, which also drops branch messages whose
parent_message_id is None (root-level alternatives); instead, adjust the logic
that constructs mainline and mainline_by_parent so root-level branch messages
are preserved: when computing mainline from copied_messages keep messages either
with _mapping_branch_index(message) == 0 or with a non-None parent (i.e., only
exclude non-root branch messages that should not be mainline), and when building
mainline_by_parent (and the similar mappings around lines 89-97 and 125-136)
ensure you attach branch messages whose parent_message_id is None into a
separate root-level branch bucket rather than dropping them, using the same
helpers (_mapping_branch_index, _mapping_parent_message_id) to identify and
correctly classify root-level branches.

Comment on lines +28 to +38
if isinstance(obj, str):
return _plain_text_from_markup(obj)

if isinstance(obj, Table):
buf = io.StringIO()
tmp = RichConsole(file=buf, highlight=False, no_color=True)
tmp.print(obj)
return buf.getvalue().rstrip()

raw = str(obj)
return _plain_text_from_markup(raw)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Demonstrate how Rich markup parsing can transform plain strings.
python - <<'PY'
from rich.text import Text

samples = [
    "[bold]styled[/]",
    "markdown [bold](https://example.com)",
    "literal [red] marker in user text",
    "array[index] = value",
]

for sample in samples:
    try:
        rendered = Text.from_markup(sample).plain
    except Exception as exc:
        rendered = f"<raised {type(exc).__name__}: {exc}>"
    print(f"{sample!r} -> {rendered!r}")
PY

Repository: Sinity/polylogue

Length of output: 276


🏁 Script executed:

# First, locate the _plain_text_from_markup function and PlainConsole implementation
rg -n "_plain_text_from_markup" polylogue/

Repository: Sinity/polylogue

Length of output: 292


🏁 Script executed:

# Check the implementation of PlainConsole
rg -n "class PlainConsole" polylogue/

Repository: Sinity/polylogue

Length of output: 113


🏁 Script executed:

# Check render_code and render_markdown implementations
rg -n "def render_code|def render_markdown" polylogue/

Repository: Sinity/polylogue

Length of output: 764


🏁 Script executed:

# Look at the actual usage of PlainConsole.print in render functions
rg -n "plain_console\.print|PlainConsole" polylogue/ -A 3 -B 3

Repository: Sinity/polylogue

Length of output: 1961


🏁 Script executed:

# Read the _plain_text_from_markup implementation
sed -n '19,40p' polylogue/ui/facade_console.py

Repository: Sinity/polylogue

Length of output: 624


🏁 Script executed:

# Read the render_code and render_markdown implementations
sed -n '92,130p' polylogue/ui/facade_rendering.py

Repository: Sinity/polylogue

Length of output: 973


Preserve raw content in plain-text rendering mode.

Raw user content passed to render_code(), render_markdown(), and similar functions in plain mode gets corrupted by Text.from_markup(). For example, code containing array[index] becomes array, and markdown with bracket syntax loses delimiters. This happens because _render_plain_object() treats all strings as Rich markup even when they're user-authored raw content.

Return strings and raw conversions directly without markup parsing; only apply Text.from_markup() to actual Text objects and explicit markup values:

Proposed fix
 if isinstance(obj, str):
-    return _plain_text_from_markup(obj)
+    return obj
 
 if isinstance(obj, Table):
     buf = io.StringIO()
     tmp = RichConsole(file=buf, highlight=False, no_color=True)
     tmp.print(obj)
     return buf.getvalue().rstrip()
 
 raw = str(obj)
-return _plain_text_from_markup(raw)
+return raw
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/ui/facade_console.py` around lines 28 - 38, The plain-text renderer
_render_plain_object() is treating all strings as Rich markup which corrupts raw
user content (used by render_code()/render_markdown()); change it so that when
obj is an instance of str or when falling back to raw = str(obj) it returns the
string directly (or buf.getvalue().rstrip() for Table) without calling
Text.from_markup(); only call Text.from_markup() (or equivalent markup parsing)
when the incoming object is already a Rich Text instance or when an explicit
markup flag/value indicates markup should be parsed. Ensure references:
_render_plain_object(), render_code(), render_markdown(), and any use of
Text.from_markup() are updated accordingly.

@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: 14ce089ba9

ℹ️ 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".

@mcp.resource("polylogue://conversations")
async def conversations_resource() -> str:
convs = await build_query_spec().list(hooks.get_query_store())
convs = await MCPConversationQueryRequest().build_spec(hooks.clamp_limit).list(hooks.get_query_store())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Remove unintended default cap from conversations resource

The polylogue://conversations resource is now built from MCPConversationQueryRequest() with no explicit limit, but that request type defaults limit to 10; this silently truncates the resource to 10 conversations whenever the archive is larger. Before this refactor the same resource used build_query_spec() with no limit, so callers got the full list. Because this resource has no pagination/filter inputs, clients cannot recover the missing rows once truncated.

Useful? React with 👍 / 👎.

@Sinity
Sinity merged commit f706f45 into master Apr 20, 2026
14 checks passed
@Sinity
Sinity deleted the feature/refactor/cli-mcp-ui-surface-contraction branch April 20, 2026 19:58
Sinity added a commit that referenced this pull request Apr 22, 2026
…277)

## Summary

Contract the CLI, MCP, and UI layers around typed request/output surfaces instead of raw dict envelopes and duplicated presentation glue.

Ref #273

## Problem

After the substrate renewals, several surface paths still rebuilt semantics ad hoc:

- query execution mixed raw param dicts, action routing, output destinations, and mutation flags without a stable contract
- MCP/server helpers repeated their own query normalization and product-tool argument coercion
- UI/rendering/check/schema helpers still carried presentation-side coercion and fallback logic that belonged in shared surface contracts
- tests still targeted the older `execute_query`/raw-param seams, so the surface contraction work left stale routing assumptions behind

## Solution

Introduce and propagate typed surface contracts across the query-first entrypoints and adjacent helpers:

- add explicit CLI query contracts in `polylogue/cli/query_contracts.py`, `polylogue/cli/query_feedback.py`, and `polylogue/cli/product_command_contracts.py`
- route `polylogue/cli/query.py`, `query_actions.py`, `query_output.py`, `query_stats.py`, `query_semantic.py`, `query_verbs.py`, and `root_request.py` through `RootModeRequest`, `QueryExecutionPlan`, `QueryOutputSpec`, `QueryMutationSpec`, and parsed delivery targets
- simplify schema/check/helper/run support surfaces in `polylogue/cli/check_options.py`, `check_rendering_plain.py`, `schema_command_support.py`, `schema_rendering_explain.py`, `schema_rendering_results.py`, `helper_summary.py`, `helpers.py`, `run_display_workflow.py`, `run_watch_workflow.py`, and `run_workflow.py`
- contract MCP/UI/rendering helpers in `polylogue/mcp/query_contracts.py`, `product_tool_contracts.py`, `server_tools.py`, `server_prompts.py`, `server_resources.py`, `server_product_tools.py`, `polylogue/ui/facade.py`, `facade_console.py`, `facade_rendering.py`, `polylogue/rendering/blocks.py`, `core_messages.py`, `core_markdown.py`, and `renderers/html_messages.py`
- align CLI routing/query execution tests with the new typed request seam in `tests/unit/cli/test_click_app.py`, `test_query_exec.py`, and `test_query_exec_laws.py`

## Verification

```bash
devtools verify
mypy tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py
pytest -q tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py
mypy tests/unit/cli/test_click_app.py
pytest -q tests/unit/cli/test_click_app.py
pytest -q tests/unit/cli/test_run.py tests/unit/cli/test_run_laws.py tests/unit/cli/test_source_selection_helpers.py tests/unit/ui/test_ui.py
pytest -q tests/unit/cli/test_check.py tests/unit/cli/test_cli_error_boundaries.py
pytest -q tests/unit/ui/test_ui.py tests/unit/mcp/test_server_surfaces.py tests/unit/rendering/test_rendering.py
```
Sinity added a commit that referenced this pull request Apr 22, 2026
…277)

After the substrate renewals, several surface paths still rebuilt
semantics ad hoc: query execution mixed raw param dicts, action
routing, output destinations, and mutation flags without a stable
contract; MCP/server helpers repeated their own query normalization
and product-tool argument coercion; UI/rendering/check/schema
helpers carried presentation-side coercion and fallback logic that
belonged in shared surface contracts; tests still targeted the older
`execute_query` / raw-param seams.

Introduces explicit CLI query contracts in `cli/query_contracts.py`,
`cli/query_feedback.py`, and `cli/product_command_contracts.py`.
Routes `cli/query.py`, `query_actions.py`, `query_output.py`,
`query_stats.py`, `query_semantic.py`, `query_verbs.py`, and
`root_request.py` through `RootModeRequest`, `QueryExecutionPlan`,
`QueryOutputSpec`, `QueryMutationSpec`, and parsed delivery targets.
Simplifies schema/check/helper/run support surfaces (check_options,
check_rendering_plain, schema_command_support, schema_rendering_*,
helpers, run_display_workflow, run_watch_workflow, run_workflow).
Contracts MCP/UI/rendering helpers (`mcp/query_contracts.py`,
`product_tool_contracts.py`, server_tools, server_prompts,
server_resources, server_product_tools, ui/facade*, rendering/
blocks, core_messages, core_markdown, renderers/html_messages).
Aligns CLI routing/query execution tests with the new typed request
seam.

Verification: devtools verify; mypy + pytest over query_exec,
click_app, run, source_selection, UI, check, error-boundaries,
MCP, and rendering suites.

Ref #273
Sinity added a commit that referenced this pull request Apr 22, 2026
…277)

After the substrate renewals, several surface paths still rebuilt
semantics ad hoc: query execution mixed raw param dicts, action
routing, output destinations, and mutation flags without a stable
contract; MCP/server helpers repeated their own query normalization
and product-tool argument coercion; UI/rendering/check/schema
helpers carried presentation-side coercion and fallback logic that
belonged in shared surface contracts; tests still targeted the older
`execute_query` / raw-param seams.

Introduces explicit CLI query contracts in `cli/query_contracts.py`,
`cli/query_feedback.py`, and `cli/product_command_contracts.py`.
Routes `cli/query.py`, `query_actions.py`, `query_output.py`,
`query_stats.py`, `query_semantic.py`, `query_verbs.py`, and
`root_request.py` through `RootModeRequest`, `QueryExecutionPlan`,
`QueryOutputSpec`, `QueryMutationSpec`, and parsed delivery targets.
Simplifies schema/check/helper/run support surfaces (check_options,
check_rendering_plain, schema_command_support, schema_rendering_*,
helpers, run_display_workflow, run_watch_workflow, run_workflow).
Contracts MCP/UI/rendering helpers (`mcp/query_contracts.py`,
`product_tool_contracts.py`, server_tools, server_prompts,
server_resources, server_product_tools, ui/facade*, rendering/
blocks, core_messages, core_markdown, renderers/html_messages).
Aligns CLI routing/query execution tests with the new typed request
seam.

Verification: devtools verify; mypy + pytest over query_exec,
click_app, run, source_selection, UI, check, error-boundaries,
MCP, and rendering suites.

Ref #273
Sinity added a commit that referenced this pull request Apr 22, 2026
…277)

After the substrate renewals, several surface paths still rebuilt
semantics ad hoc: query execution mixed raw param dicts, action
routing, output destinations, and mutation flags without a stable
contract; MCP/server helpers repeated their own query normalization
and product-tool argument coercion; UI/rendering/check/schema
helpers carried presentation-side coercion and fallback logic that
belonged in shared surface contracts; tests still targeted the older
`execute_query` / raw-param seams.

Introduces explicit CLI query contracts in `cli/query_contracts.py`,
`cli/query_feedback.py`, and `cli/product_command_contracts.py`.
Routes `cli/query.py`, `query_actions.py`, `query_output.py`,
`query_stats.py`, `query_semantic.py`, `query_verbs.py`, and
`root_request.py` through `RootModeRequest`, `QueryExecutionPlan`,
`QueryOutputSpec`, `QueryMutationSpec`, and parsed delivery targets.
Simplifies schema/check/helper/run support surfaces (check_options,
check_rendering_plain, schema_command_support, schema_rendering_*,
helpers, run_display_workflow, run_watch_workflow, run_workflow).
Contracts MCP/UI/rendering helpers (`mcp/query_contracts.py`,
`product_tool_contracts.py`, server_tools, server_prompts,
server_resources, server_product_tools, ui/facade*, rendering/
blocks, core_messages, core_markdown, renderers/html_messages).
Aligns CLI routing/query execution tests with the new typed request
seam.

Verification: devtools verify; mypy + pytest over query_exec,
click_app, run, source_selection, UI, check, error-boundaries,
MCP, and rendering suites.

Ref #273
@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. 3 finding(s) confirmed still present → tracked in #550.

@Sinity
Sinity requested a review from Copilot May 1, 2026 00:43
@Sinity
Sinity requested review from Copilot and removed request for Copilot May 1, 2026 01:05
@Sinity
Sinity removed the request for review from Copilot May 1, 2026 02:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant