Skip to content

refactor: rebuild storage and product runtime boundary contracts - #276

Merged
Sinity merged 6 commits into
masterfrom
feature/refactor/storage-product-runtime-boundaries
Apr 20, 2026
Merged

Sinity merged 6 commits into
masterfrom
feature/refactor/storage-product-runtime-boundaries

Conversation

@Sinity

@Sinity Sinity commented Apr 20, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • centralize typed storage query contracts for session-profile, timeline, thread, and artifact reads
  • tighten archive/run hydration around explicit row coercion helpers instead of loose row-value plumbing
  • normalize semantic-fact protocols so Conversation, MessageCollection, and action-event callers satisfy the intended read-only contracts

Problem

The storage/lib/product-runtime tranche still relied on repeated result-shape normalization, loose row hydration, and protocol contracts that were only mypy-clean because values flowed through weak helper types. That left duplicated coercion logic across repository/product mappers and made downstream semantic-fact callers depend on accidental mutability assumptions.

Solution

  • add explicit query dataclasses and shared product-read hydration helpers for profile/timeline/thread/artifact reads
  • rebuild row-mapper support around typed JSON parsing, scalar coercion, JSON tuple/dict helpers, and null-preserving run hydration
  • tighten semantic action-event and semantic-fact protocols to model read-only properties and iterable message collections actually used by the domain models
  • update the small publication-manifest tests that index persisted JSON manifests through typed object boundaries

Verification

  • devtools verify
  • mypy polylogue/storage/backends/queries/mappers.py polylogue/storage/backends/queries/mappers_archive.py polylogue/storage/backends/queries/mappers_product_profiles.py polylogue/storage/backends/queries/mappers_product_timelines.py polylogue/storage/backends/queries/mappers_product_aggregates.py polylogue/storage/backends/queries/attachment_records.py polylogue/storage/session_product_rebuild.py polylogue/lib/action_events.py polylogue/lib/semantic_fact_support.py polylogue/lib/semantic_facts.py polylogue/lib/pricing.py polylogue/storage/action_event_rows.py polylogue/pipeline/services/ingest_worker.py polylogue/pipeline/run_finalization.py polylogue/cli/query_stats.py polylogue/cli/query_semantic.py polylogue/lib/query_retrieval_search.py polylogue/lib/session_profile_runtime.py polylogue/lib/phase_extraction.py polylogue/lib/attribution.py polylogue/lib/work_event_extraction.py tests/unit/storage/test_publications.py tests/unit/site/test_builder.py tests/unit/core/test_semantic_facts.py
  • pytest -q tests/unit/storage/test_query_mappers.py tests/unit/storage/test_publications.py tests/unit/site/test_builder.py tests/unit/core/test_semantic_facts.py
  • pytest -q tests/unit/cli/test_run_int.py -k latest_run_parsing

Closes #272

@coderabbitai

coderabbitai Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Large refactoring that strengthens type contracts across storage/lib/product-runtime boundaries by introducing Protocol-based structural typing, typed query models for list operations, centralized JSON document handling with type-safe coercion, and standardized row mapping utilities. Replaces broad Any plumbing and keyword-argument APIs with explicit, composable interfaces while preserving all existing control flow.

Changes

Cohort / File(s) Summary
Protocol-Based Structural Typing
polylogue/lib/action_events.py, polylogue/lib/semantic_fact_support.py
Introduced lightweight Protocols (ActionEventMessageLike, TextMessageLike, HarmonizedMessageLike, SemanticMessageLike) to replace concrete Message/MessageRecord dependencies in function signatures. Updated helper functions to accept structured protocol types instead of broad concrete types.
Semantic Fact Models & Return Types
polylogue/lib/semantic_fact_models.py, polylogue/lib/semantic_facts.py
Updated all to_proof_input() methods to return JSONDocument instead of dict[str, Any]. Introduced Protocol types (ProjectionLike, SemanticConversationLike, SemanticSummaryLike, etc.) for semantic fact builders; tightened internal typing (list[datetime] instead of list[Any]).
Query Model Infrastructure
polylogue/storage/query_models.py, polylogue/storage/product_read_support.py
Added six frozen dataclass query models (SessionProfileListQuery, SessionTimelineListQuery, WorkThreadListQuery, SessionTagRollupListQuery, DaySessionSummaryListQuery, ArtifactObservationListQuery) to replace keyword-argument APIs. Introduced generic hydration helpers (hydrate_optional, hydrate_sequence, hydrate_mapping) for record transformation.
Typed Row Mappers & JSON Coercion
polylogue/storage/backends/queries/mappers.py, mappers_archive.py, mappers_product_*.py
Added typed row accessors (_row_int, _row_float, _row_text) and JSON helpers (_json_object, _json_text_tuple, _json_int_dict) to replace generic _row_get. Expanded _parse_json to validate input types and use polylogue.lib.json.loads. Updated all mappers to use specific accessors instead of untyped casts.
Artifact & Attachment Record Handling
polylogue/storage/backends/queries/attachment_records.py, polylogue/storage/artifact_queries.py, polylogue/schemas/verification_artifacts.py
Refactored artifact queries to use ArtifactObservationListQuery object; replaced mutable dict buckets with _ArtifactCohortBucket dataclass. Updated attachment provider_meta parsing to apply _json_object(...) post-coercion.
Publication & Run Record JSON Handling
polylogue/storage/backends/queries/publications.py, runs.py
Added _json_object helper to convert parsed JSON documents into dict[str, object]. Updated manifest and plan_snapshot/drift to wrap parsed JSON; changed counts to use validated RunCounts model.
Session Product Query Integration
polylogue/storage/backends/queries/session_product_profile_reads.py, session_product_timeline_reads.py, session_product_thread_queries.py, session_product_summary_queries.py
Replaced individual keyword-argument filter parameters with single query parameter accepting typed query models. Updated all SQL WHERE/LIMIT/OFFSET logic to derive from query object fields.
Query Store & Repository Delegation
polylogue/storage/backends/query_store.py, query_store_product_*.py, polylogue/storage/repository_product_*.py
Introduced private query helpers that construct and pass typed query models to underlying functions. Updated public methods to build query objects and delegate via helpers; replaced inline hydration with hydrate_* helpers.
Record Type Strengthening & Artifact Handling
polylogue/storage/store_runtime_archive_records.py, polylogue/storage/session_product_rebuild.py, polylogue/pipeline/run_finalization.py, polylogue/storage/backends/queries/raw_state.py
Introduced JSONObject type alias and field validators for JSON coercion across record classes. Updated row parsing to use typed accessors (_row_int, _row_float, _row_text). Fixed counts assignment and parameter typing.
Test Defensive Access
tests/unit/site/test_builder.py, tests/unit/storage/test_publications.py
Made manifest assertions more defensive by retrieving nested JSON via .get("outputs") with type checks instead of direct chained indexing.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 From concrete types to protocols bright,
Query models shine with structured light,
JSON coercion finds its rightful place,
Types and hydration set the pace,
Boundaries rebuilt with steady grace!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.85% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: refactoring storage and product runtime boundary contracts to rebuild type contracts and centralize coercion logic.
Description check ✅ Passed The PR description follows the template structure with Summary, Problem, Solution, and Verification sections. It comprehensively covers what changed, why it was needed, what was done, and exactly how it was verified with specific mypy and pytest commands.
Linked Issues check ✅ Passed The PR fully addresses the acceptance criteria from issue #272: centralizes coercion logic, replaces loose types with explicit contracts (query dataclasses, protocols), maintains substrate-first design, and lands as one coherent PR with complete verification (mypy + pytest).
Out of Scope Changes check ✅ Passed All changes are scoped to the stated boundaries (polylogue/storage, polylogue/lib, product-runtime mixins) and focus on contracts, typing, and coercion helpers. Test updates for manifest indexing are directly required follow-ups. No unrelated polish or cleanup detected.

