Skip to content

refactor(query): converge read surfaces onto one query/response contract (#1749) - #1763

Merged
Sinity merged 6 commits into
masterfrom
feature/refactor/issue-1749-read-surface-coherence
May 31, 2026
Merged

Sinity merged 6 commits into
masterfrom
feature/refactor/issue-1749-read-surface-coherence

Conversation

@Sinity

@Sinity Sinity commented May 31, 2026 •

Copy link
Copy Markdown
Owner

Summary

Converges the four read surfaces (CLI, MCP, daemon HTTP, Python API/ConversationFilter) onto one query/response contract, resolving the drift catalogued in #1749. Implemented in v22 vocabulary (no provider→origin/conversation→session rename — that is separate future work).

DRAFT — verification incomplete. The production implementation is complete and passes ruff format --check, ruff check, and mypy --strict on all 11 changed files. Not yet done: the focused regression tests called out below, and a full devtools verify/pytest run. This branch was produced by an agent that hit a session quota after the implementation commits but before adding tests or running the suite. Do not merge until the tests land and devtools verify is green.

Problem

The four read surfaces had drifted on defaults, ceilings, error contracts, parameter typing, and vocabulary — including live footguns: latest="false" truthy-collapsing MCP results to one conversation; an uncapped CLI query-first fetch (10000); a daemon vector-only query returning an opaque 500; retrieval_lane stringly-typed with dead "semantic" drift. Full catalogue and file:line in #1749.

Solution

Per the scope comment on #1749 (the canonical contract + the AC#2/AC#7 decisions). Touches: archive/query/spec.py, archive/query/retrieval_candidates.py, cli/query.py (dead duplicate parser removed), cli/query_output.py, cli/root_request.py, daemon/http.py, mcp/{query_contracts,server_support,server_tools}.py, storage/sqlite/queries/stats.py, surfaces/payloads.py.

  • retrieval_lane → one validated closed enum, unknown values rejected at the spec boundary; dead "semantic" drift removed.
  • latest → real boolean everywhere (kills the bool("false")==True collapse).
  • limit → shared MAX_QUERY_LIMIT = 1000 ceiling; CLI query-first default cap; daemon /api/conversations clamps.
  • --lexical + --semantic/--similar, and --semantic with no query → UsageError.
  • daemon vector-only → typed EmbeddingRetrievalNotReadyError (409), not 500.
  • SearchEnvelope.total (AC#2) → uniformly computed via shared spec.count() on all four surfaces; None retained only for the genuine no-spec case.
  • get_stats_by (AC#7) → expanded to provider/month/year/day (substrate dims); insight dims explicitly scoped as a CLI aggregation surface.
  • footguns: duplicate since_session* collapsed; negative count bounds rejected (ge=0); dead cli/query.py parser removed.

Verification

ruff format --check <11 files>   # 11 files already formatted
ruff check <11 files>            # All checks passed!
mypy --strict <11 files>         # Success: no issues found in 11 source files

Remaining before ready-for-review: add the focused tests (the latest="false" collapse, lexical/semantic mutual-exclusion, lane validation rejection, daemon limit clamp, daemon vector-only typed error), then run full devtools verify.

Ref #1749

Summary by CodeRabbit

  • New Features

    • Added --json CLI shortcut option for JSON-formatted output
    • Conversation stats now support grouping by day
    • Search results now report accurate total count information
  • Bug Fixes

    • Fixed validation to reject negative message/word count filters
    • Added mutual exclusion validation for lexical and semantic search modes
    • Fixed semantic search to require query terms
    • Improved vector-only search error handling with proper HTTP status
  • Documentation

    • Updated blob garbage collection concurrency model documentation
    • Clarified search envelope field semantics and behavior
    • Expanded MCP tool documentation with additional details
  • Tests

    • Added comprehensive regression test suite for search and query features

Sinity and others added 3 commits May 31, 2026 02:14
…red limit cap

Add the canonical query-boundary contract pieces in the shared spec:

- normalize_retrieval_lane() validates against the closed
  QUERY_RETRIEVAL_LANES vocabulary and rejects unknown values
  (e.g. the dead "semantic" drift) with QuerySpecError.
- MAX_QUERY_LIMIT (1000) + clamp_query_limit() give every read surface
  one shared page-size ceiling.
- optional_non_negative_int() rejects negative min_messages/max_messages/
  min_words at the boundary (symmetric with limit/offset).
- Collapse the redundant since_session param into since_session_id.

Ref #1749

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adapt every read surface (CLI query-first, MCP, daemon HTTP, Python API)
to the canonical query/response contract:

- CLI: reject --lexical with --semantic/--similar (UsageError); reject
  --semantic with no query terms (was a silent no-op); thread spec.count()
  into the JSON search envelope so total is concrete like every other
  surface; cap the bare-token query-first fetch at MAX_QUERY_LIMIT;
  remove the dead drifted query-first arg splitter (live copy in
  cli/query_group.py).
- MCP: retype latest str|None -> bool (kills the latest="false" truthy
  data-collapse); add ge=0 on min/max_messages + min_words; drop the
  redundant since_session param; delegate clamp_limit to the shared
  clamp_query_limit; expand get_stats_by to provider/day/month/year and
  document the CLI-only insight dimensions.
- Daemon HTTP: clamp /api/conversations limit to MAX_QUERY_LIMIT; route
  vector-only (similar_text) requests through operations so the typed
  EmbeddingRetrievalNotReadyError (409) replaces the opaque 500; drop the
  redundant since_session param.
- Substrate: get_stats_by gains the day dimension.
- Docs: SearchEnvelope docstring states the uniform total semantics and
  distinguishes the closed request retrieval_lane vocabulary from the
  resolved per-hit lane (which may report "semantic").

Ref #1749

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented May 31, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements read-surface coherence fixes across query validation, type safety, and output formatting. It introduces a shared query-limit ceiling (1000), validates retrieval lanes against closed vocabulary, enforces non-negative count bounds, consolidates session-ID naming, types MCP boolean flags, guards CLI mutual exclusion, threads JSON envelope totals, and routes daemon vector-only queries to typed error paths, with comprehensive regression test coverage.

Changes

Read-surface coherence fixes: query validation, MCP types, CLI safety, and envelope totals

Layer / File(s) Summary
Shared query spec boundary validators
polylogue/archive/query/spec.py
Introduces MAX_QUERY_LIMIT=1000, clamp_query_limit helper, normalize_retrieval_lane closed-vocabulary validator, optional_non_negative_int parser, and updates parameter whitelist to recognize since_session_id and enforce non-negative count bounds in the spec builder.
MCP request type-safety updates
polylogue/mcp/query_contracts.py
Adds MCPCountBound type alias, types latest as bool (default False), constrains count fields to non-negative via MCPCountBound, removes since_session field in favor of since_session_id, and updates build_spec wiring.
CLI retrieval-mode validation and JSON envelope total threading
polylogue/cli/root_request.py, polylogue/cli/query.py, polylogue/cli/query_output.py
Adds mutual-exclusion and semantic-without-query validation in RootModeRequest; implements _envelope_total() to compute spec counts for JSON output; threads total parameter through format_search_envelope and output_search_hits to populate concrete totals in SearchEnvelope.
Daemon HTTP query handling and vector-only routing
polylogue/daemon/http.py
Removes since_session HTTP parameter, clamps limit via canonical clamp_query_limit, enforces non-negative offset, and routes vector-only requests (similar_text without query) through _do_search_list for typed embeddings error behavior.
MCP server limit clamping and stats day grouping
polylogue/mcp/server_support.py, polylogue/mcp/server_tools.py, polylogue/storage/sqlite/queries/stats.py
Delegates MCP _clamp_limit to canonical clamp_query_limit; adds "day" grouping option to get_stats_by in both server tools and storage layer with corresponding SQL branch.
Query plan fallback limit unification
polylogue/archive/query/retrieval_candidates.py
Updates search_limit() fallback to use MAX_QUERY_LIMIT instead of hardcoded 10000, aligning CLI query-first path with shared ceiling.
API schema and agent documentation updates
AGENTS.md, docs/openapi/search.yaml, polylogue/surfaces/payloads.py, docs/topology-status.md
Clarifies SearchEnvelope total semantics (concrete count vs None for no-spec), retrieval_lane vocabulary (resolved vs request input), blob-GC lease concurrency control flow, and generation age-check logic; updates topology metrics.
Comprehensive regression test suite
tests/unit/test_read_surface_coherence.py, tests/unit/cli/__snapshots__/test_help_snapshots.ambr
Covers CLI mutual-exclusion, MCP latest bool typing, shared MAX_QUERY_LIMIT ceiling, closed retrieval_lane vocabulary, negative count-bound rejection, since_session alias removal, and daemon vector-only 409 error mapping; includes help snapshot updates.

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related issues

Possibly related PRs

  • Sinity/polylogue#1015: Blob-GC lease concurrency documentation overlaps with AGENTS.md blob lease/generation documentation updates in this PR.
  • Sinity/polylogue#1327: Query-mode flag handling and RootModeRequest updates for --lexical/--semantic mutual exclusion directly align with this PR's CLI validation changes.
  • Sinity/polylogue#505: Shared query-limit clamping (MAX_QUERY_LIMIT/clamp_query_limit) and MCP _clamp_limit behavior touched in both PRs.

Suggested labels

type:refactor, area:mcp, area:storage, area:pipeline, type:test

🐰 A rabbit's ode to boundaries

Query walls now stand so tall and true,
Thousand limits fence the view,
No negatives slip through the mesh,
Each boundary gleams, all fresh,
Coherent surfaces at last!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.12% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main refactoring objective: converging four read surfaces onto a unified query/response contract, with the issue reference adding specificity.
Description check ✅ Passed The description covers all required template sections: Summary, Problem, Solution, and Verification. It includes detailed rationale, architectural scope, key changes, and current status. Risks/Follow-ups section appropriately documents remaining work (tests and devtools verify).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/issue-1749-read-surface-coherence

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

❤️ Share

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

Sinity and others added 3 commits May 31, 2026 02:50
Pins the behavioral contracts introduced by the implementation commits:

- AC#1: --lexical + --semantic/--similar raises UsageError; --semantic with
  no query terms raises UsageError (was silent no-op).
- AC#3: MCPConversationQueryRequest.latest typed as bool; spec builder
  receives False not truthy "false" (kills bool("false")==True collapse).
- AC#4: MAX_QUERY_LIMIT = 1000; clamp_query_limit ceiling enforced;
  CLI query-first search_limit fallback is 1000 not 10000.
- AC#5: EmbeddingRetrievalNotReadyError.http_status_code is 409; daemon
  daemon_safe_handler maps it to 409 not 500.
- AC#6: normalize_retrieval_lane rejects "bogus"/"semantic"/unknown values;
  QUERY_RETRIEVAL_LANES closed vocabulary excludes "semantic".
- Footguns: negative min_messages/max_messages/min_words raise QuerySpecError;
  since_session alias removed from spec and MCP request (since_session_id remains).

Ref #1749

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Regenerate docs/openapi/search.yaml (SearchEnvelope.total doc updated in #1749)
- Regenerate docs/topology-status.md (test file added)
- Update AGENTS.md from CLAUDE.md (devshell sync)
- Fix test_read_surface_coherence.py: use ConversationQueryPlan() directly
  (it is a dataclass, not a ConversationQuerySpec wrapper) — mypy caught the
  arg-type mismatch

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The root help snapshot was stale: the CLI gained --json, blackboard,
commands, context, and correlate since the snapshot was taken.  None
of these are part of #1749 — the snapshot drift is pre-existing.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
github-actions Bot pushed a commit that referenced this pull request May 31, 2026
@Sinity
Sinity marked this pull request as ready for review May 31, 2026 01:05
@Sinity

Sinity commented May 31, 2026

Copy link
Copy Markdown
Owner Author

Verification complete — AC status

Verification commands run

devtools verify --quick   # pre-push hook: all 15 static gates exit 0
devtools verify --all     # full suite: 10084 passed, 225 failed, 10309 total

Key output line: "passed": 10084, "failed": 225, "total": 10309, "exit_code": 1

The 225 failures are all pre-existing on master (confirmed independently):

  • 175 test_iter_messages_keyset.py — ValidationError: content_hash empty in mappers_archive.py:71; same failure on master
  • Remaining 50 split across CLI snapshots, pipeline/encoding tests, benchmarks
  • 0 failures in tests/unit/test_read_surface_coherence.py (52 new tests all pass)

AC#1 — --lexical + --semantic/--similar raises UsageError ✅

Pinned by: TestLexicalSemanticMutualExclusion (6 tests).
--semantic with no query now also raises UsageError (was silent no-op).

AC#2 — SearchEnvelope.total uniform ✅

Implementation already in the PR. total is now threaded from spec.count() on the CLI path. Not independently regression-tested (adding a test would require a live-archive round-trip); accepted via code review: cli/query_output.py:519 now passes total=total instead of hard-coded None.

AC#3 — MCP latest typed as bool ✅

Pinned by: TestMCPLatestTyped (6 tests).
latest="false" (old truthy collapse) now handled at Pydantic coercion → False, not truthy "false". Type annotation is bool, confirmed via typing.get_type_hints().

AC#4 — Shared limit ceiling + CLI query-first cap ✅

Pinned by: TestSharedLimitCeiling (7 tests).
MAX_QUERY_LIMIT = 1000 is the single source; clamp_query_limit is the shared function; CLI query-first search_limit now falls back to 1000 not 10000.

AC#5 — Daemon vector-only → typed 409, not 500 ✅

Pinned by: TestDaemonVectorOnlyTypedError (2 tests).
EmbeddingRetrievalNotReadyError.http_status_code == HTTPStatus.CONFLICT (409); daemon_safe_handler calls _send_json(409, ...) not the generic 500 path. Daemon HTTP routing for similar_text now goes through _do_search_list which raises the typed error.

AC#6 — retrieval_lane closed enum, unknown values rejected ✅

Pinned by: TestRetrievalLaneValidation (8 tests).
normalize_retrieval_lane("bogus") and normalize_retrieval_lane("semantic") raise QuerySpecError. QUERY_RETRIEVAL_LANES vocabulary confirmed closed: {"auto","dialogue","actions","hybrid"}.

AC#7 — MCP get_stats_by expanded ✅

Implementation in PR (mcp/server_tools.py): Literal["provider","day","month","year"]. Not regression-tested (trivial Literal annotation; covered by mypy). Documented decision: CLI action/tool/repo/work-kind dims are insight-aggregation paths, not substrate counts — explicitly scoped out.

AC#8 — Footguns addressed ✅

Pinned by: TestNegativeCountBoundsRejected (11 tests) + TestSinceSessionCollapsed (4 tests).

  • min_messages/max_messages/min_words negative values → QuerySpecError
  • since_session alias removed from MCP request and _RECOGNIZED_PARAMS
  • since_session_id remains as the canonical field
  • Dead cli/query.py parser removed (covered by implementation diff)

New tests added

tests/unit/test_read_surface_coherence.py — 52 tests, all pass.

Test classes: TestLexicalSemanticMutualExclusion, TestMCPLatestTyped, TestSharedLimitCeiling, TestRetrievalLaneValidation, TestNegativeCountBoundsRejected, TestSinceSessionCollapsed, TestDaemonVectorOnlyTypedError.

Other changes in this verification pass

  • docs/openapi/search.yaml — regenerated (SearchEnvelope.total doc update)
  • docs/topology-status.md — regenerated (new test file)
  • AGENTS.md — devshell sync
  • tests/unit/cli/__snapshots__/test_help_snapshots.ambr — updated (stale: CLI gained --json, blackboard, commands, context, correlate since last snapshot; none related to [cleanup] Reconcile read-surface coherence across CLI, MCP, and daemon #1749)

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

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

Comment thread polylogue/daemon/http.py Resolved

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

Caution

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

⚠️ Outside diff range comments (1)
polylogue/archive/query/spec.py (1)

292-344: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix latest boolean coercion in build_query_spec_from_params
polylogue/archive/query/spec.py sets latest=bool(params.get("latest")), so string values like "false"/"0" become True. polylogue/mcp/query_contracts.py’s normalize_query_params() only aliases keys and does not parse boolean tokens, so this remains reachable for any raw mapping passed into ConversationQuerySpec.from_params() (same truthy coercion is also used for reverse, filter_has_*, and typed_only).

Suggested fix
+def optional_bool(field: str, value: object) -> bool:
+    if value is None or value == "":
+        return False
+    if isinstance(value, bool):
+        return value
+    candidate = str(value).strip().lower()
+    if candidate in {"1", "true", "yes", "on"}:
+        return True
+    if candidate in {"0", "false", "no", "off"}:
+        return False
+    raise QuerySpecError(field, str(value))
+
 def build_query_spec_from_params(
     spec_cls: type[_SpecT],
     params: Mapping[str, object],
     *,
     strict_params: bool = False,
@@
-        latest=bool(params.get("latest")),
+        latest=optional_bool("latest", params.get("latest")),
🤖 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/archive/query/spec.py` around lines 292 - 344, The code in
build_query_spec_from_params uses bool(params.get(...)) for flags (e.g., latest,
reverse, filter_has_tool_use, filter_has_thinking, filter_has_paste, typed_only)
which treats any non-empty string like "false"/"0" as True; replace those
coercions with a proper boolean parse (e.g., implement a helper like
parse_bool(value, default=False) that accepts True/False, numeric 1/0, and
case-insensitive tokens "true"/"false","yes"/"no","1"/"0") and use it when
constructing the spec in build_query_spec_from_params (and ensure
ConversationQuerySpec.from_params / normalize_query_params callers get the same
semantics). Ensure the helper returns the provided default for None/unset and
reference the exact parameter names above when applying the replacement.
🤖 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 `@docs/openapi/search.yaml`:
- Around line 418-435: The OpenAPI docs are inconsistent: the response docs list
"semantic" as a resolved retrieval_lane but the request parameter enum
(QUERY_RETRIEVAL_LANES) still advertises "semantic" as an allowed query value;
remove "semantic" from the request-side enum so the parameter schema matches the
description. Update the generator/model that produces QUERY_RETRIEVAL_LANES (the
request parameter enum for retrieval_lane) to exclude "semantic" (leave
"auto","dialogue","actions","hybrid" only), regenerate the OpenAPI YAML, and
verify that retrieval_lane remains documented as a possible resolved value in
responses but is not listed as a valid input value.

In `@polylogue/surfaces/payloads.py`:
- Around line 767-771: Update the SearchEnvelope.total docstring to reflect that
total is only concrete when the caller has and threads a query spec to compute
spec.count() (e.g., when a surface like the daemon/Python API or the CLI path
that calls spec.count() passes it through), and that total==None means “count
not provided/available” (for example the CLI JSON formatter
format_search_envelope may not compute it and leaves it as None), rather than
saying None is reserved only for the absence of a backing query spec. Mention
SearchEnvelope.total, spec.count(), and format_search_envelope to guide readers
to the relevant behaviors.

In `@tests/unit/test_read_surface_coherence.py`:
- Around line 329-345: Update the
test_mcp_count_bound_type_alias_declared_with_ge_zero test to not only assert
MCPCountBound is a Union but to use typing.get_origin and typing.get_args to
extract the two union branches, identify the Annotated branch (the non-None
branch), and then inspect that Annotated's metadata includes a pydantic Field
with ge=0; specifically call typing.get_origin(MCPCountBound) and
typing.get_args(MCPCountBound), locate the Annotated type among the args, then
use typing.get_origin/typing.get_args on that Annotated to access its metadata
and assert the Field metadata contains ge==0.

---

Outside diff comments:
In `@polylogue/archive/query/spec.py`:
- Around line 292-344: The code in build_query_spec_from_params uses
bool(params.get(...)) for flags (e.g., latest, reverse, filter_has_tool_use,
filter_has_thinking, filter_has_paste, typed_only) which treats any non-empty
string like "false"/"0" as True; replace those coercions with a proper boolean
parse (e.g., implement a helper like parse_bool(value, default=False) that
accepts True/False, numeric 1/0, and case-insensitive tokens
"true"/"false","yes"/"no","1"/"0") and use it when constructing the spec in
build_query_spec_from_params (and ensure ConversationQuerySpec.from_params /
normalize_query_params callers get the same semantics). Ensure the helper
returns the provided default for None/unset and reference the exact parameter
names above when applying the replacement.
🪄 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: 81fb3c22-39e6-4282-8d1b-ccbb8dfdd064

📥 Commits

Reviewing files that changed from the base of the PR and between 3604177 and b92dbdc.

📒 Files selected for processing (16)
  • AGENTS.md
  • docs/openapi/search.yaml
  • docs/topology-status.md
  • polylogue/archive/query/retrieval_candidates.py
  • polylogue/archive/query/spec.py
  • polylogue/cli/query.py
  • polylogue/cli/query_output.py
  • polylogue/cli/root_request.py
  • polylogue/daemon/http.py
  • polylogue/mcp/query_contracts.py
  • polylogue/mcp/server_support.py
  • polylogue/mcp/server_tools.py
  • polylogue/storage/sqlite/queries/stats.py
  • polylogue/surfaces/payloads.py
  • tests/unit/cli/__snapshots__/test_help_snapshots.ambr
  • tests/unit/test_read_surface_coherence.py

Comment thread docs/openapi/search.yaml
Comment on lines +418 to +435
\ — see #873).\n- ``total``: total number of matching conversations. Every read surface\n (CLI, MCP, daemon HTTP,\
\ Python API) computes this via the shared\n ``spec.count()`` so the field carries a concrete count uniformly\n \
\ (#1749). ``None`` is reserved for the genuine no-spec case where a\n surface emits a hits list with no backing\
\ query spec to count from.\n- ``limit``: applied page size.\n- ``offset``: applied byte/row offset (offset-based\
\ pagination is\n \"best-effort, not stable\" for ranked results; prefer ``next_cursor``).\n- ``next_offset``: convenience\
\ pointer for offset-based clients; only\n set when more results are likely available.\n- ``next_cursor``: opaque\
\ keyset cursor encoding (rank, conversation_id)\n for stable rank-first pagination. Pass back unchanged in the\n\
\ following request.\n- ``query``: the search query text actually applied (after CLI/MCP/HTTP\n coercion). Empty\
\ string when there is no FTS query.\n- ``sort``: applied sort field, e.g. ``\"rank\"`` (default for ranked\n search),\
\ ``\"date\"``, ``\"messages\"``. ``None`` when no explicit sort\n was requested and the underlying lane order is\
\ preserved.\n- ``retrieval_lane``: resolved lane name — one of ``\"dialogue\"``,\n ``\"actions\"``, ``\"hybrid\"\
``, ``\"semantic\"``, ``\"auto\"``. ``auto``\n means the surface left the lane to the planner.\n- ``ranking_policy``:\
\ policy identifier the lane used to order hits.\n Currently always :data:`RANKING_POLICY_MIXED`.\n- ``ranking_policy_version``:\
\ numeric version of the ranking policy\n so external consumers can detect ordering changes.\n- ``diagnostics``:\
\ optional zero-result explanation when the query\n produced no hits but filters were applied."
\ preserved.\n- ``retrieval_lane``: the *resolved* per-hit ranking lane — one of\n ``\"dialogue\"``, ``\"actions\"\
``, ``\"hybrid\"``, ``\"semantic\"``,\n ``\"auto\"``. This is distinct from the *request* ``retrieval_lane``\n input\
\ parameter, whose closed accepted vocabulary is only\n ``QUERY_RETRIEVAL_LANES`` (``\"auto\"``/``\"dialogue\"``/``\"\
actions\"``/\n ``\"hybrid\"``) — ``\"semantic\"`` is never a request lane (a vector-only\n run is driven by ``similar_text``)\
\ but IS reported here as the\n resolved lane for vector hits (#1749). ``auto`` means the surface\n left the lane\
\ to the planner.\n- ``ranking_policy``: policy identifier the lane used to order hits.\n Currently always :data:`RANKING_POLICY_MIXED`.\n\
- ``ranking_policy_version``: numeric version of the ranking policy\n so external consumers can detect ordering changes.\n\
- ``diagnostics``: optional zero-result explanation when the query\n produced no hits but filters were applied."

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 | ⚡ Quick win

Remove semantic from the documented request-lane vocabulary.

This description now says request retrieval_lane only accepts QUERY_RETRIEVAL_LANES, but Lines 61-73 in the same generated schema still advertise semantic as a valid query-parameter enum value. That leaves the public contract internally inconsistent and tells clients to send a value the spec boundary now rejects. Please update the source model/generator so the parameter schema matches this new description.

🤖 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 `@docs/openapi/search.yaml` around lines 418 - 435, The OpenAPI docs are
inconsistent: the response docs list "semantic" as a resolved retrieval_lane but
the request parameter enum (QUERY_RETRIEVAL_LANES) still advertises "semantic"
as an allowed query value; remove "semantic" from the request-side enum so the
parameter schema matches the description. Update the generator/model that
produces QUERY_RETRIEVAL_LANES (the request parameter enum for retrieval_lane)
to exclude "semantic" (leave "auto","dialogue","actions","hybrid" only),
regenerate the OpenAPI YAML, and verify that retrieval_lane remains documented
as a possible resolved value in responses but is not listed as a valid input
value.

Comment on lines +767 to +771
- ``total``: total number of matching conversations. Every read surface
(CLI, MCP, daemon HTTP, Python API) computes this via the shared
``spec.count()`` so the field carries a concrete count uniformly
(#1749). ``None`` is reserved for the genuine no-spec case where a
surface emits a hits list with no backing query spec to count from.

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 | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check CLI query output total computation.

# Search for total assignment/computation in CLI query output layer
rg -nP -C5 'total\s*[=:]' polylogue/cli/query_output.py

# Check for spec.count() usage in CLI layer
rg -nP '\bspec\.count\(\)' polylogue/cli/

# Verify test expectations for CLI total
rg -nP -C3 'CLI.*total.*None|total.*CLI.*unknown' tests/unit/surfaces/test_search_envelope_contract.py

Repository: Sinity/polylogue

Length of output: 2117


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show the relevant portion of CLI query output where total is threaded/rendered.
sed -n '450,620p' polylogue/cli/query_output.py

# Look specifically for spec.count in the CLI subtree.
rg -nP '\bspec\.count\(\)' polylogue/cli/ || true

# Find where CLI constructs SearchEnvelope / canonical envelope and passes `total=...`.
rg -nP 'build_search_envelope\(|SearchEnvelope|render_.*envelope|total=\w+|total\s*=' polylogue/cli/ -S

# Re-open the unit test lines referenced by the earlier rg match.
sed -n '150,230p' tests/unit/surfaces/test_search_envelope_contract.py

Repository: Sinity/polylogue

Length of output: 11000


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Read the exact docstring region in payloads.py around the total field description.
sed -n '730,830p' polylogue/surfaces/payloads.py

# 2) Trace CLI computation of `total` from polylogue/cli/query.py
rg -nP '_envelope_total\(' polylogue/cli/query.py
sed -n '420,520p' polylogue/cli/query.py
sed -n '660,760p' polylogue/cli/query.py

# 3) Find where `spec.count()` is computed/used in CLI
rg -nP '\bspec\.count\(\)' polylogue/cli/

# 4) Confirm the unit test behavior referenced earlier
sed -n '140,220p' tests/unit/surfaces/test_search_envelope_contract.py

Repository: Sinity/polylogue

Length of output: 15187


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect _envelope_total implementation and any spec.count usage.
rg -nP 'async def _envelope_total|def _envelope_total|_envelope_total\(' -n polylogue/cli/query.py
sed -n '160,240p' polylogue/cli/query.py
rg -nP '\bspec\.count\(\)|count\(\)' polylogue/cli/query.py

# Inspect unit test helpers around how CLI total is handled/ignored.
rg -nP '_normalise_envelope_dict|total.*payload\.get\("total"\)' tests/unit/surfaces/test_search_envelope_contract.py
sed -n '1,140p' tests/unit/surfaces/test_search_envelope_contract.py
sed -n '140,240p' tests/unit/surfaces/test_search_envelope_contract.py

Repository: Sinity/polylogue

Length of output: 12572


Soften SearchEnvelope.total docstring to match CLI’s threading behavior
SearchEnvelope.total claims every read surface computes total via shared spec.count() uniformly, but the CLI JSON formatter (format_search_envelope) doesn’t compute it—it uses the passed-in total (defaulting to None), and the cross-surface contract test calls it without total and therefore expects CLI to emit total=None (“unknown”). Update the docstring to state that total is concrete when the caller has the query spec and threads spec.count() (e.g., the CLI --format json path), and that None reflects “count not provided/available”, not strictly only a “no backing query spec” case.

🤖 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/surfaces/payloads.py` around lines 767 - 771, Update the
SearchEnvelope.total docstring to reflect that total is only concrete when the
caller has and threads a query spec to compute spec.count() (e.g., when a
surface like the daemon/Python API or the CLI path that calls spec.count()
passes it through), and that total==None means “count not provided/available”
(for example the CLI JSON formatter format_search_envelope may not compute it
and leaves it as None), rather than saying None is reserved only for the absence
of a backing query spec. Mention SearchEnvelope.total, spec.count(), and
format_search_envelope to guide readers to the relevant behaviors.

Comment on lines +329 to +345
def test_mcp_count_bound_type_alias_declared_with_ge_zero(self) -> None:
"""MCPCountBound TypeAlias carries Field(ge=0) for FastMCP schema generation.

MCPConversationQueryRequest is a dataclass (not Pydantic), so Python
itself doesn't validate at construction time. The ge=0 constraint is
expressed in the TypeAlias so FastMCP generates a JSON schema that
rejects negatives in the tool binding layer. The actual runtime gate
is the spec builder's optional_non_negative_int.
"""
import typing

from polylogue.mcp.query_contracts import MCPCountBound

# MCPCountBound is Annotated[int, Field(ge=0)] | None
# Verify its type structure carries the Annotated form
origin = getattr(MCPCountBound, "__origin__", None)
assert origin is typing.Union, "MCPCountBound must be a Union (Annotated[int, Field(ge=0)] | 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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Inspect the referenced test section
sed -n '300,380p' tests/unit/test_read_surface_coherence.py

# 2) Confirm the full contents of the type assertion test (if longer/nearby)
rg -n "test_mcp_count_bound_type_alias_declared_with_ge_zero|MCPCountBound" tests/unit/test_read_surface_coherence.py

# 3) Check for disallowed wall-clock / monotonic usage in this test file
rg -n "(datetime\.now|datetime\.utcnow|time\.time|time\.monotonic)" tests/unit/test_read_surface_coherence.py || true
rg -n "(from datetime import|import datetime|import time)" tests/unit/test_read_surface_coherence.py || true

# 4) Locate MCPCountBound definition and inspect it
fd -a "query_contracts" . | head -n 50
fd -a "MCPCountBound" -g "*.py" polylogue tests devtools . | head -n 50

# Use rg to pinpoint the definition
rg -n "MCPCountBound" polylogue/mcp/query_contracts.py polylogue -S || true

# Print the relevant snippet from the definition file
if [ -f polylogue/mcp/query_contracts.py ]; then
  rg -n "MCPCountBound" polylogue/mcp/query_contracts.py
  # show some surrounding lines
  start=$(python3 - <<'PY'
import re
p="polylogue/mcp/query_contracts.py"
import pathlib
txt=pathlib.Path(p).read_text()
m=re.search(r"^.*MCPCountBound.*$", txt, re.M)
print(m.start() if m else 0)
PY
)
fi

# Fallback: show likely surrounding area with rg context
rg -n "MCPCountBound" polylogue/mcp/query_contracts.py -C 6 || true

Repository: Sinity/polylogue

Length of output: 6458


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import typing
from polylogue.mcp.query_contracts import MCPCountBound
from pydantic import Field

print("MCPCountBound =", MCPCountBound)
print("type(MCPCountBound) =", type(MCPCountBound))

print("getattr __origin__:", getattr(MCPCountBound, "__origin__", None))
print("typing.get_origin:", typing.get_origin(MCPCountBound))
print("typing.get_args:", typing.get_args(MCPCountBound))

# Drill into the union members
for i, arg in enumerate(typing.get_args(MCPCountBound)):
    print(f"\narg[{i}] =", arg)
    print("  arg type =", type(arg))
    print("  arg __origin__ =", getattr(arg, "__origin__", None))
    print("  arg typing.get_origin =", typing.get_origin(arg))
    print("  arg typing.get_args =", typing.get_args(arg))
    # Look for ge=0 metadata in Annotated
    if typing.get_origin(arg) is int and typing.get_args(arg):
        meta = typing.get_args(arg)[1:]
        print("  Annotated meta tail =", meta)
PY

Repository: Sinity/polylogue

Length of output: 1359


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import typing
try:
    from pydantic import Field
except Exception as e:
    print("Cannot import pydantic.Field:", e)
    raise

T = typing.Annotated[int, Field(ge=0)] | None

print("T =", T)
print("type(T) =", type(T))
print("getattr(T,'__origin__') =", getattr(T, "__origin__", None))
print("typing.get_origin(T) =", typing.get_origin(T))
print("typing.get_args(T) =", typing.get_args(T))

# Check sub-args for Annotated and its metadata
for a in typing.get_args(T):
    print("\narg =", a)
    print("  type(arg) =", type(a))
    print("  getattr(arg,'__origin__') =", getattr(a, "__origin__", None))
    print("  typing.get_origin(arg) =", typing.get_origin(a))
    print("  typing.get_args(arg) =", typing.get_args(a))
PY

Repository: Sinity/polylogue

Length of output: 926


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '1,120p' polylogue/mcp/query_contracts.py

Repository: Sinity/polylogue

Length of output: 4447


🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n "(datetime\.now|datetime\.utcnow|datetime\.fromtimestamp|time\.time|time\.monotonic|datetime\.)" tests/unit/test_read_surface_coherence.py || true
rg -n "frozen_clock|frozen_clock_modules" tests/unit/test_read_surface_coherence.py || true

Repository: Sinity/polylogue

Length of output: 42


Strengthen MCPCountBound assertion to check Field(ge=0) metadata
In tests/unit/test_read_surface_coherence.py (329-345), the test only verifies MCPCountBound.__origin__ is a typing.Union, so it would still pass if MCPCountBound regressed to int | None and dropped the Annotated[..., Field(ge=0)] constraint. Use typing.get_origin()/typing.get_args() and assert the Annotated branch’s Field metadata contains ge=0.

🤖 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/test_read_surface_coherence.py` around lines 329 - 345, Update the
test_mcp_count_bound_type_alias_declared_with_ge_zero test to not only assert
MCPCountBound is a Union but to use typing.get_origin and typing.get_args to
extract the two union branches, identify the Annotated branch (the non-None
branch), and then inspect that Annotated's metadata includes a pydantic Field
with ge=0; specifically call typing.get_origin(MCPCountBound) and
typing.get_args(MCPCountBound), locate the Annotated type among the args, then
use typing.get_origin/typing.get_args on that Annotated to access its metadata
and assert the Field metadata contains ge==0.

@Sinity
Sinity merged commit 9f037ae into master May 31, 2026
7 checks passed
@Sinity
Sinity deleted the feature/refactor/issue-1749-read-surface-coherence branch May 31, 2026 06:17
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

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

  • 63.F079 / P2: fixed-already at the checked revision: The canonical search-envelope builder recognizes vector and hybrid requests as ranked-only at polylogue/api/search_envelope_builder.py:132. It sets total to None for that lane at line 133 rather than calling the provider-less repository count path that raised the reported exception.

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant