Skip to content

refactor: tighten quality and verification contracts - #314

Merged
Sinity merged 16 commits into
masterfrom
feature/refactor/quality-debt-cleanup
Apr 21, 2026
Merged

Sinity merged 16 commits into
masterfrom
feature/refactor/quality-debt-cleanup

Conversation

@Sinity

@Sinity Sinity commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Tighten remaining JSON/type-boundary seams and remove broad mock/source casts.
  • Add archive scenario, semantic fact, surface adapter, query-case, and lifecycle harness infrastructure.
  • Port retrieval and cross-surface laws onto shared semantic oracles.
  • Fix repository, logging, Drive acquisition, and Drive service test-double safety issues found while expanding verification.

Problem

The mypy cleanup wave reduced suppression debt, but verification remained too path-dependent: several storage/query laws built bespoke fixture setup and direct SQL assertions instead of reusable scenario projections. Full-suite verification also exposed a subprocess CLI startup crash caused by treating structlog lazy proxies as invalid loggers, a runtime-only Drive acquisition protocol import gap, and Python 3.13 test failures from using MagicMock where a runtime-checkable Drive service protocol was required.

Repository writes also had a lossy edge where hydrated domain conversations could be re-saved without message records, risking runtime-state replacement with an empty graph.

Ref #274

Solution

Introduce reusable archive-verification fixtures under tests/infra: declarative scenarios, semantic facts/oracles, surface adapters, query cases, pipeline roundtrip helpers, and repository lifecycle state harnesses. Rework retrieval readiness, cross-surface agreement, pipeline roundtrip, and repository lifecycle tests to compare semantic facts across direct SQL records, hydrated records, repository, and public facade surfaces.

Harden RepositoryWriteMixin.save_conversation() to reject lossy domain-conversation saves. Simplify get_logger() so structlog lazy loggers work at CLI startup. Import the Drive UI protocol at runtime where it is used for a runtime-checkable isinstance guard. Replace Drive gateway cache lifecycle MagicMock service doubles with MockDriveService objects that satisfy the service protocol on Python 3.13.

Verification

  • uv run devtools verify --quick
  • uv run pytest -q tests/unit/pipeline/test_parsing_service.py
  • UV_PYTHON=3.13 uv run pytest -q tests/unit/sources/test_drive_gateway.py
  • uv run ruff check tests/unit/sources/test_drive_gateway.py && uv run mypy tests/unit/sources/test_drive_gateway.py

@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR systematically replaces runtime typing.cast() usages across the codebase with explicit runtime validation, stricter type contracts (TypedDict, Protocol), and new validation helpers. It introduces schema enforcement for JSON payloads, marks Protocols as @runtime_checkable, and refactors function signatures to accept more general types while validating at call boundaries rather than relying on static type assertions.

Changes

Cohort / File(s) Summary
JSON Contract Enforcement
polylogue/lib/json.py
Added require_json_value() and require_json_document() public validation helpers that enforce JSON type contracts at runtime, replacing unchecked casts throughout the codebase.
DevTools Refactoring
devtools/command_catalog.py, devtools/pipeline_probe.py, devtools/query_memory_budget.py
Added runtime validation in CommandSpec.resolve_main (callable/return-type checks), introduced MemoryBudgetResult TypedDict, and refactored pipeline_probe.py to use shared JSON validation helpers and JSONDocument types instead of loose dict payloads.
CLI Type Safety
polylogue/cli/click_option_groups.py, polylogue/cli/embed_runtime.py, polylogue/cli/machine_errors.py, polylogue/cli/query.py, polylogue/cli/run_observers.py, polylogue/cli/schema_command_support.py
Replaced parameter/variable casts with isinstance checks and explicit type guards; marked _HasUI as @runtime_checkable; added overload signatures and _privacy_level() helper for literal validation; updated RichProgressObserver to accept typed TaskID.
Library Type Refinements
polylogue/lib/conversation_runtime.py, polylogue/lib/messages.py, polylogue/lib/metrics.py, polylogue/lib/provider_semantics.py, polylogue/lib/query_spec.py, polylogue/lib/filter_builder.py, polylogue/lib/dates.py
Added runtime type checks in ConversationRuntimeMixin.project(); generalized provider semantic extractors to accept Sequence/Mapping instead of specific JSON types; removed unused imports; added _privacy_level() and type-guarding helpers.
Stream/Payload Abstraction
polylogue/lib/raw_payload_streams.py, polylogue/lib/raw_payload_decode.py, polylogue/lib/raw_payload_sampling_extract.py
Added new raw_line_stream() context manager to centralize file/bytes/string stream handling, replacing duplicated BytesIO/StringIO and resource-management logic across payload processing modules.
Protocol & Runtime Checkability
polylogue/sources/drive_types.py, polylogue/sources/drive_gateway.py, polylogue/pipeline/services/acquisition.py, polylogue/pipeline/services/ingest_batch.py
Marked DriveUILike/_DriveService as @runtime_checkable; refined protocol signatures; introduced _DriveSourceGateway protocol for decoupling; updated visit_sources() and _persist_batch_raw_state_updates() with explicit isinstance checks.
Storage Layer Refactoring
polylogue/storage/backends/queries/mappers_support.py, polylogue/storage/backends/queries/mappers*.py
Extracted shared row-mapping helpers (_parse_json, _row_text, _row_int, etc.) into new mappers_support.py module; updated all mapper files to import from the centralized support module instead of inline definitions.
Validation Helpers for Storage
polylogue/storage/action_event_status.py, polylogue/storage/embedding_stats.py, polylogue/storage/embedding_stats_support.py, polylogue/storage/repository*.py, polylogue/storage/hydrators.py
Added _sql_row(), _stats_row(), and similar helpers for SQLite row validation; replaced cast-based typing with explicit type guards; introduced _content_hash_from_metadata_or_domain() for deterministic hash computation.
Schema & Operator Validation
polylogue/schemas/operator_models.py, polylogue/schemas/code_detection_tree_sitter.py, polylogue/schemas/generation_semantic_relations.py, polylogue/schemas/pinning.py, polylogue/schemas/synthetic/build_batch.py, polylogue/schemas/tooling_registry.py
Added _is_operator_json_value() and _is_operator_json_document() TypeGuard helpers; refactored validation from set-membership to explicit equality checks; replaced casts with require_json_value() calls.
HTTP & Webhook Refactoring
polylogue/pipeline/observers.py
Replaced urllib.request webhook implementation with http.client-based helpers (_webhook_request_target(), _post_webhook()); centralized URL parsing and timeout handling.
Test Infrastructure (New Modules)
tests/infra/archive_scenarios.py, tests/infra/surfaces.py, tests/infra/oracles.py, tests/infra/semantic_facts.py, tests/infra/query_cases.py, tests/infra/pipeline_roundtrip.py, tests/infra/state_machines.py
Added comprehensive test abstractions: scenario-driven archive seeding, multi-surface verification (SQLite record/hydrated/repository/facade), semantic fact extraction and comparison, query case definition, and repository lifecycle harnesses.
Test Utility Updates
tests/infra/drive_mocks.py, tests/infra/mcp.py, tests/infra/pty_cli.py, tests/infra/strategies/search.py, tests/conftest.py, pyproject.toml
Updated mock return types to use DrivePayloadRecord/DriveListFilesResponse; added @runtime_checkable to MCPServerUnderTest; refactored pyte character extraction; removed TerminalChar protocol; added MyPy stubs path.
Test File Updates (Unit Tests)
tests/unit/cli/test_*.py, tests/unit/core/test_*.py, tests/unit/devtools/test_*.py, tests/unit/mcp/conftest.py, tests/unit/pipeline/test_*.py, tests/unit/rendering/test_*.py, tests/unit/scenarios/test_*.py, tests/unit/showcase/test_*.py, tests/unit/sources/test_*.py, tests/unit/storage/test_*.py, tests/unit/ui/test_tui.py
Systematically replaced cast() with runtime validation helpers (_as_mock(), _as_console_like(), _dict_payload(), etc.); updated mocked objects to use real implementations where possible; replaced pyte/MagicMock stubs with proper type guards.
Major Test Refactors
tests/unit/storage/test_retrieval_readiness_laws.py, tests/unit/storage/test_repository_lifecycle_laws.py, tests/unit/test_cross_surface_agreement.py
Replaced low-level SQL-law tests with high-level surface-agreement tests; introduced scenario-driven fixture architecture; updated assertions to use assert_same_archive_facts() and assert_same_conversation_facts().
Documentation & Configuration
docs/cli-reference.md, stubs/dateparser/__init__.pyi
Added -u, --user-only CLI option documentation; created new dateparser type stub for improved typing support.
UI & Logging
polylogue/ui/facade.py, polylogue/logging.py, polylogue/readiness.py
Added _StderrProxy full TextIO implementation with delegation methods; replaced _module_available() helper using importlib.util.find_spec(); added runtime Console validation in ConsoleFacade.
Payload & Showcase
polylogue/surface_payloads.py, polylogue/showcase/qa_markdown.py, polylogue/showcase/qa_summary.py, polylogue/scenarios/payloads.py, polylogue/mcp/server_support.py, polylogue/mcp/server_tools.py
Replaced cast-based payload normalization with require_json_document() validation; added key-stringification helpers; updated sort parameter in list_conversations() to optional; changed ToJSONPayload protocol to explicit validation.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

area:cli, area:pipeline, area:storage, area:testing, refactor


🐰 Cast spells be gone, now truth shines bright,
Runtime guards dance in the safety light,
TypedDict contracts, protocols in place,
No more blind trust—validation's grace!

✨ 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/quality-debt-cleanup

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

ℹ️ 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/pipeline/observers.py Resolved
Comment thread polylogue/readiness.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: 36

Caution

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

⚠️ Outside diff range comments (9)
polylogue/lib/query_spec.py (1)

124-140: 🧹 Nitpick | 🔵 Trivial

Optional: collapse the if-chain into a membership check.

The explicit per-value branches are equivalent to a single membership test against the known SortField literals, and keep the validation behavior (raising QuerySpecError on unknown inputs) intact while removing the repetition.

♻️ Proposed simplification
+_SORT_FIELDS: frozenset[SortField] = frozenset(
+    ("date", "tokens", "messages", "words", "longest", "random")
+)
+
+
 def optional_sort_field(value: object) -> SortField | None:
     candidate = optional_text(value)
     if candidate is None:
         return None
-    if candidate == "date":
-        return "date"
-    if candidate == "tokens":
-        return "tokens"
-    if candidate == "messages":
-        return "messages"
-    if candidate == "words":
-        return "words"
-    if candidate == "longest":
-        return "longest"
-    if candidate == "random":
-        return "random"
-    raise QuerySpecError("sort", candidate)
+    if candidate in _SORT_FIELDS:
+        return candidate  # type: ignore[return-value]
+    raise QuerySpecError("sort", candidate)

Note: narrowing str to the Literal SortField via membership in a frozenset[SortField] isn't inferred by mypy today, so a single localized ignore (or typing.get_args(SortField) + cast) is the tradeoff vs. the six-branch form. If the point of this refactor was specifically to eliminate cast, feel free to disregard.

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