✏️ 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-product-runtime-boundaries

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: 12

Caution

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

⚠️ Outside diff range comments (4)
polylogue/storage/backends/query_store_product_timelines.py (1)

75-96: ⚠️ Potential issue | 🟠 Major

Forward the timeline search query for phases too.

SessionTimelineListQuery has a query field for full-text search, and work-event listing forwards it, but list_session_phases drops that filter entirely. The lower-level query function checks if query.query: for work events but not for phases, preventing callers through this mixin from reaching the FTS capability.

This same gap exists in the repository layer methods (list_session_phases and list_session_phase_records).

🐛 Proposed fix for query_store_product_timelines.py
     async def list_session_phases(
         self,
         *,
         conversation_id: str | None = None,
         provider: str | None = None,
         since: str | None = None,
         until: str | None = None,
         kind: str | None = None,
         limit: int | None = 50,
         offset: int = 0,
+        query: str | None = None,
     ) -> list[SessionPhaseRecord]:
         return await self._list_session_phases_query(
             SessionTimelineListQuery(
                 conversation_id=conversation_id,
                 provider=provider,
                 since=since,
                 until=until,
                 kind=kind,
                 limit=limit,
                 offset=offset,
+                query=query,
             )
         )

Apply the same fix to list_session_phases and list_session_phase_records in polylogue/storage/repository_product_timeline_reads.py.

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

In `@polylogue/storage/backends/query_store_product_timelines.py` around lines 75
- 96, list_session_phases currently builds a SessionTimelineListQuery but omits
the full-text `query` field, so phase listing never receives the FTS filter;
modify list_session_phases to accept and pass through the `query` parameter into
the SessionTimelineListQuery (same symbol) and ensure the lower-level
_list_session_phases_query will see query.query; apply the identical change to
the repository-layer methods list_session_phases and list_session_phase_records
in repository_product_timeline_reads.py so they also forward the
SessionTimelineListQuery.query value.
polylogue/storage/backends/queries/publications.py (1)

17-51: 🛠️ Refactor suggestion | 🟠 Major

Duplicate of mappers._json_object; prefer importing the canonical helper.

This is the same locally-redefined helper as in polylogue/storage/backends/queries/runs.py. The mappers module already exposes a None-safe _json_object(value: JSONValue | None) -> JSONObject | None. Since PublicationRecord.manifest is typed as required JSONObject, using the mappers helper (which returns None on empty/null) will also surface NULL/empty manifests clearly rather than relying on json_document to raise, and removes the cross-module duplication.

♻️ Suggested fix
-from polylogue.lib.json import json_document
-from polylogue.storage.backends.queries.mappers import _parse_json
+from polylogue.storage.backends.queries.mappers import _json_object, _parse_json
@@
-def _json_object(value: object) -> dict[str, object]:
-    document = json_document(value)
-    result: dict[str, object] = {}
-    for key, item in document.items():
-        result[key] = item
-    return result
-
-
 async def get_latest_publication(

Note: if manifest must remain non-optional, coerce None -> {} explicitly at the call site so the invariant is visible.

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

In `@polylogue/storage/backends/queries/publications.py` around lines 17 - 51, The
file redefines a local _json_object identical to mappers._json_object; remove
the local helper and import and use mappers._json_object in
get_latest_publication (and any other use sites) so you don't duplicate
logic—call mappers._json_object around the result of
_parse_json(row["manifest_json"], field="manifest_json",
record_id=row["publication_id"]). If PublicationRecord.manifest must remain
non-optional, explicitly coerce a None result to {} at the call site so the
invariant is visible (e.g., manifest = mappers._json_object(...) or manifest =
mappers._json_object(...) or {}).
polylogue/storage/repository_product_thread_reads.py (1)

24-52: 🧹 Nitpick | 🔵 Trivial

LGTM.

hydrate_optional / hydrate_sequence nicely replace the ad-hoc conditional and list-comprehension hydration. The WorkThreadListQuery plumbing is duplicated verbatim in list_work_threads and list_work_thread_records (lines 43–51 vs 63–71); if the argument lists drift, consider extracting a small _build_work_thread_query(...) helper, but it's fine as-is for a two-call-site duplication.

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

In `@polylogue/storage/repository_product_thread_reads.py` around lines 24 - 52,
Duplicate construction of WorkThreadListQuery appears in list_work_threads and
list_work_thread_records; extract a small helper (e.g.,
_build_work_thread_query) that accepts the parameters (since, until, limit,
offset, query) and returns WorkThreadListQuery, then replace both sites
(list_work_threads and list_work_thread_records/_list_work_thread_records_query
callers) to call _build_work_thread_query(...) before passing the result to
_list_work_thread_records_query or other query methods to remove verbatim
duplication.
polylogue/storage/repository_product_profile_reads.py (1)

51-145: 🧹 Nitpick | 🔵 Trivial

Collapse duplicated SessionProfileListQuery construction.

list_session_profiles, list_session_profile_records, and list_session_enrichment_records each take the same keyword surface and build an identical SessionProfileListQuery (only tier differs for the enrichment variant). Extract a small helper to keep the three call sites in lock-step as fields are added to the query model.

♻️ Proposed refactor
+    `@staticmethod`
+    def _build_profile_list_query(
+        *,
+        provider: str | None,
+        since: str | None,
+        until: str | None,
+        first_message_since: str | None,
+        first_message_until: str | None,
+        session_date_since: str | None,
+        session_date_until: str | None,
+        tier: str,
+        limit: int | None,
+        offset: int,
+        query: str | None,
+    ) -> SessionProfileListQuery:
+        return SessionProfileListQuery(
+            provider=provider,
+            since=since,
+            until=until,
+            first_message_since=first_message_since,
+            first_message_until=first_message_until,
+            session_date_since=session_date_since,
+            session_date_until=session_date_until,
+            tier=tier,
+            limit=limit,
+            offset=offset,
+            query=query,
+        )

Then reuse it in all three call sites.

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

In `@polylogue/storage/repository_product_profile_reads.py` around lines 51 - 145,
Multiple methods (list_session_profiles, list_session_profile_records,
list_session_enrichment_records) duplicate construction of
SessionProfileListQuery; extract a small helper like
_build_session_profile_list_query(...) that accepts the shared parameters
(provider, since, until, first_message_since, first_message_until,
session_date_since, session_date_until, limit, offset, query) and returns a
SessionProfileListQuery, then call that helper from each method and only
override tier in list_session_enrichment_records (or allow tier as an optional
param to the helper). Update usages of SessionProfileListQuery in those three
methods to use _build_session_profile_list_query (and pass tier="enrichment" for
get_session_enrichment_records) so all call sites remain in sync as fields
change.
🤖 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/action_events.py`:
- Around line 58-63: Change the ActionEventMessageLike protocol's id property
from object to str (i.e., def id(self) -> str) so it reflects the concrete
Message type; then remove the redundant str(...) coercions where message_id is
produced/assigned and where make_action_event_id is called (references:
ActionEventMessageLike, make_action_event_id, and the message_id / message.id
usages) so you rely on the typed string id directly.

In `@polylogue/lib/semantic_facts.py`:
- Around line 67-70: The Protocol type SemanticConversationMessagesLike is used
by the public contract (e.g., referenced by SemanticConversationLike.messages)
but is not exported; update the module exports by adding
"SemanticConversationMessagesLike" to the __all__ list(s) that export the public
Protocol types (the existing __all__ near the top and the similar __all__ block
around the later section), ensuring both declaration(s) include that symbol so
the public typed boundary is complete and consistent.

In `@polylogue/storage/backends/queries/mappers_archive.py`:
- Around line 107-111: Cache the result of _row_text(row, "payload_provider")
into a local variable (e.g., payload_provider_text) in the mapper where
payload_provider is built, then pass that local to Provider.from_string only
once and use it in the ternary
(payload_provider=Provider.from_string(payload_provider_text) if
payload_provider_text is not None else None); apply the same refactor in
_row_to_artifact_observation so both places follow the file's pattern of
extracting row text into a named local (matching how parent_conversation_id,
role, validation_status, etc. are handled).

In `@polylogue/storage/backends/queries/mappers_product_legacy.py`:
- Around line 291-345: The scalar coercion helpers (_legacy_text, _legacy_float,
_legacy_int, _legacy_bool) must tolerate bytes/bytearray and malformed strings
without raising: first detect bytes/bytearray and decode them (e.g.
value.decode('utf-8', errors='ignore')) before further processing; for
_legacy_float and _legacy_int wrap numeric conversion in try/except and return
the provided default on failure; for _legacy_bool, after decoding handle common
textual booleans ('0','1','false','true','no','yes') and numeric parsing in
try/except, falling back to False for unrecognized values; ensure _legacy_text
returns None for empty or whitespace-only decoded strings.

In `@polylogue/storage/backends/queries/mappers.py`:
- Around line 107-116: The helper _json_object currently treats an empty JSON
object as falsy and returns None, losing the distinction between an explicit {}
and null; change the logic in _json_object (and where it calls json_document) so
that only a None/absent document maps to None, while an empty dict is preserved
and returned as an empty JSONObject: call document = json_document(value), if
document is None return None, otherwise iterate document (or simply cast) to
build and return a JSONObject (including {}), referencing the _json_object
function and json_document/JSONObject types to locate the change.

In `@polylogue/storage/backends/queries/runs.py`:
- Around line 32-38: The code should validate that counts_payload is an object
before passing it to RunCounts.model_validate: after calling _parse_json for
"counts_json" (in the block constructing RunRecord), if counts_payload is None
keep counts=None, else if not isinstance(counts_payload, dict) raise a
DatabaseError (including field="counts_json" and record_id=row["run_id"]) to
match the other parsing errors, otherwise call
RunCounts.model_validate(counts_payload).to_payload(); update the counts=
assignment in the RunRecord construction accordingly to use these guards around
RunCounts.model_validate.
- Around line 18-38: The local helper _json_object used by get_latest_run is not
None-safe and duplicates the canonical function in mappers.py; replace the local
definition with an import from polylogue.storage.backends.queries.mappers (use
the existing mappers._json_object or exported name) and update get_latest_run to
call that imported _json_object for plan_snapshot and drift (ensuring it accepts
JSONValue | None as returned by _parse_json), removing the local function so
NULL JSON columns produce None instead of raising.

In `@polylogue/storage/backends/queries/session_product_summary_queries.py`:
- Around line 44-46: The tag search currently builds a LIKE pattern from
query.query without escaping SQL LIKE metacharacters, causing `%` and `_` in
user input to act as wildcards; update the code that appends to where and params
(the block that checks query.query and uses where.append("LOWER(tag) LIKE ?")
and params.append(...)) to first escape backslashes, percent and underscore in
the user string (e.g., s = query.query.strip().lower(); s = s.replace("\\",
"\\\\").replace("%", "\\%").replace("_", "\\_")), then build the pattern like
f"%{s}%" and append it to params, and change the SQL clause to include an ESCAPE
clause (e.g., where.append("LOWER(tag) LIKE ? ESCAPE '\\\\'")) so the escaped
characters are treated literally.

In `@polylogue/storage/repository_product_profile_reads.py`:
- Around line 45-49: The repository currently calls the private query helper
self.queries._list_session_profiles_query from
_list_session_profile_records_query, which crosses module boundaries and uses a
leading-underscore API; change this to use a public contract: either rename the
query-store method to list_session_profiles_query on SQLiteQueryStore and call
that, or route through the existing public list_session_profiles(...) API on
self.queries (accepting SessionProfileListQuery or expanded kwargs) so
_list_session_profile_records_query only invokes a non-underscored, public
method; update any sibling mixin timeline list usages the same way to remove
calls to _list_* helpers across modules.

In `@polylogue/storage/repository_product_summary_reads.py`:
- Around line 21-31: The wrapper methods _list_session_tag_rollup_rows_query and
_list_day_session_summary_records_query call module-private methods on
self.queries (_list_session_tag_rollup_rows_query and
_list_day_session_summaries_query) across mixin boundaries; either make the
query-store API public by renaming those target methods to remove the leading
underscore, or keep them private but add a short comment above these wrapper
methods stating that the cross-mixin access is intentional and these query
methods are treated as part of the typed contract; update whichever method
names/comments you choose consistently for both
_list_session_tag_rollup_rows_query and _list_day_session_summary_records_query
and their corresponding targets on the queries object.

In `@polylogue/storage/session_product_rebuild.py`:
- Around line 199-200: Normalize empty-string fields returned by _row_text to
None before any enum or typed construction: for both parent_conversation_id and
branch_type retrieved via _row_text, treat "" the same as NULL (set to None)
before passing to BranchType(branch_type) or any other constructor to avoid
ValueError on legacy/blank rows; apply the same blank-to-None normalization at
the analogous locations in polylogue/storage/backends/queries/mappers_archive.py
where branch_type and parent_conversation_id are hydrated.

In `@polylogue/storage/store_runtime_archive_records.py`:
- Around line 26-35: _coerce_json_object currently treats empty dicts as falsy
and returns None, collapsing {} to null; update it to preserve explicit empty
mappings by checking the original input type before coercion: if the incoming
value is None return None, if it's not a dict return None, otherwise coerce via
json_document(value) and return a shallow copy of the resulting mapping (use
dict(document) instead of the manual loop) so {} stays {} while non-dict inputs
map to None; refer to the _coerce_json_object function and json_document call to
locate the change.

---

Outside diff comments:
In `@polylogue/storage/backends/queries/publications.py`:
- Around line 17-51: The file redefines a local _json_object identical to
mappers._json_object; remove the local helper and import and use
mappers._json_object in get_latest_publication (and any other use sites) so you
don't duplicate logic—call mappers._json_object around the result of
_parse_json(row["manifest_json"], field="manifest_json",
record_id=row["publication_id"]). If PublicationRecord.manifest must remain
non-optional, explicitly coerce a None result to {} at the call site so the
invariant is visible (e.g., manifest = mappers._json_object(...) or manifest =
mappers._json_object(...) or {}).

In `@polylogue/storage/backends/query_store_product_timelines.py`:
- Around line 75-96: list_session_phases currently builds a
SessionTimelineListQuery but omits the full-text `query` field, so phase listing
never receives the FTS filter; modify list_session_phases to accept and pass
through the `query` parameter into the SessionTimelineListQuery (same symbol)
and ensure the lower-level _list_session_phases_query will see query.query;
apply the identical change to the repository-layer methods list_session_phases
and list_session_phase_records in repository_product_timeline_reads.py so they
also forward the SessionTimelineListQuery.query value.

In `@polylogue/storage/repository_product_profile_reads.py`:
- Around line 51-145: Multiple methods (list_session_profiles,
list_session_profile_records, list_session_enrichment_records) duplicate
construction of SessionProfileListQuery; extract a small helper like
_build_session_profile_list_query(...) that accepts the shared parameters
(provider, since, until, first_message_since, first_message_until,
session_date_since, session_date_until, limit, offset, query) and returns a
SessionProfileListQuery, then call that helper from each method and only
override tier in list_session_enrichment_records (or allow tier as an optional
param to the helper). Update usages of SessionProfileListQuery in those three
methods to use _build_session_profile_list_query (and pass tier="enrichment" for
get_session_enrichment_records) so all call sites remain in sync as fields
change.

In `@polylogue/storage/repository_product_thread_reads.py`:
- Around line 24-52: Duplicate construction of WorkThreadListQuery appears in
list_work_threads and list_work_thread_records; extract a small helper (e.g.,
_build_work_thread_query) that accepts the parameters (since, until, limit,
offset, query) and returns WorkThreadListQuery, then replace both sites
(list_work_threads and list_work_thread_records/_list_work_thread_records_query
callers) to call _build_work_thread_query(...) before passing the result to
_list_work_thread_records_query or other query methods to remove verbatim
duplication.
🪄 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: b25ddbf6-dd3b-44f7-99ce-b8171e9bcabb

📥 Commits

Reviewing files that changed from the base of the PR and between 90fef43 and c90edea.

📒 Files selected for processing (34)
  • polylogue/lib/action_events.py
  • polylogue/lib/semantic_fact_models.py
  • polylogue/lib/semantic_fact_support.py
  • polylogue/lib/semantic_facts.py
  • polylogue/pipeline/run_finalization.py
  • polylogue/schemas/verification_artifacts.py
  • polylogue/storage/artifact_queries.py
  • polylogue/storage/backends/queries/attachment_records.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/publications.py
  • polylogue/storage/backends/queries/raw_state.py
  • polylogue/storage/backends/queries/runs.py
  • polylogue/storage/backends/queries/session_product_profile_reads.py
  • polylogue/storage/backends/queries/session_product_summary_queries.py
  • polylogue/storage/backends/queries/session_product_thread_queries.py
  • polylogue/storage/backends/queries/session_product_timeline_reads.py
  • polylogue/storage/backends/query_store.py
  • polylogue/storage/backends/query_store_product_profiles.py
  • polylogue/storage/backends/query_store_product_timelines.py
  • polylogue/storage/product_read_support.py
  • polylogue/storage/query_models.py
  • polylogue/storage/repository_product_profile_reads.py
  • polylogue/storage/repository_product_summary_reads.py
  • polylogue/storage/repository_product_thread_reads.py
  • polylogue/storage/repository_product_timeline_reads.py
  • polylogue/storage/session_product_rebuild.py
  • polylogue/storage/store_runtime_archive_records.py
  • tests/unit/site/test_builder.py
  • tests/unit/storage/test_publications.py

Comment on lines +58 to +63
class ActionEventMessageLike(Protocol):
@property
def id(self) -> object: ...

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

🧹 Nitpick | 🔵 Trivial

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm Message.id is str-typed and no caller passes a non-str id.
rg -nP -C2 '\bid\s*:\s*str\b' -g 'polylogue/**/message*.py'
ast-grep --pattern 'class Message($$$):
  $$$
  id: $_
  $$$'

Repository: Sinity/polylogue

Length of output: 2568


🏁 Script executed:

#!/bin/bash
# Check the complete action_events.py file to see lines 80-81 and context
wc -l polylogue/lib/action_events.py
head -n 100 polylogue/lib/action_events.py | tail -n 50

Repository: Sinity/polylogue

Length of output: 1573


🏁 Script executed:

#!/bin/bash
# Search for all uses of message.id in action_events.py
rg -nP 'message\.id|make_action_event_id' polylogue/lib/action_events.py -A 2 -B 2

Repository: Sinity/polylogue

Length of output: 467


🏁 Script executed:

#!/bin/bash
# Search for implementations/users of ActionEventMessageLike protocol
rg -nP 'ActionEventMessageLike' polylogue/

Repository: Sinity/polylogue

Length of output: 276


🏁 Script executed:

#!/bin/bash
# Check if any code passes non-str values as message.id
rg -nP 'Message\(' polylogue/ -A 5 | grep -E 'id\s*[:=]'

Repository: Sinity/polylogue

Length of output: 2286


🏁 Script executed:

#!/bin/bash
# See the function around line 111 that uses ActionEventMessageLike
sed -n '105,120p' polylogue/lib/action_events.py

Repository: Sinity/polylogue

Length of output: 421


🏁 Script executed:

#!/bin/bash
# Search for any other classes that might implement ActionEventMessageLike or use it
rg -nP 'class.*Protocol|implements.*ActionEventMessageLike' polylogue/ -A 3

Repository: Sinity/polylogue

Length of output: 23722


🏁 Script executed:

#!/bin/bash
# Check if there are any test files or mocks that might use ActionEventMessageLike
find polylogue -name '*test*.py' -o -name '*mock*.py' | xargs rg -l 'ActionEventMessageLike' 2>/dev/null || echo "No test files found using ActionEventMessageLike"

Repository: Sinity/polylogue

Length of output: 90


🏁 Script executed:

#!/bin/bash
# Check what make_action_event_id expects - find its definition
rg -nP 'def make_action_event_id' polylogue/ -A 3

Repository: Sinity/polylogue

Length of output: 446


Tighten id to str in the protocol.

make_action_event_id (which expects message_id: str) and both message_id assignments wrap message.id in str(...) on lines 80–81. Since the concrete Message class already types id as str, narrowing the protocol from object to str eliminates the redundant coercions and prevents silent conversion of arbitrary objects to strings.

♻️ Suggested fix
 class ActionEventMessageLike(Protocol):
     `@property`
-    def id(self) -> object: ...
+    def id(self) -> str: ...

     `@property`
     def timestamp(self) -> datetime | None: ...

Then drop the str(...) coercions on lines 80–81.

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

In `@polylogue/lib/action_events.py` around lines 58 - 63, Change the
ActionEventMessageLike protocol's id property from object to str (i.e., def
id(self) -> str) so it reflects the concrete Message type; then remove the
redundant str(...) coercions where message_id is produced/assigned and where
make_action_event_id is called (references: ActionEventMessageLike,
make_action_event_id, and the message_id / message.id usages) so you rely on the
typed string id directly.

Comment on lines +67 to +70
class SemanticConversationMessagesLike(Protocol):
def __iter__(self) -> Iterator[SemanticConversationMessageLike]: ...

def __len__(self) -> int: ...

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

Export the message-collection protocol used by the public conversation contract.

SemanticConversationLike.messages exposes SemanticConversationMessagesLike, but __all__ omits it while exporting the other new Protocol types. Add it so the public typed boundary is complete and consistent.

Proposed fix
 __all__ = [
     "ProjectionAttachmentLike",
     "ProjectionLike",
     "ProjectionMessageLike",
     "SemanticConversationLike",
+    "SemanticConversationMessagesLike",
     "SemanticConversationMessageLike",
     "SemanticSummaryLike",

Also applies to: 388-394

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

In `@polylogue/lib/semantic_facts.py` around lines 67 - 70, The Protocol type
SemanticConversationMessagesLike is used by the public contract (e.g.,
referenced by SemanticConversationLike.messages) but is not exported; update the
module exports by adding "SemanticConversationMessagesLike" to the __all__
list(s) that export the public Protocol types (the existing __all__ near the top
and the similar __all__ block around the later section), ensuring both
declaration(s) include that symbol so the public typed boundary is complete and
consistent.

Comment on lines 107 to 111
payload_provider=(
Provider.from_string(_row_get(row, "payload_provider"))
if _row_get(row, "payload_provider") is not None
Provider.from_string(_row_text(row, "payload_provider"))
if _row_text(row, "payload_provider") is not None
else None
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Cache payload_provider text into a local, matching the pattern used elsewhere in this file.

_row_text(row, "payload_provider") is invoked twice in each branch. The rest of the file already extracts once into a named local (see parent_conversation_id, role, validation_status, validation_provider, validation_mode). Following the same convention avoids a second row lookup and makes the mapper uniform.

♻️ Proposed refactor
 def _row_to_raw_conversation(row: sqlite3.Row) -> RawConversationRecord:
     validation_status = _row_text(row, "validation_status")
     validation_provider = _row_text(row, "validation_provider")
     validation_mode = _row_text(row, "validation_mode")
+    payload_provider = _row_text(row, "payload_provider")
     return RawConversationRecord(
         raw_id=row["raw_id"],
         provider_name=row["provider_name"],
-        payload_provider=(
-            Provider.from_string(_row_text(row, "payload_provider"))
-            if _row_text(row, "payload_provider") is not None
-            else None
-        ),
+        payload_provider=(
+            Provider.from_string(payload_provider) if payload_provider is not None else None
+        ),

Apply the analogous change in _row_to_artifact_observation.

Also applies to: 134-138

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

In `@polylogue/storage/backends/queries/mappers_archive.py` around lines 107 -
111, Cache the result of _row_text(row, "payload_provider") into a local
variable (e.g., payload_provider_text) in the mapper where payload_provider is
built, then pass that local to Provider.from_string only once and use it in the
ternary (payload_provider=Provider.from_string(payload_provider_text) if
payload_provider_text is not None else None); apply the same refactor in
_row_to_artifact_observation so both places follow the file's pattern of
extracting row text into a named local (matching how parent_conversation_id,
role, validation_status, etc. are handled).

Comment on lines +291 to +345
def _legacy_text(value: JSONValue | bytes | bytearray) -> str | None:
if value is None:
return None
text = str(value)
return text if text else None


def _legacy_float(value: object, default: float = 0.0) -> float:
def _legacy_float(value: JSONValue | bytes | bytearray, default: float = 0.0) -> float:
if isinstance(value, bool):
return float(int(value))
if isinstance(value, str | int | float):
return float(value or default)
return default


def _legacy_int(value: object, default: int = 0) -> int:
def _legacy_int(value: JSONValue | bytes | bytearray, default: int = 0) -> int:
if isinstance(value, bool):
return int(value)
if isinstance(value, str | int | float):
return int(value or default)
return default


def _legacy_text_tuple(value: object) -> tuple[str, ...]:
def _legacy_text_tuple(
value: JSONValue | bytes | bytearray | list[JSONValue] | tuple[JSONValue, ...],
) -> tuple[str, ...]:
if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping):
return ()
return tuple(str(item) for item in value if item is not None)


def _legacy_dict_tuple(value: object) -> tuple[dict[str, object], ...]:
def _legacy_dict_tuple(
value: JSONValue | list[JSONValue] | tuple[JSONValue, ...] | bytes | bytearray,
) -> tuple[LegacyPayload, ...]:
if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping):
return ()
items: list[dict[str, object]] = []
items: list[LegacyPayload] = []
for item in value:
if isinstance(item, Mapping):
items.append({str(key): val for key, val in item.items()})
items.append(json_document(dict(item)))
return tuple(items)


def _legacy_int_dict(value: object) -> dict[str, int]:
def _legacy_int_dict(value: JSONValue | bytes | bytearray | Mapping[str, JSONValue]) -> dict[str, int]:
if not isinstance(value, Mapping):
return {}
return {str(key): int(item) for key, item in value.items() if item is not None}
return {str(key): _legacy_int(item) for key, item in value.items() if item is not None}


def _legacy_bool(value: JSONValue | bytes | bytearray) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, str | int | float):
return bool(int(value or 0))
return bool(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

Make legacy scalar coercion actually tolerate bytes and malformed values.

These helpers now accept bytes | bytearray, but _legacy_int(b"12") returns the default, _legacy_bool(b"0") returns True, and invalid strings like "unknown" raise. A malformed legacy payload can abort hydration instead of falling back.

🐛 Proposed fix
+def _legacy_scalar_text(value: JSONValue | bytes | bytearray) -> str | None:
+    if value is None:
+        return None
+    if isinstance(value, bytes | bytearray):
+        return value.decode("utf-8", errors="replace")
+    if isinstance(value, str):
+        return value
+    return None
+
+
 def _legacy_text(value: JSONValue | bytes | bytearray) -> str | None:
     if value is None:
         return None
-    text = str(value)
+    text = _legacy_scalar_text(value) if isinstance(value, str | bytes | bytearray) else str(value)
     return text if text else None
 
 
 def _legacy_float(value: JSONValue | bytes | bytearray, default: float = 0.0) -> float:
     if isinstance(value, bool):
         return float(int(value))
-    if isinstance(value, str | int | float):
-        return float(value or default)
+    if isinstance(value, int | float):
+        try:
+            return float(value)
+        except (OverflowError, ValueError):
+            return default
+    text = _legacy_scalar_text(value)
+    if text is not None:
+        try:
+            return float(text or default)
+        except ValueError:
+            return default
     return default
 
 
 def _legacy_int(value: JSONValue | bytes | bytearray, default: int = 0) -> int:
     if isinstance(value, bool):
         return int(value)
-    if isinstance(value, str | int | float):
-        return int(value or default)
+    if isinstance(value, int | float):
+        try:
+            return int(value)
+        except (OverflowError, ValueError):
+            return default
+    text = _legacy_scalar_text(value)
+    if text is not None:
+        try:
+            return int(text or default)
+        except ValueError:
+            return default
     return default
@@
 def _legacy_text_tuple(
     value: JSONValue | bytes | bytearray | list[JSONValue] | tuple[JSONValue, ...],
 ) -> tuple[str, ...]:
-    if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping):
+    if not isinstance(value, Iterable) or isinstance(value, str | bytes | bytearray | Mapping):
         return ()
     return tuple(str(item) for item in value if item is not None)
@@
 def _legacy_bool(value: JSONValue | bytes | bytearray) -> bool:
     if isinstance(value, bool):
         return value
-    if isinstance(value, str | int | float):
-        return bool(int(value or 0))
-    return bool(value)
+    if isinstance(value, int | float):
+        return bool(value)
+    text = _legacy_scalar_text(value)
+    if text is None:
+        return False
+    normalized = text.strip().lower()
+    if normalized in {"1", "true", "yes"}:
+        return True
+    if normalized in {"", "0", "false", "no"}:
+        return False
+    return False
📝 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 _legacy_text(value: JSONValue | bytes | bytearray) -> str | None:
if value is None:
return None
text = str(value)
return text if text else None
def _legacy_float(value: object, default: float = 0.0) -> float:
def _legacy_float(value: JSONValue | bytes | bytearray, default: float = 0.0) -> float:
if isinstance(value, bool):
return float(int(value))
if isinstance(value, str | int | float):
return float(value or default)
return default
def _legacy_int(value: object, default: int = 0) -> int:
def _legacy_int(value: JSONValue | bytes | bytearray, default: int = 0) -> int:
if isinstance(value, bool):
return int(value)
if isinstance(value, str | int | float):
return int(value or default)
return default
def _legacy_text_tuple(value: object) -> tuple[str, ...]:
def _legacy_text_tuple(
value: JSONValue | bytes | bytearray | list[JSONValue] | tuple[JSONValue, ...],
) -> tuple[str, ...]:
if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping):
return ()
return tuple(str(item) for item in value if item is not None)
def _legacy_dict_tuple(value: object) -> tuple[dict[str, object], ...]:
def _legacy_dict_tuple(
value: JSONValue | list[JSONValue] | tuple[JSONValue, ...] | bytes | bytearray,
) -> tuple[LegacyPayload, ...]:
if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping):
return ()
items: list[dict[str, object]] = []
items: list[LegacyPayload] = []
for item in value:
if isinstance(item, Mapping):
items.append({str(key): val for key, val in item.items()})
items.append(json_document(dict(item)))
return tuple(items)
def _legacy_int_dict(value: object) -> dict[str, int]:
def _legacy_int_dict(value: JSONValue | bytes | bytearray | Mapping[str, JSONValue]) -> dict[str, int]:
if not isinstance(value, Mapping):
return {}
return {str(key): int(item) for key, item in value.items() if item is not None}
return {str(key): _legacy_int(item) for key, item in value.items() if item is not None}
def _legacy_bool(value: JSONValue | bytes | bytearray) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, str | int | float):
return bool(int(value or 0))
return bool(value)
def _legacy_scalar_text(value: JSONValue | bytes | bytearray) -> str | None:
if value is None:
return None
if isinstance(value, bytes | bytearray):
return value.decode("utf-8", errors="replace")
if isinstance(value, str):
return value
return None
def _legacy_text(value: JSONValue | bytes | bytearray) -> str | None:
if value is None:
return None
text = _legacy_scalar_text(value) if isinstance(value, str | bytes | bytearray) else str(value)
return text if text else None
def _legacy_float(value: JSONValue | bytes | bytearray, default: float = 0.0) -> float:
if isinstance(value, bool):
return float(int(value))
if isinstance(value, int | float):
try:
return float(value)
except (OverflowError, ValueError):
return default
text = _legacy_scalar_text(value)
if text is not None:
try:
return float(text or default)
except ValueError:
return default
return default
def _legacy_int(value: JSONValue | bytes | bytearray, default: int = 0) -> int:
if isinstance(value, bool):
return int(value)
if isinstance(value, int | float):
try:
return int(value)
except (OverflowError, ValueError):
return default
text = _legacy_scalar_text(value)
if text is not None:
try:
return int(text or default)
except ValueError:
return default
return default
def _legacy_text_tuple(
value: JSONValue | bytes | bytearray | list[JSONValue] | tuple[JSONValue, ...],
) -> tuple[str, ...]:
if not isinstance(value, Iterable) or isinstance(value, str | bytes | bytearray | Mapping):
return ()
return tuple(str(item) for item in value if item is not None)
def _legacy_dict_tuple(
value: JSONValue | list[JSONValue] | tuple[JSONValue, ...] | bytes | bytearray,
) -> tuple[LegacyPayload, ...]:
if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping):
return ()
items: list[LegacyPayload] = []
for item in value:
if isinstance(item, Mapping):
items.append(json_document(dict(item)))
return tuple(items)
def _legacy_int_dict(value: JSONValue | bytes | bytearray | Mapping[str, JSONValue]) -> dict[str, int]:
if not isinstance(value, Mapping):
return {}
return {str(key): _legacy_int(item) for key, item in value.items() if item is not None}
def _legacy_bool(value: JSONValue | bytes | bytearray) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, int | float):
return bool(value)
text = _legacy_scalar_text(value)
if text is None:
return False
normalized = text.strip().lower()
if normalized in {"1", "true", "yes"}:
return True
if normalized in {"", "0", "false", "no"}:
return False
return False
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/backends/queries/mappers_product_legacy.py` around lines
291 - 345, The scalar coercion helpers (_legacy_text, _legacy_float,
_legacy_int, _legacy_bool) must tolerate bytes/bytearray and malformed strings
without raising: first detect bytes/bytearray and decode them (e.g.
value.decode('utf-8', errors='ignore')) before further processing; for
_legacy_float and _legacy_int wrap numeric conversion in try/except and return
the provided default on failure; for _legacy_bool, after decoding handle common
textual booleans ('0','1','false','true','no','yes') and numeric parsing in
try/except, falling back to False for unrecognized values; ensure _legacy_text
returns None for empty or whitespace-only decoded strings.

Comment on lines +107 to +116
def _json_object(value: JSONValue | None) -> JSONObject | None:
if value is None:
return None
document = json_document(value)
if not document:
return None
result: JSONObject = {}
for key, item in document.items():
result[key] = item
return result

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Preserve empty JSON objects.

_json_object({}) currently returns None, which loses the distinction between an explicitly persisted empty object and a missing/null JSON value. That can break null-preserving hydration semantics.

🐛 Proposed fix
 def _json_object(value: JSONValue | None) -> JSONObject | None:
     if value is None:
         return None
-    document = json_document(value)
-    if not document:
+    if not isinstance(value, dict):
         return None
     result: JSONObject = {}
-    for key, item in document.items():
+    for key, item in json_document(value).items():
         result[key] = item
     return result
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/backends/queries/mappers.py` around lines 107 - 116, The
helper _json_object currently treats an empty JSON object as falsy and returns
None, losing the distinction between an explicit {} and null; change the logic
in _json_object (and where it calls json_document) so that only a None/absent
document maps to None, while an empty dict is preserved and returned as an empty
JSONObject: call document = json_document(value), if document is None return
None, otherwise iterate document (or simply cast) to build and return a
JSONObject (including {}), referencing the _json_object function and
json_document/JSONObject types to locate the change.

Comment on lines +44 to +46
if query.query:
where.append("LOWER(tag) LIKE ?")
params.append(f"%{query.strip().lower()}%")
params.append(f"%{query.query.strip().lower()}%")

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

User-provided tag query is interpolated into a LIKE pattern without escaping % / _.

A user searching for, say, "v1_0" or "50%" will hit unintended wildcard behavior. The query is still parameterized (no injection), but matches won't correspond to what users expect. Escape LIKE metacharacters and use an ESCAPE clause.

🛡️ Proposed fix
     if query.query:
-        where.append("LOWER(tag) LIKE ?")
-        params.append(f"%{query.query.strip().lower()}%")
+        escaped = query.query.strip().lower().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+        where.append(r"LOWER(tag) LIKE ? ESCAPE '\'")
+        params.append(f"%{escaped}%")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if query.query:
where.append("LOWER(tag) LIKE ?")
params.append(f"%{query.strip().lower()}%")
params.append(f"%{query.query.strip().lower()}%")
if query.query:
escaped = query.query.strip().lower().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
where.append(r"LOWER(tag) LIKE ? ESCAPE '\'")
params.append(f"%{escaped}%")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/backends/queries/session_product_summary_queries.py` around
lines 44 - 46, The tag search currently builds a LIKE pattern from query.query
without escaping SQL LIKE metacharacters, causing `%` and `_` in user input to
act as wildcards; update the code that appends to where and params (the block
that checks query.query and uses where.append("LOWER(tag) LIKE ?") and
params.append(...)) to first escape backslashes, percent and underscore in the
user string (e.g., s = query.query.strip().lower(); s = s.replace("\\",
"\\\\").replace("%", "\\%").replace("_", "\\_")), then build the pattern like
f"%{s}%" and append it to params, and change the SQL clause to include an ESCAPE
clause (e.g., where.append("LOWER(tag) LIKE ? ESCAPE '\\\\'")) so the escaped
characters are treated literally.

Comment on lines +45 to +49
async def _list_session_profile_records_query(
self,
query: SessionProfileListQuery,
) -> list[SessionProfileRecord]:
return await self.queries._list_session_profiles_query(query)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Avoid calling leading-underscore methods across module boundaries.

self.queries._list_session_profiles_query(...) invokes a name-mangled-by-convention "private" helper on SQLiteQueryStore from a different module. The same pattern appears for timeline list helpers in the sibling mixin. If the query-store method is part of the typed-query contract the repository layer relies on, rename it (e.g. list_session_profiles_query) and expose it as public API; otherwise route through the existing public list_session_profiles(**kwargs) path. As is, external use of underscored symbols invites future churn and weakens the "read-only contract / substrate-first boundary" intent of this PR.

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

In `@polylogue/storage/repository_product_profile_reads.py` around lines 45 - 49,
The repository currently calls the private query helper
self.queries._list_session_profiles_query from
_list_session_profile_records_query, which crosses module boundaries and uses a
leading-underscore API; change this to use a public contract: either rename the
query-store method to list_session_profiles_query on SQLiteQueryStore and call
that, or route through the existing public list_session_profiles(...) API on
self.queries (accepting SessionProfileListQuery or expanded kwargs) so
_list_session_profile_records_query only invokes a non-underscored, public
method; update any sibling mixin timeline list usages the same way to remove
calls to _list_* helpers across modules.

Comment on lines +21 to +31
async def _list_session_tag_rollup_rows_query(
self,
query: SessionTagRollupListQuery,
) -> list[SessionTagRollupRecord]:
return await self.queries._list_session_tag_rollup_rows_query(query)

async def _list_day_session_summary_records_query(
self,
query: DaySessionSummaryListQuery,
) -> list[DaySessionSummaryRecord]:
return await self.queries._list_day_session_summaries_query(query)

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: calling _-prefixed methods across mixin boundaries.

_list_session_tag_rollup_rows_query / _list_day_session_summaries_query are module-private by convention on SQLiteQueryStore but are consumed from a different class here. Since this pattern is already adopted uniformly across the PR, it's consistent, but consider either dropping the underscore (these are de-facto part of the query-store's typed contract) or adding a brief comment noting the intentional cross-mixin coupling.

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

