Repository navigation
refactor: renew source and showcase boundary contracts - #228
Conversation
📝 WalkthroughWalkthroughThis pull request significantly strengthens type safety across the polylogue codebase by replacing generic Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Suggested labels
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
💡 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".
| records: list[JsonValue] = [] | ||
| try: | ||
| for item in ijson_module.items(handle, prefix): | ||
| found_any = True | ||
| records.append(item) | ||
| return (found_any, records) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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 | 🟠 MajorApply
record_limit/record_offsetafter the final provider filter.Line 233 passes the requested window into
iter_verification_rows, but Line 280 filters again usingactual_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 | 🔵 TrivialReturn
VHSTapefromgenerate_tapeinstead of round-tripping through.content.
generate_tapeconstructs aVHSTapeonly to discard it and return.content, andgenerate_all_tapesthen re-wraps that string in a secondVHSTapejust to gettape.filename. Either drop the wrapper insidegenerate_tape(it adds nothing) or, preferably, letgenerate_tapereturn 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.contentReturning a string from
generate_tapeis 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 | 🟡 MinorNon-string
Mappingkeys are silently coerced viastr(key).By broadening the dict check to
isinstance(value, Mapping)while keyingstatic_keys,dict_key_sets, andco_occurrencebystr(key), two distinct keys that share a string representation (e.g.,1and"1") collapse into one path, and their subtrees are merged underf"{path}.{key}". For pure JSON samples this is unreachable, but the newMappingbranch 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 | 🟠 MajorUse the nested message payload for all message-scoped metadata.
msg_datais used forusageandmodel, butid,cost, andduration_msare still read only fromraw. 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 | 🟡 MinorTighten the Drive UI type contract at the service boundary instead of casting.
The service methods
visit_sourcesandacquire_sourcesacceptui: object | None, but they pass it directly (or viacast()) toiter_raw_record_stream, which expectsui: DriveUILike | None. SinceDriveUILikeis already imported underTYPE_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 useuidirectly- Remove the
castimport if no longer needed elsewhereThis 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 | 🟠 MajorPreserve explicit
exit_code=Noneduring payload round-trips.
to_payload()emits{"exit_code": None}for “ignore exit code”, butfrom_payload()converts that explicitNoneback to0, 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 | 🟠 MajorDo not silently resolve folders to
""or the folder name when Drive omitsid.Line 76 can return
""for a folder-ID lookup, and Line 90 can returnfolder_reffor a name lookup when the matched payload has no usableid. 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 | 🟠 MajorStale-cache risk when Drive payload changes.
The fast-path on Lines 223-224 reuses
cache_pathwhenever it exists, but the cache file is written by this same function (Lines 242-243) with no tie tofile_meta.modified_time. After theknown_mtimesgate (Lines 206-211) is bypassed — e.g., on a fresh run withoutknown_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 whosemodified_timehas advanced. This silently causes downstream ingestion to miss Drive-side updates.Consider validating the cache against
file_meta.modified_time(e.g., compare againstcache_path.stat().st_mtimeor 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 | 🔵 TrivialDuplicate
drive_cache_file_pathcall.
dest_path(Line 194) andcache_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 | 🟡 MinorStale 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 | 🔵 TrivialMinor: two separate timestamps for nested session records.
datetime.now(...)is evaluated once forbuild_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 inqa_summary.pyandqa_markdown.pydefault-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 | 🟠 MajorHonor already-decoded
JSONValueinputs.Line 187 widens the contract to accept decoded JSON, but Lines 221-241 stringify non-
Path/bytes/strvalues and re-parse them. A decodeddict/listwill fail, and withprefer_jsonl=Truemay even hitStringIO(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=Noneyields a misleading "Drive authorization cancelled" error.When
prompter is None,announce_auth_urlis skipped,codestaysNone, and the function falls into theif 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._prompteris stored but never read.The constructor captures
prompterintoself._prompter, but nothing in this class consumes it —inputalways returnsNoneand ignores both arguments. Either wireself._prompter.request_authorization_code()(or a suitable prompter method) intoinput(...)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 | 🟠 MajorReplace fragile version sort with
_version_sort_keyand ensure default_version always has a fallback.Two issues in this block:
Version sort crashes on non-standard formats.
int(item.version[1:])raisesValueErrorfor any version not matchingv<digits>(e.g.,"v1-beta", or migrated schemas).polylogue/schemas/runtime_registry.pyalready defines_version_sort_keyat line 95 to handle this safely. Use it here for consistency and robustness.
default_versionandrecommended_versioncan both collapse toNone. Whenmanifest is not Nonebutmanifest.default_version is None, line 84 setsrecommended_version = None, which is then propagated to both fields (lines 89–90). Callers throughout the codebase rely on fallback chains (_resolved_package_versioninruntime_registry.py:169,operator_inference.py:150, etc.); the catalog should ensuredefault_versionalways falls back tolatest_versionrather than propagatingNonesilently.Apply the proposed fix: import
_version_sort_key, replace the inline sort logic, and ensuredefault_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
📒 Files selected for processing (138)
devtools/benchmark_campaign.pypolylogue/cli/qa_finalization.pypolylogue/health.pypolylogue/lib/payload_coercion.pypolylogue/lib/raw_payload_decode.pypolylogue/lib/viewport_tools.pypolylogue/pipeline/prepare_transform.pypolylogue/pipeline/semantic_capture.pypolylogue/pipeline/semantic_metadata.pypolylogue/pipeline/services/acquisition.pypolylogue/pipeline/services/acquisition_streams.pypolylogue/pipeline/services/ingest_batch.pypolylogue/pipeline/services/ingest_worker.pypolylogue/pipeline/services/validation_runtime.pypolylogue/rendering/block_models.pypolylogue/rendering/blocks.pypolylogue/rendering/core.pypolylogue/rendering/core_formatter.pypolylogue/rendering/core_markdown.pypolylogue/rendering/core_messages.pypolylogue/rendering/formatting.pypolylogue/rendering/renderers/__init__.pypolylogue/rendering/renderers/html.pypolylogue/rendering/renderers/html_highlighting.pypolylogue/rendering/renderers/html_messages.pypolylogue/rendering/renderers/html_template.pypolylogue/rendering/renderers/markdown.pypolylogue/scenarios/__init__.pypolylogue/scenarios/assertions.pypolylogue/scenarios/cli_surfaces.pypolylogue/scenarios/corpus.pypolylogue/scenarios/executable.pypolylogue/scenarios/execution.pypolylogue/scenarios/metadata.pypolylogue/scenarios/payloads.pypolylogue/scenarios/projections.pypolylogue/scenarios/specs.pypolylogue/schemas/extraction.pypolylogue/schemas/field_stats_collection.pypolylogue/schemas/generation_schema_builder.pypolylogue/schemas/generation_support.pypolylogue/schemas/observation_runtime.pypolylogue/schemas/operator_models.pypolylogue/schemas/privacy_config.pypolylogue/schemas/runtime_registry.pypolylogue/schemas/sampling_db.pypolylogue/schemas/synthetic/build_batch.pypolylogue/schemas/synthetic/build_records.pypolylogue/schemas/synthetic/build_wire_formats.pypolylogue/schemas/synthetic/core.pypolylogue/schemas/synthetic/models.pypolylogue/schemas/synthetic/runtime.pypolylogue/schemas/synthetic/selection.pypolylogue/schemas/synthetic/wire_formats.pypolylogue/schemas/tooling_registry.pypolylogue/schemas/unified_adapters.pypolylogue/schemas/validator.pypolylogue/schemas/verification_corpus.pypolylogue/showcase/catalog_loader.pypolylogue/showcase/cli_boundary.pypolylogue/showcase/context.pypolylogue/showcase/corpus_requests.pypolylogue/showcase/dimensions.pypolylogue/showcase/exercises.pypolylogue/showcase/generators.pypolylogue/showcase/invariants.pypolylogue/showcase/qa_markdown.pypolylogue/showcase/qa_report.pypolylogue/showcase/qa_runner.pypolylogue/showcase/qa_runner_models.pypolylogue/showcase/qa_runner_reporting.pypolylogue/showcase/qa_runner_request.pypolylogue/showcase/qa_runner_stages.pypolylogue/showcase/qa_runner_workflow.pypolylogue/showcase/qa_session_payload.pypolylogue/showcase/qa_summary.pypolylogue/showcase/report_common.pypolylogue/showcase/report_files.pypolylogue/showcase/report_models.pypolylogue/showcase/runner.pypolylogue/showcase/showcase_report_payloads.pypolylogue/showcase/showcase_report_text.pypolylogue/showcase/showcase_runner_models.pypolylogue/showcase/showcase_runner_support.pypolylogue/showcase/vhs.pypolylogue/showcase/workspace.pypolylogue/site/builder.pypolylogue/site/conversation_pages.pypolylogue/site/index_pages.pypolylogue/site/models.pypolylogue/site/publication_flow.pypolylogue/site/scan.pypolylogue/site/search.pypolylogue/site/site_builder_archive.pypolylogue/site/site_builder_pages.pypolylogue/site/template_environment.pypolylogue/site/templates.pypolylogue/site/templates_conversation.pypolylogue/site/templates_dashboard.pypolylogue/site/templates_index.pypolylogue/site/templates_index_body.pypolylogue/site/templates_index_style.pypolylogue/sources/assembly.pypolylogue/sources/assembly_claude_code.pypolylogue/sources/assembly_codex.pypolylogue/sources/decoder_json.pypolylogue/sources/decoders.pypolylogue/sources/dispatch.pypolylogue/sources/drive.pypolylogue/sources/drive_auth.pypolylogue/sources/drive_auth_support.pypolylogue/sources/drive_gateway.pypolylogue/sources/drive_source_client.pypolylogue/sources/drive_source_factory.pypolylogue/sources/drive_source_support.pypolylogue/sources/drive_types.pypolylogue/sources/emitter.pypolylogue/sources/parsers/base_models.pypolylogue/sources/parsers/claude_code_parser.pypolylogue/sources/parsers/drive_support_attachments.pypolylogue/sources/providers/gemini_message.pypolylogue/sources/source_acquisition.pypolylogue/sources/source_parsing.pypolylogue/sources/source_walk.pypolylogue/storage/artifact_inspection.pypolylogue/storage/repair.pypolylogue/storage/repository_archive_conversations.pypolylogue/storage/repository_contracts.pytests/unit/cli/test_query_fmt.pytests/unit/core/test_operator_models.pytests/unit/core/test_raw_payload_decode.pytests/unit/pipeline/test_concurrency_guards.pytests/unit/pipeline/test_differential_paths.pytests/unit/pipeline/test_ingest_batch.pytests/unit/pipeline/test_ingestion_chaos.pytests/unit/showcase/test_report.pytests/unit/sources/test_drive_gateway.pytests/unit/ui/test_ui_visual.py
💤 Files with no reviewable changes (2)
- polylogue/rendering/renderers/markdown.py
- polylogue/site/site_builder_archive.py
| 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, |
There was a problem hiding this comment.
🧹 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).
| 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")), | ||
| ) |
There was a problem hiding this comment.
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".
| 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})") |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
_normalize_timestamp emits inconsistent formats for datetime vs numeric inputs.
int/floatpath forces a UTCZ-terminated ISO string.datetimepath returnstimestamp.isoformat()as-is: a tz-aware UTC datetime yields...+00:00(notZ), and a naivedatetimeyields 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.
| 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.
| 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, |
There was a problem hiding this comment.
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).
| provider_meta: DriveDocMetadata = {"attachment_kind": "youtube_video", **video_dict} | ||
| if url is not None: | ||
| provider_meta["url"] = url |
There was a problem hiding this comment.
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.
| 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.
| def _normalize_mapping(payload: BaseModel | GeminiDictValue) -> GeminiDictValue: | ||
| if isinstance(payload, BaseModel): | ||
| return payload.model_dump() | ||
| return payload |
There was a problem hiding this comment.
🧹 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.
| def _string_or_empty_dict(value: object) -> GeminiDictValue: | ||
| return value if isinstance(value, dict) else {} |
There was a problem hiding this comment.
🧹 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.
| 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), | ||
| ) |
There was a problem hiding this comment.
🧩 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())
PYRepository: 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 catRepository: 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 10Repository: Sinity/polylogue
Length of output: 1599
🏁 Script executed:
# Check imports and overall structure
head -30 polylogue/storage/repository_archive_conversations.pyRepository: 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.pyRepository: 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 -3Repository: 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 -50Repository: 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/nullRepository: 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 15Repository: 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.pyRepository: 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).
| 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)) |
There was a problem hiding this comment.
🧩 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))
PYRepository: 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 -nRepository: 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}")
PYRepository: 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.
| JSONScalar: TypeAlias = str | int | float | bool | None | ||
| JSONValue: TypeAlias = JSONScalar | list["JSONValue"] | Mapping[str, "JSONValue"] |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm whether JSONScalar/JSONValue are referenced outside their definition site.
rg -nP '\bJSON(Scalar|Value)\b' --type=pyRepository: Sinity/polylogue
Length of output: 5772
🏁 Script executed:
cat -n polylogue/health.py | head -50Repository: Sinity/polylogue
Length of output: 1987
🏁 Script executed:
rg -n '__all__' polylogue/health.py && echo "---" && rg -n 'JSONValue|JSONScalar' polylogue/health.pyRepository: Sinity/polylogue
Length of output: 223
🏁 Script executed:
sed -n '577,600p' polylogue/health.pyRepository: 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.
| 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) |
There was a problem hiding this comment.
🧹 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.
| 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) |
There was a problem hiding this comment.
Plaintext and HTML renderers use different conditions for structured blocks — the two surfaces can disagree.
display_textfalls back torender_blocks_plaintext(content_blocks)whenevercontent_blocksis non-empty.html_contentonly usesrender_blocks_html(content_blocks)whenhas_structured_blocks(content_blocks)is true; otherwise it renderstextviarender_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.
| 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.
| @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) |
There was a problem hiding this comment.
🧩 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' | headRepository: Sinity/polylogue
Length of output: 429
🏁 Script executed:
cat polylogue/lib/outcomes.pyRepository: Sinity/polylogue
Length of output: 3186
🏁 Script executed:
cat polylogue/showcase/report_models.py | head -100Repository: Sinity/polylogue
Length of output: 2736
🏁 Script executed:
fd -t f 'invariants.py' polylogue/showcaseRepository: Sinity/polylogue
Length of output: 92
🏁 Script executed:
cat polylogue/showcase/invariants.pyRepository: 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 += 1This 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.
| 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) |
There was a problem hiding this comment.
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.
| 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 | ||
|
|
There was a problem hiding this comment.
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.
| 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, | ||
| ) | ||
| ) |
There was a problem hiding this comment.
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.
| JSONScalar: TypeAlias = str | int | float | bool | None | ||
| JSONValue: TypeAlias = JSONScalar | list["JSONValue"] | dict[str, "JSONValue"] |
There was a problem hiding this comment.
🧹 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.
| 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: |
There was a problem hiding this comment.
🧩 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.pyRepository: 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.
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'`
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
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
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
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
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
polylogue/sources/dispatch.pyandpolylogue/schemas/unified_adapters.pypolylogue/sources/polylogue/schemas/synthetic/*, registry/validator/extraction, and verification helperspolylogue/pipeline/services/*,polylogue/pipeline/semantic_*, and adjacent helperspolylogue/rendering/block_models.py,polylogue/scenarios/payloads.py, andpolylogue/showcase/report_models.pywhere shared contracts needed explicit homesVerification
devtools verifypytest -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::TestSyntheticRoundtripFactAgreementpytest -q tests/unit/core/test_synthetic_semantics.py tests/unit/sources/test_drive_source_client.py tests/unit/sources/test_drive_gateway.pypytest -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'