Repository navigation
refactor(query): converge read surfaces onto one query/response contract (#1749) - #1763
Conversation
…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]>
📝 WalkthroughWalkthroughThis 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. ChangesRead-surface coherence fixes: query validation, MCP types, CLI safety, and envelope totals
🎯 3 (Moderate) | ⏱️ ~22 minutes Possibly related issues
Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
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]>
Verification complete — AC statusVerification commands runKey output line: The 225 failures are all pre-existing on master (confirmed independently):
AC#1 —
|
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
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 winFix
latestboolean coercion inbuild_query_spec_from_params
polylogue/archive/query/spec.pysetslatest=bool(params.get("latest")), so string values like"false"/"0"becomeTrue.polylogue/mcp/query_contracts.py’snormalize_query_params()only aliases keys and does not parse boolean tokens, so this remains reachable for any raw mapping passed intoConversationQuerySpec.from_params()(same truthy coercion is also used forreverse,filter_has_*, andtyped_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
📒 Files selected for processing (16)
AGENTS.mddocs/openapi/search.yamldocs/topology-status.mdpolylogue/archive/query/retrieval_candidates.pypolylogue/archive/query/spec.pypolylogue/cli/query.pypolylogue/cli/query_output.pypolylogue/cli/root_request.pypolylogue/daemon/http.pypolylogue/mcp/query_contracts.pypolylogue/mcp/server_support.pypolylogue/mcp/server_tools.pypolylogue/storage/sqlite/queries/stats.pypolylogue/surfaces/payloads.pytests/unit/cli/__snapshots__/test_help_snapshots.ambrtests/unit/test_read_surface_coherence.py
| \ — 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." |
There was a problem hiding this comment.
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.
| - ``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. |
There was a problem hiding this comment.
🧩 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.pyRepository: 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.pyRepository: 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.pyRepository: 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.pyRepository: 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.
| 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)" |
There was a problem hiding this comment.
🧩 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 || trueRepository: 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)
PYRepository: 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))
PYRepository: Sinity/polylogue
Length of output: 926
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '1,120p' polylogue/mcp/query_contracts.pyRepository: 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 || trueRepository: 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.
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
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 (noprovider→origin/conversation→sessionrename — that is separate future work).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_lanestringly-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 thebool("false")==Truecollapse).limit→ sharedMAX_QUERY_LIMIT = 1000ceiling; CLI query-first default cap; daemon/api/conversationsclamps.--lexical+--semantic/--similar, and--semanticwith no query →UsageError.EmbeddingRetrievalNotReadyError(409), not 500.SearchEnvelope.total(AC#2) → uniformly computed via sharedspec.count()on all four surfaces;Noneretained only for the genuine no-spec case.get_stats_by(AC#7) → expanded toprovider/month/year/day(substrate dims); insight dims explicitly scoped as a CLI aggregation surface.since_session*collapsed; negative count bounds rejected (ge=0); deadcli/query.pyparser removed.Verification
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 fulldevtools verify.Ref #1749
Summary by CodeRabbit
New Features
--jsonCLI shortcut option for JSON-formatted outputBug Fixes
Documentation
Tests