In `@polylogue/storage/repository_product_summary_reads.py` around lines 21 - 31,
The wrapper methods _list_session_tag_rollup_rows_query and
_list_day_session_summary_records_query call module-private methods on
self.queries (_list_session_tag_rollup_rows_query and
_list_day_session_summaries_query) across mixin boundaries; either make the
query-store API public by renaming those target methods to remove the leading
underscore, or keep them private but add a short comment above these wrapper
methods stating that the cross-mixin access is intentional and these query
methods are treated as part of the typed contract; update whichever method
names/comments you choose consistently for both
_list_session_tag_rollup_rows_query and _list_day_session_summary_records_query
and their corresponding targets on the queries object.

Comment on lines +199 to +200
parent_conversation_id = _row_text(row, "parent_conversation_id")
branch_type = _row_text(row, "branch_type")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Expect to find either schema constraints/writer normalization that prevent empty
# branch_type values, or otherwise apply the mapper-side normalization above.
rg -n -C3 '\bbranch_type\b' --glob '!**/.venv/**' --glob '!**/node_modules/**'

Repository: Sinity/polylogue

Length of output: 50372


🏁 Script executed:

#!/bin/bash
# Find _row_text definition to understand its behavior
rg -n "def _row_text" -A 3

Repository: Sinity/polylogue

Length of output: 1159


🏁 Script executed:

#!/bin/bash
# Verify the fix applies to both session_product_rebuild.py and mappers_archive.py
# Check context around lines 199-200 and 39-40 respectively
echo "=== session_product_rebuild.py lines 195-220 ===" && \
sed -n '195,220p' polylogue/storage/session_product_rebuild.py && \
echo -e "\n=== mappers_archive.py lines 35-60 ===" && \
sed -n '35,60p' polylogue/storage/backends/queries/mappers_archive.py

Repository: Sinity/polylogue

Length of output: 2382


🏁 Script executed:

#!/bin/bash
# Complete the _row_text definition to see full implementation
sed -n '60,70p' polylogue/storage/backends/queries/mappers.py

Repository: Sinity/polylogue

Length of output: 459


🏁 Script executed:

#!/bin/bash
# Check if there are any test cases or references showing empty strings for branch_type
rg "branch_type.*=.*['\"]\"['\"]|branch_type.*=.*''" --type py -n

Repository: Sinity/polylogue

Length of output: 421


🏁 Script executed:

#!/bin/bash
# Verify the imports in session_product_rebuild.py to see if it uses _row_text from the same module
head -50 polylogue/storage/session_product_rebuild.py | grep -E "^from|^import|_row_text"

Repository: Sinity/polylogue

Length of output: 1125


🏁 Script executed:

#!/bin/bash
# Check if mappers_archive.py also imports _row_text from mappers.py (to confirm same function)
grep -n "from.*_row_text\|import.*_row_text" polylogue/storage/backends/queries/mappers_archive.py

Repository: Sinity/polylogue

Length of output: 205


🏁 Script executed:

#!/bin/bash
# Look for any test data or migration that might create empty branch_type values
rg "branch_type.*['\"]\"['\"]|INSERT.*branch_type.*['\"]\"['\"]" --type py --type sql -n

Repository: Sinity/polylogue

Length of output: 173


Normalize blank parent/branch fields before enum hydration.

Line 215 casts any non-NULL value with BranchType(branch_type). Since _row_text can return "" (empty string), historical rows or legacy data with a blank branch_type will raise ValueError and abort session-product rebuild. Treat blank parent/branch fields as missing before casting.

🐛 Proposed fix
-    parent_conversation_id = _row_text(row, "parent_conversation_id")
-    branch_type = _row_text(row, "branch_type")
+    parent_conversation_id = _row_text(row, "parent_conversation_id") or None
+    branch_type = _row_text(row, "branch_type") or None
@@
-        parent_conversation_id=ConversationId(parent_conversation_id) if parent_conversation_id is not None else None,
-        branch_type=BranchType(branch_type) if branch_type is not None else None,
+        parent_conversation_id=ConversationId(parent_conversation_id) if parent_conversation_id else None,
+        branch_type=BranchType(branch_type) if branch_type else None,

Also applies to polylogue/storage/backends/queries/mappers_archive.py:39-40, 55-56.

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

In `@polylogue/storage/session_product_rebuild.py` around lines 199 - 200,
Normalize empty-string fields returned by _row_text to None before any enum or
typed construction: for both parent_conversation_id and branch_type retrieved
via _row_text, treat "" the same as NULL (set to None) before passing to
BranchType(branch_type) or any other constructor to avoid ValueError on
legacy/blank rows; apply the same blank-to-None normalization at the analogous
locations in polylogue/storage/backends/queries/mappers_archive.py where
branch_type and parent_conversation_id are hydrated.

Comment on lines +26 to +35
def _coerce_json_object(value: object) -> JSONObject | None:
if value is None:
return None
document = json_document(value)
if not document:
return None
result: JSONObject = {}
for key, item in document.items():
result[key] = item
return result

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 | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Look for assertions or comparisons that could regress under the {} -> None coercion
rg -nP -C2 '\.(provider_meta|metadata|plan_snapshot|drift)\s*(==|is\s+None|is\s+not\s+None)'
rg -nP -C2 'assert(_equal)?\s*\(.*(provider_meta|plan_snapshot|drift|metadata)'

Repository: Sinity/polylogue

Length of output: 17008


_coerce_json_object silently collapses empty JSON objects to None, breaking round-trip semantics.

if not document: return None treats {} as absent. Every time a record with stored provider_meta = {} / metadata = {} / plan_snapshot = {} / drift = {} (or attachment provider_meta = {}) is hydrated, the field becomes None. This is a semantic regression from "empty object" to "missing", and breaks tests like test_pipeline_ids.py:77 which explicitly assert attachment.provider_meta == {}.

The distinction between "explicitly empty" and "null/missing" is critical for equality/diff logic and field semantics. While PublicationRecord.manifest papers over this with or {}, other fields are exposed.

The fix should check the original input type before coercion: return None only for non-dict inputs, and preserve empty dicts as-is. Also, replace the hand-rolled shallow copy with idiomatic dict(...).

🐛 Proposed fix
 def _coerce_json_object(value: object) -> JSONObject | None:
     if value is None:
         return None
     document = json_document(value)
-    if not document:
-        return None
-    result: JSONObject = {}
-    for key, item in document.items():
-        result[key] = item
-    return result
+    # json_document() returns {} for non-dict/non-string-keyed inputs; distinguish
+    # those from a legitimately-empty dict by checking the original value first.
+    if not isinstance(value, dict):
+        return None
+    return dict(document)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/store_runtime_archive_records.py` around lines 26 - 35,
_coerce_json_object currently treats empty dicts as falsy and returns None,
collapsing {} to null; update it to preserve explicit empty mappings by checking
the original input type before coercion: if the incoming value is None return
None, if it's not a dict return None, otherwise coerce via json_document(value)
and return a shallow copy of the resulting mapping (use dict(document) instead
of the manual loop) so {} stays {} while non-dict inputs map to None; refer to
the _coerce_json_object function and json_document call to locate the change.

@Sinity
Sinity merged commit 973c15a into master Apr 20, 2026
14 checks passed
@Sinity
Sinity deleted the feature/refactor/storage-product-runtime-boundaries branch April 20, 2026 17:13
Sinity added a commit that referenced this pull request Apr 22, 2026
## Summary
- centralize typed storage query contracts for session-profile, timeline, thread, and artifact reads
- tighten archive/run hydration around explicit row coercion helpers instead of loose row-value plumbing
- normalize semantic-fact protocols so Conversation, MessageCollection, and action-event callers satisfy the intended read-only contracts

## Problem
The storage/lib/product-runtime tranche still relied on repeated result-shape normalization, loose row hydration, and protocol contracts that were only mypy-clean because values flowed through weak helper types. That left duplicated coercion logic across repository/product mappers and made downstream semantic-fact callers depend on accidental mutability assumptions.

## Solution
- add explicit query dataclasses and shared product-read hydration helpers for profile/timeline/thread/artifact reads
- rebuild row-mapper support around typed JSON parsing, scalar coercion, JSON tuple/dict helpers, and null-preserving run hydration
- tighten semantic action-event and semantic-fact protocols to model read-only properties and iterable message collections actually used by the domain models
- update the small publication-manifest tests that index persisted JSON manifests through typed object boundaries

## Verification
- `devtools verify`
- `mypy polylogue/storage/backends/queries/mappers.py polylogue/storage/backends/queries/mappers_archive.py polylogue/storage/backends/queries/mappers_product_profiles.py polylogue/storage/backends/queries/mappers_product_timelines.py polylogue/storage/backends/queries/mappers_product_aggregates.py polylogue/storage/backends/queries/attachment_records.py polylogue/storage/session_product_rebuild.py polylogue/lib/action_events.py polylogue/lib/semantic_fact_support.py polylogue/lib/semantic_facts.py polylogue/lib/pricing.py polylogue/storage/action_event_rows.py polylogue/pipeline/services/ingest_worker.py polylogue/pipeline/run_finalization.py polylogue/cli/query_stats.py polylogue/cli/query_semantic.py polylogue/lib/query_retrieval_search.py polylogue/lib/session_profile_runtime.py polylogue/lib/phase_extraction.py polylogue/lib/attribution.py polylogue/lib/work_event_extraction.py tests/unit/storage/test_publications.py tests/unit/site/test_builder.py tests/unit/core/test_semantic_facts.py`
- `pytest -q tests/unit/storage/test_query_mappers.py tests/unit/storage/test_publications.py tests/unit/site/test_builder.py tests/unit/core/test_semantic_facts.py`
- `pytest -q tests/unit/cli/test_run_int.py -k latest_run_parsing`

Closes #272
@Sinity Sinity added area:parser Parser 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/product-runtime tranche relied on repeated
result-shape normalization, loose row hydration, and protocol
contracts that were only mypy-clean because values flowed through
weak helper types. Coercion logic was duplicated across
repository/product mappers, and downstream semantic-fact callers
depended on accidental mutability assumptions.

Adds explicit query dataclasses and shared product-read hydration
helpers for profile / timeline / thread / artifact reads. Rebuilds
row-mapper support around typed JSON parsing, scalar coercion, JSON
tuple/dict helpers, and null-preserving run hydration. Tightens
semantic action-event and semantic-fact protocols to model
read-only properties and iterable message collections actually used
by the domain models. Updates the small publication-manifest tests
that index persisted JSON manifests through typed object boundaries.

Verification: mypy + pytest over storage query mappers,
publications, site builder, and semantic-facts suites; devtools
verify green.

Closes #272
Sinity added a commit that referenced this pull request Apr 22, 2026
The storage/lib/product-runtime tranche relied on repeated
result-shape normalization, loose row hydration, and protocol
contracts that were only mypy-clean because values flowed through
weak helper types. Coercion logic was duplicated across
repository/product mappers, and downstream semantic-fact callers
depended on accidental mutability assumptions.

Adds explicit query dataclasses and shared product-read hydration
helpers for profile / timeline / thread / artifact reads. Rebuilds
row-mapper support around typed JSON parsing, scalar coercion, JSON
tuple/dict helpers, and null-preserving run hydration. Tightens
semantic action-event and semantic-fact protocols to model
read-only properties and iterable message collections actually used
by the domain models. Updates the small publication-manifest tests
that index persisted JSON manifests through typed object boundaries.

Verification: mypy + pytest over storage query mappers,
publications, site builder, and semantic-facts suites; devtools
verify green.

Closes #272
Sinity added a commit that referenced this pull request Apr 22, 2026
The storage/lib/product-runtime tranche relied on repeated
result-shape normalization, loose row hydration, and protocol
contracts that were only mypy-clean because values flowed through
weak helper types. Coercion logic was duplicated across
repository/product mappers, and downstream semantic-fact callers
depended on accidental mutability assumptions.

Adds explicit query dataclasses and shared product-read hydration
helpers for profile / timeline / thread / artifact reads. Rebuilds
row-mapper support around typed JSON parsing, scalar coercion, JSON
tuple/dict helpers, and null-preserving run hydration. Tightens
semantic action-event and semantic-fact protocols to model
read-only properties and iterable message collections actually used
by the domain models. Updates the small publication-manifest tests
that index persisted JSON manifests through typed object boundaries.

Verification: mypy + pytest over storage query mappers,
publications, site builder, and semantic-facts suites; devtools
verify green.

Closes #272
@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@Sinity
Sinity requested a review from Copilot May 1, 2026 00:43

@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: 973c15a45b

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

area:parser Parser area:storage Storage tool:claude Claude type:refactor Code restructuring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: rebuild storage and product runtime boundary contracts

1 participant