In `@polylogue/lib/query_spec.py` around lines 124 - 140, The function
optional_sort_field currently uses an explicit if-chain to accept known
SortField literals; replace that with a single membership check: use
optional_text(value) to get candidate, return None if None, then if candidate is
in the allowed SortField set (e.g., a frozenset of the SortField literals or
typing.get_args(SortField) cast appropriately) return candidate, otherwise raise
QuerySpecError("sort", candidate); update optional_sort_field to reference
optional_text, SortField, and QuerySpecError as above and add a localized mypy
ignore or cast if needed to satisfy type narrowing.
tests/unit/cli/test_deterministic_output.py (1)

46-61: 🧹 Nitpick | 🔵 Trivial

Minor: unnecessary shallow copy after isinstance narrowing.

After the isinstance(parsed, dict) / isinstance(result, dict) checks, the type is already narrowed to dict[Any, Any], which is assignable to JSONEnvelope (dict[str, object]). The dict(parsed) / dict(result) calls allocate a new dict on every call purely to satisfy typing — you can just return parsed / return result (optionally with # type: ignore[return-value] only if mypy complains, or keep the cast-free form by annotating the local). Not a correctness issue, but it's a wasted allocation on a hot-path helper used by many parametrized tests.

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

In `@tests/unit/cli/test_deterministic_output.py` around lines 46 - 61, Both
helpers (_extract_json and _result_payload) perform an unnecessary shallow copy
via dict(parsed) / dict(result) after an isinstance(..., dict) type-narrowing;
remove the allocations and return the already-narrowed parsed and result values
directly (in _extract_json return parsed, in _result_payload return result). If
mypy complains about return types, satisfy it by annotating the local variable
(e.g., parsed: JSONEnvelope or result: JSONEnvelope) or add a narrow # type:
ignore[return-value] comment — do not allocate a new dict.
tests/unit/cli/test_json_envelope_contract.py (1)

67-91: 🧹 Nitpick | 🔵 Trivial

Same dict(...) materialization nit as the sibling helper.

Mirrors the comment on tests/unit/cli/test_deterministic_output.py: once isinstance(parsed, dict) / isinstance(result, dict) has narrowed the type, returning the original reference is sufficient and avoids the per-call shallow copy. Also worth noting that these two helper pairs (_parse_json_output/_extract_json and _result_payload) are now duplicated verbatim across the two test modules — consider lifting them into a shared tests/unit/cli/_json_helpers.py (or a conftest) to keep the JSON-envelope parsing contract in one place.

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

In `@tests/unit/cli/test_json_envelope_contract.py` around lines 67 - 91, The
helpers _parse_json_output and _result_payload are needlessly returning shallow
copies via dict(parsed) and dict(result); after the isinstance(..., dict) checks
you can safely return the original parsed and result objects directly to avoid
extra allocations—replace the dict(...) returns with returning parsed and result
respectively. Also consider deduplicating these helpers by moving
_parse_json_output/_result_payload into a shared tests unit helper (e.g.,
tests/unit/cli/_json_helpers.py or conftest) and importing them from both test
modules.
polylogue/scenarios/payloads.py (1)

82-88: 🛠️ Refactor suggestion | 🟠 Major

Inconsistent failure mode vs. sibling helpers, and redundant str(key) coercion.

payload_mapping here returns None when keys are non-string, whereas the analogous _payload_mapping helpers in polylogue/showcase/qa_markdown.py and polylogue/showcase/qa_summary.py raise TypeError for the same condition. Callers of this helper now silently get None on bad input while the showcase helpers fail loudly — worth aligning (or documenting) the contract so the two patterns don't drift further.

Also, since line 86 already guarantees every key is a str, the str(key) on line 88 is a redundant coercion; a plain dict(value) (or {k: v for k, v in value.items()}) would suffice and make the intent clearer.

♻️ Suggested simplification
-    return {str(key): item for key, item in value.items()}
+    return dict(value)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/scenarios/payloads.py` around lines 82 - 88, payload_mapping
currently returns None on non-Mapping input or non-string keys and unnecessarily
calls str(key) when keys are already strings; align its behavior with the
sibling helpers (_payload_mapping in polylogue/showcase/qa_markdown.py and
qa_summary.py) by raising a TypeError when value is a Mapping but contains any
non-str keys instead of returning None, and simplify the return to a plain dict
(e.g., dict(value) or a simple {k: v for k, v in value.items()}) removing the
redundant str(key) coercion; keep the initial isinstance(value, Mapping) check
and raise TypeError with a clear message (mentioning payload_mapping) when key
types are invalid.
tests/infra/test_storage_records.py (1)

40-65: 🧹 Nitpick | 🔵 Trivial

Guard conn.close() against assertion failures.

If any assert between Lines 62–64 fails, conn.close() on Line 65 is skipped and the in-memory SQLite connection leaks for the remainder of the test process. Wrap in try/finally (or contextlib.closing) so the connection is always closed regardless of assertion outcome.

♻️ Proposed refactor
-    result = storage_helpers.store_records(
-        conversation=make_conversation("test:1", title="Test", content_hash="abc123"),
-        messages=[make_message("test:1:msg1", "test:1", text="Hello")],
-        attachments=[],
-        conn=conn,
-    )
-
-    assert result["conversations"] == 1
-    assert result["messages"] == 1
-    assert conn.commit_states == [True]
-    conn.close()
+    try:
+        result = storage_helpers.store_records(
+            conversation=make_conversation("test:1", title="Test", content_hash="abc123"),
+            messages=[make_message("test:1:msg1", "test:1", text="Hello")],
+            attachments=[],
+            conn=conn,
+        )
+
+        assert result["conversations"] == 1
+        assert result["messages"] == 1
+        assert conn.commit_states == [True]
+    finally:
+        conn.close()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/test_storage_records.py` around lines 40 - 65, The test leaves
the in-memory SQLite connection open if an assertion fails; wrap the use of conn
around a try/finally (or use contextlib.closing) so conn.close() always runs:
after creating conn (TrackingConnection) and before calling
storage_helpers.store_records / asserting on result and conn.commit_states,
ensure you place the store_records call and subsequent asserts inside a try
block and call conn.close() in the finally block (or replace the manual
lifecycle with a context manager) to guarantee closure even on test failures.
polylogue/lib/json.py (1)

19-26: ⚠️ Potential issue | 🟠 Major

Reject non-finite floats in the JSON contract helpers.

is_json_value() accepts all float values including NaN, Infinity, and -Infinity, while loads() explicitly rejects them via parse_constant=_reject_non_finite_token. Add math.isfinite() to enforce consistency.

Proposed fix
 import json
+import math
 from collections.abc import Callable
 from decimal import Decimal
 from typing import TypeAlias, TypeGuard
@@
 def is_json_value(value: object) -> TypeGuard[JSONValue]:
     """Return whether *value* is representable as JSON."""
-    if value is None or isinstance(value, (str, int, float, bool)):
+    if value is None or isinstance(value, (str, bool, int)):
         return True
+    if isinstance(value, float):
+        return math.isfinite(value)
     if isinstance(value, list):
         return all(is_json_value(item) for item in value)

Also applies to: require_json_document() (lines 47-51).

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

In `@polylogue/lib/json.py` around lines 19 - 26, The helpers currently accept
non-finite float values (NaN, Infinity, -Infinity); update is_json_value and
require_json_document to reject those by adding a math.isfinite() check for
float instances: when checking isinstance(value, float) ensure
math.isfinite(value) is True (or combine with isinstance(value, (int, float))
but treat floats via math.isfinite), and likewise when validating dict/list
items ensure any float encountered is finite; import math and apply
math.isfinite in both is_json_value and require_json_document to make their
behavior consistent with loads(parse_constant=_reject_non_finite_token).
tests/unit/sources/test_drive_gateway.py (1)

168-180: ⚠️ Potential issue | 🟡 Minor

Replace bare MagicMock with MockDriveService in service Protocol validation tests.

Lines 170 and 178 use bare MagicMock() instances passed to _as_drive_service(), which validates against the @runtime_checkable Protocol _DriveService via isinstance(). While this currently works due to MagicMock's dynamic attribute creation, it's fragile and non-portable across Python versions. Use the concrete MockDriveService class (already imported at line 21) instead, and assign explicit _http attributes using SimpleNamespace.

Proposed fix
+from types import SimpleNamespace
 
 def test_service_handle_returns_cached_service_when_not_expired(monkeypatch: pytest.MonkeyPatch) -> None:
     gw = _gateway()
-    service = MagicMock()
-    service._http.credentials.expired = False
+    service = MockDriveService()
+    service._http = SimpleNamespace(credentials=SimpleNamespace(expired=False))
     gw._service = _as_drive_service(service)
     assert gw._service_handle() is service


 def test_service_handle_rebuilds_on_expired_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
     gw = _gateway()
-    expired = MagicMock()
-    expired._http.credentials.expired = True
+    expired = MockDriveService()
+    expired._http = SimpleNamespace(credentials=SimpleNamespace(expired=True))
     gw._service = _as_drive_service(expired)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/sources/test_drive_gateway.py` around lines 168 - 180, Replace the
bare MagicMock instances used in
test_service_handle_returns_cached_service_when_not_expired and
test_service_handle_rebuilds_on_expired_credentials with the concrete
MockDriveService class and give it an explicit _http attribute built from
types.SimpleNamespace so it satisfies the _DriveService runtime Protocol;
specifically, instantiate MockDriveService, set its _http =
SimpleNamespace(credentials=SimpleNamespace(expired=False)) for the non-expired
case and expired=True for the expired case, then pass those instances into
_as_drive_service(gw._service = _as_drive_service(...)) so the isinstance checks
in _as_drive_service() no longer rely on MagicMock's dynamic attributes.
tests/unit/storage/test_store_ops.py (1)

1757-1816: ⚠️ Potential issue | 🟡 Minor

Leaked backend: vector async-boundary tests never close SQLiteBackend.

test_search_similar_offloads_vector_query, test_embed_conversation_offloads_vector_upsert, and test_similarity_search_offloads_vector_query now construct a real SQLiteBackend(db_path=tmp_path / "vectors.db") but — unlike the other backend-using tests in this file — never call await backend.close(). With the real backend this leaves the connection / thread pool open until GC, which can surface as ResourceWarning: unclosed database (or hang under --fail-on-unclosed) once strict asyncio teardown is enabled by the new verification harness.

♻️ Suggested fix (applied consistently to all three tests)
-        backend = SQLiteBackend(db_path=tmp_path / "vectors.db")
-        repo = ConversationRepository(backend=backend)
-        ...
-        result = await repo.search_similar("semantic query", limit=4, vector_provider=provider)
-
-        assert ...
+        backend = SQLiteBackend(db_path=tmp_path / "vectors.db")
+        repo = ConversationRepository(backend=backend)
+        try:
+            ...
+            result = await repo.search_similar("semantic query", limit=4, vector_provider=provider)
+            assert ...
+        finally:
+            await backend.close()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/storage/test_store_ops.py` around lines 1757 - 1816, Each test
that constructs a real SQLiteBackend (test_search_similar_offloads_vector_query,
test_embed_conversation_offloads_vector_upsert,
test_similarity_search_offloads_vector_query) leaks the DB connection; ensure
the backend is closed by calling await backend.close() before the test returns
(or wrap usage in try/finally and call await backend.close() in finally). Locate
the local variable backend = SQLiteBackend(...) in each test and add the close
call (or the try/finally) so the SQLiteBackend instance is properly closed.
tests/infra/semantic_facts.py (1)

75-96: ⚠️ Potential issue | 🟠 Major

Compute text-role counts and attachment totals from the same subset as the other surfaces.

text_role_counts=dict(roles) counts every message, while the record/domain paths only count messages with non-blank text. attachment_count=sum(1 for message ...) also counts attachment-bearing messages, not attachments. Both fields are part of comparable_core(), so a payload with tool-only messages or multiple attachments on one message will falsely disagree with the hydrated/record surfaces.

Suggested fix
         messages = json_document_list(payload.get("messages"))
         roles = Counter(_string_value(m.get("role")) or "unknown" for m in messages)
+        text_roles = Counter(
+            _string_value(m.get("role")) or "unknown"
+            for m in messages
+            if _string_value(m.get("text")).strip()
+        )
         has_tool_use = any(
             any(block.get("type") in ("tool_use", "tool_result") for block in _content_blocks(message))
             for message in messages
         )
@@
             message_ids=tuple(_string_value(message.get("id")) for message in messages),
             text_message_ids=tuple(
                 _string_value(message.get("id")) for message in messages if _string_value(message.get("text")).strip()
             ),
-            text_role_counts=dict(roles),
-            attachment_count=sum(1 for message in messages if bool(message.get("attachments"))),
+            text_role_counts=dict(text_roles),
+            attachment_count=sum(len(json_document_list(message.get("attachments"))) for message in messages),
             has_attachments=has_attachments,
             has_tool_use=has_tool_use,
             has_thinking=has_thinking,
         )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/semantic_facts.py` around lines 75 - 96, The current code builds
roles and attachment_count over all messages, causing mismatches with other
fields that only consider messages with non-blank text; change to derive these
from the same filtered set used for text_message_ids: create a filtered_messages
list like [m for m in messages if _string_value(m.get("text")).strip()], then
compute text_role_counts = dict(Counter(_string_value(m.get("role")) or
"unknown" for m in filtered_messages)) and compute attachment_count =
sum(len(m.get("attachments") or []) for m in filtered_messages) before calling
cls so that text_role_counts and attachment_count align with text_message_ids
and comparable_core().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@devtools/command_catalog.py`:
- Around line 47-53: The current return-type guard in the generated wrapper
_main accepts bool because bool subclasses int; change the check in _main that
validates entrypoint's result to reject booleans (e.g., use a strict type check
so only plain int is allowed or explicitly exclude bool) so that a True/False
return no longer passes the guard; update the error path that references
self.module and self.entrypoint accordingly.

In `@devtools/pipeline_probe.py`:
- Around line 755-819: The helper validators (_string_value, _int_value,
_string_list_value, _int_map_value, _document_list_value) currently use
document.get(key) so a missing key appears as a type error; change each to first
check key in document and raise a clearer error (e.g. KeyError or a TypeError
with message like "manifest field 'X' is required/missing") before fetching the
value, then keep the existing type checks and error messages (refer to the
functions _string_value, _int_value, _string_list_value, _int_map_value, and
_document_list_value to apply the same fix).

In `@polylogue/cli/embed_runtime.py`:
- Around line 37-39: The current runtime check only ensures env has a ui
attribute (via _HasUI) but doesn't validate the UI object's shape, causing
runtime failures when accessing ui.plain, ui.progress(), or ui.console.print();
update the guard around env usage to validate the nested UI object too — either
by checking isinstance(env.ui, _EmbedUI) if _EmbedUI is runtime_checkable, or by
explicit attribute checks (hasattr(ui, "plain"), hasattr(ui, "progress"),
hasattr(ui, "console") and hasattr(ui.console, "print")) before calling
ui.plain, ui.progress(), or ui.console.print(); modify the logic where
isinstance(env, _HasUI) is used and where ui is dereferenced so the code only
proceeds when the nested UI satisfies the required shape.

In `@polylogue/cli/query.py`:
- Around line 61-72: The helper _resolve_maybe_awaitable currently uses a
generic _T which allows ambiguous overload resolution; change its annotated
types to specifically handle bools: replace the two overloads and the
implementation signature so the function accepts Awaitable[bool] | bool and
returns bool (update the overload declarations and the def signature of
_resolve_maybe_awaitable accordingly), ensuring the implementation body still
awaits when inspect.isawaitable(value) and returns a bool result; this targets
the caller that resolves a boolean and removes mypy ambiguity for
_resolve_maybe_awaitable.

In `@polylogue/cli/schema_command_support.py`:
- Around line 28-35: The _privacy_level function silently defaults unknown
values to "standard" and even returns raw strings instead of the PrivacyLevel
enum; change it to validate explicitly against allowed values
("strict","standard","permissive"), return the corresponding PrivacyLevel enum
member (e.g., PrivacyLevel.strict) and raise an error
(argparse.ArgumentTypeError or ValueError used by the CLI) for any invalid input
with a clear message listing valid options; apply the same validation + error
behavior to the analogous validator at lines 46-57 so typos fail closed rather
than defaulting.

In `@polylogue/lib/messages.py`:
- Around line 129-132: The code incorrectly tries to call generate() on a
GetJsonSchemaHandler; replace that with calling the handler as a callable:
ensure handler is callable (raise TypeError if not), obtain the core schema for
Message (e.g. via the GetCoreSchemaHandler or Message.__pydantic_core_schema__),
call json_schema = handler(_core_schema), then pass that into
handler.resolve_ref_schema(json_schema) so the return becomes
{"type":"array","items": handler.resolve_ref_schema(json_schema)}; update the
checks around generate_schema and the use of generate() accordingly (references:
handler, generate_schema, GetJsonSchemaHandler, GetCoreSchemaHandler, Message,
resolve_ref_schema).

In `@polylogue/lib/provider_semantics.py`:
- Around line 215-218: The function extract_codex_text currently narrows the
declared Sequence[object] input by rejecting non-list sequences (e.g., tuples)
with isinstance(content, list); update extract_codex_text to accept any Sequence
by removing the list-only check and iterating over content (use
collections.abc.Sequence if you need explicit type checks),
accumulate/concatenate text elements the same way as before (handling
dicts/strings as original logic), and return the joined string—ensure you still
handle None/empty inputs and non-text items the same as the original behavior
while referencing the extract_codex_text function to locate the change.

In `@polylogue/logging.py`:
- Around line 49-55: The _StderrProxy.close method must not close the global
sys.stderr; change close() to be a no-op that only flushes the underlying stream
if available (e.g., call getattr(self._stream, "flush", lambda: None)()), and
ensure the closed property does not cause a global close — either return
getattr(self._stream, "closed", False) or simply False to reflect a non-owning
proxy. Apply the same change to the corresponding stdout proxy (the analogous
methods around lines 95-105, e.g., _StdoutProxy.close and its closed property)
so both proxies match the non-closing __exit__ behavior.

In `@polylogue/pipeline/observers.py`:
- Around line 134-157: The _post_webhook helper currently ignores non-2xx
responses from the webhook server, so update _post_webhook (used by
WebhookObserver.on_completed) to inspect the http.client.HTTPResponse returned
by connection.getresponse(), check response.status and treat any status outside
200-299 as an error: read the body for context, and either raise an exception
(e.g., http.client.HTTPException or a custom exception) or return/fail so the
caller's existing except/logging path can record the failure; ensure you still
close the connection in the finally block and include response.status and
response body (or a trimmed excerpt) in the error message to preserve
observability.

In `@polylogue/pipeline/services/acquisition.py`:
- Around line 77-79: The runtime isinstance check against DriveUILike only
verifies the presence of attributes/methods (plain, console, input) and not
their signatures, so the error message is misleading; update the check in
acquisition.py (the block that inspects ui and uses isinstance(ui, DriveUILike)
and sets drive_ui) to either change the TypeError message to something like
"Drive acquisition UI must expose the DriveUILike surface (attributes plain,
console, input)" or add a short comment/docstring above the check clarifying
that this is a structural check and full type validation relies on static typing
(mypy), so callers must ensure correct signatures for plain/console/input.

In `@polylogue/schemas/code_detection_tree_sitter.py`:
- Around line 33-42: The _is_node_like guard only validates the root shape but
_walk inside ts_error_ratio iterates node.children and recurses without
re-checking each descendant, so either (a) make the intent explicit by adding a
brief comment in _is_node_like and above ts_error_ratio/_walk saying the check
is intentionally shallow (defensive typing only), or (b) make it defensive by
calling _is_node_like on each child before recursing in _walk (validate
node.children elements and skip or bail if they aren’t TreeSitterNodeLike). Also
simplify by inlining the literal strings "type" and "is_missing" instead of
using the local variables type_attr/missing_attr. Ensure references to
_is_node_like, ts_error_ratio, _walk, TreeSitterNodeLike, and node.children are
updated accordingly.

In `@polylogue/schemas/operator_models.py`:
- Around line 24-31: The type guard _is_operator_json_value currently treats all
floats as valid JSON values, which lets NaN/Inf through; update the function so
that when value is a float it only returns True if the float is finite (use
math.isfinite or equivalent) and otherwise return False; ensure the same
finite-float check applies inside the Sequence/Mapping recursion so that
_is_operator_json_value rejects non-finite floats before JSONDocument
serialization.

In `@polylogue/showcase/qa_markdown.py`:
- Around line 15-20: The _payload_mapping function is duplicated; consolidate it
with the existing qa_summary._payload_mapping (or unify with
scenarios.payloads.payload_mapping) by extracting a single shared helper (e.g.,
report_common.payload_mapping) and update all callers to import that one
function; also simplify the implementation inside _payload_mapping (or the
unified helper) by removing the redundant str(key) conversion after the
isinstance(key, str) check and return dict(value) (or use dict(value.items()))
and keep the same TypeError failure contract so callers behave identically.

In `@polylogue/sources/drive_gateway.py`:
- Around line 46-55: The TypedDict _DriveListKwargs currently requires all four
keys (q, fields, pageToken, pageSize); change pageToken and pageSize to optional
by using NotRequired (e.g., from typing_extensions import NotRequired or typing
import NotRequired on 3.11+) so callers using Unpack[_DriveListKwargs] aren't
forced to provide those optional Google API params; update the _DriveListKwargs
definition (and add the NotRequired import if missing) and ensure any call sites
like list_files still work with the loosened contract.

In `@polylogue/storage/backends/queries/mappers_support.py`:
- Around line 42-58: The overloads for _row_get are incorrect: the second
overload claims returning _T when a default is provided, but at runtime _row_get
returns the stored _RowValue (or default only if the column is missing). Update
the overloads (or remove the optimistic one) so the signature for calls with a
default reflects _RowValue | _T (i.e., default does not guarantee coercion), and
clarify the docstring to state "default is returned only when the column is
missing, otherwise the raw _RowValue is returned"; also ensure callers that need
typed values use the typed wrappers _row_int, _row_text, or _row_float instead
of relying on _row_get to coerce types.
- Around line 36-39: The except clause that converts JSON decode failures into
DatabaseError should catch ValueError in addition to json.JSONDecodeError
because polylogue.lib.json.loads may raise ValueError (or
orjson.JSONDecodeError); update the handler around the loads(raw) call in
mappers_support.py to except (json.JSONDecodeError, ValueError) as exc and
re-raise DatabaseError with the same message using field, record_id, raw_preview
and raw to preserve context.

In `@polylogue/storage/embedding_stats_support.py`:
- Around line 23-24: The helper _sqlite_rows currently swallows tuple rows by
filtering with isinstance and should instead follow a fail-fast pattern: change
it to validate that every item in rows is an sqlite3.Row and if any item is not,
raise a TypeError with a clear message instructing to set conn.row_factory via
configure_connection/configure_read_connection; apply the same
validation/TypeError change to the other row-filtering helper in this file (the
other function that currently filters tuple rows) so misconfigured async
connections fail loudly rather than silently producing incorrect stats.

