Skip to content

refactor: renew source and showcase boundary contracts - #228

Merged
Sinity merged 15 commits into
masterfrom
feature/refactor/source-renewal-sweep
Apr 19, 2026
Merged

Sinity merged 15 commits into
masterfrom
feature/refactor/source-renewal-sweep

Conversation

@Sinity

@Sinity Sinity commented Apr 19, 2026 •

Copy link
Copy Markdown
Owner

Closes #223
Ref #222

Summary

Renew a large source-to-surface tranche by rebuilding provider dispatch, synthetic/runtime schema contracts, source acquisition and emission seams, and the scenario/showcase/site layers that sit on top of them.

Problem

The codebase was fully type-checked but still carried older path-dependent boundary code: broad payload dictionaries, repeated coercion glue, weakly modeled runtime seams, and surface code compensating for ambiguity below. The existing branch had completed that renewal work locally, but it still needed to land as a real reviewed slice before the next tranche could continue.

Solution

  • rebuilt provider dispatch and viewport/unified-adapter seams in polylogue/sources/dispatch.py and polylogue/schemas/unified_adapters.py
  • tightened Drive/source boundaries across auth, gateway, client, support, decoder, attachment, and emission paths under polylogue/sources/
  • renewed synthetic corpus/runtime and schema support contracts across polylogue/schemas/synthetic/*, registry/validator/extraction, and verification helpers
  • hardened ingest/provider metadata seams in polylogue/pipeline/services/*, polylogue/pipeline/semantic_*, and adjacent helpers
  • rebuilt scenario/showcase/report/site surfaces so they consume stronger substrate contracts instead of preserving old glue
  • added new support modules such as polylogue/rendering/block_models.py, polylogue/scenarios/payloads.py, and polylogue/showcase/report_models.py where shared contracts needed explicit homes

Verification

  • devtools verify
  • pytest -q tests/unit/sources/test_drive_gateway.py tests/unit/sources/test_source_laws.py -k 'drive_gateway or detect_provider or parse_payload or parse_drive_payload'
  • pytest -q tests/unit/sources/test_unified_semantic_laws.py -k 'extract_harmonized_message or fallback_contract'
  • pytest -q tests/unit/test_cross_surface_agreement.py::TestSyntheticRoundtripFactAgreement
  • pytest -q tests/unit/core/test_synthetic_semantics.py tests/unit/sources/test_drive_source_client.py tests/unit/sources/test_drive_gateway.py
  • pytest -q tests/unit/core/test_synthetic_semantics.py tests/unit/sources/test_source_laws.py -k 'conversation_emitter or synthetic or iter_source_conversations_with_raw_preserves_grouped_bytes_contract or iter_source_conversations_with_raw_streams_plain_grouped_capture_to_blob_store or iter_source_conversations_with_raw_streams_grouped_zip_capture_to_blob_store or iter_entry_payloads_locks_provider_after_first_detected_payload'

@coderabbitai

coderabbitai Bot commented Apr 19, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This pull request significantly strengthens type safety across the polylogue codebase by replacing generic Any types with structured models, introducing Protocol-based abstractions for external dependencies, and refactoring core pipelines (rendering, schemas, sources, showcase) to use immutable typed dataclasses and TypedDicts instead of dictionaries. The changes span over 100 files.

Changes

Cohort / File(s) Summary
Core Payload Typing
polylogue/lib/payload_coercion.py, polylogue/lib/raw_payload_decode.py, polylogue/lib/viewport_tools.py
Introduced PayloadMapping type alias and is_payload_mapping predicate; tightened return types in coercion functions to use PayloadMapping; added JSON typing (JSONScalar, JSONValue, JSONRecord) throughout payload decoding; broadened classify_tool input from dict to Mapping.
Scenario & Campaign Infrastructure
polylogue/scenarios/payloads.py (new), polylogue/scenarios/__init__.py, polylogue/scenarios/assertions.py, polylogue/scenarios/cli_surfaces.py, polylogue/scenarios/corpus.py, polylogue/scenarios/execution.py, polylogue/scenarios/metadata.py, polylogue/scenarios/projections.py, polylogue/scenarios/specs.py, devtools/benchmark_campaign.py
Added new payloads module with PayloadDict, PayloadMap, and coercion helpers (payload_string, payload_int, merge_unique_string_tuples, etc.); refactored scenario metadata extraction to use typed helpers; updated all payload serialization to use PayloadDict return type; extended CampaignResult with maintenance_targets field.
Schema Extraction & Validation
polylogue/schemas/extraction.py, polylogue/schemas/field_stats_collection.py, polylogue/schemas/generation_schema_builder.py, polylogue/schemas/generation_support.py, polylogue/schemas/observation_runtime.py, polylogue/schemas/operator_models.py, polylogue/schemas/privacy_config.py, polylogue/schemas/runtime_registry.py, polylogue/schemas/sampling_db.py, polylogue/schemas/validator.py
Introduced schema-specific type aliases (SchemaPayload, SchemaRecord, SchemaValue); replaced dict[str, Any] with structured types throughout; added helper protocols (PrivacyConfigLike, _WireFormatContext); tightened schema builder/validator signatures with concrete types; refactored privacy config loading with typed field parsing.
Synthetic Corpus & Runtime
polylogue/schemas/synthetic/models.py, polylogue/schemas/synthetic/core.py, polylogue/schemas/synthetic/build_batch.py, polylogue/schemas/synthetic/build_records.py, polylogue/schemas/synthetic/build_wire_formats.py, polylogue/schemas/synthetic/runtime.py, polylogue/schemas/synthetic/selection.py, polylogue/schemas/synthetic/wire_formats.py
Introduced SchemaRecord, SyntheticStyle, WireEncoding type aliases; replaced untyped self: Any contexts with Protocol-based typing; refactored generation/selection to use dependency injection for registry/provider resolution; added JSON coercion helpers; tightened return types across build pipeline.
Schema Tooling & Adapters
polylogue/schemas/tooling_registry.py, polylogue/schemas/unified_adapters.py
Introduced SchemaPayload, ObservedSchemaSample, and ViewportRecord Protocol; updated public signatures to use concrete schema types; added adapter builder type alias and validation helpers.
Rendering Pipeline Core
polylogue/rendering/block_models.py (new), polylogue/rendering/blocks.py, polylogue/rendering/core.py, polylogue/rendering/core_formatter.py, polylogue/rendering/core_markdown.py, polylogue/rendering/core_messages.py, polylogue/rendering/formatting.py
Introduced RenderableBlock dataclass with coercion helpers; replaced dict-based blocks with typed blocks throughout renderers; added RenderedMessage dataclass replacing build_rendered_message_payload dict returns; introduced MarkdownMessage and MarkdownAttachment frozen dataclasses; added FormattedConversationMetadata dataclass; refactored message payload building to use structured types.
Rendering HTML & Templates
polylogue/rendering/renderers/html.py, polylogue/rendering/renderers/html_highlighting.py, polylogue/rendering/renderers/html_messages.py, polylogue/rendering/renderers/html_template.py, polylogue/rendering/renderers/markdown.py, polylogue/rendering/renderers/__init__.py
Updated HTML renderer to use attribute access on metadata; extracted template building logic; switched message payloads from dict to RenderedMessage objects; refactored renderer factory to use lookup-based pattern instead of conditionals; added _plain_code_block helper.
Site Generation Models & Infrastructure
polylogue/site/models.py, polylogue/site/search.py, polylogue/site/builder.py, polylogue/site/conversation_pages.py, polylogue/site/index_pages.py, polylogue/site/publication_flow.py, polylogue/site/scan.py, polylogue/site/site_builder_pages.py, polylogue/site/site_builder_archive.py, polylogue/site/template_environment.py, polylogue/site/templates.py, polylogue/site/templates_conversation.py, polylogue/site/templates_dashboard.py, polylogue/site/templates_index.py, polylogue/site/templates_index_body.py, polylogue/site/templates_index_style.py
Introduced SearchDocument, ProviderIndex, SearchBuildStatus enum, and SearchIndexWriter class; made SiteConfig, ConversationIndex, ExerciseDimensions frozen with slots; refactored template building into helper functions; updated search/provider handling to use typed index objects instead of dicts.
Source Dispatch & Parsing
polylogue/sources/dispatch.py, polylogue/sources/decoders.py, polylogue/sources/decoder_json.py
Introduced JSON typing (JsonScalar, JsonValue, JsonReadable); added Protocol-based logger/ijson interfaces; refactored JSONL parsing with helper functions; tightened payload parameter types from Any to object; added type guards and payload coercion helpers.
Drive Integration
polylogue/sources/drive.py, polylogue/sources/drive_auth.py, polylogue/sources/drive_auth_support.py, polylogue/sources/drive_gateway.py, polylogue/sources/drive_source_client.py, polylogue/sources/drive_source_factory.py, polylogue/sources/drive_source_support.py, polylogue/sources/drive_types.py (new))
Added new drive_types module with Protocol-based abstractions (DriveConfigLike, DriveUILike, DriveCredentialLike, DriveTokenStoreLike, etc.); replaced Any across auth manager, gateway, and client with Protocol types; refactored credential handling and UI prompting; introduced DrivePayloadRecord alias; added payload normalization helpers.
Source Assembly & Parsing
polylogue/sources/assembly.py, polylogue/sources/assembly_claude_code.py, polylogue/sources/assembly_codex.py, polylogue/sources/parsers/base_models.py, polylogue/sources/parsers/claude_code_parser.py, polylogue/sources/parsers/drive_support_attachments.py, polylogue/sources/providers/gemini_message.py
Introduced SidecarData type alias; updated sidecar/enrichment signatures to use Mapping instead of concrete dict; added coercion helpers for provider-specific data; refined Gemini message typing with TypeAlias definitions; strengthened attachment handling with type-safe extraction helpers.
Source Acquisition & Emission
polylogue/sources/source_acquisition.py, polylogue/sources/source_parsing.py, polylogue/sources/source_walk.py, polylogue/sources/emitter.py
Introduced payload streaming helpers and _SniffResult dataclass; replaced tuple unpacking with structured result objects; tightened cursor/payload typing from Any to object; added type aliases for callbacks and detection payloads.
Pipeline Semantic Processing
polylogue/pipeline/semantic_capture.py, polylogue/pipeline/semantic_metadata.py, polylogue/pipeline/prepare_transform.py
Introduced TypedDict-based return shapes (ContextCompactionSummary, ThinkingTraceSummary, ToolInvocationSummary, etc.); added ToolInputPayload and ToolMetadata type aliases; refactored extraction functions with payload coercion utilities; updated signatures to accept Sequence[Mapping[...]] instead of list[dict[...]].
Pipeline Ingestion
polylogue/pipeline/services/ingest_batch.py, polylogue/pipeline/services/ingest_worker.py, polylogue/pipeline/services/acquisition.py, polylogue/pipeline/services/acquisition_streams.py
Introduced BatchObservation, ConversationTuple, MessageTuple, and metadata type aliases; refactored metadata extraction with typed helpers (_normalized_conversation, _merged_conversation_provider_meta, _attachment_provider_meta); tightened stream/worker signatures; added read pool context manager usage.
Pipeline Validation & QA
polylogue/pipeline/services/validation_runtime.py, polylogue/showcase/qa_session_payload.py (updated), polylogue/showcase/qa_runner.py, polylogue/showcase/qa_runner_models.py, polylogue/showcase/qa_runner_request.py, polylogue/showcase/qa_runner_stages.py, polylogue/showcase/qa_runner_workflow.py, polylogue/showcase/qa_summary.py, polylogue/showcase/qa_markdown.py
Added QAWorkspaceMode enum and QASessionPlan dataclass; refactored validation runtime with helper functions for payload normalization and envelope construction; updated QA session handling to use typed QASessionRecord instead of dicts; introduced staged workflow helpers in runner.
Showcase Report Models & Infrastructure
polylogue/showcase/report_models.py (new), polylogue/showcase/report_files.py, polylogue/showcase/report_common.py, polylogue/showcase/showcase_report_payloads.py, polylogue/showcase/showcase_report_text.py, polylogue/showcase/showcase_runner_models.py, polylogue/showcase/showcase_runner_support.py, polylogue/showcase/vhs.py, polylogue/showcase/workspace.py
Introduced comprehensive report model hierarchy (InvariantCheckRecord, ShowcaseExerciseRecord, ShowcaseSessionRecord, QASessionRecord etc.); added ShowcaseGroupCounts and ShowcaseSummary dataclasses; introduced ShowcaseReportArtifact and VHSTape dataclasses; refactored report generation/serialization to use typed builders; updated workspace handling with helper functions.
Showcase Infrastructure
polylogue/showcase/cli_boundary.py, polylogue/showcase/context.py, polylogue/showcase/corpus_requests.py, polylogue/showcase/dimensions.py, polylogue/showcase/exercises.py, polylogue/showcase/generators.py, polylogue/showcase/invariants.py, polylogue/showcase/qa_finalization.py, polylogue/showcase/catalog_loader.py, polylogue/showcase/runner.py
Updated dataclass definitions to use slots=True; extracted constants (SHOWCASE_CORPUS_COUNT, etc.); introduced FilterFlagDescriptor dataclass and FormatScenarioSpec for cleaner flag/format handling; refactored generators with dedicated helpers; added succeeded property to ShowcaseCliResult.
Health & Artifact Storage
polylogue/health.py, polylogue/storage/repair.py, polylogue/storage/artifact_inspection.py, polylogue/storage/repository_archive_conversations.py, polylogue/storage/repository_contracts.py
Strengthened health API typing with Config instead of Any; introduced JSON type aliases (JSONScalar, JSONValue); refactored archive debt handling with type guards; added read_pool method to backend protocol; introduced inspection helpers with payload normalization.
Tests
tests/unit/cli/test_query_fmt.py, tests/unit/core/test_*.py, tests/unit/pipeline/test_*.py, tests/unit/showcase/test_*.py, tests/unit/sources/test_*.py, tests/unit/ui/test_*.py
Updated test assertions to work with typed objects instead of dicts; added helper functions for dict coercion; updated payload validation checks; refined concurrent operation tests; updated metadata access to use attributes instead of subscripting.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

  • #224: Directly related - refactors devtools/benchmark_campaign.py to consume polylogue.scenarios.ScenarioMetadata including new maintenance_targets, which depends on the ScenarioMetadata and payload type infrastructure changes in this PR.

Suggested labels

area:types, area:refactoring, area:pipeline, area:schemas, area:rendering, area:sources, area:showcase

Poem

🐰 A thousand dicts transformed to types so bright,
With Protocols and TypedDicts, all feels right!
From Any chaos springs a structured song,
Type safety whispers: "Finally we belong!"
—Your rabbity reviewer ✨

✨ 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/source-renewal-sweep

@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: 8660e4c86a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +147 to +152
records: list[JsonValue] = []
try:
for item in ijson_module.items(handle, prefix):
found_any = True
records.append(item)
return (found_any, records)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Stream ijson items instead of buffering whole payload

_stream_prefixed_items now appends every parsed item to records and returns the full list, so iter_json_stream_with no longer yields incrementally for large JSON arrays. This turns a streaming path into full in-memory materialization and can cause large memory spikes or OOM when ingesting big exports (the exact workload this module is meant to handle).

Useful? React with 👍 / 👎.

Comment thread polylogue/rendering/blocks.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 49

Caution

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

⚠️ Outside diff range comments (15)
polylogue/schemas/verification_corpus.py (1)

89-104: ⚠️ Potential issue | 🟠 Major

Apply record_limit/record_offset after the final provider filter.

Line 233 passes the requested window into iter_verification_rows, but Line 280 filters again using actual_provider. Rows skipped there still consume the SQL-applied limit/offset, so provider-filtered verification can miss later matching records when stored provider metadata is stale or approximate.

Keep the SQL clause as a candidate prefilter, but apply the requested window only after the definitive provider match succeeds.

Also applies to: 233-288

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

In `@polylogue/schemas/verification_corpus.py` around lines 89 - 104, The
SQL-applied limit/offset is being consumed before the definitive provider
filter, causing matches filtered later (by actual_provider) to be skipped;
update iter_verification_rows so that bounded_limit/record_offset are enforced
only after the provider check: keep provider_where in the SQL as a prefilter but
stop decrementing/consuming bounded_limit/records_fetched (and avoid shrinking
batch_size because of remaining) until after each row passes the final provider
match; i.e., fetch unbounded or fixed-size batches via
base_query/last_rowid/provider_where, run the definitive provider filter
(actual_provider) on each row, then apply record_offset/record_limit to
increment records_fetched and decide when to break. Ensure variables referenced
are bounded_limit, records_fetched, batch_size_limit, provider_where,
base_query, last_rowid, and the iter_verification_rows loop logic.
polylogue/showcase/vhs.py (1)

74-98: 🧹 Nitpick | 🔵 Trivial

Return VHSTape from generate_tape instead of round-tripping through .content.

generate_tape constructs a VHSTape only to discard it and return .content, and generate_all_tapes then re-wraps that string in a second VHSTape just to get tape.filename. Either drop the wrapper inside generate_tape (it adds nothing) or, preferably, let generate_tape return the tape object and keep the one instance.

♻️ Proposed refactor
-def generate_tape(
+def generate_tape(
     exercise: Exercise,
     *,
     output_width: int = 100,
     output_height: int = 30,
     font_size: int = 16,
     padding: int = 20,
-) -> str:
+) -> VHSTape:
@@
-    return VHSTape(exercise_name=exercise.name, content="\n".join(lines)).content
+    return VHSTape(exercise_name=exercise.name, content="\n".join(lines))
@@
-        tape = VHSTape(exercise_name=ex.name, content=generate_tape(ex))
-        tapes[ex.name] = tape.content
+        tape = generate_tape(ex)
+        tapes[ex.name] = tape.content

Returning a string from generate_tape is an external API change; if that is unacceptable, at minimum remove the throwaway wrapper on line 74.

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

In `@polylogue/showcase/vhs.py` around lines 74 - 98, generate_tape currently
builds a VHSTape then returns its .content, causing generate_all_tapes to
reconstruct VHSTape just to access filename; change generate_tape to return the
VHSTape object (not a string) and update callers (notably generate_all_tapes) to
accept a VHSTape and use its .content and .filename directly so you keep one
VHSTape instance (update type hints/annotations for generate_tape and any call
sites that expect a string).
polylogue/schemas/field_stats_collection.py (1)

62-83: ⚠️ Potential issue | 🟡 Minor

Non-string Mapping keys are silently coerced via str(key).

By broadening the dict check to isinstance(value, Mapping) while keying static_keys, dict_key_sets, and co_occurrence by str(key), two distinct keys that share a string representation (e.g., 1 and "1") collapse into one path, and their subtrees are merged under f"{path}.{key}". For pure JSON samples this is unreachable, but the new Mapping branch no longer guarantees that. Consider either restricting collection to string keys explicitly or documenting that non-string keys are normalized.

🛡️ Suggested guard
             for key, item in value.items():
-                if is_dynamic_key(key):
+                if not isinstance(key, str):
+                    # Mapping allows non-str keys; synthesize as dynamic.
+                    dynamic_values.append(item)
+                    continue
+                if is_dynamic_key(key):
                     dynamic_values.append(item)
                 else:
-                    static_keys[str(key)] = item
+                    static_keys[key] = item
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/schemas/field_stats_collection.py` around lines 62 - 83, The
Mapping branch currently coerces non-string keys via str(key) which can collapse
distinct keys (e.g., 1 vs "1"); update the logic in the _walk handling for
Mapping so only string keys are treated as JSON object keys: when iterating
value.items() (the Mapping branch), filter keys with isinstance(key, str) and
skip or record non-string keys separately (do not add them to static_keys,
dict_key_sets, or co_occurrence), and keep the existing
is_dynamic_key/static_keys/dynamic_values flow for string keys only; ensure all
places that build paths (f"{path}.{key}", dict_key_sets[path].update(...), and
co_occurrence[path][sample_idx]) use the original string key without implicit
str() coercion.
polylogue/schemas/extraction.py (1)

276-294: ⚠️ Potential issue | 🟠 Major

Use the nested message payload for all message-scoped metadata.

msg_data is used for usage and model, but id, cost, and duration_ms are still read only from raw. Wrapped payloads like {"message": {"id": "...", "costUSD": 0.01}} will lose the new metadata.

🐛 Proposed fix
-    msg_data = raw.get("message")
-    if not isinstance(msg_data, dict):
-        msg_data = raw
-    usage_raw = msg_data.get("usage")
+    msg_data = _schema_payload(raw.get("message")) or raw
+    usage_raw = msg_data.get("usage")
     tokens = extract_token_usage(usage_raw) if isinstance(usage_raw, dict) else None
     model = msg_data.get("model")
+    message_id = _extract_message_id(msg_data) or _extract_message_id(raw)
+    cost = _extract_cost(msg_data)
+    if cost is None:
+        cost = _extract_cost(raw)
+    duration_ms = _extract_duration_ms(msg_data)
+    if duration_ms is None:
+        duration_ms = _extract_duration_ms(raw)
 
     return HarmonizedMessage(
-        id=_extract_message_id(raw),
+        id=message_id,
         role=role,
         text=text,
         timestamp=timestamp,
@@
         content_blocks=content_blocks,
         model=model if isinstance(model, str) else None,
         tokens=tokens,
-        cost=_extract_cost(raw),
-        duration_ms=_extract_duration_ms(raw),
+        cost=cost,
+        duration_ms=duration_ms,
         provider=provider,
         raw=raw,
     )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/schemas/extraction.py` around lines 276 - 294, The constructor
currently reads id, cost and duration only from raw, which drops nested payload
values; use the nested message payload (msg_data) as the primary source and fall
back to raw when missing. Update the HarmonizedMessage field values so id uses
_extract_message_id(msg_data) if present else _extract_message_id(raw), cost
uses _extract_cost(msg_data) else _extract_cost(raw), and duration_ms uses
_extract_duration_ms(msg_data) else _extract_duration_ms(raw); keep model and
tokens logic unchanged. This ensures wrapped payloads like {"message": {...}}
preserve message-scoped metadata while still supporting top-level fields.
polylogue/pipeline/services/acquisition.py (1)

64-74: ⚠️ Potential issue | 🟡 Minor

Tighten the Drive UI type contract at the service boundary instead of casting.

The service methods visit_sources and acquire_sources accept ui: object | None, but they pass it directly (or via cast()) to iter_raw_record_stream, which expects ui: DriveUILike | None. Since DriveUILike is already imported under TYPE_CHECKING, change both method signatures to enforce the correct type at the service boundary:

  • Line 65: ui: object | None = None, → ui: DriveUILike | None = None,
  • Line 117: ui: object | None = None, → ui: DriveUILike | None = None,
  • Remove the cast("DriveUILike | None", ui) at line 74 and use ui directly
  • Remove the cast import if no longer needed elsewhere

This shifts type validation from the implementation (via cast()) to the public contract, enabling static checking at call sites.

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

In `@polylogue/pipeline/services/acquisition.py` around lines 64 - 74, Change the
public signatures of visit_sources and acquire_sources to accept ui: DriveUILike
| None instead of ui: object | None, remove the runtime cast("DriveUILike |
None", ui) usage in visit_sources (use ui directly when calling
iter_raw_record_stream) and in acquire_sources, and then remove the now-unused
cast import; ensure iter_raw_record_stream is called with the typed ui and
update any docstring/annotations referencing ui accordingly.
polylogue/scenarios/assertions.py (1)

25-49: ⚠️ Potential issue | 🟠 Major

Preserve explicit exit_code=None during payload round-trips.

to_payload() emits {"exit_code": None} for “ignore exit code”, but from_payload() converts that explicit None back to 0, changing validation semantics.

🐛 Proposed fix
     `@classmethod`
     def from_payload(cls, payload: Mapping[str, object] | None) -> AssertionSpec:
         if payload is None:
             return cls()
+        exit_code = payload_int(payload.get("exit_code"), "exit_code") if "exit_code" in payload else 0
         return cls(
-            exit_code=payload_int(payload.get("exit_code"), "exit_code") if payload.get("exit_code") is not None else 0,
+            exit_code=exit_code,
             stdout_contains=tuple(str(item) for item in payload_items(payload.get("stdout_contains"))),
             stdout_not_contains=tuple(str(item) for item in payload_items(payload.get("stdout_not_contains"))),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/scenarios/assertions.py` around lines 25 - 49, The from_payload()
logic currently treats a payload with an explicit "exit_code": None as absent
and returns 0; change it so an explicit key with value None is preserved as None
while a missing key still defaults to 0. In from_payload(), inspect membership
of "exit_code" in the payload mapping (e.g. "exit_code" in payload) and: if the
key is present and value is None set exit_code=None; if present and not None
parse via payload_int(payload["exit_code"], "exit_code"); if not present keep
the current default 0; update the call to cls(...) accordingly so
to_payload()/from_payload() round-trip preserves explicit None.
polylogue/sources/drive_source_client.py (1)

73-90: ⚠️ Potential issue | 🟠 Major

Do not silently resolve folders to "" or the folder name when Drive omits id.

Line 76 can return "" for a folder-ID lookup, and Line 90 can return folder_ref for a name lookup when the matched payload has no usable id. That turns a malformed Drive response into a later empty/incorrect scan instead of a clear resolution failure.

🛠️ Proposed fix
     def _resolve_folder_by_id(self, folder_ref: str) -> str | None:
         meta = self._gateway.get_file(folder_ref, "id,name,mimeType")
         if self._as_mime_type(meta.get("mimeType")) == FOLDER_MIME_TYPE:
-            return self._as_file_id(meta.get("id"))
+            return self._as_file_id(meta.get("id"), default=folder_ref) or folder_ref
         return None
@@
         if not matches:
             raise DriveNotFoundError(f"Folder not found: {folder_ref}")
         first = self._as_payload_dict(matches[0])
-        return self._as_file_id(first.get("id"), default=folder_ref)
+        folder_id = self._as_file_id(first.get("id"))
+        if not folder_id:
+            raise DriveNotFoundError(f"Folder lookup did not include an id: {folder_ref}")
+        return folder_id
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/sources/drive_source_client.py` around lines 73 - 90, The current
folder resolution methods can return misleading values when Drive omits an id (
_resolve_folder_by_id may return "" and _resolve_folder_by_name may return
folder_ref ), so change both methods to validate the resolved id and fail
loudly: in _resolve_folder_by_id ensure meta.get("id") yields a non-empty file
id (after calling _as_file_id) and raise DriveNotFoundError if it is missing or
not a folder; in _resolve_folder_by_name, after obtaining first via
_as_payload_dict, require that first.get("id") produces a non-empty valid id (do
not fall back to folder_ref) and raise DriveNotFoundError if the id is absent or
invalid. Ensure you reference and use the existing helpers (_as_mime_type,
_as_file_id, _as_payload_list, _as_payload_dict) but do not return empty/default
values when id is missing.
polylogue/sources/drive.py (2)

206-244: ⚠️ Potential issue | 🟠 Major

Stale-cache risk when Drive payload changes.

The fast-path on Lines 223-224 reuses cache_path whenever it exists, but the cache file is written by this same function (Lines 242-243) with no tie to file_meta.modified_time. After the known_mtimes gate (Lines 206-211) is bypassed — e.g., on a fresh run without known_mtimes, or when a record was never yielded successfully before — the function will happily read an outdated local copy instead of re-downloading a remote payload whose modified_time has advanced. This silently causes downstream ingestion to miss Drive-side updates.

Consider validating the cache against file_meta.modified_time (e.g., compare against cache_path.stat().st_mtime or persist a sidecar mtime) before preferring the cache, or keying the cache path by mtime/etag so a change invalidates it.

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

In `@polylogue/sources/drive.py` around lines 206 - 244, The cache fast-path
currently uses cache_path whenever it exists without validating freshness, so
update the logic around cache_path.exists() in the block using
drive_cache_file_path, file_meta.modified_time, and blob_store.write_from_path
to ensure the cached file is valid: compute the cache mtime (e.g.,
cache_path.stat().st_mtime or a sidecar mtime/etag) and compare it to
file_meta.modified_time (convert types/units as needed); only call
blob_store.write_from_path(cache_path) when the times/etag match, otherwise fall
back to drive_client.download_bytes(file_meta.file_id), write the new bytes via
blob_store.write_from_bytes, and overwrite the cache (cache_path.write_bytes) so
the cache is kept in sync. Ensure any cursor_state/error handling around
drive_client.download_bytes remains intact.

194-219: 🧹 Nitpick | 🔵 Trivial

Duplicate drive_cache_file_path call.

dest_path (Line 194) and cache_path (Line 219) are computed from the same arguments and refer to the same file. Consider computing once and reusing.

♻️ Proposed simplification
-    for file_meta in drive_client.iter_json_files(folder_id):
-        dest_path = drive_cache_file_path(source.path or Path(source.name), file_meta.name)
-        source_path = str(dest_path)
+    for file_meta in drive_client.iter_json_files(folder_id):
+        cache_path = drive_cache_file_path(source.path or Path(source.name), file_meta.name)
+        source_path = str(cache_path)
@@
-        cache_path = drive_cache_file_path(source.path or Path(source.name), file_meta.name)
         blob_hash: str | None = None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/sources/drive.py` around lines 194 - 219, The code calls
drive_cache_file_path twice for the same arguments producing dest_path and
cache_path; remove the second call and reuse dest_path (and its string alias
source_path) where cache_path is used later. Replace the later reference to
cache_path with dest_path (or source_path when a string is needed), keeping the
initial dest_path = drive_cache_file_path(source.path or Path(source.name),
file_meta.name) and ensuring all subsequent logic (the local cache check and any
downstream uses) refer to that single variable; update any variable name usage
to preserve types (Path vs str) around source_path and file_meta.
polylogue/rendering/blocks.py (1)

14-24: ⚠️ Potential issue | 🟡 Minor

Stale docstring wording.

Docstring still says "Render a list of content block dicts" even though the signature now takes Sequence[RenderableBlock]. Minor, but worth updating alongside the typed-model migration.

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

In `@polylogue/rendering/blocks.py` around lines 14 - 24, Update the stale
docstring on render_blocks_markdown to reflect the typed-model change: replace
"content block dicts" with wording that references the actual type returned by
the signature (e.g., "Sequence[RenderableBlock]" or "RenderableBlock instances")
and adjust any other phrasing that implies dicts so it accurately describes the
function now accepting RenderableBlock objects; ensure the type description and
bullet list stay correct for render_blocks_markdown.
polylogue/showcase/qa_session_payload.py (1)

23-35: 🧹 Nitpick | 🔵 Trivial

Minor: two separate timestamps for nested session records.

datetime.now(...) is evaluated once for build_showcase_session_record(...) and again for the outer payload, so the embedded showcase timestamp and the outer QA-session timestamp will differ by microseconds even though they represent the same run. Same duplication exists in qa_summary.py and qa_markdown.py default-session builders. Consider computing a single timestamp at the top and reusing it for diff-stable reports.

♻️ Proposed fix
 def generate_qa_session(result: QAResult) -> PayloadDict:
     """Generate a structured full QA session record."""
     from polylogue.showcase.showcase_report_payloads import build_showcase_session_record
 
+    timestamp = datetime.now(timezone.utc).isoformat()
     showcase_session = (
         build_showcase_session_record(
             result.showcase_result,
-            timestamp=datetime.now(timezone.utc).isoformat(),
+            timestamp=timestamp,
         )
         if result.showcase_result is not None
         else None
     )
     return build_qa_session_payload(
         result,
-        timestamp=datetime.now(timezone.utc).isoformat(),
+        timestamp=timestamp,
         showcase_session=showcase_session,
     )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/showcase/qa_session_payload.py` around lines 23 - 35, Compute a
single timestamp once and reuse it for the nested records instead of calling
datetime.now(...) twice: capture timestamp =
datetime.now(timezone.utc).isoformat() before building the showcase session and
pass that same timestamp into build_showcase_session_record and
build_qa_session_payload (and apply the same change to the default-session
builders in qa_summary.py and qa_markdown.py) so both the embedded showcase
timestamp and the outer QA-session timestamp are identical and diff-stable;
update references to build_showcase_session_record and build_qa_session_payload
to use this shared timestamp variable.
polylogue/lib/raw_payload_decode.py (1)

186-241: ⚠️ Potential issue | 🟠 Major

Honor already-decoded JSONValue inputs.

Line 187 widens the contract to accept decoded JSON, but Lines 221-241 stringify non-Path/bytes/str values and re-parse them. A decoded dict/list will fail, and with prefer_jsonl=True may even hit StringIO(raw_content) with a non-string value.

🐛 Proposed fix
 def _decode_raw_payload(
     raw_content: Path | bytes | str | JSONValue,
     *,
     jsonl_dict_only: bool = False,
     prefer_jsonl: bool = False,
 ) -> tuple[JSONValue, WireFormat, int, str | None]:
@@
     For JSON files the path is read in one shot via ``orjson.loads``.
     """
+    if not isinstance(raw_content, (Path, bytes, str)):
+        return raw_content, "json", 0, None
+
     if isinstance(raw_content, Path):
         if prefer_jsonl:
             try:
polylogue/sources/drive_auth_support.py (2)

148-163: ⚠️ Potential issue | 🟡 Minor

prompter=None yields a misleading "Drive authorization cancelled" error.

When prompter is None, announce_auth_url is skipped, code stays None, and the function falls into the if not code: raise DriveAuthError("Drive authorization cancelled.") branch. The user never actually saw a prompt to cancel — the real failure is "no prompter was provided".

Either make the parameter required (drop the | None), or raise a distinct error for the None case so callers/users see an accurate message:

-def run_manual_auth_flow(
-    *,
-    flow: DriveAuthFlowLike,
-    prompter: DriveAuthPrompter | None,
-) -> object:
-    auth_url, _ = flow.authorization_url(prompt="consent", access_type="offline")
-    if prompter is not None:
-        prompter.announce_auth_url(auth_url)
-    code = prompter.request_authorization_code() if prompter is not None else None
-    if not code:
-        raise DriveAuthError("Drive authorization cancelled.") from None
+def run_manual_auth_flow(
+    *,
+    flow: DriveAuthFlowLike,
+    prompter: DriveAuthPrompter | None,
+) -> object:
+    if prompter is None:
+        raise DriveAuthError(
+            "Drive authorization requires an interactive prompter; none was provided."
+        )
+    auth_url, _ = flow.authorization_url(prompt="consent", access_type="offline")
+    prompter.announce_auth_url(auth_url)
+    code = prompter.request_authorization_code()
+    if not code:
+        raise DriveAuthError("Drive authorization cancelled.") from None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/sources/drive_auth_support.py` around lines 148 - 163, The function
run_manual_auth_flow currently treats a missing prompter as a cancelled auth
which is misleading; modify it to detect prompter is None and raise a distinct
DriveAuthError (e.g., "No prompter provided for manual auth") before trying to
call announce_auth_url or request_authorization_code, referencing the prompter
parameter and preserving the existing cancellation error path when prompter is
present and request_authorization_code returns falsy; keep all existing
try/except around flow.fetch_token and return flow.credentials as before.

51-65: 🧹 Nitpick | 🔵 Trivial

_PromptBridge._prompter is stored but never read.

The constructor captures prompter into self._prompter, but nothing in this class consumes it — input always returns None and ignores both arguments. Either wire self._prompter.request_authorization_code() (or a suitable prompter method) into input(...) so the bridge actually bridges, or drop the field.

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

In `@polylogue/sources/drive_auth_support.py` around lines 51 - 65, The
_PromptBridge currently stores DriveAuthPrompter in self._prompter but never
uses it; change input(...) in class _PromptBridge to call the prompter (e.g.
self._prompter.request_authorization_code(...) or the appropriate
DriveAuthPrompter method) and return that result instead of ignoring
prompt/default and returning None, so the bridge actually forwards credential
prompts; ensure you pass prompt/default through or handle defaults as the
prompter API expects and remove the unused field only if you choose to drop
bridging behavior instead.
polylogue/schemas/tooling_registry.py (1)

83-95: ⚠️ Potential issue | 🟠 Major

Replace fragile version sort with _version_sort_key and ensure default_version always has a fallback.

Two issues in this block:

  1. Version sort crashes on non-standard formats. int(item.version[1:]) raises ValueError for any version not matching v<digits> (e.g., "v1-beta", or migrated schemas). polylogue/schemas/runtime_registry.py already defines _version_sort_key at line 95 to handle this safely. Use it here for consistency and robustness.

  2. default_version and recommended_version can both collapse to None. When manifest is not None but manifest.default_version is None, line 84 sets recommended_version = None, which is then propagated to both fields (lines 89–90). Callers throughout the codebase rely on fallback chains (_resolved_package_version in runtime_registry.py:169, operator_inference.py:150, etc.); the catalog should ensure default_version always falls back to latest_version rather than propagating None silently.

Apply the proposed fix: import _version_sort_key, replace the inline sort logic, and ensure default_version = manifest.default_version or latest_version.

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

In `@polylogue/schemas/tooling_registry.py` around lines 83 - 95, Replace the
fragile inline sort and the nullable default logic: use the existing
_version_sort_key to sort packages (instead of int(item.version[1:])), ensure
latest_version is computed as before, then set recommended_version =
manifest.default_version or latest_version (so
default_version/recommended_version never end up None when manifest exists);
update the SchemaPackageCatalog creation (provider=provider_token,
packages=sorted(packages, key=_version_sort_key), latest_version=latest_version,
default_version=recommended_version, recommended_version=recommended_version)
and leave calls to self.replace_provider_packages(...) and
self.save_cluster_manifest(manifest) unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1d17cf15-672d-49c6-b99d-45814262d115

📥 Commits

Reviewing files that changed from the base of the PR and between c961613 and 8660e4c.

📒 Files selected for processing (138)
  • devtools/benchmark_campaign.py
  • polylogue/cli/qa_finalization.py
  • polylogue/health.py
  • polylogue/lib/payload_coercion.py
  • polylogue/lib/raw_payload_decode.py
  • polylogue/lib/viewport_tools.py
  • polylogue/pipeline/prepare_transform.py
  • polylogue/pipeline/semantic_capture.py
  • polylogue/pipeline/semantic_metadata.py
  • polylogue/pipeline/services/acquisition.py
  • polylogue/pipeline/services/acquisition_streams.py
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/pipeline/services/ingest_worker.py
  • polylogue/pipeline/services/validation_runtime.py
  • polylogue/rendering/block_models.py
  • polylogue/rendering/blocks.py
  • polylogue/rendering/core.py
  • polylogue/rendering/core_formatter.py
  • polylogue/rendering/core_markdown.py
  • polylogue/rendering/core_messages.py
  • polylogue/rendering/formatting.py
  • polylogue/rendering/renderers/__init__.py
  • polylogue/rendering/renderers/html.py
  • polylogue/rendering/renderers/html_highlighting.py
  • polylogue/rendering/renderers/html_messages.py
  • polylogue/rendering/renderers/html_template.py
  • polylogue/rendering/renderers/markdown.py
  • polylogue/scenarios/__init__.py
  • polylogue/scenarios/assertions.py
  • polylogue/scenarios/cli_surfaces.py
  • polylogue/scenarios/corpus.py
  • polylogue/scenarios/executable.py
  • polylogue/scenarios/execution.py
  • polylogue/scenarios/metadata.py
  • polylogue/scenarios/payloads.py
  • polylogue/scenarios/projections.py
  • polylogue/scenarios/specs.py
  • polylogue/schemas/extraction.py
  • polylogue/schemas/field_stats_collection.py
  • polylogue/schemas/generation_schema_builder.py
  • polylogue/schemas/generation_support.py
  • polylogue/schemas/observation_runtime.py
  • polylogue/schemas/operator_models.py
  • polylogue/schemas/privacy_config.py
  • polylogue/schemas/runtime_registry.py
  • polylogue/schemas/sampling_db.py
  • polylogue/schemas/synthetic/build_batch.py
  • polylogue/schemas/synthetic/build_records.py
  • polylogue/schemas/synthetic/build_wire_formats.py
  • polylogue/schemas/synthetic/core.py
  • polylogue/schemas/synthetic/models.py
  • polylogue/schemas/synthetic/runtime.py
  • polylogue/schemas/synthetic/selection.py
  • polylogue/schemas/synthetic/wire_formats.py
  • polylogue/schemas/tooling_registry.py
  • polylogue/schemas/unified_adapters.py
  • polylogue/schemas/validator.py
  • polylogue/schemas/verification_corpus.py
  • polylogue/showcase/catalog_loader.py
  • polylogue/showcase/cli_boundary.py
  • polylogue/showcase/context.py
  • polylogue/showcase/corpus_requests.py
  • polylogue/showcase/dimensions.py
  • polylogue/showcase/exercises.py
  • polylogue/showcase/generators.py
  • polylogue/showcase/invariants.py
  • polylogue/showcase/qa_markdown.py
  • polylogue/showcase/qa_report.py
  • polylogue/showcase/qa_runner.py
  • polylogue/showcase/qa_runner_models.py
  • polylogue/showcase/qa_runner_reporting.py
  • polylogue/showcase/qa_runner_request.py
  • polylogue/showcase/qa_runner_stages.py
  • polylogue/showcase/qa_runner_workflow.py
  • polylogue/showcase/qa_session_payload.py
  • polylogue/showcase/qa_summary.py
  • polylogue/showcase/report_common.py
  • polylogue/showcase/report_files.py
  • polylogue/showcase/report_models.py
  • polylogue/showcase/runner.py
  • polylogue/showcase/showcase_report_payloads.py
  • polylogue/showcase/showcase_report_text.py
  • polylogue/showcase/showcase_runner_models.py
  • polylogue/showcase/showcase_runner_support.py
  • polylogue/showcase/vhs.py
  • polylogue/showcase/workspace.py
  • polylogue/site/builder.py
  • polylogue/site/conversation_pages.py
  • polylogue/site/index_pages.py
  • polylogue/site/models.py
  • polylogue/site/publication_flow.py
  • polylogue/site/scan.py
  • polylogue/site/search.py
  • polylogue/site/site_builder_archive.py
  • polylogue/site/site_builder_pages.py
  • polylogue/site/template_environment.py
  • polylogue/site/templates.py
  • polylogue/site/templates_conversation.py
  • polylogue/site/templates_dashboard.py
  • polylogue/site/templates_index.py
  • polylogue/site/templates_index_body.py
  • polylogue/site/templates_index_style.py
  • polylogue/sources/assembly.py
  • polylogue/sources/assembly_claude_code.py
  • polylogue/sources/assembly_codex.py
  • polylogue/sources/decoder_json.py
  • polylogue/sources/decoders.py
  • polylogue/sources/dispatch.py
  • polylogue/sources/drive.py
  • polylogue/sources/drive_auth.py
  • polylogue/sources/drive_auth_support.py
  • polylogue/sources/drive_gateway.py
  • polylogue/sources/drive_source_client.py
  • polylogue/sources/drive_source_factory.py
  • polylogue/sources/drive_source_support.py
  • polylogue/sources/drive_types.py
  • polylogue/sources/emitter.py
  • polylogue/sources/parsers/base_models.py
  • polylogue/sources/parsers/claude_code_parser.py
  • polylogue/sources/parsers/drive_support_attachments.py
  • polylogue/sources/providers/gemini_message.py
  • polylogue/sources/source_acquisition.py
  • polylogue/sources/source_parsing.py
  • polylogue/sources/source_walk.py
  • polylogue/storage/artifact_inspection.py
  • polylogue/storage/repair.py
  • polylogue/storage/repository_archive_conversations.py
  • polylogue/storage/repository_contracts.py
  • tests/unit/cli/test_query_fmt.py
  • tests/unit/core/test_operator_models.py
  • tests/unit/core/test_raw_payload_decode.py
  • tests/unit/pipeline/test_concurrency_guards.py
  • tests/unit/pipeline/test_differential_paths.py
  • tests/unit/pipeline/test_ingest_batch.py
  • tests/unit/pipeline/test_ingestion_chaos.py
  • tests/unit/showcase/test_report.py
  • tests/unit/sources/test_drive_gateway.py
  • tests/unit/ui/test_ui_visual.py
💤 Files with no reviewable changes (2)
  • polylogue/rendering/renderers/markdown.py
  • polylogue/site/site_builder_archive.py

Comment thread polylogue/health.py
Comment on lines +188 to +192
unhealthy_status = spec.archive_health_unhealthy_status or VerifyStatus.WARNING
checks.append(
HealthCheck(
debt.name,
VerifyStatus.OK if debt.healthy else cast(VerifyStatus, spec.archive_health_unhealthy_status),
VerifyStatus.OK if debt.healthy else unhealthy_status,

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

or VerifyStatus.WARNING relies on enum truthiness.

spec.archive_health_unhealthy_status or VerifyStatus.WARNING defaults to WARNING whenever the field is falsy. This works today because every OutcomeStatus/VerifyStatus member has a non-empty string value, but it silently misroutes if anyone later introduces a status whose value is "" or 0. Prefer an explicit None-check to make the intent unambiguous:

-            unhealthy_status = spec.archive_health_unhealthy_status or VerifyStatus.WARNING
+            unhealthy_status = (
+                spec.archive_health_unhealthy_status
+                if spec.archive_health_unhealthy_status is not None
+                else VerifyStatus.WARNING
+            )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/health.py` around lines 188 - 192, The current expression uses
truthiness and can mischoose VerifyStatus.WARNING when a valid enum value is
falsy; change the fallback to an explicit None check so
spec.archive_health_unhealthy_status is used when present and otherwise fallback
to VerifyStatus.WARNING (update the assignment to unhealthy_status used in the
HealthCheck constructor where spec.archive_health_unhealthy_status and
VerifyStatus.WARNING are referenced).

Comment on lines +55 to +69
def _coerce_mapping_block(block: Mapping[str, object]) -> RenderableBlock:
block_type = str(block.get("type", "text"))
source = _mapping_with_string_keys(block.get("source")) or {}
name = block.get("name") or block.get("title")
return RenderableBlock(
type=block_type,
text=cast(str | None, block.get("thinking") or block.get("text") or block.get("code") or block.get("content")),
language=cast(str | None, block.get("language")),
url=cast(str | None, block.get("url") or source.get("url")),
name=str(name) if isinstance(name, str) else None,
mime_type=cast(str | None, block.get("media_type") or block.get("mime_type")),
tool_name=cast(str | None, block.get("name")) if block_type == "tool_use" else None,
tool_id=cast(str | None, block.get("id") or block.get("tool_use_id") or block.get("tool_id")),
tool_input=_coerce_tool_input(block.get("input")),
)

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 internal tool_name and tool_input mapping fields.

Lines 66 and 68 only read external-style name/input keys. Parsed or serialized internal blocks using tool_name and tool_input will render without tool identity/input details.

🐛 Proposed fix
 def _coerce_mapping_block(block: Mapping[str, object]) -> RenderableBlock:
     block_type = str(block.get("type", "text"))
     source = _mapping_with_string_keys(block.get("source")) or {}
     name = block.get("name") or block.get("title")
+    tool_name = block.get("tool_name") or block.get("name")
+    tool_input = block.get("tool_input") if "tool_input" in block else block.get("input")
     return RenderableBlock(
         type=block_type,
         text=cast(str | None, block.get("thinking") or block.get("text") or block.get("code") or block.get("content")),
         language=cast(str | None, block.get("language")),
         url=cast(str | None, block.get("url") or source.get("url")),
         name=str(name) if isinstance(name, str) else None,
         mime_type=cast(str | None, block.get("media_type") or block.get("mime_type")),
-        tool_name=cast(str | None, block.get("name")) if block_type == "tool_use" else None,
+        tool_name=tool_name if block_type == "tool_use" and isinstance(tool_name, str) else None,
         tool_id=cast(str | None, block.get("id") or block.get("tool_use_id") or block.get("tool_id")),
-        tool_input=_coerce_tool_input(block.get("input")),
+        tool_input=_coerce_tool_input(tool_input),
     )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/rendering/block_models.py` around lines 55 - 69,
_coerce_mapping_block drops internal-style keys for tool identity/input; update
it to prefer internal keys when present: for tool_name use
block.get("tool_name") or block.get("name") (only when block_type ==
"tool_use"), and for tool_input pass block.get("tool_input") or
block.get("input") into _coerce_tool_input; keep other behavior unchanged when
internal keys are absent. Ensure changes reference the function
_coerce_mapping_block, the RenderableBlock constructor fields tool_name and
tool_input, and the mapping keys "tool_name"/"tool_input" vs "name"/"input".

Comment on lines +55 to 67
def append_attachment_markdown(att: MarkdownAttachment, lines: list[str], archive_root: Path) -> None:
"""Append a single attachment line to a markdown output buffer."""
name = None
meta = att.get("provider_meta")
meta = att.provider_meta
if meta:
try:
meta_dict = meta if isinstance(meta, dict) else json.loads(meta)
meta_dict = meta if isinstance(meta, dict) else json.loads(meta) if isinstance(meta, str) else {}
name = meta_dict.get("name") or meta_dict.get("provider_id") or meta_dict.get("drive_id")
except (json.JSONDecodeError, TypeError):
name = None
label = name or att["attachment_id"]
path_value = att.get("path") or str(asset_path(archive_root, att["attachment_id"]))
label = name or att.attachment_id
path_value = att.path or str(asset_path(archive_root, att.attachment_id))
lines.append(f"- Attachment: {label} ({path_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 | 🟡 Minor

AttributeError can escape if provider_meta decodes to a non-dict JSON value.

json.loads(meta) is called when meta is a str, but nothing constrains the result to be an object. For inputs like "[1, 2]", "null", or "\"x\"", meta_dict becomes a list / None / str, and the immediately-following meta_dict.get("name") raises AttributeError, which is not in the except (json.JSONDecodeError, TypeError) tuple — the entire markdown render then fails on a single malformed attachment. Either broaden the except or guard the decoded type.

🛡️ Proposed fix
     if meta:
         try:
-            meta_dict = meta if isinstance(meta, dict) else json.loads(meta) if isinstance(meta, str) else {}
-            name = meta_dict.get("name") or meta_dict.get("provider_id") or meta_dict.get("drive_id")
-        except (json.JSONDecodeError, TypeError):
+            if isinstance(meta, dict):
+                meta_dict: dict[str, object] = meta
+            elif isinstance(meta, str):
+                decoded = json.loads(meta)
+                meta_dict = decoded if isinstance(decoded, dict) else {}
+            else:
+                meta_dict = {}
+            name = meta_dict.get("name") or meta_dict.get("provider_id") or meta_dict.get("drive_id")
+        except (json.JSONDecodeError, TypeError, AttributeError):
             name = None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/rendering/core_markdown.py` around lines 55 - 67, In
append_attachment_markdown, provider_meta may be a JSON string that decodes to
non-dict values causing an AttributeError when calling meta_dict.get; fix by
ensuring the decoded meta is a dict before calling .get (or treat non-dict
results as {}), e.g. after json.loads(meta) check isinstance(meta_dict, dict)
and fall back to {} (or catch AttributeError in the same except tuple) so name
resolution uses a safe meta_dict; reference symbols: append_attachment_markdown,
provider_meta, meta, meta_dict, name, attachment_id.

Comment on lines +32 to +42
def _normalize_timestamp(timestamp: object) -> str | None:
if timestamp is None:
return None
if isinstance(timestamp, datetime):
return timestamp.isoformat()
if isinstance(timestamp, int | float):
try:
return datetime.fromtimestamp(float(timestamp), tz=timezone.utc).isoformat().replace("+00:00", "Z")
except (ValueError, OSError):
return None
return str(timestamp)

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

_normalize_timestamp emits inconsistent formats for datetime vs numeric inputs.

  • int/float path forces a UTC Z-terminated ISO string.
  • datetime path returns timestamp.isoformat() as-is: a tz-aware UTC datetime yields ...+00:00 (not Z), and a naive datetime yields an offset-less string that downstream consumers may misinterpret.

Given the field is typed str | None and feeds HTML/site surfaces, normalize both branches to the same canonical UTC Z form (and decide explicitly how to handle naive datetimes — e.g., assume UTC or reject).

🛠️ Suggested normalization
     if isinstance(timestamp, datetime):
-        return timestamp.isoformat()
+        dt = timestamp if timestamp.tzinfo is not None else timestamp.replace(tzinfo=timezone.utc)
+        return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
     if isinstance(timestamp, int | float):
📝 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 _normalize_timestamp(timestamp: object) -> str | None:
if timestamp is None:
return None
if isinstance(timestamp, datetime):
return timestamp.isoformat()
if isinstance(timestamp, int | float):
try:
return datetime.fromtimestamp(float(timestamp), tz=timezone.utc).isoformat().replace("+00:00", "Z")
except (ValueError, OSError):
return None
return str(timestamp)
def _normalize_timestamp(timestamp: object) -> str | None:
if timestamp is None:
return None
if isinstance(timestamp, datetime):
dt = timestamp if timestamp.tzinfo is not None else timestamp.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
if isinstance(timestamp, int | float):
try:
return datetime.fromtimestamp(float(timestamp), tz=timezone.utc).isoformat().replace("+00:00", "Z")
except (ValueError, OSError):
return None
return str(timestamp)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/rendering/core_messages.py` around lines 32 - 42, The
_normalize_timestamp function currently returns inconsistent ISO strings:
convert all datetime and numeric inputs to a canonical UTC "Z" terminated
ISO8601 string; in _normalize_timestamp detect if timestamp is a datetime, if
tz-aware convert to UTC then format with .isoformat(timespec="auto") replacing
"+00:00" with "Z", and if naive assume UTC (attach timezone.utc) before
converting; keep the numeric (int|float) branch as-is but ensure it also
produces the same "Z" form and preserves the existing exception handling; ensure
the final fallback returns str(timestamp) only for non-datetime/non-numeric
types.

Comment on lines +178 to +185
def _serialize_message(message: Any) -> ConversationMessagePayload:
timestamp = message.timestamp
isoformat = getattr(timestamp, "isoformat", None)
return {
"id": str(message.id),
"role": str(message.role),
"text": message.text,
"timestamp": isoformat() if callable(isoformat) 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.

⚠️ Potential issue | 🟡 Minor

Avoid serializing missing roles as the literal string "None".

Other formatters treat a missing role as blank/unknown, but _serialize_message() turns None into "None" for JSON/YAML exports.

🐛 Proposed fix
     return {
         "id": str(message.id),
-        "role": str(message.role),
+        "role": str(message.role) if message.role is not None else "",
         "text": message.text,
         "timestamp": isoformat() if callable(isoformat) else None,
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/rendering/formatting.py` around lines 178 - 185, The serializer
currently converts a missing role into the literal "None" by unconditionally
calling str(message.role); update _serialize_message to only call str(...) when
message.role is not None and otherwise emit an empty string (or whatever
blank/unknown sentinel the codebase uses) so missing roles are serialized as
blank rather than "None". Specifically, replace the "role": str(message.role)
entry in _serialize_message with a conditional expression like role if role is
not None else "" where role = message.role (or str(message.role) when non-None).

Comment on lines +151 to 153
provider_meta: DriveDocMetadata = {"attachment_kind": "youtube_video", **video_dict}
if url is not None:
provider_meta["url"] = url

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

attachment_kind sentinel can be overwritten by provider payload.

Because **video_dict is spread after the "attachment_kind": "youtube_video" literal, a YouTube payload that happens to carry an attachment_kind (or, below, a url) key will clobber the sentinel this code is trying to stamp. Downstream consumers that branch on provider_meta["attachment_kind"] would then misclassify the attachment. Put the sentinel last (and the computed url as well) so local values win over arbitrary provider fields.

Proposed fix
-    provider_meta: DriveDocMetadata = {"attachment_kind": "youtube_video", **video_dict}
-    if url is not None:
-        provider_meta["url"] = url
+    provider_meta: DriveDocMetadata = {**video_dict, "attachment_kind": "youtube_video"}
+    if url is not None:
+        provider_meta["url"] = url
📝 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
provider_meta: DriveDocMetadata = {"attachment_kind": "youtube_video", **video_dict}
if url is not None:
provider_meta["url"] = url
provider_meta: DriveDocMetadata = {**video_dict, "attachment_kind": "youtube_video"}
if url is not None:
provider_meta["url"] = url
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/sources/parsers/drive_support_attachments.py` around lines 151 -
153, The provider_meta merge currently spreads video_dict after the sentinel,
allowing provider payload keys to overwrite the intended sentinel and computed
url; update the creation of provider_meta in drive_support_attachments.py so
that you merge video_dict first and then set "attachment_kind": "youtube_video"
and (if present) provider_meta["url"] = url afterward (i.e., ensure the literal
sentinel and the computed url are assigned last) so local values in
provider_meta override any keys from video_dict.

Comment on lines +30 to +33
def _normalize_mapping(payload: BaseModel | GeminiDictValue) -> GeminiDictValue:
if isinstance(payload, BaseModel):
return payload.model_dump()
return payload

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

_normalize_mapping returns the caller's dict by reference.

For BaseModel inputs model_dump() returns a fresh dict, but for GeminiDictValue inputs the helper returns the same reference it received. Downstream this value is stored as ContentBlock.raw= (e.g., line 179, 186) — if any consumer mutates that raw dict, they're mutating the part's underlying payload. Consider dict(payload) on the mapping branch to keep raw logically immutable from the producer's perspective:

 def _normalize_mapping(payload: BaseModel | GeminiDictValue) -> GeminiDictValue:
     if isinstance(payload, BaseModel):
         return payload.model_dump()
-    return payload
+    return dict(payload)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/sources/providers/gemini_message.py` around lines 30 - 33,
Normalize _normalize_mapping to avoid returning the caller's dict by reference:
when payload is a BaseModel keep using model_dump(), but when payload is a
GeminiDictValue return a shallow copy (e.g., dict(payload)) so consumers writing
to ContentBlock.raw (referenced elsewhere) won't mutate the producer's original
mapping; update the _normalize_mapping function to always return a new dict for
mapping inputs.

Comment on lines +60 to +61
def _string_or_empty_dict(value: object) -> GeminiDictValue:
return value if isinstance(value, dict) else {}

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

_string_or_empty_dict is misnamed — it actually returns "dict or empty dict".

The helper tests isinstance(value, dict), so the "string" arm never fires; a str input falls into the {} fallback despite the name suggesting it would be preserved. Since its only caller (youtubeVideo) is already typed GeminiDictValue | None and checked truthy before the call, the {} branch is effectively unreachable in practice. Either rename (e.g., _dict_or_empty) or drop the helper and inline the cast.

-def _string_or_empty_dict(value: object) -> GeminiDictValue:
-    return value if isinstance(value, dict) else {}
+def _dict_or_empty(value: object) -> GeminiDictValue:
+    return value if isinstance(value, dict) else {}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/sources/providers/gemini_message.py` around lines 60 - 61, The
helper _string_or_empty_dict is misnamed and misleading because it checks
isinstance(value, dict) and returns a dict or {}, so rename it to _dict_or_empty
(or remove it and inline the cast) and update its usage in youtubeVideo to
either cast the already-validated GeminiDictValue | None to dict directly or
call the renamed helper; ensure the function signature and any docstring/typing
reflect that it returns a dict (GeminiDictValue) or empty dict so callers and
tests match actual behavior.

Comment on lines +85 to +89
async with self._backend.read_pool(size=2):
msgs_by_id, atts_by_id = await asyncio.gather(
self.queries.get_messages_batch(present_ids),
self.queries.get_attachments_batch(present_ids),
)

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
python - <<'PY'
import asyncio

async def fail_fast():
    await asyncio.sleep(0.01)
    raise RuntimeError("first failure")

async def slow_sibling():
    try:
        await asyncio.sleep(0.2)
    finally:
        print("sibling finalized after gather propagated")

async def main():
    try:
        await asyncio.gather(fail_fast(), slow_sibling())
    except RuntimeError:
        print("gather propagated first exception")
        await asyncio.sleep(0.3)

asyncio.run(main())
PY

Repository: Sinity/polylogue

Length of output: 135


🏁 Script executed:

cat -n polylogue/storage/repository_archive_conversations.py | sed -n '75,100p'

Repository: Sinity/polylogue

Length of output: 1397


🏁 Script executed:

# Check for Python version requirements
fd -e "pyproject.toml" -o -e "setup.py" -o -e "setup.cfg" | head -5 | xargs cat

Repository: Sinity/polylogue

Length of output: 176


🏁 Script executed:

# Find the read_pool implementation to understand what __aexit__ does
rg -n "def read_pool|class.*read_pool" --type py -A 10

Repository: Sinity/polylogue

Length of output: 1599


🏁 Script executed:

# Check imports and overall structure
head -30 polylogue/storage/repository_archive_conversations.py

Repository: Sinity/polylogue

Length of output: 1074


🏁 Script executed:

# Find _read_pool implementation
rg -n "_read_pool" --type py -A 20 polylogue/storage/backends/async_sqlite.py

Repository: Sinity/polylogue

Length of output: 5940


🏁 Script executed:

# Check for Python version requirements
find . -name "pyproject.toml" -o -name "setup.py" -o -name "setup.cfg" | xargs grep -l "python" 2>/dev/null | head -3

Repository: Sinity/polylogue

Length of output: 76


🏁 Script executed:

# Try to read pyproject.toml if it exists
cat pyproject.toml 2>/dev/null || cat setup.py 2>/dev/null || echo "No config found"

Repository: Sinity/polylogue

Length of output: 7249


🏁 Script executed:

# Check the queries implementation to see what could fail
rg -n "get_messages_batch|get_attachments_batch" --type py -B 2 -A 10 | head -50

Repository: Sinity/polylogue

Length of output: 4285


🏁 Script executed:

# Check if there are any test failures or issues related to this
find tests -name "*.py" -type f | xargs grep -l "read_pool\|get_messages_batch\|get_attachments_batch" 2>/dev/null

Repository: Sinity/polylogue

Length of output: 213


🏁 Script executed:

# Check how these batch queries are implemented to understand their behavior
rg -n "async def get_messages_batch|async def get_attachments_batch" --type py -A 15

Repository: Sinity/polylogue

Length of output: 10079


🏁 Script executed:

# Look for any existing issues or TODOs related to this
rg -n "gather|TaskGroup|read_pool" --type py polylogue/storage/repository_archive_conversations.py

Repository: Sinity/polylogue

Length of output: 296


🏁 Script executed:

# Check lines 42 and 53 to see the other gather calls
cat -n polylogue/storage/repository_archive_conversations.py | sed -n '35,60p'

Repository: Sinity/polylogue

Length of output: 1333


Keep sibling read tasks inside the pool lifetime on failure.

asyncio.gather() propagates the first exception before sibling coroutines complete, allowing read_pool.__aexit__() to run while a batch query is still acquiring or using a pool connection. Use asyncio.TaskGroup (Python 3.11+) or create tasks with explicit cleanup to ensure both operations finish before the pool closes.

Example fix using TaskGroup
         async with self._backend.read_pool(size=2):
-            msgs_by_id, atts_by_id = await asyncio.gather(
-                self.queries.get_messages_batch(present_ids),
-                self.queries.get_attachments_batch(present_ids),
-            )
+            async with asyncio.TaskGroup() as tg:
+                messages_task = tg.create_task(self.queries.get_messages_batch(present_ids))
+                attachments_task = tg.create_task(self.queries.get_attachments_batch(present_ids))
+            msgs_by_id = messages_task.result()
+            atts_by_id = attachments_task.result()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/repository_archive_conversations.py` around lines 85 - 89,
Replace the asyncio.gather call inside the self._backend.read_pool context so
sibling read tasks can't be cancelled by an early exception; instead run both
queries under an asyncio.TaskGroup (Python 3.11+) or explicit tasks and await
their completion before the pool context exits. Concretely, in the method where
you call self._backend.read_pool and currently call
asyncio.gather(self.queries.get_messages_batch(present_ids),
self.queries.get_attachments_batch(present_ids)), create an asyncio.TaskGroup
and schedule both self.queries.get_messages_batch(present_ids) and
self.queries.get_attachments_batch(present_ids) as tasks within that group, then
retrieve/await both task results after the TaskGroup completes so that
read_pool.__aexit__() only runs once both batch queries have finished
(alternatively, create explicit asyncio.create_task tasks and ensure you await
both in a finally/cleanup block).

Comment on lines +363 to 369
write_failures = [result for result in write_results if isinstance(result, Exception)]
assert write_failures == [], f"Got write exceptions during concurrent read/write: {write_failures}"

unexpected = [
r
for r in results
for r in read_results
if isinstance(r, Exception) and not (isinstance(r, OperationalError) and "locked" in str(r))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
python - <<'PY'
import asyncio
print("CancelledError is Exception:", issubclass(asyncio.CancelledError, Exception))
print("CancelledError is BaseException:", issubclass(asyncio.CancelledError, BaseException))
PY

Repository: Sinity/polylogue

Length of output: 132


🏁 Script executed:

cat -n tests/unit/pipeline/test_concurrency_guards.py | sed -n '360,375p'

Repository: Sinity/polylogue

Length of output: 896


🏁 Script executed:

# Check if there are other similar isinstance(result, Exception) patterns in this file
rg "isinstance.*Exception" tests/unit/pipeline/test_concurrency_guards.py -n

Repository: Sinity/polylogue

Length of output: 267


🏁 Script executed:

# Verify the behavior difference between Exception and BaseException with asyncio context
python - <<'PY'
import asyncio
import sys

print(f"Python version: {sys.version}")
print()
print("Exception hierarchy:")
print(f"  Exception.__bases__ = {Exception.__bases__}")
print(f"  asyncio.CancelledError.__bases__ = {asyncio.CancelledError.__bases__}")
print()
print("Subclass checks:")
print(f"  issubclass(asyncio.CancelledError, Exception): {issubclass(asyncio.CancelledError, Exception)}")
print(f"  issubclass(asyncio.CancelledError, BaseException): {issubclass(asyncio.CancelledError, BaseException)}")
print()
print("Practical impact with isinstance() checks:")
try:
    async def test():
        await asyncio.sleep(0)
    
    async def main():
        task = asyncio.create_task(test())
        task.cancel()
        try:
            await task
        except asyncio.CancelledError as e:
            print(f"  Caught CancelledError: {type(e)}")
            print(f"  isinstance(e, Exception): {isinstance(e, Exception)}")
            print(f"  isinstance(e, BaseException): {isinstance(e, BaseException)}")
            return e
    
    result = asyncio.run(main())
    print(f"  Return type: {type(result)}")
except Exception as e:
    print(f"  Error: {e}")
PY

Repository: Sinity/polylogue

Length of output: 636


Use BaseException instead of Exception to catch cancelled tasks.

With return_exceptions=True, cancelled tasks are returned as asyncio.CancelledError, which does not inherit from Exception in Python 3.10+. This means cancelled read/write tasks would pass through the guards undetected instead of failing the test. Change both isinstance(result, Exception) checks to isinstance(result, BaseException) on lines 363 and 369.

🧪 Proposed test hardening
-        write_failures = [result for result in write_results if isinstance(result, Exception)]
+        write_failures = [result for result in write_results if isinstance(result, BaseException)]
         assert write_failures == [], f"Got write exceptions during concurrent read/write: {write_failures}"
 
         unexpected = [
             r
             for r in read_results
-            if isinstance(r, Exception) and not (isinstance(r, OperationalError) and "locked" in str(r))
+            if isinstance(r, BaseException) and not (isinstance(r, OperationalError) and "locked" in str(r))
         ]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/pipeline/test_concurrency_guards.py` around lines 363 - 369, The
list comprehensions that detect task failures use isinstance(..., Exception)
which misses asyncio.CancelledError; update both checks to use isinstance(...,
BaseException) so cancelled tasks returned with return_exceptions=True are
detected — specifically change the predicates in the write_results comprehension
(variable write_failures) and the read_results filter (variable unexpected) to
use BaseException instead of Exception.

@Sinity
Sinity merged commit babc243 into master Apr 19, 2026
13 of 14 checks passed
@Sinity
Sinity deleted the feature/refactor/source-renewal-sweep branch April 19, 2026 21:59

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

Review continued from previous batch...

Comment thread polylogue/health.py
Comment on lines +29 to +30
JSONScalar: TypeAlias = str | int | float | bool | None
JSONValue: TypeAlias = JSONScalar | list["JSONValue"] | Mapping[str, "JSONValue"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm whether JSONScalar/JSONValue are referenced outside their definition site.
rg -nP '\bJSON(Scalar|Value)\b' --type=py

Repository: Sinity/polylogue

Length of output: 5772


🏁 Script executed:

cat -n polylogue/health.py | head -50

Repository: Sinity/polylogue

Length of output: 1987


🏁 Script executed:

rg -n '__all__' polylogue/health.py && echo "---" && rg -n 'JSONValue|JSONScalar' polylogue/health.py

Repository: Sinity/polylogue

Length of output: 223


🏁 Script executed:

sed -n '577,600p' polylogue/health.py

Repository: Sinity/polylogue

Length of output: 256


Remove unused type aliases JSONScalar and JSONValue.

These are defined at lines 29–30 but never used within health.py and not exported in __all__, so they serve no purpose in this module. The canonical definitions exist in polylogue.lib.raw_payload_decode which is the proper import source across the codebase. Remove them to keep the module clean.

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

In `@polylogue/health.py` around lines 29 - 30, Remove the unused type aliases
JSONScalar and JSONValue from this module: delete the declarations of JSONScalar
and JSONValue so they are no longer defined in health.py; verify nothing else in
health.py references these names and do not add them to __all__; rely on
importing the canonical definitions from polylogue.lib.raw_payload_decode where
needed instead.

Comment on lines 162 to +170
elif tool_name == "Edit":
path = input_data.get("file_path") or input_data.get("path")
old_string = input_data.get("old_string")
new_string = input_data.get("new_string")
if path:
changes.append(
{
"path": path,
"operation": "edit",
"old_content": old_string[:200] if isinstance(old_string, str) else None,
"new_content": new_string[:200] if isinstance(new_string, str) else None,
}
)
entry = {"path": path, "operation": "edit"}
old_string = optional_string(input_data.get("old_string"))
new_string = optional_string(input_data.get("new_string"))
if old_string is not None:
entry["old_content"] = old_string[:200]
if new_string is not None:
entry["new_content"] = new_string[:200]
changes.append(entry)

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

Annotate entry as FileChangeSummary for the Edit branch (consistency with Write).

The Write branch at line 158 explicitly types entry: FileChangeSummary = {...} so that the NotRequired[str] fields (old_content, new_content) are understood. The Edit branch reassigns entry without the annotation, making it a plain dict[str, str] from the type checker's perspective; subsequent entry["old_content"] = … / entry["new_content"] = … assignments are only permissible under the TypedDict type. Runtime-safe, but inconsistent and likely to trip strict typing.

♻️ Proposed tweak
         elif tool_name == "Edit":
-            entry = {"path": path, "operation": "edit"}
+            entry: FileChangeSummary = {"path": path, "operation": "edit"}
             old_string = optional_string(input_data.get("old_string"))
             new_string = optional_string(input_data.get("new_string"))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/pipeline/semantic_capture.py` around lines 162 - 170, The Edit
branch creates entry as a plain dict which breaks consistency with the Write
branch's typed annotation; update the Edit branch to declare entry:
FileChangeSummary = {"path": path, "operation": "edit"} (matching the Write
branch) so subsequent assignments to entry["old_content"] and
entry["new_content"] are accepted by the type checker; ensure you import or
reference FileChangeSummary the same way used by the Write branch.

Comment on lines +74 to +77
display_text = render_blocks_plaintext(content_blocks) if content_blocks else text
if not display_text:
display_text = text
html_content = render_blocks_html(content_blocks) if has_structured_blocks(content_blocks) else render_html(text)

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

Plaintext and HTML renderers use different conditions for structured blocks — the two surfaces can disagree.

  • display_text falls back to render_blocks_plaintext(content_blocks) whenever content_blocks is non-empty.
  • html_content only uses render_blocks_html(content_blocks) when has_structured_blocks(content_blocks) is true; otherwise it renders text via render_html.

If content_blocks is non-empty but not considered "structured" (e.g., only unstructured text blocks), plaintext comes from the blocks while HTML comes from the raw text parameter, which may be a different representation. Rendered HTML and plaintext views of the same message can show different content.

Align both renderers on a single condition — e.g., route both through blocks when content_blocks is present (with fallback to text/render_html(text) otherwise).

🐛 Suggested alignment
-    display_text = render_blocks_plaintext(content_blocks) if content_blocks else text
-    if not display_text:
-        display_text = text
-    html_content = render_blocks_html(content_blocks) if has_structured_blocks(content_blocks) else render_html(text)
+    use_blocks = has_structured_blocks(content_blocks)
+    display_text = render_blocks_plaintext(content_blocks) if use_blocks else text
+    if not display_text:
+        display_text = text
+    html_content = render_blocks_html(content_blocks) if use_blocks else render_html(text)
📝 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
display_text = render_blocks_plaintext(content_blocks) if content_blocks else text
if not display_text:
display_text = text
html_content = render_blocks_html(content_blocks) if has_structured_blocks(content_blocks) else render_html(text)
use_blocks = has_structured_blocks(content_blocks)
display_text = render_blocks_plaintext(content_blocks) if use_blocks else text
if not display_text:
display_text = text
html_content = render_blocks_html(content_blocks) if use_blocks else render_html(text)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/rendering/core_messages.py` around lines 74 - 77, The plaintext and
HTML rendering diverge because display_text uses render_blocks_plaintext when
content_blocks is non-empty while html_content only uses render_blocks_html when
has_structured_blocks(content_blocks) is true; change the logic to use the same
condition for both surfaces — when content_blocks is present route both
display_text (via render_blocks_plaintext) and html_content (via
render_blocks_html) through the blocks, and otherwise fall back to text and
render_html(text); update the expressions that set display_text and html_content
(referencing display_text, html_content, render_blocks_plaintext,
render_blocks_html, has_structured_blocks, render_html, content_blocks, and
text) so they use a single consistency condition.

Comment on lines +60 to +72
@classmethod
def from_results(cls, results: list[InvariantResult]) -> InvariantSummary:
passed = 0
failed = 0
skipped = 0
for result in results:
if result.status.value == "ok":
passed += 1
elif result.status.value == "error":
failed += 1
else:
skipped += 1
return cls(passed=passed, failed=failed, skipped=skipped)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect OutcomeStatus enum members to confirm "ok"/"error" are the only meaningful buckets.
rg -nP -C3 '\bclass\s+OutcomeStatus\b'
fd -t f 'outcomes.py' | head

Repository: Sinity/polylogue

Length of output: 429


🏁 Script executed:

cat polylogue/lib/outcomes.py

Repository: Sinity/polylogue

Length of output: 3186


🏁 Script executed:

cat polylogue/showcase/report_models.py | head -100

Repository: Sinity/polylogue

Length of output: 2736


🏁 Script executed:

fd -t f 'invariants.py' polylogue/showcase

Repository: Sinity/polylogue

Length of output: 92


🏁 Script executed:

cat polylogue/showcase/invariants.py

Repository: Sinity/polylogue

Length of output: 6859


Use enum comparison instead of string literals in from_results().

The method compares result.status.value against hardcoded strings "ok" and "error", then bins all other values into "skipped". This is fragile: if OutcomeStatus.WARNING is returned by future invariant checks, it would silently miscount as skipped. Additionally, the module already uses the better pattern elsewhere (see format_invariant_summary() at line 168, which compares directly to OutcomeStatus enum members).

Rewrite the comparison to use enum members directly:

if result.status is OutcomeStatus.OK:
    passed += 1
elif result.status is OutcomeStatus.ERROR:
    failed += 1
elif result.status is OutcomeStatus.SKIP:
    skipped += 1

This makes the intent explicit and is resilient to enum evolution.

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

In `@polylogue/showcase/report_models.py` around lines 60 - 72, The from_results
classmethod in InvariantSummary currently compares result.status.value to string
literals; change it to compare the enum members directly (use OutcomeStatus.OK,
OutcomeStatus.ERROR, OutcomeStatus.SKIP) when inspecting each
InvariantResult.status so counts are explicit and robust; update the
conditionals in from_results to check result.status is OutcomeStatus.OK /
OutcomeStatus.ERROR / OutcomeStatus.SKIP (mirroring the pattern used in
format_invariant_summary) and leave other statuses uncounted or handled
explicitly as needed.

Comment on lines +148 to +157
try:
for item in ijson_module.items(handle, prefix):
found_any = True
records.append(item)
return (found_any, records)
except ijson_module.common.JSONError:
return (found_any, records)
except Exception as exc:
logger_obj.debug("Strategy %s failed for %s: %s", strategy_name, path_name, exc)
return (found_any, records)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

except Exception at debug level can silently swallow real bugs in the strategy.

_stream_prefixed_items only needs to tolerate ijson_module.common.JSONError (malformed JSON under this strategy). Catching bare Exception also hides programmer errors (e.g., TypeError/AttributeError from unexpected handle types), logs them at debug, and returns whatever partial records had accumulated. The caller then treats that as a successful strategy and returns without falling back, so a latent bug here manifests as a silent, empty stream.

Narrow the catch or re-raise non-JSON errors:

     try:
         for item in ijson_module.items(handle, prefix):
             found_any = True
             records.append(item)
         return (found_any, records)
     except ijson_module.common.JSONError:
         return (found_any, records)
-    except Exception as exc:
-        logger_obj.debug("Strategy %s failed for %s: %s", strategy_name, path_name, exc)
-        return (found_any, records)
+    except (OSError, UnicodeError) as exc:
+        logger_obj.warning("Strategy %s failed for %s: %s", strategy_name, path_name, exc)
+        return (found_any, records)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/sources/decoder_json.py` around lines 148 - 157, The except block
in _stream_prefixed_items is too broad: only ijson_module.common.JSONError
should be swallowed; any other Exception (e.g., TypeError/AttributeError) must
be re-raised so programmer errors aren't hidden. Change the catch to only handle
ijson_module.common.JSONError and remove the generic except Exception; if you
need logging for unexpected exceptions include a logger_obj.exception or
re-raise after logging using the same strategy_name and path_name context so
non-JSON errors propagate instead of returning partial records.

Comment on lines +217 to +234
if record := _payload_mapping(shaped_payload):
if conversations := _payload_conversations(record):
results: list[ParsedConversation] = []
for index, item in enumerate(conversations):
if item_record := _payload_mapping(item):
results.extend(
parse_payload(
runtime_provider,
item_record,
f"{fallback_id}-{index}",
_depth + 1,
schema_resolution=schema_resolution,
)
)
)
return results
return results
else:
record = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Walrus truthy check silently discards empty-mapping payloads.

if record := _payload_mapping(shaped_payload): uses truthiness rather than is not None, so an empty mapping ({}) falls into the else branch and forces record = None. Downstream branches (CHATGPT line 240, CLAUDE_AI line 245, and the generic fallback at 269) therefore return [] instead of invoking the provider parser with the empty record — a subtle behavior change relative to a plain isinstance(payload, dict) guard. The same pattern exists in detect_provider (line 122), _parse_grouped_records (line 112), and parse_drive_payload (line 320), but the effect is most visible here because the provider branches rely on record is not None afterward.

If the intent is truly "any mapping, including empty", prefer an explicit is not None check.

♻️ Suggested shape
-    if record := _payload_mapping(shaped_payload):
+    record = _payload_mapping(shaped_payload)
+    if record is not None:
         if conversations := _payload_conversations(record):
             results: list[ParsedConversation] = []
             for index, item in enumerate(conversations):
                 if item_record := _payload_mapping(item):
                     results.extend(
                         parse_payload(
                             runtime_provider,
                             item_record,
                             f"{fallback_id}-{index}",
                             _depth + 1,
                             schema_resolution=schema_resolution,
                         )
                     )
             return results
-    else:
-        record = None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/sources/dispatch.py` around lines 217 - 234, The walrus checks like
"if record := _payload_mapping(shaped_payload):" use truthiness and drop empty
mappings; change them to an explicit None check (e.g., "record :=
_payload_mapping(...); if record is not None:") so empty dicts are preserved and
downstream provider parsing (the CHATGPT/CLAUDE_AI branches and generic fallback
that expect record is not None) still run; apply the same fix to other
occurrences of this pattern such as in detect_provider, _parse_grouped_records,
and parse_drive_payload to ensure any returned mapping (including {}) is treated
as present.

Comment on lines 205 to 217
if self.codeExecutionResult:
outcome = self.codeExecutionResult.get("outcome", "")
output = self.codeExecutionResult.get("output", "")
result_raw = self.codeExecutionResult
outcome = result_raw.get("outcome", "")
output = result_raw.get("output", "")
output_text = _to_text(output)
if output or outcome:
blocks.append(
ContentBlock(
type=ContentType.TOOL_RESULT,
text=str(output) if output else f"[{outcome}]",
raw=self.codeExecutionResult,
text=output_text if output_text else f"[{outcome}]",
raw=result_raw,
)
)

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

codeExecutionResult output rendering uses str(dict) when output is a mapping.

If output is a non-string payload (e.g., a dict returned by a tool), _to_text(output) reduces to str(output), producing Python-style repr such as {'stdout': 'foo'} — which is what users see as the tool-result block text. Similarly the f"[{outcome}]" fallback will stringify a non-string outcome. Prefer a structured fallback (e.g., json.dumps(output, ensure_ascii=False, default=str) for non-string payloads) so the rendered text is consumable:

-            output_text = _to_text(output)
+            if isinstance(output, str) or output is None:
+                output_text = _to_text(output)
+            else:
+                import json
+                try:
+                    output_text = json.dumps(output, ensure_ascii=False, default=str)
+                except (TypeError, ValueError):
+                    output_text = str(output)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/sources/providers/gemini_message.py` around lines 205 - 217, The
code currently renders tool results by calling _to_text(output) which falls back
to Python's str() for mappings, producing unhelpful reprs; update the block in
the branch handling self.codeExecutionResult (inspect result_raw, outcome,
output, output_text) to detect non-string structured payloads (e.g., dict/list)
and serialize them with json.dumps(output, ensure_ascii=False, default=str) for
output_text, and likewise use a JSON-safe fallback for outcome when not a
string, before creating the ContentBlock (references: codeExecutionResult,
result_raw, outcome, output, _to_text, ContentBlock, ContentType.TOOL_RESULT);
keep using the original text when output is already a string.

Comment on lines +26 to +27
JSONScalar: TypeAlias = str | int | float | bool | None
JSONValue: TypeAlias = JSONScalar | list["JSONValue"] | dict[str, "JSONValue"]

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

Use the new JSON alias for serializer return types.

dict[str, object] allows non-JSON values through the type contract, while the new JSONValue alias can enforce the intended serialization boundary.

♻️ Proposed type tightening
-    def to_dict(self) -> dict[str, object]:
+    def to_dict(self) -> dict[str, JSONValue]:
         return {
             "name": self.name,
             "category": self.category.value,
             "destructive": self.destructive,
             "repaired_count": self.repaired_count,
@@
-    def to_dict(self) -> dict[str, object]:
+    def to_dict(self) -> dict[str, JSONValue]:
         return {
             "name": self.name,
             "category": self.category.value,
             "destructive": self.destructive,
             "issue_count": self.issue_count,

Also applies to: 46-54, 238-247

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

In `@polylogue/storage/repair.py` around lines 26 - 27, The code defines
JSONScalar and JSONValue but still uses loose dict[str, object] return types for
serializers; update those serializer type annotations to use JSONValue (or
dict[str, JSONValue] where appropriate) so the type system enforces only
JSON-serializable values; find places using dict[str, object] (serializer
functions/methods) and replace with JSONValue or dict[str, JSONValue], keeping
JSONScalar/JSONValue aliases as the canonical JSON types.

Comment on lines +436 to 439
def repair_orphaned_messages(config: Config, dry_run: bool = False) -> RepairResult:
from polylogue.storage.backends.connection import connection_context

with connection_context(None) as conn:

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

echo "Locate relevant helper files:"
fd '^(config|paths|connection)\.py$' polylogue | sort

echo
echo "Inspect Config, db_path, and connection_context definitions:"
rg -n -C5 'class Config\b|def db_path\b|def connection_context\b' $(fd '^(config|paths|connection)\.py$' polylogue)

echo
echo "Confirm repair handlers currently ignore config when opening storage:"
rg -n -C3 '\bconnection_context\(None\)|\bdb_path\(\)|def repair_|def run_selected_maintenance|def run_safe_repairs|def run_archive_cleanup' polylogue/storage/repair.py

Repository: Sinity/polylogue

Length of output: 6873


Wire Config into the repair handlers or keep it out of the contract.

These handlers accept Config but completely ignore it—all call connection_context(None) and repair_wal_checkpoint calls db_path() directly without config context. Callers supplying a non-default config for campaign/benchmark/isolated runs will still target the default database.

If the storage layer cannot support config-aware routing, the config parameter should be removed from the handlers' public signatures. Alternatively, pass config.db_path (or equivalent) through to connection_context to enable proper database targeting.

Also applies to: 488–492, 510–517, 543–549, 597–610, 724–736, 788–793, 855–861

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

In `@polylogue/storage/repair.py` around lines 436 - 439, The handlers (e.g.,
repair_orphaned_messages and other repair_* functions) accept a Config but
ignore it—calling connection_context(None) and letting repair_wal_checkpoint
call db_path() directly—so they always hit the default DB; either remove the
unused config parameter from these public signatures, or wire the config through
by passing the intended path (e.g., config.db_path or config.get_db_path()) into
connection_context and into calls to repair_wal_checkpoint so the functions
actually operate on the provided Config; update all affected handlers (lines
referenced around repair_orphaned_messages, repair_wal_checkpoint and the
similarly patterned functions at the other ranges) to consistently use the
config-derived DB path instead of None, or remove config from their signatures
if config-aware routing is unsupported.

Sinity added a commit that referenced this pull request Apr 22, 2026
Closes #223
Ref #222

## Summary

Renew a large source-to-surface tranche by rebuilding provider dispatch, synthetic/runtime schema contracts, source acquisition and emission seams, and the scenario/showcase/site layers that sit on top of them.

## Problem

The codebase was fully type-checked but still carried older path-dependent boundary code: broad payload dictionaries, repeated coercion glue, weakly modeled runtime seams, and surface code compensating for ambiguity below. The existing branch had completed that renewal work locally, but it still needed to land as a real reviewed slice before the next tranche could continue.

## Solution

- rebuilt provider dispatch and viewport/unified-adapter seams in `polylogue/sources/dispatch.py` and `polylogue/schemas/unified_adapters.py`
- tightened Drive/source boundaries across auth, gateway, client, support, decoder, attachment, and emission paths under `polylogue/sources/`
- renewed synthetic corpus/runtime and schema support contracts across `polylogue/schemas/synthetic/*`, registry/validator/extraction, and verification helpers
- hardened ingest/provider metadata seams in `polylogue/pipeline/services/*`, `polylogue/pipeline/semantic_*`, and adjacent helpers
- rebuilt scenario/showcase/report/site surfaces so they consume stronger substrate contracts instead of preserving old glue
- added new support modules such as `polylogue/rendering/block_models.py`, `polylogue/scenarios/payloads.py`, and `polylogue/showcase/report_models.py` where shared contracts needed explicit homes

## Verification

- `devtools verify`
- `pytest -q tests/unit/sources/test_drive_gateway.py tests/unit/sources/test_source_laws.py -k 'drive_gateway or detect_provider or parse_payload or parse_drive_payload'`
- `pytest -q tests/unit/sources/test_unified_semantic_laws.py -k 'extract_harmonized_message or fallback_contract'`
- `pytest -q tests/unit/test_cross_surface_agreement.py::TestSyntheticRoundtripFactAgreement`
- `pytest -q tests/unit/core/test_synthetic_semantics.py tests/unit/sources/test_drive_source_client.py tests/unit/sources/test_drive_gateway.py`
- `pytest -q tests/unit/core/test_synthetic_semantics.py tests/unit/sources/test_source_laws.py -k 'conversation_emitter or synthetic or iter_source_conversations_with_raw_preserves_grouped_bytes_contract or iter_source_conversations_with_raw_streams_plain_grouped_capture_to_blob_store or iter_source_conversations_with_raw_streams_grouped_zip_capture_to_blob_store or iter_entry_payloads_locks_provider_after_first_detected_payload'`
Sinity added a commit that referenced this pull request Apr 22, 2026
Renews a source-to-surface tranche of boundary code that was fully
type-checked but still carried path-dependent glue: broad payload
dictionaries, repeated coercion glue, weakly modeled runtime seams,
and surface code compensating for ambiguity below. The branch had
completed the renewal work locally but still needed to land as a
reviewed slice before the next tranche could continue.

Rebuilds provider dispatch and viewport/unified-adapter seams in
`polylogue/sources/dispatch.py` and
`polylogue/schemas/unified_adapters.py`. Tightens Drive/source
boundaries across auth, gateway, client, support, decoder,
attachment, and emission paths under `polylogue/sources/`. Renews
synthetic corpus/runtime and schema support contracts across
`polylogue/schemas/synthetic/*`, registry/validator/extraction, and
verification helpers. Hardens ingest/provider metadata seams in
`polylogue/pipeline/services/*` and `pipeline/semantic_*`. Rebuilds
scenario/showcase/report/site surfaces to consume stronger substrate
contracts instead of preserving old glue. Adds new support modules
(`rendering/block_models.py`, `scenarios/payloads.py`,
`showcase/report_models.py`) where shared contracts needed explicit
homes.

Verification: devtools verify green plus focused pytest over
source/dispatch/drive/synthetic/unified-semantic suites.

Closes #223
Ref #222
Sinity added a commit that referenced this pull request Apr 22, 2026
Renews a source-to-surface tranche of boundary code that was fully
type-checked but still carried path-dependent glue: broad payload
dictionaries, repeated coercion glue, weakly modeled runtime seams,
and surface code compensating for ambiguity below. The branch had
completed the renewal work locally but still needed to land as a
reviewed slice before the next tranche could continue.

Rebuilds provider dispatch and viewport/unified-adapter seams in
`polylogue/sources/dispatch.py` and
`polylogue/schemas/unified_adapters.py`. Tightens Drive/source
boundaries across auth, gateway, client, support, decoder,
attachment, and emission paths under `polylogue/sources/`. Renews
synthetic corpus/runtime and schema support contracts across
`polylogue/schemas/synthetic/*`, registry/validator/extraction, and
verification helpers. Hardens ingest/provider metadata seams in
`polylogue/pipeline/services/*` and `pipeline/semantic_*`. Rebuilds
scenario/showcase/report/site surfaces to consume stronger substrate
contracts instead of preserving old glue. Adds new support modules
(`rendering/block_models.py`, `scenarios/payloads.py`,
`showcase/report_models.py`) where shared contracts needed explicit
homes.

Verification: devtools verify green plus focused pytest over
source/dispatch/drive/synthetic/unified-semantic suites.

Closes #223
Ref #222
Sinity added a commit that referenced this pull request Apr 22, 2026
Renews a source-to-surface tranche of boundary code that was fully
type-checked but still carried path-dependent glue: broad payload
dictionaries, repeated coercion glue, weakly modeled runtime seams,
and surface code compensating for ambiguity below. The branch had
completed the renewal work locally but still needed to land as a
reviewed slice before the next tranche could continue.

Rebuilds provider dispatch and viewport/unified-adapter seams in
`polylogue/sources/dispatch.py` and
`polylogue/schemas/unified_adapters.py`. Tightens Drive/source
boundaries across auth, gateway, client, support, decoder,
attachment, and emission paths under `polylogue/sources/`. Renews
synthetic corpus/runtime and schema support contracts across
`polylogue/schemas/synthetic/*`, registry/validator/extraction, and
verification helpers. Hardens ingest/provider metadata seams in
`polylogue/pipeline/services/*` and `pipeline/semantic_*`. Rebuilds
scenario/showcase/report/site surfaces to consume stronger substrate
contracts instead of preserving old glue. Adds new support modules
(`rendering/block_models.py`, `scenarios/payloads.py`,
`showcase/report_models.py`) where shared contracts needed explicit
homes.

Verification: devtools verify green plus focused pytest over
source/dispatch/drive/synthetic/unified-semantic suites.

Closes #223
Ref #222
@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. 33 finding(s) confirmed still present → tracked in #550. 4 finding(s) confirmed fixed/stale.

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

  • 71.F004 / P2: fixed-already at the checked revision: polylogue/rendering/blocks.py:359 now unions the media block types into _STRUCTURED_BLOCK_TYPES. That set includes image, document and file, so media-only messages take the structured HTML/Markdown rendering route.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: tighten dispatch, synthetic runtime, and source emission seams

1 participant