Skip to content

refactor: renew storage runtime query contracts - #247

Merged
Sinity merged 4 commits into
masterfrom
feature/refactor/storage-lib-runtime-renewal
Apr 20, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/refactor/storage-lib-runtime-renewal

Conversation

@Sinity

@Sinity Sinity commented Apr 20, 2026 •

Copy link
Copy Markdown
Owner

Closes #225

Summary

  • type the canonical query runtime against explicit repository protocols
  • split transient storage runtime views into focused modules and remove the aggregate shim
  • tighten CLI query/stat/semantic helpers onto narrower read/query contracts

Problem

The storage/lib runtime tranche still had two path-dependent seams:

  • canonical query execution and grouped CLI helpers depended on the concrete ConversationRepository more often than their semantics required
  • transient runtime/result shapes were funneled through polylogue/storage/state_views.py, a grab-bag aggregate that obscured ownership and kept broad container-style plumbing in place

Solution

  • added explicit query/runtime protocols in polylogue/protocols.py, including ConversationQueryRuntimeStore and narrower CLI-facing output/stats/semantic surfaces
  • replaced action-readiness probing with direct ActionEventArtifactState accessors and propagated that through query runtime helpers
  • split state_views.py into cursor_state.py, raw_state_models.py, artifact_views.py, archive_views.py, and run_state.py
  • fanned imports out across pipeline, storage, CLI run surfaces, rendering, sources, showcase, devtools, and tests, then deleted the aggregate module entirely

Verification

  • ruff check polylogue/storage/cursor_state.py polylogue/storage/raw_state_models.py polylogue/storage/artifact_views.py polylogue/storage/archive_views.py polylogue/storage/run_state.py polylogue/storage/state_views.py polylogue/cli/query_actions.py
  • mypy polylogue/storage/cursor_state.py polylogue/storage/raw_state_models.py polylogue/storage/artifact_views.py polylogue/storage/archive_views.py polylogue/storage/run_state.py polylogue/storage/state_views.py polylogue/cli/query_actions.py
  • pytest -q tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py
  • pytest -q tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_fts5.py tests/unit/storage/test_embedding_stats.py tests/unit/storage/test_derived_status.py
  • pytest -q tests/unit/cli/test_check.py tests/unit/cli/test_run.py tests/unit/cli/test_run_int.py tests/unit/cli/test_run_laws.py tests/unit/core/test_semantic_facts.py tests/unit/pipeline/test_ingest_batch.py tests/unit/pipeline/test_quarantine_fixtures.py tests/unit/pipeline/test_run_sources.py tests/unit/sources/test_acquisition_encoding.py tests/unit/sources/test_decoders.py tests/unit/sources/test_drive_ops.py tests/unit/sources/test_source_laws.py tests/unit/storage/test_parse_tracking.py tests/integration/test_security.py
  • devtools verify

@coderabbitai

coderabbitai Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR reorganizes storage type definitions across dedicated modules and establishes new protocol boundaries for repository capabilities. It moves types like RunResult, CursorStatePayload, RawConversationState, and others into purpose-built modules, replaces broad ConversationRepository type parameters with specialized protocols across CLI and lib layers, and updates action-event status APIs to use a new ActionEventArtifactState type.

Changes

Cohort / File(s) Summary
New Storage Type Modules
polylogue/storage/archive_views.py, polylogue/storage/artifact_views.py, polylogue/storage/cursor_state.py, polylogue/storage/raw_state_models.py
New modules defining focused type contracts: ExistingConversation and ConversationRenderProjection for archive views, ArtifactCohortSummary for artifact summaries, CursorFailurePayload and CursorStatePayload for cursor state, and RawConversationState/RawConversationStateUpdate for raw ingestion models.
Storage Core Refactoring
polylogue/storage/run_state.py, polylogue/storage/action_event_status.py
Consolidated run/plan result types in run_state.py and refactored action-event status API: renamed functions to use new ActionEventArtifactState type and reintroduced original status functions as wrappers for backward compatibility.
New Protocol Layer
polylogue/protocols.py
Added six new @runtime_checkable protocols: ActionEventArtifactReader, ConversationQueryRuntimeStore, ArchiveMessageQueryStore, SemanticArchiveQueryStore, ConversationOutputStore, ConversationSemanticStatsStore, and ConversationArchiveStatsStore to formalize repository capability contracts.
CLI Type Boundary Updates
polylogue/cli/query_actions.py, polylogue/cli/query_output.py, polylogue/cli/query_semantic.py, polylogue/cli/query_stats.py
Updated CLI function signatures to accept specialized protocols (ConversationQueryRuntimeStore, ConversationOutputStore, ConversationSemanticStatsStore, ConversationArchiveStatsStore) instead of generic ConversationRepository.
CLI Display & Workflow
polylogue/cli/run_display_workflow.py, polylogue/cli/run_observers.py, polylogue/cli/run_workflow.py, polylogue/cli/formatting.py
Updated imports for RunResult, PlanResult, and CursorStatePayload to reference new storage modules (run_state, cursor_state).
Lib Query/Retrieval Refactoring
polylogue/lib/query_spec.py, polylogue/lib/query_plan.py, polylogue/lib/query_plan_execution.py, polylogue/lib/query_retrieval_candidates.py, polylogue/lib/query_retrieval_search.py, polylogue/lib/filters.py
Updated all query/retrieval functions to depend on ConversationQueryRuntimeStore instead of ConversationRepository; removed complex readiness-probing logic and replaced with direct calls to get_action_event_artifact_state().
Pipeline & Observer Type Updates
polylogue/pipeline/run_state.py, polylogue/pipeline/run_planning.py, polylogue/pipeline/run_execution.py, polylogue/pipeline/run_finalization.py, polylogue/pipeline/run_stages.py, polylogue/pipeline/observers.py, polylogue/pipeline/prepare_enrichment.py, polylogue/pipeline/prepare_models.py, polylogue/pipeline/services/...
Redirected imports for pipeline state types (RunResult, PlanResult, RunCounts, CursorStatePayload, RawConversationState, etc.) to their new dedicated modules.
Storage Backend & Repository Mixins
polylogue/storage/backends/query_store.py, polylogue/storage/backends/async_sqlite_raw.py, polylogue/storage/backends/queries/raw_*.py, polylogue/storage/repository_*.py
Updated repository mixin methods and query backend to use new type contracts and action-event artifact state API; import paths adjusted for RawConversationState, ConversationRenderProjection, and related types.
Source & Ingestion Layer
polylogue/sources/cursor.py, polylogue/sources/decoder_zip.py, polylogue/sources/drive.py, polylogue/sources/source_*.py
Relocated CursorStatePayload and related type imports to polylogue.storage.cursor_state.
Rendering & Display
polylogue/rendering/core_formatter.py, polylogue/rendering/core_markdown.py, polylogue/rendering/renderers/html*.py
Updated ConversationRenderProjection imports from state_views to archive_views.
Schema & Showcase
polylogue/schemas/operator_models.py, polylogue/schemas/verification_artifacts.py, polylogue/showcase/workspace.py
Redirected imports: ArtifactCohortSummary to artifact_views, RunResult to run_state.
Test Import Migrations
tests/unit/cli/test_*.py, tests/unit/pipeline/test_*.py, tests/unit/sources/test_*.py, tests/unit/storage/test_*.py, tests/integration/test_security.py, devtools/pipeline_probe.py
Updated test imports to follow new type module locations and adjusted mock setups to use get_action_event_artifact_state() instead of get_action_event_read_model_status().
Action Event Status Core
polylogue/lib/run_activity.py
Relocated imports for RunCounts and RunDrift to run_state module.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested labels

area:cli, area:pipeline, area:storage, type:refactor

Poem

🐰 A type-tidy tale unfolds,
Where scattered models find new homes,
Protocols bloom where chaos dwelt,
And storage breathes with clearer seams. 🏠✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.98% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: renew storage runtime query contracts' clearly summarizes the main change: refactoring storage runtime contracts and protocols.
Description check ✅ Passed The description covers all required sections: Summary, Problem, Solution, Verification, and Risks/Follow-ups. It clearly explains what changed and why, addressing the architectural improvements.
Linked Issues check ✅ Passed The PR fully addresses the objectives in #225: it introduces explicit runtime protocols (ConversationQueryRuntimeStore), splits aggregate state_views into focused modules, replaces action-readiness probing with ActionEventArtifactState, and reduces cast pressure through narrower contracts.
Out of Scope Changes check ✅ Passed All changes are in-scope: new protocols and storage modules, import reorganization across pipeline/CLI/tests, action-event artifact refactoring, and type annotation updates directly support the stated objectives of #225.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/storage-lib-runtime-renewal

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (2)
polylogue/cli/query_semantic.py (1)

239-244: ⚠️ Potential issue | 🟠 Major

Use row readiness for batch action-event stats.

Line 239 requires .ready, which also requires FTS readiness. This path only calls get_action_events_batch() on Line 244, so materialized rows are sufficient; stale/pending FTS will unnecessarily force the expensive hydration fallback.

🐛 Proposed fix
-    action_read_model_ready = (await repo.get_action_event_artifact_state()).ready
+    action_event_rows_ready = (await repo.get_action_event_artifact_state()).rows_ready
 
     for offset in range(0, len(conversation_ids), batch_size):
         batch_ids = conversation_ids[offset : offset + batch_size]
-        if action_read_model_ready:
+        if action_event_rows_ready:
             action_events_by_conversation = await repo.get_action_events_batch(batch_ids)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/query_semantic.py` around lines 239 - 244, The code is checking
artifact readiness via action_read_model_ready = (await
repo.get_action_event_artifact_state()).ready which forces full FTS hydration;
instead check the artifact's materialized/row-level readiness before calling
get_action_events_batch so we don't trigger the expensive FTS fallback. Replace
the .ready check with the row/materialized readiness flag returned by
get_action_event_artifact_state (e.g., use the property named rows_materialized,
materialized, or rows_ready on that result) and only call
repo.get_action_events_batch(batch_ids) when that row-level flag is true; keep
the single call to get_action_event_artifact_state and reuse its row-readiness
result for the loop over conversation_ids/batch_size.
polylogue/storage/action_event_status.py (1)

99-155: ⚠️ Potential issue | 🟡 Minor

ActionEventArtifactState.ready becomes unconditionally truthy when verify_source_alignment=False.

In both the sync (Lines 99–101) and async (Lines 143–145) branches, valid_source_conversation_count is aliased to materialized_conversation_count and orphan/stale counts are zeroed. Combined with stale_count = 0 and matches_version = True, the resulting ActionEventArtifactState will always report rows_ready=True and (assuming the FTS row count matches) ready=True, regardless of actual source alignment. This matches the prior dict-based behavior, but the typed .ready property reads as an unconditional guarantee, which is easy to misuse from callers that aren’t aware of the flag. Consider either:

  • documenting on ActionEventArtifactState that ready is relative to the verification mode used to construct it, or
  • having action_event_artifact_state_{sync,async} return a sentinel (e.g., leave source_conversations=0 and flag it) when alignment wasn’t verified so rows_ready reflects that explicitly.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/action_event_status.py` around lines 99 - 155, When
verify_source_alignment is False in action_event_artifact_state_sync and
action_event_artifact_state_async, the returned ActionEventArtifactState
currently reports matches_version=True and thus rows_ready may be misleading;
update both functions so that when verify_source_alignment=False they return a
clearly "unverified" state (e.g., set matches_version=False and/or use a
sentinel for source_conversations like None or 0 plus set stale_rows to a
sentinel) so callers can distinguish unverified vs verified readiness, and
ensure the change is applied in the return construction of
ActionEventArtifactState in both functions (refer to
action_event_artifact_state_sync, action_event_artifact_state_async and the
verify_source_alignment parameter).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/lib/query_retrieval_candidates.py`:
- Around line 42-64: Multiple helpers repeatedly call
repository.get_action_event_artifact_state() causing redundant work; fetch the
ActionEventArtifactState once per query execution and thread it into the helpers
instead of always awaiting the repository. Concretely: change
action_event_rows_ready, action_search_ready, and
can_use_action_event_stats_with to accept an optional artifact_state parameter
(or accept a pre-fetched ActionEventArtifactState) and only call
repository.get_action_event_artifact_state() when that parameter is None; update
callers along the search/hybrid path (e.g., candidate_record_query_for and the
call site that invokes action_search_ready) to fetch
repository.get_action_event_artifact_state() once and pass it to these
functions. This ensures the frozen ActionEventArtifactState is reused for the
duration of the plan execution.

In `@polylogue/protocols.py`:
- Around line 213-329: The protocol types mix bare list[...] and
builtins.list[...] causing inconsistency; standardize to builtins.list[...]
across the protocol surfaces in this file. Update return/arg annotations in
ConversationQueryRuntimeStore (list_summaries_by_query, list_by_query,
search_actions providers already uses builtins.list), ArchiveMessageQueryStore
(get_messages, get_message_counts_batch, get_conversation_stats signatures),
SemanticArchiveQueryStore (get_conversations_batch, get_messages_batch,
get_attachments_batch), and any other protocol methods using bare list[...] to
use builtins.list[...] for uniformity.

In `@polylogue/storage/repository_archive_queries.py`:
- Line 10: The import of ConversationQueryRuntimeStore is only needed for typing
in the cast on line where typing.cast(...) is used (around the cast at/near line
212); move the ConversationQueryRuntimeStore import into a TYPE_CHECKING block
(from typing import TYPE_CHECKING) and change the cast to use a string literal
type name (e.g., typing.cast("ConversationQueryRuntimeStore", ...)) so the
symbol is not imported at runtime and removes the runtime coupling.

In `@tests/unit/pipeline/test_run_sources.py`:
- Line 338: Remove the redundant inner import of RunResult: delete the local
"from polylogue.storage.run_state import RunResult" found inside the test (it is
already imported at module scope), leaving references to RunResult to use the
existing module-level import; run tests to verify no unresolved references
remain.

---

Outside diff comments:
In `@polylogue/cli/query_semantic.py`:
- Around line 239-244: The code is checking artifact readiness via
action_read_model_ready = (await repo.get_action_event_artifact_state()).ready
which forces full FTS hydration; instead check the artifact's
materialized/row-level readiness before calling get_action_events_batch so we
don't trigger the expensive FTS fallback. Replace the .ready check with the
row/materialized readiness flag returned by get_action_event_artifact_state
(e.g., use the property named rows_materialized, materialized, or rows_ready on
that result) and only call repo.get_action_events_batch(batch_ids) when that
row-level flag is true; keep the single call to get_action_event_artifact_state
and reuse its row-readiness result for the loop over
conversation_ids/batch_size.

In `@polylogue/storage/action_event_status.py`:
- Around line 99-155: When verify_source_alignment is False in
action_event_artifact_state_sync and action_event_artifact_state_async, the
returned ActionEventArtifactState currently reports matches_version=True and
thus rows_ready may be misleading; update both functions so that when
verify_source_alignment=False they return a clearly "unverified" state (e.g.,
set matches_version=False and/or use a sentinel for source_conversations like
None or 0 plus set stale_rows to a sentinel) so callers can distinguish
unverified vs verified readiness, and ensure the change is applied in the return
construction of ActionEventArtifactState in both functions (refer to
action_event_artifact_state_sync, action_event_artifact_state_async and the
verify_source_alignment parameter).
🪄 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: 79632740-d461-4415-a8de-a63cff984b56

📥 Commits

Reviewing files that changed from the base of the PR and between 8a0af74 and a826a16.

📒 Files selected for processing (79)
  • devtools/pipeline_probe.py
  • polylogue/cli/commands/run.py
  • polylogue/cli/formatting.py
  • polylogue/cli/query_actions.py
  • polylogue/cli/query_output.py
  • polylogue/cli/query_semantic.py
  • polylogue/cli/query_stats.py
  • polylogue/cli/run_display_workflow.py
  • polylogue/cli/run_observers.py
  • polylogue/cli/run_workflow.py
  • polylogue/lib/filters.py
  • polylogue/lib/query_plan.py
  • polylogue/lib/query_plan_execution.py
  • polylogue/lib/query_retrieval_candidates.py
  • polylogue/lib/query_retrieval_search.py
  • polylogue/lib/query_spec.py
  • polylogue/lib/run_activity.py
  • polylogue/pipeline/observers.py
  • polylogue/pipeline/prepare_enrichment.py
  • polylogue/pipeline/prepare_models.py
  • polylogue/pipeline/run_execution.py
  • polylogue/pipeline/run_finalization.py
  • polylogue/pipeline/run_planning.py
  • polylogue/pipeline/run_stages.py
  • polylogue/pipeline/run_state.py
  • polylogue/pipeline/services/acquisition.py
  • polylogue/pipeline/services/acquisition_records.py
  • polylogue/pipeline/services/acquisition_streams.py
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/pipeline/services/planning_models.py
  • polylogue/pipeline/services/planning_runtime.py
  • polylogue/pipeline/services/rendering.py
  • polylogue/pipeline/watch.py
  • polylogue/protocols.py
  • polylogue/rendering/core_formatter.py
  • polylogue/rendering/core_markdown.py
  • polylogue/rendering/renderers/html.py
  • polylogue/rendering/renderers/html_messages.py
  • polylogue/schemas/operator_models.py
  • polylogue/schemas/verification_artifacts.py
  • polylogue/showcase/workspace.py
  • polylogue/sources/cursor.py
  • polylogue/sources/decoder_zip.py
  • polylogue/sources/drive.py
  • polylogue/sources/source_acquisition.py
  • polylogue/sources/source_parsing.py
  • polylogue/sources/source_walk.py
  • polylogue/storage/action_event_status.py
  • polylogue/storage/archive_views.py
  • polylogue/storage/artifact_queries.py
  • polylogue/storage/artifact_views.py
  • polylogue/storage/backends/async_sqlite_raw.py
  • polylogue/storage/backends/queries/raw_reads.py
  • polylogue/storage/backends/queries/raw_state.py
  • polylogue/storage/backends/query_store.py
  • polylogue/storage/cursor_state.py
  • polylogue/storage/raw_ingest_artifacts.py
  • polylogue/storage/raw_state_models.py
  • polylogue/storage/repository_action_reads.py
  • polylogue/storage/repository_archive_conversations.py
  • polylogue/storage/repository_archive_queries.py
  • polylogue/storage/repository_raw.py
  • polylogue/storage/run_state.py
  • tests/integration/test_security.py
  • tests/unit/cli/test_check.py
  • tests/unit/cli/test_query_exec.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/cli/test_run.py
  • tests/unit/cli/test_run_int.py
  • tests/unit/cli/test_run_laws.py
  • tests/unit/core/test_semantic_facts.py
  • tests/unit/pipeline/test_ingest_batch.py
  • tests/unit/pipeline/test_quarantine_fixtures.py
  • tests/unit/pipeline/test_run_sources.py
  • tests/unit/sources/test_acquisition_encoding.py
  • tests/unit/sources/test_decoders.py
  • tests/unit/sources/test_drive_ops.py
  • tests/unit/sources/test_source_laws.py
  • tests/unit/storage/test_parse_tracking.py

Comment on lines 42 to 64
async def action_event_rows_ready(
plan: ConversationQueryPlan,
repository: ConversationRepository,
repository: ConversationQueryRuntimeStore,
) -> bool:
if not uses_action_read_model(plan):
return True
status_reader = getattr(repository, "get_action_event_read_model_status", None)
if status_reader is None:
return True
status = status_reader()
if inspect.isawaitable(status):
status = await status
if not isinstance(status, dict):
return True
return bool(status.get("rows_ready", status.get("ready", False)))
return (await repository.get_action_event_artifact_state()).rows_ready


async def action_search_ready(
plan: ConversationQueryPlan,
repository: ConversationRepository,
repository: ConversationQueryRuntimeStore,
) -> bool:
if not uses_action_read_model(plan):
return True
status_reader = getattr(repository, "get_action_event_read_model_status", None)
if status_reader is None:
return True
status = status_reader()
if inspect.isawaitable(status):
status = await status
if not isinstance(status, dict):
return True
return bool(status.get("ready", False))
return (await repository.get_action_event_artifact_state()).ready


async def can_use_action_event_stats_with(
plan: ConversationQueryPlan,
repository: ConversationRepository,
repository: ConversationQueryRuntimeStore,
) -> bool:
return plan.can_use_action_event_stats() and await action_event_rows_ready(plan, repository)

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

Consider memoizing get_action_event_artifact_state() for the duration of a single query execution.

action_event_rows_ready, action_search_ready, and can_use_action_event_stats_with each issue an independent await repository.get_action_event_artifact_state(). On the search/hybrid path we typically hit action_search_ready (Line 57), then candidate_record_query_for (Line 25 → action_event_rows_ready at Line 48) within the same plan execution, re-running the full artifact-state aggregation query each time. The previous status-probe path had the same shape, so this isn't a regression, but since the new ActionEventArtifactState is a frozen dataclass that composes rows_ready/ready, a single fetch threaded through these helpers would be a cheap win.

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

In `@polylogue/lib/query_retrieval_candidates.py` around lines 42 - 64, Multiple
helpers repeatedly call repository.get_action_event_artifact_state() causing
redundant work; fetch the ActionEventArtifactState once per query execution and
thread it into the helpers instead of always awaiting the repository.
Concretely: change action_event_rows_ready, action_search_ready, and
can_use_action_event_stats_with to accept an optional artifact_state parameter
(or accept a pre-fetched ActionEventArtifactState) and only call
repository.get_action_event_artifact_state() when that parameter is None; update
callers along the search/hybrid path (e.g., candidate_record_query_for and the
call site that invokes action_search_ready) to fetch
repository.get_action_event_artifact_state() once and pass it to these
functions. This ensures the frozen ActionEventArtifactState is reused for the
duration of the plan execution.

Comment thread polylogue/protocols.py
Comment on lines +213 to +329
@runtime_checkable
class ActionEventArtifactReader(Protocol):
"""Read-only action-event artifact readiness surface."""

async def get_action_event_artifact_state(self) -> ActionEventArtifactState: ...


@runtime_checkable
class ConversationQueryRuntimeStore(
ConversationReader,
SearchStore,
ActionEventArtifactReader,
Protocol,
):
"""Repository/query runtime surface consumed by canonical query execution."""

async def list_summaries_by_query(
self,
query: ConversationRecordQuery,
) -> list[ConversationSummary]: ...

async def list_by_query(
self,
query: ConversationRecordQuery,
) -> list[Conversation]: ...

async def count_by_query(self, query: ConversationRecordQuery) -> int: ...

async def delete_conversation(self, conversation_id: str) -> bool: ...

async def search_actions(
self,
query: str,
limit: int = 20,
providers: builtins.list[str] | None = None,
) -> list[Conversation]: ...


@runtime_checkable
class ArchiveMessageQueryStore(Protocol):
"""Low-level archive/message query band used by CLI output and stats helpers."""

async def get_conversation(self, conversation_id: str) -> ConversationRecord | None: ...

async def get_messages(self, conversation_id: str) -> list[MessageRecord]: ...

async def get_conversation_stats(self, conversation_id: str) -> dict[str, int]: ...

async def get_message_counts_batch(self, conversation_ids: list[str]) -> dict[str, int]: ...

async def aggregate_message_stats(
self,
conversation_ids: list[str] | None = None,
) -> AggregateMessageStats: ...


@runtime_checkable
class SemanticArchiveQueryStore(ArchiveMessageQueryStore, Protocol):
"""Archive query band needed to hydrate semantic facts in batch."""

async def get_conversations_batch(self, ids: list[str]) -> list[ConversationRecord]: ...

async def get_messages_batch(
self,
conversation_ids: list[str],
) -> dict[str, list[MessageRecord]]: ...

async def get_attachments_batch(
self,
conversation_ids: list[str],
) -> dict[str, list[AttachmentRecord]]: ...


@runtime_checkable
class ConversationOutputStore(ConversationReader, Protocol):
"""Conversation output surface used by streaming and summary display helpers."""

@property
def queries(self) -> SemanticArchiveQueryStore: ...


@runtime_checkable
class ConversationSemanticStatsStore(ActionEventArtifactReader, Protocol):
"""Semantic stats surface for action-event-backed grouped output."""

@property
def queries(self) -> SemanticArchiveQueryStore: ...

async def get_action_events_batch(
self,
conversation_ids: list[str],
) -> dict[str, tuple[ActionEvent, ...]]: ...


@runtime_checkable
class ConversationArchiveStatsStore(
ConversationOutputStore,
ConversationSemanticStatsStore,
Protocol,
):
"""Archive stats/profile surface consumed by grouped CLI output helpers."""

@property
def backend(self) -> RepositoryBackendProtocol: ...

async def get_archive_stats(
self,
*,
conn: aiosqlite.Connection | None = None,
) -> ArchiveStats: ...

async def get_session_profiles_batch(
self,
conversation_ids: list[str],
) -> dict[str, SessionProfile]: ...

async def get_many(self, conversation_ids: list[str]) -> list[Conversation]: ...

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm ConversationRepository exposes the full ConversationArchiveStatsStore surface.
rg -nP --type=py -C2 '\b(get_archive_stats|get_session_profiles_batch|get_action_events_batch|get_many|get_message_counts_batch|aggregate_message_stats|get_conversations_batch|get_messages_batch|get_attachments_batch)\s*\('
rg -nP --type=py -C3 '\bdef\s+backend\b|\bbackend\s*:\s*RepositoryBackendProtocol'

Repository: Sinity/polylogue

Length of output: 47918


Protocol surface is coherent with correct structural satisfaction.

The hierarchy cleanly narrows the surfaces, and the queries property return type is consistent across both parents of ConversationArchiveStatsStore — diamond inheritance resolves without conflict.

ConversationRepository structurally satisfies ConversationArchiveStatsStore through its mixins: it exposes backend, get_archive_stats(*, conn=None), get_session_profiles_batch(), get_action_events_batch(), get_many(), and all inherited query methods. Since these are @runtime_checkable protocols, structural satisfaction is verified at the isinstance call sites.

Optional refinement: For consistency, consider using builtins.list uniformly across all protocols, or leave bare list[...] as-is (current approach is acceptable since none of the new methods are named list). ConversationReader uses builtins.list due to list() method shadowing, but that constraint doesn't apply here—this is purely a style preference.

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

In `@polylogue/protocols.py` around lines 213 - 329, The protocol types mix bare
list[...] and builtins.list[...] causing inconsistency; standardize to
builtins.list[...] across the protocol surfaces in this file. Update return/arg
annotations in ConversationQueryRuntimeStore (list_summaries_by_query,
list_by_query, search_actions providers already uses builtins.list),
ArchiveMessageQueryStore (get_messages, get_message_counts_batch,
get_conversation_stats signatures), SemanticArchiveQueryStore
(get_conversations_batch, get_messages_batch, get_attachments_batch), and any
other protocol methods using bare list[...] to use builtins.list[...] for
uniformity.

from typing import TYPE_CHECKING, cast

from polylogue.lib.conversation_models import Conversation, ConversationSummary
from polylogue.protocols import ConversationQueryRuntimeStore

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect relevant import edges around protocols, filters, and repository archive queries.
python - <<'PY'
import ast
from pathlib import Path

for path in [
    Path("polylogue/protocols.py"),
    Path("polylogue/lib/filters.py"),
    Path("polylogue/storage/repository_archive_queries.py"),
]:
    print(f"\n== {path} ==")
    tree = ast.parse(path.read_text(encoding="utf-8"))
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            print("import", ", ".join(alias.name for alias in node.names))
        elif isinstance(node, ast.ImportFrom):
            module = node.module or ""
            names = ", ".join(alias.name for alias in node.names)
            print(f"from {module} import {names}")
PY

Repository: Sinity/polylogue

Length of output: 2288


🏁 Script executed:

# Check the actual usage of ConversationQueryRuntimeStore in repository_archive_queries.py
cat -n polylogue/storage/repository_archive_queries.py | head -30

Repository: Sinity/polylogue

Length of output: 1191


🏁 Script executed:

# Search for all occurrences of ConversationQueryRuntimeStore in the file
rg "ConversationQueryRuntimeStore" polylogue/storage/repository_archive_queries.py -n -B2 -A2

Repository: Sinity/polylogue

Length of output: 436


🏁 Script executed:

# Check the line count to determine file size
wc -l polylogue/storage/repository_archive_queries.py

Repository: Sinity/polylogue

Length of output: 111


🏁 Script executed:

# Check the full context around line 212
sed -n '200,215p' polylogue/storage/repository_archive_queries.py

Repository: Sinity/polylogue

Length of output: 579


Keep the protocol import type-only.

ConversationQueryRuntimeStore is only used in typing.cast() on line 212, where the first argument is discarded at runtime. Moving this to the TYPE_CHECKING block and using a string literal removes unnecessary runtime coupling.

♻️ Proposed cleanup
 from polylogue.lib.conversation_models import Conversation, ConversationSummary
-from polylogue.protocols import ConversationQueryRuntimeStore
 from polylogue.storage.query_models import ConversationRecordQuery
 
 if TYPE_CHECKING:
+    from polylogue.protocols import ConversationQueryRuntimeStore
     from polylogue.lib.filters import ConversationFilter
     from polylogue.storage.backends.query_store import SQLiteQueryStore
-        return filters.ConversationFilter(cast(ConversationQueryRuntimeStore, self))
+        return filters.ConversationFilter(cast("ConversationQueryRuntimeStore", self))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/repository_archive_queries.py` at line 10, The import of
ConversationQueryRuntimeStore is only needed for typing in the cast on line
where typing.cast(...) is used (around the cast at/near line 212); move the
ConversationQueryRuntimeStore import into a TYPE_CHECKING block (from typing
import TYPE_CHECKING) and change the cast to use a string literal type name
(e.g., typing.cast("ConversationQueryRuntimeStore", ...)) so the symbol is not
imported at runtime and removes the runtime coupling.

class TestRunSourcesRenderFailures:
def test_render_failure_tracked_in_result(self, workspace_env: WorkspaceEnv) -> None:
from polylogue.storage.state_views import RunResult
from polylogue.storage.run_state import RunResult

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

Remove the redundant local RunResult import.

RunResult is already imported at module scope on Line 28, so this inner import can be dropped.

♻️ Proposed cleanup
-        from polylogue.storage.run_state import RunResult
-
         archive_root = workspace_env["archive_root"]
📝 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
from polylogue.storage.run_state import RunResult
archive_root = workspace_env["archive_root"]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/pipeline/test_run_sources.py` at line 338, Remove the redundant
inner import of RunResult: delete the local "from polylogue.storage.run_state
import RunResult" found inside the test (it is already imported at module
scope), leaving references to RunResult to use the existing module-level import;
run tests to verify no unresolved references remain.

@Sinity
Sinity merged commit 583abbe into master Apr 20, 2026
14 checks passed
@Sinity
Sinity deleted the feature/refactor/storage-lib-runtime-renewal branch April 20, 2026 04:13
Sinity added a commit that referenced this pull request Apr 22, 2026
Closes #225

## Summary
- type the canonical query runtime against explicit repository protocols
- split transient storage runtime views into focused modules and remove the aggregate shim
- tighten CLI query/stat/semantic helpers onto narrower read/query contracts

## Problem
The storage/lib runtime tranche still had two path-dependent seams:
- canonical query execution and grouped CLI helpers depended on the concrete `ConversationRepository` more often than their semantics required
- transient runtime/result shapes were funneled through `polylogue/storage/state_views.py`, a grab-bag aggregate that obscured ownership and kept broad container-style plumbing in place

## Solution
- added explicit query/runtime protocols in `polylogue/protocols.py`, including `ConversationQueryRuntimeStore` and narrower CLI-facing output/stats/semantic surfaces
- replaced action-readiness probing with direct `ActionEventArtifactState` accessors and propagated that through query runtime helpers
- split `state_views.py` into `cursor_state.py`, `raw_state_models.py`, `artifact_views.py`, `archive_views.py`, and `run_state.py`
- fanned imports out across pipeline, storage, CLI run surfaces, rendering, sources, showcase, devtools, and tests, then deleted the aggregate module entirely

## Verification
- `ruff check polylogue/storage/cursor_state.py polylogue/storage/raw_state_models.py polylogue/storage/artifact_views.py polylogue/storage/archive_views.py polylogue/storage/run_state.py polylogue/storage/state_views.py polylogue/cli/query_actions.py`
- `mypy polylogue/storage/cursor_state.py polylogue/storage/raw_state_models.py polylogue/storage/artifact_views.py polylogue/storage/archive_views.py polylogue/storage/run_state.py polylogue/storage/state_views.py polylogue/cli/query_actions.py`
- `pytest -q tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py`
- `pytest -q tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_fts5.py tests/unit/storage/test_embedding_stats.py tests/unit/storage/test_derived_status.py`
- `pytest -q tests/unit/cli/test_check.py tests/unit/cli/test_run.py tests/unit/cli/test_run_int.py tests/unit/cli/test_run_laws.py tests/unit/core/test_semantic_facts.py tests/unit/pipeline/test_ingest_batch.py tests/unit/pipeline/test_quarantine_fixtures.py tests/unit/pipeline/test_run_sources.py tests/unit/sources/test_acquisition_encoding.py tests/unit/sources/test_decoders.py tests/unit/sources/test_drive_ops.py tests/unit/sources/test_source_laws.py tests/unit/storage/test_parse_tracking.py tests/integration/test_security.py`
- `devtools verify`
@Sinity Sinity added area:cli CLI 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 storage/lib runtime had two path-dependent seams. Canonical
query execution and grouped CLI helpers depended on the concrete
`ConversationRepository` more often than their semantics required.
Transient runtime/result shapes funneled through
`storage/state_views.py`, a grab-bag aggregate that obscured
ownership and kept broad container-style plumbing in place.

Adds explicit query/runtime protocols in `protocols.py` including
`ConversationQueryRuntimeStore` and narrower CLI-facing output /
stats / semantic surfaces. Replaces action-readiness probing with
direct `ActionEventArtifactState` accessors; propagates through
query runtime helpers. Splits `state_views.py` into `cursor_state.py`,
`raw_state_models.py`, `artifact_views.py`, `archive_views.py`, and
`run_state.py`. Fans imports out across pipeline, storage, CLI run
surfaces, rendering, sources, showcase, devtools, and tests, then
deletes the aggregate module entirely.

Verification: ruff + mypy over touched modules; focused pytest over
query-exec, action-event-artifact, FTS, embedding-stats, check, run,
semantic-facts, ingest, quarantine, and security suites; devtools
verify green.

Closes #225
Sinity added a commit that referenced this pull request Apr 22, 2026
The storage/lib runtime had two path-dependent seams. Canonical
query execution and grouped CLI helpers depended on the concrete
`ConversationRepository` more often than their semantics required.
Transient runtime/result shapes funneled through
`storage/state_views.py`, a grab-bag aggregate that obscured
ownership and kept broad container-style plumbing in place.

Adds explicit query/runtime protocols in `protocols.py` including
`ConversationQueryRuntimeStore` and narrower CLI-facing output /
stats / semantic surfaces. Replaces action-readiness probing with
direct `ActionEventArtifactState` accessors; propagates through
query runtime helpers. Splits `state_views.py` into `cursor_state.py`,
`raw_state_models.py`, `artifact_views.py`, `archive_views.py`, and
`run_state.py`. Fans imports out across pipeline, storage, CLI run
surfaces, rendering, sources, showcase, devtools, and tests, then
deletes the aggregate module entirely.

Verification: ruff + mypy over touched modules; focused pytest over
query-exec, action-event-artifact, FTS, embedding-stats, check, run,
semantic-facts, ingest, quarantine, and security suites; devtools
verify green.

Closes #225
Sinity added a commit that referenced this pull request Apr 22, 2026
The storage/lib runtime had two path-dependent seams. Canonical
query execution and grouped CLI helpers depended on the concrete
`ConversationRepository` more often than their semantics required.
Transient runtime/result shapes funneled through
`storage/state_views.py`, a grab-bag aggregate that obscured
ownership and kept broad container-style plumbing in place.

Adds explicit query/runtime protocols in `protocols.py` including
`ConversationQueryRuntimeStore` and narrower CLI-facing output /
stats / semantic surfaces. Replaces action-readiness probing with
direct `ActionEventArtifactState` accessors; propagates through
query runtime helpers. Splits `state_views.py` into `cursor_state.py`,
`raw_state_models.py`, `artifact_views.py`, `archive_views.py`, and
`run_state.py`. Fans imports out across pipeline, storage, CLI run
surfaces, rendering, sources, showcase, devtools, and tests, then
deletes the aggregate module entirely.

Verification: ruff + mypy over touched modules; focused pytest over
query-exec, action-event-artifact, FTS, embedding-stats, check, run,
semantic-facts, ingest, quarantine, and security suites; devtools
verify green.

Closes #225
@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. 2 finding(s) confirmed still present → tracked in #550. 1 finding(s) confirmed fixed/stale.

@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

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

@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@Sinity
Sinity requested a review from Copilot May 1, 2026 01:51
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

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

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

Labels

area:cli CLI area:storage Storage tool:claude Claude type:refactor Code restructuring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: renew storage, lib, and product runtime seams

1 participant