In `@polylogue/storage/repository_write_conversations.py`:
- Around line 43-50: _normalize_hash_value currently treats bools as distinct
from ints and falls back to str() for unknown types, which can cause
nondeterministic hashes; update it to explicitly normalize bools into integer
1/0 (handle isinstance(value, bool) first), remove bool from the allowed types
tuple (use (str, int, float) instead), and stop coercing arbitrary objects via
str() — either raise a TypeError for unsupported types or document that inputs
must be JSONValue-safe so callers must pre-serialize complex types; reference
the _normalize_hash_value function in your change.
- Around line 53-98: The domain hashing in _content_hash_from_metadata_or_domain
diverges from the ingest pipeline because it uses the full canonical message.id
and a different timestamp normalization; implement a single
canonical_conversation_hash(conversation: Conversation) -> str that builds the
same payload as the ingest pipeline (use the provider_message_id extracted from
message.id — e.g., split on ':' and take the provider part — for message IDs,
normalize timestamps using the same call-order as ingest by applying
_normalize_hash_value to the raw timestamp/ISO string exactly as ingest does,
and then call hash_payload), replace the existing logic in
_content_hash_from_metadata_or_domain to call canonical_conversation_hash, and
ensure the ingest path reuses this helper (or, if you prefer fallback semantics,
make _content_hash_from_metadata_or_domain reject saves when
metadata["content_hash"] is absent instead of computing a divergent hash).

In `@tests/infra/pipeline_roundtrip.py`:
- Around line 27-33: The decode_source_payload function currently swallows the
original JSON parse error when falling back to JSONL, losing the original
exception context; modify decode_source_payload so that you capture the initial
exception (e.g., original_exc = the ValueError from loads(text)) and then wrap
the JSONL fallback in its own try/except that re-raises a new ValueError with a
clear message (like "payload is not valid JSON or JSONL") using "raise ... from
original_exc" (or otherwise attach original_exc) so if the JSONL processing also
fails the original whole-document parse error is preserved for debugging.

In `@tests/infra/pty_cli.py`:
- Around line 210-223: _chardict_to_str currently accepts any object and
silently returns "" for non-mappings, uses assert (which can be disabled) to
check that Char.data is a string, and indexes chardict without checking for
missing/sparse keys; change it to fail-closed: first verify chardict is a
Mapping (from collections.abc.Mapping) and raise TypeError if not, ensure keys
are ints and compute max_col from keys, then verify that every index in range(0,
max_col+1) exists in the mapping (raise ValueError for sparse/missing indices),
access each entry and validate its .data with isinstance(data, str) and raise
TypeError if not, and remove the assert; keep history_lines using
_chardict_to_str so tests will fail loudly on malformed pyte history.

In `@tests/infra/state_machines.py`:
- Around line 92-97: The helper delete_conversation_and_assert_absent currently
only verifies repository deletion and raw-row cleanup; after asserting
repository.get(conversation_id) is None add surface-level checks to ensure the
conversation is gone from higher-level APIs and search indices: call
self.facade.get_conversation(conversation_id) (or equivalent client getter) and
assert it returns None, call self.client.list_conversations() (or equivalent
listing method) and assert the conversation_id is not in that list, and run a
search via self.search_client.search(...) (or equivalent search/index query)
asserting no results reference conversation_id before calling
self.assert_no_dangling_runtime_rows(conversation_id).

In `@tests/infra/surfaces.py`:
- Around line 142-154: The search path in query_ids is capped at 100 results,
causing mismatch with SQL surfaces; update the call in query_ids (the branch
that calls self._repository.search in the async def query_ids method) to use an
unbounded limit (or pass limit=None) instead of 100 so it returns the full
result set, and make the same change for the analogous block around lines
177-187 (the other query_ids/query_count-like methods) so search and count are
consistent across surfaces; ensure query_count continues to call query_ids when
appropriate so both functions operate on the same untruncated result set.

In `@tests/unit/cli/test_check_runtime.py`:
- Around line 454-457: Collapse the two successive assertions that iterate over
checks into a single assertion to avoid double iteration: replace the separate
all(...) checks on checks with one assert that uses all(...) and checks both
"isinstance(check, dict)" and that both "name" and "status" keys are present
(e.g., all(isinstance(check, dict) and "name" in check and "status" in check for
check in checks)); update the assertion that currently references checks so it
performs this combined validation in one pass.

In `@tests/unit/cli/test_products.py`:
- Around line 232-237: The callable assertion for callback.__wrapped__ should be
moved out of the pytest.raises block so a missing or non-callable wrapped is
reported directly; retrieve wrapped = getattr(callback, "__wrapped__", None) and
assert callable(wrapped) before the with pytest.raises(SystemExit, match=...)
context, then inside the context call wrapped(mock_ctx, json_mode=False,
refined_work_kind="planning") to exercise the SystemExit path for
session_enrichments.

In `@tests/unit/cli/test_query_fmt.py`:
- Around line 343-344: The test currently uses "tags": tags or ["law",
"example"], which treats an explicit empty list as omitted; change this to use
the default only when tags is None by replacing that expression with a
None-check (e.g., use tags if tags is not None else ["law", "example"]) so the
code preserves explicit empty tag lists when building the conversation (update
the dict assignment where "tags" is set).

In `@tests/unit/cli/test_source_selection_helpers.py`:
- Around line 350-353: The test double's print method currently drops kwargs so
it ignores sep and end and diverges from ConsoleLike.print; update the
print(self, *objects, **kwargs) in the test double to read sep =
kwargs.get("sep", " ") and end = kwargs.get("end", "\n") (and ignore unrelated
kwargs), join objects using that sep and write the result followed by end to
self._buffer (preserving the existing str(...) behavior) so test output matches
ConsoleLike.print formatting.
- Around line 366-374: The helper _summary_call should assert the number of
times the mock was called before reading call_args to avoid masking duplicate
summary() calls; modify _summary_call (or add an optional parameter
expected_calls: int = 1) to check summary_mock.call_count == expected_calls and
raise an AssertionError with a clear message if not, then proceed to unwrap
summary_mock.call_args for the final call as before (use the function name
_summary_call and the parameter/variable summary_mock to locate where to add the
check).

In `@tests/unit/core/test_raw_payload_decode.py`:
- Around line 13-15: The integer validation helper _optional_int currently
accepts bool because isinstance(value, int) returns True for True/False; change
the check to exclude bool (e.g. require type(value) is int or use
isinstance(value, int) and not isinstance(value, bool)) so the assertion becomes
value is None or an actual int, and apply the same fix to the other integer
validation helper in this file (the second occurrence around line 27) to ensure
booleans are rejected everywhere.

In `@tests/unit/devtools/test_executable_scenarios.py`:
- Around line 21-31: Extract the duplicated helpers _dict_payload and
_dict_list_payload into a single shared test helper module (e.g., a tests
support package exposing payloads) and replace the copied definitions in each
test file with imports from that module; preserve the current behavior (type
annotations and the isinstance assertions) and function names so existing tests
keep working, and update imports in every test that currently defines those
helpers to import _dict_payload and _dict_list_payload from the new shared
module.

In `@tests/unit/pipeline/test_ingest_batch.py`:
- Around line 89-95: The test's _FakeRefreshConnection must not subclass
aiosqlite.Connection without calling its constructor; replace it with a minimal
fake object that implements only the async commit method and an AsyncMock
commit_mock (do not inherit from aiosqlite.Connection), and in the test's
_connection() helper yield cast(aiosqlite.Connection, fake_conn) so the test
satisfies the _ConnectionBackendLike/AbstractAsyncContextManager type without
creating a partially-initialized aiosqlite.Connection; alternatively, narrow the
_ConnectionBackendLike.protocol to require only commit and adapt the test double
accordingly (refer to _FakeRefreshConnection, commit, _connection(),
refresh_session_products_bulk, and _ConnectionBackendLike).

In `@tests/unit/pipeline/test_ingestion_chaos.py`:
- Around line 96-98: The helper _as_record currently stringifies keys which can
silently collapse distinct non-string keys; instead, validate that every key is
already a str and fail fast on any non-string key, then return a new dict with
the original typed keys (e.g., in _as_record, assert all(isinstance(k, str) for
k in value.keys()) and raise/assert if not, then rebuild/return {k: v for k, v
in value.items()} without converting keys to str).

In `@tests/unit/sources/test_unified_semantic_laws.py`:
- Around line 79-87: The Protocol ViewportRecord's role_normalized currently
allows str | Role but the assertions later in
tests/unit/sources/test_unified_semantic_laws.py compare role_normalized to a
str; fix by making the types consistent: either change the Protocol's
role_normalized signature in ViewportRecord to return just str, or update the
test assertions that use viewport.role_normalized to normalize it to a string
before comparing (e.g., coerce via str(viewport.role_normalized) or use .value
if Role is an Enum) so the comparisons and the ViewportRecord.role_normalized
declaration agree.

In `@tests/unit/storage/test_archive_search_contracts.py`:
- Around line 30-52: The _FakeQueries test helper currently uses `@dataclass`
which bypasses SQLiteQueryStore.__init__ and leaves parent state (like
self._connection_factory) uninitialized; replace the dataclass with an explicit
__init__ on class _FakeQueries that calls super().__init__(), accepts and
assigns the fields hits, records_by_id, and last_batch_ids, and preserves the
existing overrides (search_conversation_hits, search_action_conversation_hits,
get_conversations_batch) so the base class is properly initialized and future
parent method calls won't raise AttributeError.

In `@tests/unit/storage/test_query_security.py`:
- Around line 105-111: Replace the getattr indirection with a direct call to the
repository method so attribute-name typos are caught by static checks: call
temp_repo.view(None) directly (use a localized type-ignore such as "# type:
ignore[arg-type]" on that call to express the intentional None escape hatch) and
keep the existing except (TypeError, ValueError) handling; this preserves
runtime behavior while ensuring the attribute name "view" is validated by the
type checker.

In `@tests/unit/storage/test_store_ops.py`:
- Around line 226-234: The helper _message_payloads currently returns an empty
list when value is not a list but raises TypeError for non-dict items, which can
silently hide malformed payloads; change it so it consistently raises for
invalid input: in _message_payloads, if value is not a list raise a TypeError
(same message style as used for non-dict items), otherwise iterate the list and
raise if any item is not a dict, returning a list copy only when validation
succeeds; this keeps behavior symmetric and prevents silent masking of shape
regressions.

---

Outside diff comments:
In `@polylogue/lib/json.py`:
- Around line 19-26: The helpers currently accept non-finite float values (NaN,
Infinity, -Infinity); update is_json_value and require_json_document to reject
those by adding a math.isfinite() check for float instances: when checking
isinstance(value, float) ensure math.isfinite(value) is True (or combine with
isinstance(value, (int, float)) but treat floats via math.isfinite), and
likewise when validating dict/list items ensure any float encountered is finite;
import math and apply math.isfinite in both is_json_value and
require_json_document to make their behavior consistent with
loads(parse_constant=_reject_non_finite_token).

In `@polylogue/lib/query_spec.py`:
- Around line 124-140: The function optional_sort_field currently uses an
explicit if-chain to accept known SortField literals; replace that with a single
membership check: use optional_text(value) to get candidate, return None if
None, then if candidate is in the allowed SortField set (e.g., a frozenset of
the SortField literals or typing.get_args(SortField) cast appropriately) return
candidate, otherwise raise QuerySpecError("sort", candidate); update
optional_sort_field to reference optional_text, SortField, and QuerySpecError as
above and add a localized mypy ignore or cast if needed to satisfy type
narrowing.

In `@polylogue/scenarios/payloads.py`:
- Around line 82-88: payload_mapping currently returns None on non-Mapping input
or non-string keys and unnecessarily calls str(key) when keys are already
strings; align its behavior with the sibling helpers (_payload_mapping in
polylogue/showcase/qa_markdown.py and qa_summary.py) by raising a TypeError when
value is a Mapping but contains any non-str keys instead of returning None, and
simplify the return to a plain dict (e.g., dict(value) or a simple {k: v for k,
v in value.items()}) removing the redundant str(key) coercion; keep the initial
isinstance(value, Mapping) check and raise TypeError with a clear message
(mentioning payload_mapping) when key types are invalid.

In `@tests/infra/semantic_facts.py`:
- Around line 75-96: The current code builds roles and attachment_count over all
messages, causing mismatches with other fields that only consider messages with
non-blank text; change to derive these from the same filtered set used for
text_message_ids: create a filtered_messages list like [m for m in messages if
_string_value(m.get("text")).strip()], then compute text_role_counts =
dict(Counter(_string_value(m.get("role")) or "unknown" for m in
filtered_messages)) and compute attachment_count = sum(len(m.get("attachments")
or []) for m in filtered_messages) before calling cls so that text_role_counts
and attachment_count align with text_message_ids and comparable_core().

In `@tests/infra/test_storage_records.py`:
- Around line 40-65: The test leaves the in-memory SQLite connection open if an
assertion fails; wrap the use of conn around a try/finally (or use
contextlib.closing) so conn.close() always runs: after creating conn
(TrackingConnection) and before calling storage_helpers.store_records /
asserting on result and conn.commit_states, ensure you place the store_records
call and subsequent asserts inside a try block and call conn.close() in the
finally block (or replace the manual lifecycle with a context manager) to
guarantee closure even on test failures.

In `@tests/unit/cli/test_deterministic_output.py`:
- Around line 46-61: Both helpers (_extract_json and _result_payload) perform an
unnecessary shallow copy via dict(parsed) / dict(result) after an
isinstance(..., dict) type-narrowing; remove the allocations and return the
already-narrowed parsed and result values directly (in _extract_json return
parsed, in _result_payload return result). If mypy complains about return types,
satisfy it by annotating the local variable (e.g., parsed: JSONEnvelope or
result: JSONEnvelope) or add a narrow # type: ignore[return-value] comment — do
not allocate a new dict.

In `@tests/unit/cli/test_json_envelope_contract.py`:
- Around line 67-91: The helpers _parse_json_output and _result_payload are
needlessly returning shallow copies via dict(parsed) and dict(result); after the
isinstance(..., dict) checks you can safely return the original parsed and
result objects directly to avoid extra allocations—replace the dict(...) returns
with returning parsed and result respectively. Also consider deduplicating these
helpers by moving _parse_json_output/_result_payload into a shared tests unit
helper (e.g., tests/unit/cli/_json_helpers.py or conftest) and importing them
from both test modules.

In `@tests/unit/sources/test_drive_gateway.py`:
- Around line 168-180: Replace the bare MagicMock instances used in
test_service_handle_returns_cached_service_when_not_expired and
test_service_handle_rebuilds_on_expired_credentials with the concrete
MockDriveService class and give it an explicit _http attribute built from
types.SimpleNamespace so it satisfies the _DriveService runtime Protocol;
specifically, instantiate MockDriveService, set its _http =
SimpleNamespace(credentials=SimpleNamespace(expired=False)) for the non-expired
case and expired=True for the expired case, then pass those instances into
_as_drive_service(gw._service = _as_drive_service(...)) so the isinstance checks
in _as_drive_service() no longer rely on MagicMock's dynamic attributes.

In `@tests/unit/storage/test_store_ops.py`:
- Around line 1757-1816: Each test that constructs a real SQLiteBackend
(test_search_similar_offloads_vector_query,
test_embed_conversation_offloads_vector_upsert,
test_similarity_search_offloads_vector_query) leaks the DB connection; ensure
the backend is closed by calling await backend.close() before the test returns
(or wrap usage in try/finally and call await backend.close() in finally). Locate
the local variable backend = SQLiteBackend(...) in each test and add the close
call (or the try/finally) so the SQLiteBackend instance is properly closed.
🪄 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: edca8860-d598-4ebe-9829-884ef2192b01

📥 Commits

Reviewing files that changed from the base of the PR and between d21f6fe and 7b9ecf0.

📒 Files selected for processing (139)
  • devtools/command_catalog.py
  • devtools/pipeline_probe.py
  • devtools/query_memory_budget.py
  • docs/cli-reference.md
  • polylogue/cli/click_option_groups.py
  • polylogue/cli/embed_runtime.py
  • polylogue/cli/machine_errors.py
  • polylogue/cli/query.py
  • polylogue/cli/run_observers.py
  • polylogue/cli/schema_command_support.py
  • polylogue/lib/conversation_runtime.py
  • polylogue/lib/dates.py
  • polylogue/lib/filter_builder.py
  • polylogue/lib/json.py
  • polylogue/lib/messages.py
  • polylogue/lib/metrics.py
  • polylogue/lib/provider_semantics.py
  • polylogue/lib/query_spec.py
  • polylogue/lib/raw_payload_decode.py
  • polylogue/lib/raw_payload_sampling_extract.py
  • polylogue/lib/raw_payload_streams.py
  • polylogue/logging.py
  • polylogue/mcp/server_support.py
  • polylogue/mcp/server_tools.py
  • polylogue/pipeline/observers.py
  • polylogue/pipeline/services/acquisition.py
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/readiness.py
  • polylogue/scenarios/payloads.py
  • polylogue/schemas/code_detection_tree_sitter.py
  • polylogue/schemas/generation_provider_bundle_packages.py
  • polylogue/schemas/generation_semantic_relations.py
  • polylogue/schemas/operator_annotations.py
  • polylogue/schemas/operator_models.py
  • polylogue/schemas/pinning.py
  • polylogue/schemas/synthetic/build_batch.py
  • polylogue/schemas/tooling_registry.py
  • polylogue/showcase/qa_markdown.py
  • polylogue/showcase/qa_summary.py
  • polylogue/sources/drive_auth.py
  • polylogue/sources/drive_auth_support.py
  • polylogue/sources/drive_gateway.py
  • polylogue/sources/drive_source_client.py
  • polylogue/sources/drive_types.py
  • polylogue/sources/parsers/claude_code_parser.py
  • polylogue/storage/action_event_status.py
  • polylogue/storage/backends/queries/mappers.py
  • polylogue/storage/backends/queries/mappers_archive.py
  • polylogue/storage/backends/queries/mappers_product_aggregates.py
  • polylogue/storage/backends/queries/mappers_product_legacy.py
  • polylogue/storage/backends/queries/mappers_product_profiles.py
  • polylogue/storage/backends/queries/mappers_product_timelines.py
  • polylogue/storage/backends/queries/mappers_support.py
  • polylogue/storage/backends/queries/raw_reads.py
  • polylogue/storage/embedding_stats.py
  • polylogue/storage/embedding_stats_support.py
  • polylogue/storage/hydrators.py
  • polylogue/storage/repository.py
  • polylogue/storage/repository_archive_queries.py
  • polylogue/storage/repository_write_conversations.py
  • polylogue/storage/repository_writes.py
  • polylogue/storage/search_providers/__init__.py
  • polylogue/surface_payloads.py
  • polylogue/ui/facade.py
  • pyproject.toml
  • stubs/dateparser/__init__.pyi
  • tests/conftest.py
  • tests/infra/archive_scenarios.py
  • tests/infra/drive_mocks.py
  • tests/infra/mcp.py
  • tests/infra/oracles.py
  • tests/infra/pipeline_roundtrip.py
  • tests/infra/pty_cli.py
  • tests/infra/query_cases.py
  • tests/infra/semantic_facts.py
  • tests/infra/state_machines.py
  • tests/infra/strategies/search.py
  • tests/infra/surfaces.py
  • tests/infra/test_archive_scenarios.py
  • tests/infra/test_storage_records.py
  • tests/unit/cli/test_check_runtime.py
  • tests/unit/cli/test_click_app.py
  • tests/unit/cli/test_click_app_main.py
  • tests/unit/cli/test_deterministic_output.py
  • tests/unit/cli/test_json_envelope_contract.py
  • tests/unit/cli/test_products.py
  • tests/unit/cli/test_qa_finalization.py
  • tests/unit/cli/test_query_exec.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/cli/test_query_fmt.py
  • tests/unit/cli/test_run.py
  • tests/unit/cli/test_run_int.py
  • tests/unit/cli/test_run_laws.py
  • tests/unit/cli/test_source_selection_helpers.py
  • tests/unit/core/conftest.py
  • tests/unit/core/test_code_detection.py
  • tests/unit/core/test_filters_schemas.py
  • tests/unit/core/test_raw_payload_decode.py
  • tests/unit/core/test_synthetic_semantic_wiring.py
  • tests/unit/core/test_synthetic_semantics.py
  • tests/unit/devtools/test_devtools_main.py
  • tests/unit/devtools/test_executable_scenarios.py
  • tests/unit/devtools/test_validation_lanes.py
  • tests/unit/mcp/conftest.py
  • tests/unit/pipeline/test_acquisition_streams.py
  • tests/unit/pipeline/test_branching.py
  • tests/unit/pipeline/test_ingest_batch.py
  • tests/unit/pipeline/test_ingestion_chaos.py
  • tests/unit/pipeline/test_observers.py
  • tests/unit/pipeline/test_process_pool.py
  • tests/unit/pipeline/test_roundtrip_hydration_laws.py
  • tests/unit/rendering/test_rendering.py
  • tests/unit/scenarios/test_runtime.py
  • tests/unit/scenarios/test_scenario_specs.py
  • tests/unit/showcase/test_cli_boundary.py
  • tests/unit/showcase/test_qa_markdown.py
  • tests/unit/showcase/test_report.py
  • tests/unit/showcase/test_scenario_models.py
  • tests/unit/showcase/test_verification_lane.py
  • tests/unit/sources/test_drive_auth.py
  • tests/unit/sources/test_drive_gateway.py
  • tests/unit/sources/test_drive_source_client.py
  • tests/unit/sources/test_parser_crashlessness.py
  • tests/unit/sources/test_parsers_codex.py
  • tests/unit/sources/test_parsers_props.py
  • tests/unit/sources/test_unified_semantic_laws.py
  • tests/unit/storage/test_archive_search_contracts.py
  • tests/unit/storage/test_backend.py
  • tests/unit/storage/test_embedding_stats.py
  • tests/unit/storage/test_hybrid.py
  • tests/unit/storage/test_query_mappers.py
  • tests/unit/storage/test_query_security.py
  • tests/unit/storage/test_repository_lifecycle_laws.py
  • tests/unit/storage/test_retrieval_readiness_laws.py
  • tests/unit/storage/test_session_product_mapper_fallbacks.py
  • tests/unit/storage/test_store_ops.py
  • tests/unit/storage/test_vec.py
  • tests/unit/test_cross_surface_agreement.py
  • tests/unit/ui/test_tui.py

Comment on lines +47 to +53
def _main(argv: list[str] | None = None) -> int:
result = entrypoint(argv)
if not isinstance(result, int):
raise TypeError(f"{self.module}.{self.entrypoint} returned {type(result).__name__}, expected int")
return result

return _main

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

isinstance(result, int) silently accepts bool.

bool is a subclass of int, so an entrypoint returning True/False passes the guard even though the error message advertises "expected int". If the intent is a strict exit-code contract, exclude bools:

Proposed tightening
-            if not isinstance(result, int):
+            if not isinstance(result, int) or isinstance(result, bool):
                 raise TypeError(f"{self.module}.{self.entrypoint} returned {type(result).__name__}, expected int")

Otherwise LGTM — the wrapper + callable check is a clean replacement for the prior cast.

📝 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
def _main(argv: list[str] | None = None) -> int:
result = entrypoint(argv)
if not isinstance(result, int):
raise TypeError(f"{self.module}.{self.entrypoint} returned {type(result).__name__}, expected int")
return result
return _main
def _main(argv: list[str] | None = None) -> int:
result = entrypoint(argv)
if not isinstance(result, int) or isinstance(result, bool):
raise TypeError(f"{self.module}.{self.entrypoint} returned {type(result).__name__}, expected int")
return result
return _main
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@devtools/command_catalog.py` around lines 47 - 53, The current return-type
guard in the generated wrapper _main accepts bool because bool subclasses int;
change the check in _main that validates entrypoint's result to reject booleans
(e.g., use a strict type check so only plain int is allowed or explicitly
exclude bool) so that a True/False return no longer passes the guard; update the
error path that references self.module and self.entrypoint accordingly.

Comment on lines +755 to +819
def _string_value(document: JSONDocument, key: str) -> str:
value = document.get(key)
if not isinstance(value, str):
raise TypeError(f"manifest field {key!r} must be a string")
return value


def _int_value(document: JSONDocument, key: str) -> int:
value = document.get(key)
if isinstance(value, bool) or not isinstance(value, int):
raise TypeError(f"manifest field {key!r} must be an integer")
return value


def _string_list_value(document: JSONDocument, key: str) -> list[str]:
value = document.get(key)
if not isinstance(value, list):
raise TypeError(f"manifest field {key!r} must be a list of strings")
result: list[str] = []
for item in value:
if not isinstance(item, str):
raise TypeError(f"manifest field {key!r} must be a list of strings")
result.append(item)
return result


def _int_map_value(document: JSONDocument, key: str) -> dict[str, int]:
value = document.get(key)
if not isinstance(value, dict):
raise TypeError(f"manifest field {key!r} must be an object")
result: dict[str, int] = {}
for item_key, item_value in value.items():
if isinstance(item_value, bool) or not isinstance(item_value, int):
raise TypeError(f"manifest field {key!r}.{item_key} must be an integer")
result[str(item_key)] = item_value
return result


def _document_list_value(document: JSONDocument, key: str) -> list[JSONDocument]:
value = document.get(key)
if not isinstance(value, list):
raise TypeError(f"manifest field {key!r} must be a list of JSON objects")
result: list[JSONDocument] = []
for item in value:
if not is_json_document(item):
raise TypeError(f"manifest field {key!r} must be a list of JSON objects")
result.append(item)
return result


def _archive_manifest_from_payload(payload: JSONDocument) -> ArchiveManifest:
return {
"input_mode": _string_value(payload, "input_mode"),
"source_db": _string_value(payload, "source_db"),
"source_blob_root": _string_value(payload, "source_blob_root"),
"seed": _int_value(payload, "seed"),
"sample_per_provider": _int_value(payload, "sample_per_provider"),
"provider_filters": _string_list_value(payload, "provider_filters"),
"source_filters": _string_list_value(payload, "source_filters"),
"candidate_count": _int_value(payload, "candidate_count"),
"missing_blob_count": _int_value(payload, "missing_blob_count"),
"available_by_provider": _int_map_value(payload, "available_by_provider"),
"sampled_by_provider": _int_map_value(payload, "sampled_by_provider"),
"records": _document_list_value(payload, "records"),
}

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: distinguish "missing key" from "wrong type" in manifest validator errors.

_string_value / _int_value / _string_list_value / _int_map_value / _document_list_value all call document.get(key) and then check the value's type. When a key is entirely absent, .get returns None and the user sees "manifest field 'seed' must be an integer" even though the actual fault is that the field was omitted. That makes debugging hand-edited or partial manifests harder than it needs to be.

Consider checking membership first:

♻️ Suggested diff
 def _string_value(document: JSONDocument, key: str) -> str:
-    value = document.get(key)
+    if key not in document:
+        raise TypeError(f"manifest field {key!r} is missing")
+    value = document[key]
     if not isinstance(value, str):
         raise TypeError(f"manifest field {key!r} must be a string")
     return value

Applies equivalently to the other four helpers. Strictly a UX improvement; no functional change.

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

In `@devtools/pipeline_probe.py` around lines 755 - 819, The helper validators
(_string_value, _int_value, _string_list_value, _int_map_value,
_document_list_value) currently use document.get(key) so a missing key appears
as a type error; change each to first check key in document and raise a clearer
error (e.g. KeyError or a TypeError with message like "manifest field 'X' is
required/missing") before fetching the value, then keep the existing type checks
and error messages (refer to the functions _string_value, _int_value,
_string_list_value, _int_map_value, and _document_list_value to apply the same
fix).

Comment on lines +37 to 39
@runtime_checkable
class _HasUI(Protocol):
ui: _EmbedUI

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
# Description: Show that a runtime-checkable Protocol with a data attribute accepts any object with that attribute.

python - <<'PY'
from typing import Protocol, runtime_checkable

class EmbedUI(Protocol):
    plain: bool
    def progress(self, description: str, total: int = 0): ...

`@runtime_checkable`
class HasUI(Protocol):
    ui: EmbedUI

class BadEnv:
    ui = object()

print(isinstance(BadEnv(), HasUI))
PY

Repository: Sinity/polylogue

Length of output: 64


🏁 Script executed:

# First, let's examine the file structure and locate the relevant code
fd embed_runtime.py

Repository: Sinity/polylogue

Length of output: 90


🏁 Script executed:

# Once we find it, let's examine the relevant code sections
cat -n polylogue/cli/embed_runtime.py | head -50

Repository: Sinity/polylogue

Length of output: 1643


🏁 Script executed:

# Check around line 100-102 where isinstance check happens
sed -n '95,110p' polylogue/cli/embed_runtime.py

Repository: Sinity/polylogue

Length of output: 717


🏁 Script executed:

# Check around lines 145-147 where ui attributes are accessed
sed -n '140,155p' polylogue/cli/embed_runtime.py

Repository: Sinity/polylogue

Length of output: 736


🏁 Script executed:

# Let's also check the full _HasUI definition and understand the context
sed -n '30,50p' polylogue/cli/embed_runtime.py

Repository: Sinity/polylogue

Length of output: 546


Validate the nested UI shape, not just env.ui presence.

The isinstance(env, _HasUI) check at line 100 only verifies that env exposes a ui attribute. An object with ui = object() passes this check, but then fails at line 145+ when accessing ui.plain, ui.progress(), or ui.console.print().

Proposed fix
-    if not isinstance(env, _HasUI):
+    ui = getattr(env, "ui", None)
+    console = getattr(ui, "console", None)
+    if (
+        ui is None
+        or not isinstance(getattr(ui, "plain", None), bool)
+        or not callable(getattr(ui, "progress", None))
+        or not callable(getattr(console, "print", None))
+    ):
         raise TypeError(f"Embedding environment must expose ui, got {type(env).__name__}")
-    ui = env.ui

Also applies to: lines 100-102

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

In `@polylogue/cli/embed_runtime.py` around lines 37 - 39, The current runtime
check only ensures env has a ui attribute (via _HasUI) but doesn't validate the
UI object's shape, causing runtime failures when accessing ui.plain,
ui.progress(), or ui.console.print(); update the guard around env usage to
validate the nested UI object too — either by checking isinstance(env.ui,
_EmbedUI) if _EmbedUI is runtime_checkable, or by explicit attribute checks
(hasattr(ui, "plain"), hasattr(ui, "progress"), hasattr(ui, "console") and
hasattr(ui.console, "print")) before calling ui.plain, ui.progress(), or
ui.console.print(); modify the logic where isinstance(env, _HasUI) is used and
where ui is dereferenced so the code only proceeds when the nested UI satisfies
the required shape.

Comment thread polylogue/cli/query.py
Comment on lines +61 to +72
@overload
async def _resolve_maybe_awaitable(value: Awaitable[_T]) -> _T: ...


@overload
async def _resolve_maybe_awaitable(value: _T) -> _T: ...


async def _resolve_maybe_awaitable(value: Awaitable[_T] | _T) -> _T:
if inspect.isawaitable(value):
return await cast(Awaitable[_T], value)
return cast(_T, value)
return await value
return value

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:

find . -name "query.py" | head -20

Repository: Sinity/polylogue

Length of output: 84


🏁 Script executed:

wc -l polylogue/cli/query.py 2>/dev/null || echo "File not found at expected location"

Repository: Sinity/polylogue

Length of output: 86


🏁 Script executed:

git ls-files | grep -E "(query\.py|pyproject\.toml|mypy\.ini|pyrightconfig|\.pylintrc)" | head -20

Repository: Sinity/polylogue

Length of output: 97


🏁 Script executed:

sed -n '55,80p' polylogue/cli/query.py

Repository: Sinity/polylogue

Length of output: 579


🏁 Script executed:

rg '_resolve_maybe_awaitable' polylogue/cli/query.py

Repository: Sinity/polylogue

Length of output: 354


🏁 Script executed:

cat pyproject.toml | head -50

Repository: Sinity/polylogue

Length of output: 1439


🏁 Script executed:

sed -n '1,25p' polylogue/cli/query.py

Repository: Sinity/polylogue

Length of output: 686


🏁 Script executed:

rg '_resolve_maybe_awaitable' -A 3 -B 1 polylogue/cli/query.py

Repository: Sinity/polylogue

Length of output: 630


🏁 Script executed:

grep -A 50 '\[tool\.' pyproject.toml | head -60

Repository: Sinity/polylogue

Length of output: 2121


🏁 Script executed:

rg 'TypeVar' polylogue/cli/query.py

Repository: Sinity/polylogue

Length of output: 140


🏁 Script executed:

rg 'can_use_action_event_stats_with' -A 2 -B 2

Repository: Sinity/polylogue

Length of output: 3059


🏁 Script executed:

# Check if there are other files using _resolve_maybe_awaitable
rg '_resolve_maybe_awaitable' --type py

Repository: Sinity/polylogue

Length of output: 446


🏁 Script executed:

# Check if there are any type checking errors reported or test files that might show the issue
find . -name "test*query.py" | head -10

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Look for any mypy configuration specifics in the commented areas
grep -i 'mypy\|type.*check\|overload' pyproject.toml

Repository: Sinity/polylogue

Length of output: 301


🏁 Script executed:

# Check what the actual async function signature is - look at the definition more carefully
sed -n '290,330p' polylogue/cli/query.py

Repository: Sinity/polylogue

Length of output: 1626


🏁 Script executed:

# Let's check if there's a way to see what the actual return type would be inferred as
# by examining how the function is being used more carefully
sed -n '280,310p' polylogue/cli/query.py

Repository: Sinity/polylogue

Length of output: 1185


🏁 Script executed:

# Check the signature of can_use_action_event_stats_with more carefully
sed -n '1,50p' polylogue/lib/query_retrieval_candidates.py | grep -A 10 'can_use_action_event_stats_with'

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Look for any type: ignore comments or mypy suppressions related to this function
rg '_resolve_maybe_awaitable|Awaitable\[_T\]' -B 2 -A 2

Repository: Sinity/polylogue

Length of output: 1354


🏁 Script executed:

# Create a minimal test to see if mypy flags overlapping overloads
cat > /tmp/test_overload.py << 'EOF'
from typing import TypeVar, overload
from collections.abc import Awaitable
import inspect

_T = TypeVar("_T")

`@overload`
async def resolve_maybe(value: Awaitable[_T]) -> _T: ...

`@overload`
async def resolve_maybe(value: _T) -> _T: ...

async def resolve_maybe(value: Awaitable[_T] | _T) -> _T:
    if inspect.isawaitable(value):
        return await value
    return value

# Test case: passing Awaitable[bool]
async def test() -> bool:
    async def get_bool() -> bool:
        return True
    
    # This is Awaitable[bool], could match either overload
    result = await resolve_maybe(get_bool())
    return result

EOF

# Try to run mypy on it
cd /tmp && python -m mypy --strict test_overload.py 2>&1 || true

Repository: Sinity/polylogue

Length of output: 97


🏁 Script executed:

# Check if there's a CI configuration that runs mypy
find . -name "*.yml" -o -name "*.yaml" | xargs grep -l "mypy" 2>/dev/null | head -5

Repository: Sinity/polylogue

Length of output: 86


🏁 Script executed:

# Check if there are any type: ignore comments in the query.py file around the overload
sed -n '55,75p' polylogue/cli/query.py | cat -A

Repository: Sinity/polylogue

Length of output: 509


🏁 Script executed:

# Look at the actual return type annotation of can_use_action_event_stats_with
rg 'async def can_use_action_event_stats_with' -A 5

Repository: Sinity/polylogue

Length of output: 1010


🏁 Script executed:

# Check the CI configuration to see how mypy is run
cat .github/workflows/ci.yml | grep -A 20 "mypy"

Repository: Sinity/polylogue

Length of output: 912


🏁 Script executed:

# Let's verify if there are any other uses of generic awaitables in the codebase
rg 'Awaitable\[' --type py | head -20

Repository: Sinity/polylogue

Length of output: 1931


Specialize the generic maybe-awaitable helper to eliminate overload ambiguity.

The non-awaitable overload can unify _T with Awaitable[bool], creating an overlap where both overloads match the same input with different return types. Since the only caller at line 293 resolves a boolean, narrow the signature to Awaitable[bool] | bool -> bool to keep static verification deterministic under strict mypy.

♻️ Proposed specialization
-from typing import TYPE_CHECKING, Protocol, TypeVar, overload
+from typing import TYPE_CHECKING, Protocol
@@
-_T = TypeVar("_T")
-
-
-@overload
-async def _resolve_maybe_awaitable(value: Awaitable[_T]) -> _T: ...
-
-
-@overload
-async def _resolve_maybe_awaitable(value: _T) -> _T: ...
-
-
-async def _resolve_maybe_awaitable(value: Awaitable[_T] | _T) -> _T:
+async def _resolve_maybe_awaitable(value: Awaitable[bool] | bool) -> bool:
     if inspect.isawaitable(value):
         return await value
     return value
📝 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
@overload
async def _resolve_maybe_awaitable(value: Awaitable[_T]) -> _T: ...
@overload
async def _resolve_maybe_awaitable(value: _T) -> _T: ...
async def _resolve_maybe_awaitable(value: Awaitable[_T] | _T) -> _T:
if inspect.isawaitable(value):
return await cast(Awaitable[_T], value)
return cast(_T, value)
return await value
return value
async def _resolve_maybe_awaitable(value: Awaitable[bool] | bool) -> bool:
if inspect.isawaitable(value):
return await value
return value
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/query.py` around lines 61 - 72, The helper
_resolve_maybe_awaitable currently uses a generic _T which allows ambiguous
overload resolution; change its annotated types to specifically handle bools:
replace the two overloads and the implementation signature so the function
accepts Awaitable[bool] | bool and returns bool (update the overload
declarations and the def signature of _resolve_maybe_awaitable accordingly),
ensuring the implementation body still awaits when inspect.isawaitable(value)
and returns a bool result; this targets the caller that resolves a boolean and
removes mypy ambiguity for _resolve_maybe_awaitable.

Comment on lines +28 to +35
def _privacy_level(value: str) -> PrivacyLevel:
if value == "strict":
return "strict"
if value == "standard":
return "standard"
if value == "permissive":
return "permissive"
return "standard"

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

Reject invalid privacy levels instead of silently defaulting to standard.

Line 35 turns any typo or unsupported value into "standard", which can silently change privacy behavior. Validate once and fail closed.

🛡️ Proposed validation fix
 def _privacy_level(value: str) -> PrivacyLevel:
     if value == "strict":
         return "strict"
     if value == "standard":
         return "standard"
     if value == "permissive":
         return "permissive"
-    return "standard"
+    raise ValueError(f"Unknown privacy level: {value!r}")
@@
     cli_overrides: PrivacyConfigSection = {}
-    if privacy:
-        cli_overrides["level"] = privacy
+    if privacy is not None:
+        cli_overrides["level"] = _privacy_level(privacy)
@@
     if privacy is not None:
-        return _privacy_config_payload(PrivacyConfig(level=_privacy_level(privacy)))
+        return _privacy_config_payload(PrivacyConfig(level=_privacy_level(privacy)))

Also applies to: 46-57

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

In `@polylogue/cli/schema_command_support.py` around lines 28 - 35, The
_privacy_level function silently defaults unknown values to "standard" and even
returns raw strings instead of the PrivacyLevel enum; change it to validate
explicitly against allowed values ("strict","standard","permissive"), return the
corresponding PrivacyLevel enum member (e.g., PrivacyLevel.strict) and raise an
error (argparse.ArgumentTypeError or ValueError used by the CLI) for any invalid
input with a clear message listing valid options; apply the same validation +
error behavior to the analogous validator at lines 46-57 so typos fail closed
rather than defaulting.

Comment on lines 96 to +98
def _as_record(value: object) -> dict[str, object]:
assert isinstance(value, dict)
return cast(dict[str, object], value)
return {str(key): item for key, item in value.items()}

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

Validate record keys instead of stringifying them.

Line 98 silently normalizes invalid keys and can collapse distinct fields (1 and "1" both become "1"), which makes these verification tests less strict at the JSON/type boundary. Since JSON object keys should already be strings here, fail fast on non-string keys and then rebuild the typed mapping.

🛡️ Proposed fix
 def _as_record(value: object) -> dict[str, object]:
     assert isinstance(value, dict)
-    return {str(key): item for key, item in value.items()}
+    record: dict[str, object] = {}
+    for key, item in value.items():
+        assert isinstance(key, str)
+        record[key] = item
+    return record
📝 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
def _as_record(value: object) -> dict[str, object]:
assert isinstance(value, dict)
return cast(dict[str, object], value)
return {str(key): item for key, item in value.items()}
def _as_record(value: object) -> dict[str, object]:
assert isinstance(value, dict)
record: dict[str, object] = {}
for key, item in value.items():
assert isinstance(key, str)
record[key] = item
return record
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/pipeline/test_ingestion_chaos.py` around lines 96 - 98, The helper
_as_record currently stringifies keys which can silently collapse distinct
non-string keys; instead, validate that every key is already a str and fail fast
on any non-string key, then return a new dict with the original typed keys
(e.g., in _as_record, assert all(isinstance(k, str) for k in value.keys()) and
raise/assert if not, then rebuild/return {k: v for k, v in value.items()}
without converting keys to str).

Comment on lines 79 to +87
class ViewportRecord(Protocol):
text_content: str
role_normalized: str
parsed_timestamp: datetime | None
@property
def text_content(self) -> str: ...

@property
def role_normalized(self) -> str | Role: ...

@property
def parsed_timestamp(self) -> datetime | 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

Keep the protocol and assertions aligned for role_normalized.

Line 84 allows Role, but Lines 482-490 still require and compare a str. Either keep the protocol as str, or normalize before assertions to avoid failing valid protocol implementations.

🧪 Proposed fix if `Role` is intentionally allowed
-    assert isinstance(record.role_normalized, str)
-    assert record.role_normalized in _VALID_VIEWPORT_ROLES
+    normalized_role = record.role_normalized.value if isinstance(record.role_normalized, Role) else record.role_normalized
+    assert normalized_role in _VALID_VIEWPORT_ROLES
@@
-    assert meta.role.value == record.role_normalized
+    assert meta.role.value == normalized_role

Also applies to: 481-490

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

In `@tests/unit/sources/test_unified_semantic_laws.py` around lines 79 - 87, The
Protocol ViewportRecord's role_normalized currently allows str | Role but the
assertions later in tests/unit/sources/test_unified_semantic_laws.py compare
role_normalized to a str; fix by making the types consistent: either change the
Protocol's role_normalized signature in ViewportRecord to return just str, or
update the test assertions that use viewport.role_normalized to normalize it to
a string before comparing (e.g., coerce via str(viewport.role_normalized) or use
.value if Role is an Enum) so the comparisons and the
ViewportRecord.role_normalized declaration agree.

Comment on lines 30 to 52
@dataclass
class _FakeQueries:
class _FakeQueries(SQLiteQueryStore):
hits: ConversationSearchResult
records_by_id: dict[str, ConversationRecord]
last_batch_ids: list[str] | None = None

async def search_conversation_hits(
self,
query: str,
*,
limit: int,
providers: list[str] | None,
limit: int = 20,
providers: list[str] | None = None,
) -> ConversationSearchResult:
del query, limit, providers
return self.hits

async def search_action_conversation_hits(
self,
query: str,
*,
limit: int,
providers: list[str] | None,
limit: int = 20,
providers: list[str] | None = None,
) -> ConversationSearchResult:
del query, limit, providers
return self.hits

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
# Inspect SQLiteQueryStore __init__ and the two overridden method signatures.
fd -t f 'query_store.py' | head
ast-grep --pattern $'class SQLiteQueryStore$$$:
  $$$'
rg -nP -C2 '\b(search_conversation_hits|search_action_conversation_hits)\s*\(' --type=py

Repository: Sinity/polylogue

Length of output: 7514


🏁 Script executed:

#!/bin/bash
# Read the SQLiteQueryStore definition
cat polylogue/storage/backends/query_store.py

Repository: Sinity/polylogue

Length of output: 5906


🏁 Script executed:

#!/bin/bash
# Check what the test does with _FakeQueries
grep -A 100 "class _FakeQueries" tests/unit/storage/test_archive_search_contracts.py | head -80

Repository: Sinity/polylogue

Length of output: 2645


Consider explicit __init__ instead of @dataclass to initialize parent state.

The @dataclass decorator generates an __init__ that sets the three dataclass fields but does not invoke SQLiteQueryStore.__init__. This means self._connection_factory is never initialized. Currently this works because the test only exercises the three overridden methods (search_conversation_hits, search_action_conversation_hits, get_conversations_batch), which do not depend on the connection factory. However, this is fragile: any future addition of a parent method call will crash with AttributeError.

Replace @dataclass with an explicit __init__ that explicitly calls super().__init__() and properly initializes the base class, making the dependency on parent state explicit and safer for future maintenance.

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

In `@tests/unit/storage/test_archive_search_contracts.py` around lines 30 - 52,
The _FakeQueries test helper currently uses `@dataclass` which bypasses
SQLiteQueryStore.__init__ and leaves parent state (like
self._connection_factory) uninitialized; replace the dataclass with an explicit
__init__ on class _FakeQueries that calls super().__init__(), accepts and
assigns the fields hits, records_by_id, and last_batch_ids, and preserves the
existing overrides (search_conversation_hits, search_action_conversation_hits,
get_conversations_batch) so the base class is properly initialized and future
parent method calls won't raise AttributeError.

Comment on lines 105 to 111
async def test_none_parameters_handled(temp_repo: ConversationRepository) -> None:
try:
conv = await temp_repo.view(cast(str, None))
view_method = "view"
conv = await getattr(temp_repo, view_method)(None)
assert conv is None
except (TypeError, ValueError):
pass

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

Prefer a typed escape hatch over getattr indirection.

Using getattr(temp_repo, "view")(None) to smuggle None past the type checker obscures intent and disables attribute-name checking (a typo in "view" would only surface at runtime as AttributeError, which is not in the excepted tuple and would spuriously fail the test). A direct call with a localized type-ignore conveys intent more clearly and keeps static checks on the attribute name.

♻️ Suggested refactor
 async def test_none_parameters_handled(temp_repo: ConversationRepository) -> None:
     try:
-        view_method = "view"
-        conv = await getattr(temp_repo, view_method)(None)
+        conv = await temp_repo.view(None)  # type: ignore[arg-type]
         assert conv is None
     except (TypeError, ValueError):
         pass
📝 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
async def test_none_parameters_handled(temp_repo: ConversationRepository) -> None:
try:
conv = await temp_repo.view(cast(str, None))
view_method = "view"
conv = await getattr(temp_repo, view_method)(None)
assert conv is None
except (TypeError, ValueError):
pass
async def test_none_parameters_handled(temp_repo: ConversationRepository) -> None:
try:
conv = await temp_repo.view(None) # type: ignore[arg-type]
assert conv is None
except (TypeError, ValueError):
pass
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/storage/test_query_security.py` around lines 105 - 111, Replace
the getattr indirection with a direct call to the repository method so
attribute-name typos are caught by static checks: call temp_repo.view(None)
directly (use a localized type-ignore such as "# type: ignore[arg-type]" on that
call to express the intentional None escape hatch) and keep the existing except
(TypeError, ValueError) handling; this preserves runtime behavior while ensuring
the attribute name "view" is validated by the type checker.

Comment on lines +226 to +234
def _message_payloads(value: object) -> list[dict[str, object]]:
if not isinstance(value, list):
return []
payloads: list[dict[str, object]] = []
for item in value:
if not isinstance(item, dict):
raise TypeError(f"expected message payload dict, got {type(item).__name__}")
payloads.append(dict(item))
return payloads

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: _message_payloads swallows non-list input but raises on non-dict items.

Asymmetric error handling — [] when value isn't a list, but TypeError when a list item isn't a dict — can mask a shape regression in the strategy (a stringified messages payload would silently become an empty conversation). Under today's conversation_strategy neither branch is reachable, but if both were the non-list path is the one more likely to hide a real test bug. Consider raising in both cases, or collapsing to [] in both, for consistency.

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

In `@tests/unit/storage/test_store_ops.py` around lines 226 - 234, The helper
_message_payloads currently returns an empty list when value is not a list but
raises TypeError for non-dict items, which can silently hide malformed payloads;
change it so it consistently raises for invalid input: in _message_payloads, if
value is not a list raise a TypeError (same message style as used for non-dict
items), otherwise iterate the list and raise if any item is not a dict,
returning a list copy only when validation succeeds; this keeps behavior
symmetric and prevents silent masking of shape regressions.

@Sinity
Sinity merged commit 04613f6 into master Apr 21, 2026
14 checks passed
@Sinity
Sinity deleted the feature/refactor/quality-debt-cleanup branch April 21, 2026 20:37
Sinity added a commit that referenced this pull request Apr 22, 2026
## Summary
- Tighten remaining JSON/type-boundary seams and remove broad mock/source casts.
- Add archive scenario, semantic fact, surface adapter, query-case, and lifecycle harness infrastructure.
- Port retrieval and cross-surface laws onto shared semantic oracles.
- Fix repository, logging, Drive acquisition, and Drive service test-double safety issues found while expanding verification.

## Problem
The mypy cleanup wave reduced suppression debt, but verification remained too path-dependent: several storage/query laws built bespoke fixture setup and direct SQL assertions instead of reusable scenario projections. Full-suite verification also exposed a subprocess CLI startup crash caused by treating structlog lazy proxies as invalid loggers, a runtime-only Drive acquisition protocol import gap, and Python 3.13 test failures from using `MagicMock` where a runtime-checkable Drive service protocol was required.

Repository writes also had a lossy edge where hydrated domain conversations could be re-saved without message records, risking runtime-state replacement with an empty graph.

Ref #274

## Solution
Introduce reusable archive-verification fixtures under `tests/infra`: declarative scenarios, semantic facts/oracles, surface adapters, query cases, pipeline roundtrip helpers, and repository lifecycle state harnesses. Rework retrieval readiness, cross-surface agreement, pipeline roundtrip, and repository lifecycle tests to compare semantic facts across direct SQL records, hydrated records, repository, and public facade surfaces.

Harden `RepositoryWriteMixin.save_conversation()` to reject lossy domain-conversation saves. Simplify `get_logger()` so structlog lazy loggers work at CLI startup. Import the Drive UI protocol at runtime where it is used for a runtime-checkable `isinstance` guard. Replace Drive gateway cache lifecycle `MagicMock` service doubles with `MockDriveService` objects that satisfy the service protocol on Python 3.13.

## Verification
- `uv run devtools verify --quick`
- `uv run pytest -q tests/unit/pipeline/test_parsing_service.py`
- `UV_PYTHON=3.13 uv run pytest -q tests/unit/sources/test_drive_gateway.py`
- `uv run ruff check tests/unit/sources/test_drive_gateway.py && uv run mypy tests/unit/sources/test_drive_gateway.py`
@Sinity Sinity added area:pipeline Pipeline area:qa QA area:storage Storage tool:claude Claude type:refactor Code restructuring labels Apr 22, 2026
Sinity added a commit that referenced this pull request Apr 22, 2026
The mypy cleanup wave reduced suppression debt, but verification
remained too path-dependent: several storage/query laws built
bespoke fixture setup and direct SQL assertions instead of reusable
scenario projections. Full-suite verification also exposed a
subprocess CLI startup crash caused by treating structlog lazy
proxies as invalid loggers, a runtime-only Drive acquisition
protocol import gap, and Python 3.13 test failures from using
`MagicMock` where a runtime-checkable Drive service protocol was
required. Repository writes had a lossy edge where hydrated domain
conversations could be re-saved without message records, risking
runtime-state replacement with an empty graph.

Introduces reusable archive-verification fixtures under
`tests/infra`: declarative scenarios, semantic facts/oracles,
surface adapters, query cases, pipeline roundtrip helpers, and
repository lifecycle state harnesses. Reworks retrieval readiness,
cross-surface agreement, pipeline roundtrip, and repository
lifecycle tests to compare semantic facts across direct SQL
records, hydrated records, repository, and public facade surfaces.

Hardens `RepositoryWriteMixin.save_conversation()` to reject lossy
domain-conversation saves. Simplifies `get_logger()` so structlog
lazy loggers work at CLI startup. Imports the Drive UI protocol at
runtime where it's used for a runtime-checkable `isinstance` guard.
Replaces Drive gateway cache lifecycle `MagicMock` service doubles
with `MockDriveService` objects that satisfy the service protocol
on Python 3.13.

Verification: devtools verify --quick; focused pytest over parsing
and Drive gateway (including under `UV_PYTHON=3.13`).

Ref #274
Sinity added a commit that referenced this pull request Apr 22, 2026
The mypy cleanup wave reduced suppression debt, but verification
remained too path-dependent: several storage/query laws built
bespoke fixture setup and direct SQL assertions instead of reusable
scenario projections. Full-suite verification also exposed a
subprocess CLI startup crash caused by treating structlog lazy
proxies as invalid loggers, a runtime-only Drive acquisition
protocol import gap, and Python 3.13 test failures from using
`MagicMock` where a runtime-checkable Drive service protocol was
required. Repository writes had a lossy edge where hydrated domain
conversations could be re-saved without message records, risking
runtime-state replacement with an empty graph.

Introduces reusable archive-verification fixtures under
`tests/infra`: declarative scenarios, semantic facts/oracles,
surface adapters, query cases, pipeline roundtrip helpers, and
repository lifecycle state harnesses. Reworks retrieval readiness,
cross-surface agreement, pipeline roundtrip, and repository
lifecycle tests to compare semantic facts across direct SQL
records, hydrated records, repository, and public facade surfaces.

Hardens `RepositoryWriteMixin.save_conversation()` to reject lossy
domain-conversation saves. Simplifies `get_logger()` so structlog
lazy loggers work at CLI startup. Imports the Drive UI protocol at
runtime where it's used for a runtime-checkable `isinstance` guard.
Replaces Drive gateway cache lifecycle `MagicMock` service doubles
with `MockDriveService` objects that satisfy the service protocol
on Python 3.13.

Verification: devtools verify --quick; focused pytest over parsing
and Drive gateway (including under `UV_PYTHON=3.13`).

Ref #274
Sinity added a commit that referenced this pull request Apr 22, 2026
The mypy cleanup wave reduced suppression debt, but verification
remained too path-dependent: several storage/query laws built
bespoke fixture setup and direct SQL assertions instead of reusable
scenario projections. Full-suite verification also exposed a
subprocess CLI startup crash caused by treating structlog lazy
proxies as invalid loggers, a runtime-only Drive acquisition
protocol import gap, and Python 3.13 test failures from using
`MagicMock` where a runtime-checkable Drive service protocol was
required. Repository writes had a lossy edge where hydrated domain
conversations could be re-saved without message records, risking
runtime-state replacement with an empty graph.

Introduces reusable archive-verification fixtures under
`tests/infra`: declarative scenarios, semantic facts/oracles,
surface adapters, query cases, pipeline roundtrip helpers, and
repository lifecycle state harnesses. Reworks retrieval readiness,
cross-surface agreement, pipeline roundtrip, and repository
lifecycle tests to compare semantic facts across direct SQL
records, hydrated records, repository, and public facade surfaces.

Hardens `RepositoryWriteMixin.save_conversation()` to reject lossy
domain-conversation saves. Simplifies `get_logger()` so structlog
lazy loggers work at CLI startup. Imports the Drive UI protocol at
runtime where it's used for a runtime-checkable `isinstance` guard.
Replaces Drive gateway cache lifecycle `MagicMock` service doubles
with `MockDriveService` objects that satisfy the service protocol
on Python 3.13.

Verification: devtools verify --quick; focused pytest over parsing
and Drive gateway (including under `UV_PYTHON=3.13`).

Ref #274
@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. 22 finding(s) confirmed still present → tracked in #546, #547, #550. 2 finding(s) confirmed fixed/stale.

@Sinity
Sinity requested review from Copilot and removed request for Copilot May 1, 2026 00:43
@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.

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

@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.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant