Skip to content

fix: extract structured thinking and guard sparse archive paths - #68

Closed
Sinity wants to merge 13 commits into
masterfrom
feature/fix/edge-case-hardening-and-test-coverage
Closed

Sinity wants to merge 13 commits into
masterfrom
feature/fix/edge-case-hardening-and-test-coverage

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

I followed a regression sweep here instead of a single feature thread, because the failures all came from the same pattern: real exports contain None text, typed provider objects, odd parts shapes, mixed timestamp types, and security-sensitive filenames that the happy-path code never exercised. The biggest behavioral change is in Message.extract_thinking(): it now treats structured content_blocks, Gemini isThought, and ChatGPT thinking content as first-class reasoning traces not only looking for XML-like tags embedded in text. Around that I fixed the support gaps that were making those richer records unusable in practice: dropped Claude Code token/model metadata, lost tool_result content, site-generation crashes, hidden async limits, corrupt-cache fallbacks, and path-safety issues in Drive and site output. The branch is test-heavy because these were all edge conditions that only stayed visible once I pinned them down with direct regressions. The net result is less glamorous than a new feature, but it makes the archive much more honest about the data providers actually emit.

Motivation

The starting point was output coverage. _conv_to_json() and _conv_to_csv_messages() were not wrong on normal conversations, but once I started writing explicit tests around sparse records the branch widened quickly. A few examples:

  • ChatGPT content extraction assumed parts was a list and could iterate it safely.
  • ClaudeCodeRecord.to_meta() only looked at dict-backed message payloads, so typed assistant messages could silently lose token usage and model information.
  • parse_code() could emit text=None and also drop the actual payload from tool_result blocks, which made later consumers see a shell of the event, not the data that mattered.
  • the site builder could die on a single bad conversation and take the rest of the build with it.
  • facade sorting and async list calls were making hidden assumptions about timestamp types and implicit limits.

Once I had enough failing tests in place, it stopped making sense to treat these as isolated bugs. They are all symptoms of the same issue: the archive layer still expects provider data to look cleaner and more uniform than it actually does.

Changes grouped by concern

Structured thinking extraction

The most important change is in polylogue/lib/models.py. Message.extract_thinking() used to be heavily biased toward one legacy representation: XML-style thinking tags embedded in the message text. That misses a lot of current provider output.

I changed the extraction order so that structured data wins first:

if content_blocks:
    ...  # collect type == "thinking"
if gemini_is_thought:
    return msg.text or ""
if chatgpt_content_type in {"thoughts", "reasoning_recap"}:
    return msg.text or ""
# only then fall back to XML-ish text tags

That matters because once a provider already tells us "this block is thinking", searching the text for ad-hoc delimiters is the wrong abstraction. Join multiple structured thinking blocks with double newlines so the output remains readable when a model emits more than one reasoning segment.

In the same area I tightened role fallback logic. Whitespace-only roles now normalize to "unknown" instead of surviving as an empty string that later code has to special-case.

Provider extraction and metadata preservation

There are two important provider-specific fixes here.

First, extract_chatgpt_text() in polylogue/schemas/unified.py now guards against non-list parts values. That sounds tiny, but it closes a nasty class of bugs: integers, strings, or None values in parts should not trigger TypeError or accidental character-by-character iteration. They should degrade to a reasonable string or empty value.

Second, ClaudeCodeRecord.to_meta() now extracts token usage and model information from typed ClaudeCodeMessageContent instances as well as raw dict payloads. Without that, typed assistant messages look valid at the object level but still arrive at the archive layer missing their cost/model metadata.

Claude parser and site hardening

polylogue/sources/parsers/claude.py now preserves tool_result.content and tool_result.is_error inside content_blocks, and it guarantees text is a string by falling back to "".

That combination matters more than it sounds. A tool-result record without its content field is almost useless for later inspection, and text=None has a habit of surfacing far from the parser that emitted it. The new parser behavior makes tool execution records much easier to render, serialize, and re-analyze later.

The site builder change is deliberately defensive rather than fancy. Each conversation page generation is wrapped in try/except, failed pages are counted, and the build continues. I would rather ship a site with explicit skipped-page warnings than fail the whole archive because one conversation contains a weird record.

Facade, health, acquisition, and vector helpers

This branch also closes a handful of correctness gaps that became obvious once the tests widened:

  • AsyncPolylogue.list_conversations() no longer imposes a hidden 50 default when the caller passes limit=None.
  • facade sorting uses a UTC-aware fallback instead of letting mixed datetime/string records explode at comparison time.
  • health-cache deserialization falls back to a fresh check when the cache payload is corrupt.
  • acquisition progress callbacks are fired outside the per-record try/except, so progress still advances even when individual records fail.
  • sqlite-vec availability is probed lazily and cached, which avoids unnecessary connection work in edge paths.

None of these changes are especially large in isolation. Together they remove a lot of quiet inconsistency from the archive API.

Path safety and credential handling

Folded in the path-safety fixes because they touch the same sparse/edge-data boundary. The site builder and Drive download path now sanitize provider-derived filename components, and the Drive token file is written with 0600 permissions. That is not a deep auth redesign; it is the minimum hardening needed so that provider-derived names and cached credentials do not take unnecessary liberties with the filesystem.

Testing

Most of the branch weight is in explicit regressions. The main additions are:

  • tests/test_cli_query.py for _conv_to_json() / _conv_to_csv_messages()
  • tests/test_importers_unit.py for parse_code() content and text guarantees
  • tests/test_storage.py plus tests/test_sqlite_backend.py for metadata operations and SQLite edge paths
  • tests/test_click_app_routing.py for query-routing regressions
  • tests/test_claude_code_record.py for typed Claude Code metadata extraction
  • tests/test_sqlite_vec_operations.py for vector-provider behavior
  • tests/test_filters_advanced.py and tests/test_repository_operations.py for composition and traversal behavior
  • tests/test_unified_extraction_edge_cases.py for provider extraction oddities

The test philosophy here is to hit the function that actually owned the bug. For example, I did not only verify "thinking shows up somewhere" through a high-level path; I verified extract_thinking() precedence directly.

Notes

I did not try to normalize every possible provider irregularity in one branch. The goal was narrower: make the archive stop lying by omission or crashing on data that is already common enough to be worth testing. There is still room to reduce duplication across parser/model helpers, and the site builder could eventually expose skipped-page details more explicitly than just logging a warning count. For now, the important thing is that the edge paths are visible, testable, and no longer surprising.

Sinity and others added 13 commits February 8, 2026 11:06
10 tests for JSON single-conversation output:
  - Full message content override (not just count)
  - Field selection with/without messages
  - Empty conversations, None text, None timestamps
  - ISO timestamp formatting

10 tests for CSV message output:
  - Correct header row and column order
  - Empty text messages skipped
  - Special character escaping (commas, quotes, newlines)
  - Empty conversations produce header only
  - Timestamp formatting

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
ClaudeCodeRecord.to_meta() only checked isinstance(self.message, dict)
for usage extraction, but Pydantic v2 parses assistant messages as
ClaudeCodeMessageContent (a typed model, not a dict). This silently
dropped all token counts and model names.

Now checks for the typed model first, falling back to dict for any
messages that didn't match the schema.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…ash prevention

- parse_code(): use `text or ""` to prevent ParsedMessage with text=None
  for progress/result records that have no text content (was inconsistent
  with extract_messages_from_chat_messages which guards with `if text:`)
- Tool result content blocks now extract `content` and `is_error` fields
  instead of only preserving tool_use_id (tool output was silently dropped)
- Site builder: wrap per-conversation page generation in try-except so one
  bad conversation doesn't crash the entire 4800+ conversation archive build

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Parser tests (6):
- progress/result records get text="" not None
- assistant records with only tool_use blocks get text="" not None
- tool_result content and is_error fields preserved
- mixed content blocks (thinking + text + tool_use + tool_result) all preserved

Metadata operation tests (12):
- update_metadata: set, overwrite, preserve other keys
- delete_metadata: remove key, nonexistent key is noop
- add_tag: append, idempotent, multiple tags
- remove_tag: remove, nonexistent is noop
- _metadata_read_modify_write: mutator exception rolls back
- metadata operations work after store_records (transaction nesting)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
If content["parts"] was an int, iterating it raised TypeError. If it
was a string, it iterated over characters producing corrupted output
like "h\ne\nl\nl\no". Now checks isinstance(parts, list) first and
falls back to str(parts) for scalar values.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…it truncation

- stats() sorting: conversations with both updated_at and created_at as
  None fell back to c.id (string), causing TypeError when sorted alongside
  datetime values. Use datetime.min as consistent fallback.
- list_conversations(): `limit or 50` silently capped fetch to 50 when
  limit=None, so source filter only searched the first 50 conversations.
  Now passes limit=None through when source filter needs all candidates.
- async_facade: same `limit or 50` truncation fixed.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…site paths

- health.py: Catch ValueError/KeyError when reconstructing HealthCheck from
  corrupted cache file instead of crashing
- models.py: Strip whitespace from role before truthiness check to prevent
  ValueError when accessing role_enum on whitespace-only roles
- async_sqlite.py: Add missing MessageRecord fields (provider_message_id,
  version, parent_message_id, branch_index) to match sync backend; add columns
  to async schema; use defensive key checks for schema compatibility
- site/builder.py: Sanitize provider name with safe_path_component() in
  conversation index path construction, consistent with provider index pages
- cli/helpers.py: Replace `if True:` dead condition with `if ui:`

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…waste, state mutation

- acquisition.py: Move progress_callback outside try/except to prevent
  double-counting (success + error) when callback throws
- enrichment.py: Guard against None content_blocks before passing to
  enrich_content_blocks (was silently converting None → [])
- sqlite_vec.py: Only probe connection on first _ensure_vec_available()
  call; subsequent calls just check the cached flag (was creating and
  discarding a connection on every vector operation)
- filters.py: Wrap count() limit save/restore in try/finally to prevent
  _limit_count staying None if list() or list_summaries() raises

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ve sort

- drive.py: Sanitize Drive filenames with safe_path_component() to prevent
  path traversal via names containing '/' or '..'
- drive_client.py: Set token file to 0o600 after write (was default 0o644)
- facade.py: Use timezone-aware datetime.min fallback to avoid TypeError
  when sorting conversations with mixed None/present UTC-aware timestamps

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…hinking

Previously extract_thinking() only searched for <thinking> XML tags in message
text. This missed thinking content stored in structured content_blocks (Claude
API format), Gemini isThought messages, and ChatGPT thoughts/reasoning_recap
messages — despite is_thinking() correctly detecting all these formats.

Added 5 regression tests covering all thinking extraction paths.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…traction

- SQLiteBackend (63 tests): connection_context, save/get conversation+messages,
  batch retrieval, transactions with nested savepoints, metadata/tag operations,
  delete cascades, conversation stats, helper functions, lifecycle
- CLI routing (32 tests): _handle_query_mode dispatch for all filter/output/modifier
  flags, regression tests for --id/--add-tag/--set/--delete routing bugs,
  QueryFirstGroup positional→query-term conversion
- Unified extraction (30 tests): extract_chatgpt_text with int/string/None/bool
  parts (regression), extract_codex_text with non-dict blocks, extract_harmonized_message
  provider dispatch including Gemini thinking and cost metadata

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…ions

ClaudeCodeRecord (54 tests): role mapping for all 10 record types, timestamp
parsing (Unix ms/s, ISO, edge cases), text_content extraction from dict/typed
messages with mixed blocks, content_blocks_raw extraction, to_meta() with
cost/usage/model from both typed and dict messages, boolean flag properties,
ToolUse/ThinkingBlock/Usage sub-model conversions, viewport method integration.

SqliteVecProvider (50 tests): Voyage API batching with BATCH_SIZE overflow,
HTTP error sanitization (no API key leakage), dimension reduction payload,
input_type/authorization headers, tool_result status word filtering (5 words),
boundary testing (19/20 chars), upsert flow with mocked DB operations,
provider_name extraction from metadata, connection lifecycle, query/
query_by_provider execution paths, get_embedding_stats with missing tables,
_ensure_vec_available probing and caching.

Also fixes 2 flaky SQLiteBackend transaction tests (class identity issue
in full suite — now uses Exception with match= instead of DatabaseError).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
50 tests in test_repository_operations.py covering:
- Lazy vs eager loading (6)
- resolve_id/view (5)
- Tree traversal: parent/child/root/session_tree (9)
- Transactional save with content_hash dedup (3)
- Metadata CRUD: update/delete/tags/set (7)
- FTS search and search_summaries (5)
- count/list_summaries with filters (7)
- iter_messages, stats, filter factory (8)

70 tests in test_filters_advanced.py covering:
- has() type filtering: thinking/tools/attachments/summary (7)
- sample() random sampling (7)
- Combined negative and positive+negative filters (8)
- Sort edge cases: tokens/words/longest/messages (10)
- limit(0) edge cases with sample (4)
- list_summaries() terminal with validation (15)
- pick() terminal method (5)
- Empty repository edge cases (8)
- Branching methods: is_root/is_continuation/is_sidechain (6)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Copilot AI review requested due to automatic review settings April 7, 2026 13:33
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 11 minutes and 43 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 11 minutes and 43 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 12b3d6e9-6455-44e7-bef1-94d1be2a84fb

📥 Commits

Reviewing files that changed from the base of the PR and between 0a14560 and e2f958e.

📒 Files selected for processing (27)
  • polylogue/async_facade.py
  • polylogue/cli/helpers.py
  • polylogue/facade.py
  • polylogue/health.py
  • polylogue/lib/filters.py
  • polylogue/lib/models.py
  • polylogue/pipeline/enrichment.py
  • polylogue/pipeline/services/acquisition.py
  • polylogue/schemas/unified.py
  • polylogue/site/builder.py
  • polylogue/sources/drive.py
  • polylogue/sources/drive_client.py
  • polylogue/sources/parsers/claude.py
  • polylogue/sources/providers/claude_code.py
  • polylogue/storage/backends/async_sqlite.py
  • polylogue/storage/search_providers/sqlite_vec.py
  • tests/test_claude_code_record.py
  • tests/test_cli_query.py
  • tests/test_click_app_routing.py
  • tests/test_filters_advanced.py
  • tests/test_importers_unit.py
  • tests/test_repository_operations.py
  • tests/test_semantic_api_comprehensive.py
  • tests/test_sqlite_backend.py
  • tests/test_sqlite_vec_operations.py
  • tests/test_storage.py
  • tests/test_unified_extraction_edge_cases.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/edge-case-hardening-and-test-coverage

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

Sinity added a commit that referenced this pull request Apr 7, 2026
…68)

Rewrite thinking extraction to handle structured content_blocks, Gemini
isThought, and ChatGPT thinking messages beyond the legacy XML tag
approach. Fix several null-safety gaps and routing regressions discovered
during a comprehensive testing sweep across core modules.

Thinking extraction (lib/models.py):
- extract_thinking() checks content_blocks for type="thinking" before
  falling back to XML tag parsing in message text
- Gemini isThought and ChatGPT content_type="thoughts" messages return
  full text as thinking content
- Multiple thinking blocks joined with double newlines
- Role whitespace stripped before fallback to "unknown"

ChatGPT extraction (schemas/unified.py):
- extract_chatgpt_text() guards against non-list parts values (int,
  str, None) that previously caused TypeError or character iteration

Claude Code metadata (sources/providers/claude_code.py):
- to_meta() extracts token usage and model from typed
  ClaudeCodeMessageContent, not only raw dict messages

Claude parser (sources/parsers/claude.py):
- tool_result content blocks preserve content and is_error fields
- text=None guarded with "or empty string" fallback

Path sanitization and security:
- site/builder.py provider path uses safe_path_component()
- sources/drive.py downloaded filenames use safe_path_component()
- sources/drive_client.py sets token file to 0o600 permissions

Exception safety:
- lib/filters.py limit restoration uses try/finally
- health.py corrupted cache deserialization falls through to fresh check
- site/builder.py conversation page generation wrapped in try/except
  with skip counter and warning log

Facade and pipeline:
- facade.py fetches all conversations when source filter is active
  since source lives in provider_meta, not a SQL-pushable column
- facade.py datetime sort fallback uses UTC-aware epoch
- async_facade.py removes hardcoded limit default of 50
- enrichment.py guards against None content_blocks in provider_meta
- acquisition.py fires progress callback outside try/except so count
  advances even when individual records fail

Storage alignment:
- async_sqlite.py schema and record construction include
  parent_message_id and branch_index columns
- sqlite_vec.py _ensure_vec_available probes lazily on first call and
  caches the result

Test coverage (~5,000 new lines):
- test_sqlite_backend.py: connection lifecycle, CRUD, transactions,
  metadata, batch retrieval, helper functions
- test_sqlite_vec_operations.py: Voyage API mocking, upsert flow,
  query paths, embedding stats, error handling
- test_filters_advanced.py: has() types, sample(), combined negative
  filters, sort edge cases, list_summaries, empty repo, branching
- test_click_app_routing.py: query routing regression tests covering
  all filter, output, and modifier flag combinations
- test_claude_code_record.py: role mapping, timestamps, text
  extraction, content blocks, to_meta, sub-model conversions
- test_repository_operations.py: lazy vs eager loading, tree traversal,
  transactional save, metadata CRUD, search, iter_messages
- test_unified_extraction_edge_cases.py: non-list parts, non-dict
  blocks, provider dispatch edge cases
- Additional coverage in test_cli_query, test_importers_unit,
  test_semantic_api_comprehensive, test_storage

Copilot AI 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.

Pull request overview

This PR hardens Polylogue’s ingestion/extraction/storage/site pipeline against real-world export irregularities (nulls, typed provider objects, malformed shapes, mixed timestamps) while expanding “thinking” extraction to structured provider formats.

Changes:

  • Extend Message.extract_thinking() to prioritize structured reasoning traces (content blocks / provider flags) and normalize whitespace-only roles.
  • Improve robustness across providers/storage/site: guard malformed ChatGPT parts, preserve Claude tool-result payloads, make site generation skip bad conversations, fix async/list defaults, and harden path + token-file handling.
  • Add broad regression coverage for edge cases across unified extraction, filters, repository/storage backends, CLI routing, and sqlite-vec operations.

Reviewed changes

Copilot reviewed 27 out of 27 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
polylogue/lib/models.py Structured thinking extraction + role normalization.
polylogue/schemas/unified.py Guard non-list ChatGPT parts in text extraction.
polylogue/sources/providers/claude_code.py Preserve model + token usage from typed message objects.
polylogue/sources/parsers/claude.py Preserve tool_result content/is_error; ensure text is never None.
polylogue/pipeline/enrichment.py Guard content_blocks=None during enrichment.
polylogue/pipeline/services/acquisition.py Ensure progress callback fires even when per-record store fails.
polylogue/health.py Fall back to fresh checks when health cache is corrupted.
polylogue/facade.py Remove hidden list default; robust recent-sort fallback for mixed timestamps.
polylogue/async_facade.py Stop imposing hidden 50 default limit for async listing.
polylogue/storage/backends/async_sqlite.py Align async schema/records with sync (branching fields, provider_message_id/version hydration).
polylogue/storage/search_providers/sqlite_vec.py Cache sqlite-vec availability probe; avoid redundant connections.
polylogue/site/builder.py Sanitize provider path segment; skip page generation failures instead of aborting build.
polylogue/sources/drive.py Sanitize Drive-derived filenames before writing to disk.
polylogue/sources/drive_client.py Write OAuth token files with 0600 permissions.
polylogue/cli/helpers.py Avoid unconditional analytics block execution.
tests/test_unified_extraction_edge_cases.py New regression coverage for malformed provider content shapes.
tests/test_importers_unit.py New regressions for parse_code() null-text + tool_result preservation.
tests/test_click_app_routing.py New regressions for CLI query routing matrix.
tests/test_cli_query.py New regressions for JSON/CSV conversation output helpers.
tests/test_claude_code_record.py New regressions for typed Claude Code metadata extraction.
tests/test_storage.py New coverage for metadata CRUD + RMW atomicity behavior.
tests/test_sqlite_backend.py Comprehensive SQLiteBackend behavior tests.
tests/test_repository_operations.py Repository facade traversal/CRUD/search tests.
tests/test_filters_advanced.py Expanded filter composition/sort/sample coverage.
tests/test_sqlite_vec_operations.py Comprehensive sqlite-vec provider tests (API/DB/query/error paths).
tests/test_semantic_api_comprehensive.py New regressions for structured thinking extraction precedence.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 289 to +291
parts = content.get("parts", [])
if not isinstance(parts, list):
return str(parts) if parts else ""

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

extract_chatgpt_text treats non-list parts values using str(parts) if parts else "", which returns an empty string for valid falsy values like 0 or False. That silently drops content and is inconsistent with the intent of preserving scalar parts (e.g., the regression test for 42). Handle None/missing as empty, but stringify other scalars regardless of truthiness.

Suggested change
parts = content.get("parts", [])
if not isinstance(parts, list):
return str(parts) if parts else ""
parts = content.get("parts")
if not isinstance(parts, list):
return "" if parts is None else str(parts)

Copilot uses AI. Check for mistakes.
Comment thread polylogue/site/builder.py
Comment on lines 734 to 738
updated_at=updated_at_str,
message_count=msg_counts.get(sid, 0),
preview=summary.summary or "",
path=f"{provider}/{sid[:12]}/conversation.html",
path=f"{safe_path_component(provider, fallback='provider')}/{sid[:12]}/conversation.html",
))

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

Conversation page paths sanitize the provider but still embed sid[:12] directly as a path component. Since conversation IDs are derived from provider data (e.g., provider:provider_conversation_id), this can include path separators or .. segments and lead to directory traversal or invalid paths. Sanitize the conversation-id component too (e.g., safe_path_component(sid, ...) and then truncate for display).

Copilot uses AI. Check for mistakes.
Comment thread polylogue/async_facade.py
Comment on lines 177 to 181
"""
conv_records = await self._backend.list_conversations(
provider=provider,
limit=limit or 50,
limit=limit,
)

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

AsyncPolylogue.list_conversations() now forwards limit directly to the async backend. The async backend’s list_conversations currently applies the SQL LIMIT only when if limit: (truthy check), so a caller passing limit=0 will unexpectedly return all conversations. Consider normalizing limit=0 to an explicit 0-result behavior (and/or update the backend to check limit is not None).

Copilot uses AI. Check for mistakes.
Comment on lines +293 to +303
def test_sample_randomness(self, filter_repo_advanced):
"""Multiple samples produce different results (probabilistic test)."""
# Take multiple samples and verify they vary
samples = []
for _ in range(3):
result = ConversationFilter(filter_repo_advanced).sample(2).list()
samples.append([c.id for c in result])
# At least some samples should differ (very high confidence with 3 tries)
# Note: This is probabilistic; very unlikely to fail unless sample() is broken


Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

test_sample_randomness doesn't contain any assertions, so it will pass even if sample() is completely deterministic or broken. Either add a non-flaky assertion (e.g., seed RNG and assert expected sample) or remove the test to avoid giving a false sense of coverage.

Suggested change
def test_sample_randomness(self, filter_repo_advanced):
"""Multiple samples produce different results (probabilistic test)."""
# Take multiple samples and verify they vary
samples = []
for _ in range(3):
result = ConversationFilter(filter_repo_advanced).sample(2).list()
samples.append([c.id for c in result])
# At least some samples should differ (very high confidence with 3 tries)
# Note: This is probabilistic; very unlikely to fail unless sample() is broken

Copilot uses AI. Check for mistakes.
Comment on lines 258 to 270
MessageRecord(
message_id=row["message_id"],
conversation_id=row["conversation_id"],
provider_message_id=row["provider_message_id"],
role=row["role"],
text=row["text"],
timestamp=row["timestamp"],
content_hash=row["content_hash"],
provider_meta=json.loads(row["provider_meta"]) if row["provider_meta"] else None,
version=row["version"],
parent_message_id=row["parent_message_id"] if "parent_message_id" in row.keys() else None,
branch_index=(row["branch_index"] or 0) if "branch_index" in row.keys() else 0,
)

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

get_messages() now hydrates parent_message_id and branch_index from the DB, but save_conversation() currently inserts messages without those columns. That means branching metadata written via the async backend will be lost (or inserts may fail depending on schema defaults). Update the async insert/executemany statement to persist parent_message_id and branch_index too.

Copilot uses AI. Check for mistakes.
@Sinity

Sinity commented Apr 8, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Apr 8, 2026

Copy link
Copy Markdown
✅ Actions performed

Full review triggered.

@Sinity Sinity closed this Apr 9, 2026
@Sinity Sinity added the faux-pull-request PR created as part of a history rewrite process label Apr 9, 2026
@Sinity
Sinity deleted the feature/fix/edge-case-hardening-and-test-coverage branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
…68)

Rewrite thinking extraction to handle structured content_blocks, Gemini
isThought, and ChatGPT thinking messages beyond the legacy XML tag
approach. Fix several null-safety gaps and routing regressions discovered
during a comprehensive testing sweep across core modules.

Thinking extraction (lib/models.py):
- extract_thinking() checks content_blocks for type="thinking" before
  falling back to XML tag parsing in message text
- Gemini isThought and ChatGPT content_type="thoughts" messages return
  full text as thinking content
- Multiple thinking blocks joined with double newlines
- Role whitespace stripped before fallback to "unknown"

ChatGPT extraction (schemas/unified.py):
- extract_chatgpt_text() guards against non-list parts values (int,
  str, None) that previously caused TypeError or character iteration

Claude Code metadata (sources/providers/claude_code.py):
- to_meta() extracts token usage and model from typed
  ClaudeCodeMessageContent, not only raw dict messages

Claude parser (sources/parsers/claude.py):
- tool_result content blocks preserve content and is_error fields
- text=None guarded with "or empty string" fallback

Path sanitization and security:
- site/builder.py provider path uses safe_path_component()
- sources/drive.py downloaded filenames use safe_path_component()
- sources/drive_client.py sets token file to 0o600 permissions

Exception safety:
- lib/filters.py limit restoration uses try/finally
- health.py corrupted cache deserialization falls through to fresh check
- site/builder.py conversation page generation wrapped in try/except
  with skip counter and warning log

Facade and pipeline:
- facade.py fetches all conversations when source filter is active
  since source lives in provider_meta, not a SQL-pushable column
- facade.py datetime sort fallback uses UTC-aware epoch
- async_facade.py removes hardcoded limit default of 50
- enrichment.py guards against None content_blocks in provider_meta
- acquisition.py fires progress callback outside try/except so count
  advances even when individual records fail

Storage alignment:
- async_sqlite.py schema and record construction include
  parent_message_id and branch_index columns
- sqlite_vec.py _ensure_vec_available probes lazily on first call and
  caches the result

Test coverage (~5,000 new lines):
- test_sqlite_backend.py: connection lifecycle, CRUD, transactions,
  metadata, batch retrieval, helper functions
- test_sqlite_vec_operations.py: Voyage API mocking, upsert flow,
  query paths, embedding stats, error handling
- test_filters_advanced.py: has() types, sample(), combined negative
  filters, sort edge cases, list_summaries, empty repo, branching
- test_click_app_routing.py: query routing regression tests covering
  all filter, output, and modifier flag combinations
- test_claude_code_record.py: role mapping, timestamps, text
  extraction, content blocks, to_meta, sub-model conversions
- test_repository_operations.py: lazy vs eager loading, tree traversal,
  transactional save, metadata CRUD, search, iter_messages
- test_unified_extraction_edge_cases.py: non-list parts, non-dict
  blocks, provider dispatch edge cases
- Additional coverage in test_cli_query, test_importers_unit,
  test_semantic_api_comprehensive, test_storage
@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review

path=f"{safe_path_component(provider, fallback='provider')}/{sid[:12]}/conversation.html",

P1 Badge Sanitize conversation IDs in site output paths

sid[:12] is interpolated directly into the relative HTML path, but conversation IDs come from provider data and are not constrained to safe path components. If an imported ID contains traversal tokens (for example ../), _generate_conversation_pages() will resolve page_path outside the intended provider directory and can write files outside the site output tree when rendering pages.


path=f"{safe_path_component(provider, fallback='provider')}/{sid[:12]}/conversation.html",

P2 Badge Use full safe conversation IDs for page paths

Using only sid[:12] to build ConversationIndex.path can make distinct conversations map to the same output file whenever their first 12 characters match. In that case, one conversation page overwrites or masks another (and later generation may be skipped because the file already exists), so links can point to the wrong content and data is effectively dropped from the static site.


if offset:
query += " OFFSET ?"
params.append(offset)

P2 Badge Add LIMIT -1 before OFFSET in async conversation query

This query builder appends OFFSET even when limit is None, which produces invalid SQLite syntax (... ORDER BY ... OFFSET ?) and raises an OperationalError for offset-only pagination calls. The synchronous backend already guards this case with LIMIT -1, so async pagination currently breaks for the same input pattern.

ℹ️ About Codex in GitHub

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

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

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

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

Sinity added a commit that referenced this pull request Nov 1, 2026
The daemon now returns one typed answer, `command_surface::Answer`, to
every surface. Before this change it answered with its own `Response`
enum. That enum turned empty and degraded answers into plain ok, dropped
notes and next actions, and stored the failure kind as a string plus an
untyped `detail` object. The edges then worked the outcome back out from
payload fields (`pending`, `state`, `/user_state/pending`, `currency`,
`incomplete`, `empty`, `outcome`) and rebuilt failures by reading fields
out of `detail`.

Builds on Sinity/polylogue-sinex-common#68, merged as `149e9e2`, which
adds a typed `candidates` list to the shared `Failure`. Cargo.lock is
moved to that commit here.

## What changed

- **Deleted:** `daemon::Response`, both `From` conversions,
`Response::answer`, `protocol::answer` (the code that worked out the
outcome from fields), the `detail`-parsing `protocol::failure(code,
message, detail)`, `query::response`, `execution::exit_code`, the
`daemon::query::Failure` that held a string kind and detail, the
per-module duplicate error mappings (`read::failure`, `language_error`,
`cursor_failure`, page `failure`), and `SelectionError::detail`.
- **Where the outcome is decided:** each answer's outcome is set by the
code that builds it.
- A write that Sinex has not confirmed yet is degraded, with a note.
This covers user writes, context deliveries, assertion queries, and
`StoreError::PrimaryPending`, which is now a degraded receipt.
  - An import whose user state is still pending is degraded.
- Queries return their computed outcome (`QueryAnswer { value, outcome,
notes }`). An incomplete part makes the answer degraded and names the
part in its notes.
- Status and read pages over an index that is not current are degraded,
with a note.
  - SQL, completion and resumable lists that match nothing are empty.
- **Failures:**
- The daemon has one internal error, `daemon::Failure`, which wraps the
shared failure. It exists only so `?` can convert into it. Store,
selection, query and query-language errors convert into it once, at the
owner, with typed position, correction, hint and candidates.
- The kind is the shared `FailureKind`. The product code stays in
`Failure::code`, classified once in `FAILURE_CLASSES`. `invalid_cursor`,
`attachment_unavailable`, `embeddings_off` and `confirm` are now
registered.
- Store selection refusals keep their code in a new
`StoreError::Selection`. An ambiguous ID prefix is now the typed
`StoreError::Ambiguous`, and its matches become `candidates`.
- **Timeouts:** a timeout refusal names its stage from the typed request
instead of serializing the request and reading `text` back. It sets the
narrower query as the suggestion and gives the stage and SQLite step
count in a note.
- **Edges:**
- The socket, HTTP, web pages and browser routes pass the answer through
unchanged. The browser routes keep their JSON body and take their status
from the failure kind.
- MCP structured output passes the answer through unchanged. MCP text
stays JSON for values; for a failure it lists the candidates and notes.
- CLI `--json` passes the answer through unchanged. On a terminal the
CLI prints notes and candidates on stderr.
  - The CLI output handlers receive the whole answer.
- **Docs:** `interfaces.md` says who decides the outcome and notes, and
names `candidates` in the JSON error. `query.md` lists `candidates`.

## Tests

- New test
`cli::query_surfaces::a_degraded_answer_keeps_its_outcome_and_notes_on_every_surface`
sends a degraded query (`similar:` with embeddings off) through CLI
`--json`, the socket and MCP `structuredContent`. On each surface it
checks outcome `degraded`, exit 5, the rows, and the same notes naming
the missing part. On the old code the notes were empty, so this test
fails there.
- `protocol::tests` were rewritten around the explicit constructors.
- **Owned tests:**
- `a_name_two_saved_queries_share_is_refused` and
`saved_relation_errors_reach_the_query_error_path` now check that
ambiguity is refused as `ambiguous` and lists both roots, through
`candidates` (references.md "Ambiguity is an error").
- `an_assertion_reference_names_the_current_revision_or_one_revision`:
`page:` and `file:` references now answer `not_built` (query.md,
references.md) instead of `unknown_field`.
- `every_surface_refuses_command_words_and_values_outside_a_set`: `"test
output"` is refused because a field name is never a search word (common
query-language README). The quoted form still searches.
- `native_hook_failures_reach_ordinary_mcp_reads_and_budgeted_pages`:
the previous commit's update identifies a message header by its
reference. `Source.message` is the containing message of a block, and a
header built by `Source::record` leaves it unset. Checked against the
model and kept.

## Verification

These checks ran on head `f541cca917`, rebased on `ee5b55eddb`.
Cargo.lock is at common `149e9e2`, which contains #68, and is no longer
linked to a local checkout.

- **`fast` (AgentCTL job 262):** passed. It runs fmt, boundaries and
clippy in both configurations.
- **`focused -p polylogue -p polylogue-store` (job 263):** 1455 tests,
1420 passed, 34 failed, 1 timed out, 9 skipped.
- **Against the coordinator's baseline** (job 213, the unmodified
integration head `93da945931`, 58 failures):
  - 32 of this run's 35 failures are baseline failures.
- 26 baseline failures pass here. They include four of the five assigned
tests:
`an_assertion_reference_names_the_current_revision_or_one_revision`,
`every_surface_refuses_command_words_and_values_outside_a_set`,
`a_name_two_saved_queries_share_is_refused` and
`native_hook_failures_reach_ordinary_mcp_reads_and_budgeted_pages`.
  - The new degraded-answer test passes.
- **Three failures are not in the baseline:**
- `cli::tests::literal_read_envelope_is_not_expanded_with_cli_defaults`:
a page read through the CLI now sends the restated call
(`write_out::call(&request, accepted)`) instead of the literal envelope.
That line came in with #6688 after the baseline commit; this PR does not
touch it.
-
`mcp::tests::generated_ready_mcp_call_executes_its_exact_typed_envelope`:
timed out after more than 90 seconds while the host was heavily loaded.
Not yet reproduced.
-
`daemon::service::read::object::tests::actual_no_effect_request_read_records_one_object_run_and_roundtrips_through_directory_import`:
the run outcome is not yet visible when the test reads it
(`object/tests.rs:115`). In earlier runs a sibling test failed at the
same line and then passed again, and `record` is mechanically unchanged
here. It looks like a race between the finish write and the next read,
but this is not confirmed.
- `saved_relation_errors_reach_the_query_error_path` is still a baseline
failure. It now passes the ambiguity check and fails later, where
`sessions where cost > nonsense` is not refused at plan preparation;
that is outside this change.

`rg '\bResponse\b' crates --type rust` finds only HTTP response types,
the operation trait's associated `Response`, the Claude Code parser's
own `Response` struct, comments and fixture text. No outcome is worked
out from payload fields any more.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01AcQETkbTfFMr1hgNJ8A3em

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli CLI area:parser Parser area:pipeline Pipeline area:qa QA area:site Site area:storage Storage faux-pull-request PR created as part of a history rewrite process type:fix Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants