Repository navigation
Conversation
Extract 4 shared generic methods to eliminate near-identical Conversation / ConversationSummary method pairs: - _apply_common_filters[_T](): shared metadata filtering (provider, date, title, tags, excluded_providers, id_prefix, summary) via duck typing - _apply_sort_generic[_T](): shared random-shuffle + sorted pipeline - _fetch_generic[_T](): shared ID-resolve / FTS / list-with-pushdown pipeline with callback triples (get_by_id, search, list_all) - _execute_pipeline[_T](): shared filter → sort → sample → limit flow The 4 summary-specific methods (_apply_summary_filters, _apply_summary_sort, _fetch_summary_candidates, list_summaries) become thin wrappers that delegate to the generics. -117 lines (778 → 661). 4076 tests passing. Co-Authored-By: Claude <[email protected]>
Dead code removal (verified zero callers via grep): - models.py: remove 4 unused model classes (GitOperation, FileChange, SubagentSpawn, ContextCompaction), without_attachments(), substantive_word_count - viewports.py: remove ConversationMeta, SupportsViewports protocol, computed_total property, now-unused Protocol/runtime_checkable imports - unified.py: remove unused GLOM_AVAILABLE flag SQLite backend deduplication: - Extract _VEC0_DDL constant (was copy-pasted in 3 places) - Extract _update_ref_counts() helper (was duplicated in prune/save) - Merge conditional provider branching in list_tags, search_conversations, get_raw_conversation_count into single queries with dynamic WHERE -186 lines across 4 files. 4076 tests passing. Co-Authored-By: Claude <[email protected]>
- Add _row_get() helper to handle missing optional columns across schema versions (parent_conversation_id, branch_type, raw_id for conversations; parent_message_id, branch_index for messages) - async_sqlite.py now imports _row_to_conversation/_row_to_message from sqlite.py instead of inlining JSON parsing in 3 methods - Removes ~86 lines of duplicated record construction from async_sqlite.py while gaining better error messages via shared _parse_json() Co-Authored-By: Claude <[email protected]>
…nd MCP
Bug fixes:
- Fix semantic search ranking inversion (sqlite-vec L2 distances: lower=better)
- Fix ReDoS risk in is_context_dump pattern matching (remove redundant pattern)
- Fix timestamp parser misclassifying year strings as epoch seconds (>= 86400 guard)
- Fix async SQLite schema drift by sharing SCHEMA_DDL constant with sync backend
- Fix async SQLite OFFSET without LIMIT (add LIMIT -1 guard)
- Fix async SQLite missing columns in conversation/message INSERT
- Fix MCP server: add conversation/{id} to resources/list, remove message truncation
- Mask internal error details in MCP error responses
Enhancements (Phase 1):
- Wire Gemini rich typed model into parser (safety ratings, grounding, branches,
reasoning traces, content blocks, thinking budget)
- Propagate Codex git context and instructions to message/conversation metadata
Cleanup:
- Remove empty TYPE_CHECKING blocks (html.py, search_cache.py)
- Extract SCHEMA_DDL as shared constant (single source of truth)
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Extract hardcoded provider colors, role colors, and theme tokens into a single source of truth. Replace inline conditionals in helpers.py and inline Theme dict in facade.py with imports from the shared module. Co-Authored-By: Claude Opus 4.6 <[email protected]>
ChatGPT: extract model_slug, citations, code_execution, user_context, author_name, recipient, status, end_turn per message; default_model, gizmo_id, gizmo_type, is_archived per conversation. Claude Code: extract cwd, gitBranch, version, model, token_usage, stop_reason per message; working_directories, models_used per conv. Gemini: add executableCode, codeExecutionResult, errorMessage, isEdited fields to GeminiMessage; extract code execution as content blocks. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace manual string formatting in stats-by and summary-list with Rich Tables. Add _render_conversation_rich() for interactive terminal display with role-colored bordered panels, thinking block styling, and Markdown rendering. Wire into _output_results() for markdown-to-stdout on TTY. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Remove conflicting grid-size: 2 from styles.tcss so Dashboard's DEFAULT_CSS grid-size: 5 takes effect for stat cards. Add @media (prefers-color-scheme: light) and [data-theme="light"] to polylogue/templates/style.css with appropriate light palette. Set data-theme="auto" on index.html and modern.html templates. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Store auto-generated JSON schemas as gzip-compressed .json.gz files (16K total across 5 providers). Validator loads .gz with fallback to plain .json for test fixtures. Generator writes .json.gz format. Add .gitattributes marking schemas as binary/linguist-generated. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add non-blocking schema validation to _parse_raw_record() that logs drift warnings and validation errors without interrupting ingestion. For JSONL payloads, sample-validates the first dict item. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Delete coverage_baseline.json (706K build artifact) and schemas/generated/ (532K duplicate of schemas/providers/). Add coverage_baseline.json to .gitignore. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Claude AI parser: validate via ClaudeAIConversation typed model with fallback to untyped extraction for non-standard exports - Site builder: integrate Pagefind search UI, add code syntax highlighting via PygmentsHighlighter, CSS improvements for code blocks - sqlite-vec: auto-create tables on first use (message_embeddings, embeddings_meta, embedding_status), idempotent _ensure_tables() - UI: fix PlainConsoleFacade.__post_init__ to call super(), replace inline markdown rendering with format_conversation_markdown - search_cache: fix docstring accuracy 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.6 <[email protected]>
13-phase release readiness sweep: Packaging (critical): - Fix nixos module package ref (polylogue → default) - Fix sync.nix to use `polylogue run --watch` (sync doesn't exist) - Add schema .json.gz files to setuptools package-data Nix cleanup: - Remove dead deps: fastapi, uvicorn, dependency-injector + overlay - Delete unused mkWatchService function from polylogue.nix Code quality: - Deduplicate source.py: iter_source_conversations now delegates to iter_source_conversations_with_raw(capture_raw=False), removing ~170 lines of duplicated file iteration, ZIP handling, and error recovery - Delete dead modules: schemas/common.py, schemas/claude_code_records.py - Remove unused _known_properties/_extract_known_properties from validator - Add Gemini content-based detection (chunkedPrompt/chunks keys) - Replace 8 Any types with concrete types in MCP server (TYPE_CHECKING) - Fix bare except:pass blocks with logger.debug() calls - Type annotations: conv:Any→Conversation, conn:Any→sqlite3.Connection - Add module docstrings to 6 files missing them - Fix f-string without placeholder in health.py - Move datetime imports from loop body to module level Documentation: - README: complete rewrite of CLI reference — remove 15+ phantom flags, document 5 missing subcommands, fix URLs, add Roadmap section - Update all 5 provider docs with accurate parser capabilities - Remove stale config.toml refs from integration docs - Archive MANUAL_TESTING_PROTOCOL.md - Fix all 'polylogue sync' → 'polylogue run' references Verified: 4044 tests pass, nix build clean, ruff clean on edited files, all 11 CLI subcommands present, run --preview processes 7.6k conversations. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
📝 WalkthroughWalkthroughThis pull request substantially refactors Polylogue's CLI, schema handling, and rendering infrastructure. Changes include migration from Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
Rewrite the MCP server to use the official `mcp` FastMCP SDK for
protocol compliance, centralize theming across all output surfaces,
and expand metadata extraction from all four provider parsers.
MCP server (polylogue/mcp/server.py):
- Replace hand-rolled JSON-RPC dispatch with FastMCP tool/resource/prompt
decorators for standards-compliant server implementation
- Expose tools (search, list_conversations, get_conversation, stats),
resources (polylogue://stats, conversations, conversation/{conv_id}),
and prompts (analyze_errors, summarize_week, extract_code)
- Remove 1000-char message truncation in _conversation_to_full_dict
- Lazy repository singleton via _get_repo() avoids startup cost
Theme system (polylogue/lib/theme.py):
- New centralized palette with ProviderColor and RoleColor dataclasses
carrying CSS helper methods for hex/rgb output
- PROVIDER_COLORS maps provider names to brand colors; ROLE_COLORS for
user/assistant/system/tool
- DARK_THEME and LIGHT_THEME token dictionaries for consistent UI
- rich_theme_styles() for Rich Theme integration; css_variables() for
HTML template injection
Filter pipeline (polylogue/lib/filters.py):
- Extract _apply_common_filters(), _apply_sort_generic(),
_fetch_generic(), _execute_pipeline() as generic methods
- Eliminates ~200 lines of duplicated filter/sort/sample/limit logic
between Conversation and ConversationSummary code paths
Provider extraction enhancements:
- ChatGPT: model_slug, citations, code_execution, thinking content
blocks, gizmo metadata, is_archived, end_turn
- Claude Code: cwd, gitBranch, version, model, token_usage per message;
working_directories and models_used aggregated at conversation level
- Claude AI: typed extraction via ClaudeAIConversation.model_validate()
with fallback to untyped path on validation failure
- Codex: session-level git context and system instructions in provider_meta
- Gemini: typed GeminiMessage extraction covering finishReason,
thinkingBudget, safetyRatings, grounding, branch topology, executable
code, code execution results, errorMessage, isEdited
Static site builder (polylogue/site/builder.py):
- Markdown rendering with PygmentsHighlighter and MarkdownRenderer
- Pagefind search UI wired into index template
- Incremental page generation via mtime comparison skips unchanged files
- Light-mode CSS variables and @media prefers-color-scheme support
Storage backends:
- Share SCHEMA_DDL and _VEC0_DDL constants between sync and async backends
- Extract _row_get() and _update_ref_counts() as shared helpers
- Fix vector search ranking: use min() for distance (lower=more similar)
instead of max() for score, remove incorrect reverse=True from sort
Bug fixes:
- Timestamp parsing: reject values below 86400 as epoch seconds to avoid
misinterpreting year-like integers (e.g. "2025")
- Gemini detection: add content-based check for chunkedPrompt field in
detect_provider() for direct file uploads
- Source iteration: iter_source_conversations delegates to
iter_source_conversations_with_raw(capture_raw=False), removing ~160
lines of duplicated iteration logic
Cleanup:
- Delete polylogue/schemas/claude_code_records.py and common.py
- Remove GitOperation, FileChange, SubagentSpawn from models.py
- Switch provider schemas to gzip-compressed .schema.json.gz
- Consolidate tests from 60+ files to focused set; add mcp dependency
There was a problem hiding this comment.
Pull request overview
This PR modernizes Polylogue’s MCP integration and archive fidelity by migrating to the official FastMCP SDK, enriching provider extraction to retain structured metadata, and consolidating shared plumbing (themes, filters, storage helpers). It also packages provider schemas as compressed assets, wires schema validation into ingestion, improves the static site (rendering + search + incremental builds), and fixes vector-similarity ranking semantics.
Changes:
- Replace the hand-rolled MCP JSON-RPC server with a FastMCP-based server exposing tools/resources/prompts.
- Preserve richer provider-specific metadata across parsers and propagate it through storage/rendering.
- Deduplicate and harden shared internals (theme tokens, filter pipeline, SQLite row mapping/DDL), plus site search/rendering upgrades and schema validation assets.
Reviewed changes
Copilot reviewed 58 out of 60 changed files in this pull request and generated 10 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/test_sqlite_vec.py | Adjusts sqlite-vec tests for new provider initialization behavior. |
| tests/test_schema_inference.py | Updates expected schema artifact extension to .schema.json.gz. |
| tests/test_query_execution.py | Updates text output assertions to render Rich Tables before checking content. |
| tests/test_provider_models.py | Removes merged schema-coverage tests and streamlines provider-model imports. |
| tests/test_mcp_server.py | Rewrites MCP tests for FastMCP tools/resources/prompts and helper behavior. |
| tests/test_helpers_print_summary.py | Aligns provider color expectations with shared theme palette. |
| README.md | Major CLI/API documentation refresh (commands, flags, MCP surface, roadmap). |
| pyproject.toml | Adds mcp dependency and includes compressed schemas in package data. |
| polylogue/ui/tui/screens/dashboard.py | Improves embedding stats query error handling via debug logging. |
| polylogue/ui/tui/screens/browser.py | Uses shared markdown formatter instead of bespoke message dumping. |
| polylogue/ui/tui/css/styles.tcss | Tweaks dashboard grid styling. |
| polylogue/ui/facade.py | Centralizes Rich theme styling via polylogue.lib.theme. |
| polylogue/templates/style.css | Adds light-mode CSS variables and prefers-color-scheme handling. |
| polylogue/templates/modern.html | Sets data-theme="auto" on root HTML element. |
| polylogue/templates/index.html | Updates CLI guidance from sync to run and sets data-theme="auto". |
| polylogue/storage/store.py | Adds module docstring; no functional changes in diff shown. |
| polylogue/storage/search.py | Updates “build index” error message to reference polylogue run. |
| polylogue/storage/search_providers/sqlite_vec.py | Adds table-ensuring logic and embedding metadata/status tables. |
| polylogue/storage/search_cache.py | Removes unused TYPE_CHECKING block; clarifies cache stats docstring. |
| polylogue/storage/repository.py | Fixes semantic search ranking to treat lower distance as better. |
| polylogue/storage/backends/sqlite.py | Deduplicates DDL/row mapping helpers and consolidates SQL construction. |
| polylogue/storage/backends/async_sqlite.py | Reuses shared DDL and row mappers; extends save paths for new columns. |
| polylogue/sources/source.py | Adds Gemini content-based provider detection and refactors iteration to shared helper. |
| polylogue/sources/providers/gemini.py | Preserves code-execution and edit-tracking metadata and content blocks. |
| polylogue/sources/parsers/drive.py | Uses typed Gemini parsing for chunked prompts to retain richer metadata. |
| polylogue/sources/parsers/codex.py | Captures session git/instructions and preserves structured provider_meta. |
| polylogue/sources/parsers/claude.py | Adds Claude Code metadata extraction and typed Claude AI parsing w/ fallback. |
| polylogue/sources/parsers/chatgpt.py | Preserves ChatGPT model/citations/code-execution/gizmo/archive metadata. |
| polylogue/sources/parsers/base.py | Adds module docstring; no behavioral change shown. |
| polylogue/site/builder.py | Adds Pagefind UI, markdown+syntax highlighting, and incremental page generation. |
| polylogue/schemas/validator.py | Loads provider schemas from .schema.json.gz (with plain fallback). |
| polylogue/schemas/unified.py | Removes unused GLOM_AVAILABLE flag. |
| polylogue/schemas/schema_inference.py | Writes gzipped schema assets and removes legacy uncompressed files. |
| polylogue/schemas/common.py | Deletes legacy common semantic dataclasses. |
| polylogue/schemas/claude_code_records.py | Deletes legacy Claude Code metadata record models/dispatcher. |
| polylogue/schemas/init.py | Updates package docs to reflect single rich extraction path. |
| polylogue/rendering/renderers/html.py | Removes unused TYPE_CHECKING scaffolding. |
| polylogue/rendering/core.py | Adds shared format_conversation_markdown() helper. |
| polylogue/pipeline/services/ingestion.py | Adds non-blocking schema validation during parse stage. |
| polylogue/mcp/server.py | Implements FastMCP server with tools/resources/prompts; removes truncation. |
| polylogue/lib/viewports.py | Removes unused protocol/types and computed token property. |
| polylogue/lib/timestamps.py | Avoids mis-parsing small numeric strings (e.g. “2025”) as epoch seconds. |
| polylogue/lib/theme.py | Introduces centralized theme tokens and provider/role color helpers. |
| polylogue/lib/security.py | Adds debug logging instead of silent exception swallowing. |
| polylogue/lib/models.py | Removes unused models/utilities and trims context-dump patterns. |
| polylogue/lib/filters.py | Deduplicates filter pipeline and shares logic between conversations/summaries. |
| polylogue/health.py | Adds module docstring, tightens typing, and clarifies dry-run messaging. |
| polylogue/cli/query.py | Adds Rich table output for stats-by and richer interactive rendering paths. |
| polylogue/cli/helpers.py | Uses shared provider colors instead of local hard-coded mapping. |
| polylogue/cli/commands/auth.py | Adds debug logging on config load fallback. |
| nixos-modules/sync.nix | Renames service wording and updates ExecStart to polylogue run --watch. |
| nixos-modules/polylogue.nix | Adjusts default package selection and removes legacy watch-service generator. |
| flake.nix | Drops custom overlay overrides and adds mcp to Python deps; removes unused deps. |
| docs/providers/openai-codex.md | Documents typed Codex parsing and supported formats. |
| docs/providers/gemini.md | Documents additional Gemini inputs and detection behavior. |
| docs/providers/claude-code.md | Documents typed semantic extraction and metadata aggregation. |
| docs/providers/claude-ai.md | Documents typed Claude AI parsing w/ fallback and supported inputs. |
| docs/providers/chatgpt.md | Updates docs around attachment metadata preservation. |
| .gitignore | Adds coverage_baseline.json. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # vec0 virtual table for vector storage | ||
| conn.execute(""" | ||
| CREATE VIRTUAL TABLE IF NOT EXISTS message_embeddings USING vec0( | ||
| message_id TEXT PRIMARY KEY, | ||
| embedding float[1024], | ||
| +provider_name TEXT, | ||
| +conversation_id TEXT | ||
| ) | ||
| """) |
There was a problem hiding this comment.
SqliteVecProvider._ensure_tables() hard-codes the vec0 column dimension as 1024 (embedding float[1024]). If the provider is initialized with a non-default dimension (e.g. Matryoshka reduction via self.dimension), inserts/queries will not match the table schema. Use self.dimension when generating the vec0 DDL (and ensure the existing table is migrated/validated when dimension changes).
| _VEC0_DDL = """ | ||
| CREATE VIRTUAL TABLE IF NOT EXISTS message_embeddings USING vec0( | ||
| message_id TEXT PRIMARY KEY, | ||
| embedding float[1024], | ||
| +provider_name TEXT, | ||
| +conversation_id TEXT | ||
| ) | ||
| """ |
There was a problem hiding this comment.
_VEC0_DDL hard-codes embedding float[1024]. This will be incorrect if the configured Voyage output dimension differs from 1024. Consider parameterizing the vec0 DDL based on the configured embedding dimension (and enforcing a single dimension per DB, or providing a migration strategy).
| async def _ensure_schema(self, conn: aiosqlite.Connection) -> None: | ||
| """Ensure database schema exists (same as sync version).""" | ||
| from polylogue.storage.backends.sqlite import SCHEMA_VERSION | ||
|
|
||
| await conn.executescript( | ||
| """ | ||
| CREATE TABLE IF NOT EXISTS conversations ( | ||
| conversation_id TEXT PRIMARY KEY, | ||
| provider_name TEXT NOT NULL, | ||
| provider_conversation_id TEXT NOT NULL, | ||
| title TEXT, | ||
| created_at TEXT, | ||
| updated_at TEXT, | ||
| content_hash TEXT NOT NULL, | ||
| provider_meta TEXT, | ||
| metadata TEXT DEFAULT '{}', | ||
| source_name TEXT GENERATED ALWAYS AS (json_extract(provider_meta, '$.source')) STORED, | ||
| version INTEGER NOT NULL | ||
| ); | ||
| CREATE INDEX IF NOT EXISTS idx_conversations_provider | ||
| ON conversations(provider_name, provider_conversation_id); | ||
| CREATE INDEX IF NOT EXISTS idx_conversations_source_name | ||
| ON conversations(source_name) WHERE source_name IS NOT NULL; | ||
| CREATE TABLE IF NOT EXISTS messages ( | ||
| message_id TEXT PRIMARY KEY, | ||
| conversation_id TEXT NOT NULL, | ||
| provider_message_id TEXT, | ||
| role TEXT, | ||
| text TEXT, | ||
| timestamp TEXT, | ||
| content_hash TEXT NOT NULL, | ||
| provider_meta TEXT, | ||
| version INTEGER NOT NULL, | ||
| parent_message_id TEXT, | ||
| branch_index INTEGER NOT NULL DEFAULT 0, | ||
| FOREIGN KEY (conversation_id) | ||
| REFERENCES conversations(conversation_id) ON DELETE CASCADE | ||
| ); | ||
| CREATE INDEX IF NOT EXISTS idx_messages_conversation | ||
| ON messages(conversation_id); | ||
| CREATE TABLE IF NOT EXISTS attachments ( | ||
| attachment_id TEXT PRIMARY KEY, | ||
| mime_type TEXT, | ||
| size_bytes INTEGER, | ||
| path TEXT, | ||
| ref_count INTEGER NOT NULL DEFAULT 0, | ||
| provider_meta TEXT, | ||
| UNIQUE (attachment_id) | ||
| ); | ||
| CREATE TABLE IF NOT EXISTS attachment_refs ( | ||
| ref_id TEXT PRIMARY KEY, | ||
| attachment_id TEXT NOT NULL, | ||
| conversation_id TEXT NOT NULL, | ||
| message_id TEXT, | ||
| provider_meta TEXT, | ||
| FOREIGN KEY (attachment_id) | ||
| REFERENCES attachments(attachment_id) ON DELETE CASCADE, | ||
| FOREIGN KEY (conversation_id) | ||
| REFERENCES conversations(conversation_id) ON DELETE CASCADE, | ||
| FOREIGN KEY (message_id) | ||
| REFERENCES messages(message_id) ON DELETE SET NULL | ||
| ); | ||
| CREATE INDEX IF NOT EXISTS idx_attachment_refs_conversation | ||
| ON attachment_refs(conversation_id); | ||
| CREATE INDEX IF NOT EXISTS idx_attachment_refs_message | ||
| ON attachment_refs(message_id); | ||
| CREATE TABLE IF NOT EXISTS runs ( | ||
| run_id TEXT PRIMARY KEY, | ||
| timestamp TEXT NOT NULL, | ||
| plan_snapshot TEXT, | ||
| counts_json TEXT, | ||
| drift_json TEXT, | ||
| indexed INTEGER, | ||
| duration_ms INTEGER | ||
| ); | ||
| """ | ||
| ) | ||
| """Ensure database schema exists. | ||
|
|
||
| Uses the shared ``SCHEMA_DDL`` constant (single source of truth) so | ||
| the async backend never drifts behind the canonical DDL. | ||
| """ | ||
| from polylogue.storage.backends.sqlite import SCHEMA_DDL, SCHEMA_VERSION | ||
|
|
||
| await conn.execute("PRAGMA foreign_keys = ON") | ||
| await conn.executescript(SCHEMA_DDL) | ||
| await conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}") | ||
| await conn.commit() |
There was a problem hiding this comment.
AsyncSQLiteBackend._ensure_schema() now uses SCHEMA_DDL, but it never attempts to create the vec0 virtual table when sqlite-vec is available (sync backend does this in _apply_schema). If async code paths rely on vector search/embedding tables, message_embeddings may be missing. Mirror the sqlite-vec availability check + vec0 creation here (or explicitly document that async backend doesn’t support embeddings).
| from polylogue.lib.log import get_logger | ||
| from polylogue.sources.providers.gemini import GeminiMessage | ||
|
|
||
| from .base import ParsedAttachment, ParsedConversation, ParsedMessage, normalize_role | ||
|
|
||
| _logger = get_logger(__name__) | ||
|
|
There was a problem hiding this comment.
_logger is defined but never used in this module. Ruff (F841/F401) will fail CI for unused variables/imports. Either use _logger for validation fallback diagnostics or remove it (and the get_logger import) entirely.
| except (ValidationError, Exception): | ||
| # Fallback: basic extraction for non-conforming chunks | ||
| if chunk_obj.get("isThought"): | ||
| meta["isThought"] = True | ||
| token_count = chunk_obj.get("tokenCount") | ||
| if token_count: | ||
| meta["tokenCount"] = token_count | ||
| block_type = "thinking" if chunk_obj.get("isThought") else "text" | ||
| meta["content_blocks"] = [{"type": block_type, "text": text}] |
There was a problem hiding this comment.
The exception handler catches (ValidationError, Exception), which effectively swallows all exceptions (including programming errors) and silently falls back to lossy parsing. Narrow this to ValidationError (and possibly TypeError/ValueError from bad payloads) and log the failure via _logger.debug(..., exc_info=True) so schema drift is diagnosable.
| "Schema validation errors for %s", | ||
| provider_name, | ||
| raw_id=raw_id, | ||
| errors=result.errors[:5], | ||
| ) | ||
| if result.has_drift: | ||
| logger.info( | ||
| "Schema drift detected for %s", | ||
| provider_name, | ||
| raw_id=raw_id, | ||
| drift=result.drift_warnings[:10], | ||
| ) | ||
| except Exception as exc: | ||
| logger.debug( | ||
| "Schema validation skipped for %s: %s", | ||
| provider_name, | ||
| exc, |
There was a problem hiding this comment.
These log calls mix stdlib printf-style formatting with a structlog logger returned by get_logger(). With structlog, the message will likely remain unformatted ("... %s"), and the positional arg may be dropped. Prefer logger.warning("Schema validation errors", provider=provider_name, raw_id=raw_id, errors=...) (no %-format), and include raw_id in the event explicitly (it’s currently not part of the formatted message).
| "Schema validation errors for %s", | |
| provider_name, | |
| raw_id=raw_id, | |
| errors=result.errors[:5], | |
| ) | |
| if result.has_drift: | |
| logger.info( | |
| "Schema drift detected for %s", | |
| provider_name, | |
| raw_id=raw_id, | |
| drift=result.drift_warnings[:10], | |
| ) | |
| except Exception as exc: | |
| logger.debug( | |
| "Schema validation skipped for %s: %s", | |
| provider_name, | |
| exc, | |
| "Schema validation errors", | |
| provider=provider_name, | |
| raw_id=raw_id, | |
| errors=result.errors[:5], | |
| ) | |
| if result.has_drift: | |
| logger.info( | |
| "Schema drift detected", | |
| provider=provider_name, | |
| raw_id=raw_id, | |
| drift=result.drift_warnings[:10], | |
| ) | |
| except Exception as exc: | |
| logger.debug( | |
| "Schema validation skipped", | |
| provider=provider_name, | |
| raw_id=raw_id, | |
| error=str(exc), |
| @mcp.tool() | ||
| def search( | ||
| query: str, | ||
| limit: int = 10, | ||
| provider: str | None = None, | ||
| since: str | None = None, | ||
| ) -> str: | ||
| """Search conversations by text query. Returns matching conversations with metadata. | ||
|
|
||
| Args: | ||
| query: Full-text search query | ||
| limit: Max results (default: 10) | ||
| provider: Filter by provider (claude, chatgpt, claude-code, etc.) | ||
| since: Only conversations updated after this date (ISO format or natural language like 'last week') | ||
| """ | ||
| from polylogue.lib.filters import ConversationFilter | ||
|
|
||
| repo = _get_repo() | ||
| limit = _clamp_limit(limit) | ||
|
|
||
| filter_chain = ConversationFilter(repo).contains(query).limit(limit) | ||
| if provider: | ||
| filter_chain = filter_chain.provider(provider) | ||
| if since: | ||
| filter_chain = filter_chain.since(since) | ||
| except ValueError as exc: | ||
| return _error(request_id, -32602, f"Invalid date: {exc}") | ||
| if tag: | ||
| filter_chain = filter_chain.tag(tag) | ||
|
|
||
| filter_chain = filter_chain.limit(limit) | ||
|
|
||
| # Execute query | ||
| convs = filter_chain.list() | ||
| convs_data = [_conversation_to_dict(c) for c in convs] | ||
|
|
There was a problem hiding this comment.
search() doesn’t validate that query is non-empty. Calling .contains("") will typically degrade to an expensive/ill-defined FTS query and differs from the previous behavior where query was required. Add a guard (raise a FastMCP/tool error) when query is empty/whitespace.
| repo = _get_repo() | ||
| conv = repo.view(id) | ||
| if conv is None: | ||
| return json.dumps({"error": f"Conversation not found: {id}"}) |
There was a problem hiding this comment.
get_conversation() returns a JSON string with an error field on not-found, which MCP clients will treat as a successful tool call returning arbitrary text. Prefer raising an MCP/FastMCP error (or returning a typed error response if the SDK supports it) so clients can handle failures via protocol-level errors.
| repo = _get_repo() | |
| conv = repo.view(id) | |
| if conv is None: | |
| return json.dumps({"error": f"Conversation not found: {id}"}) | |
| from mcp.server.fastmcp.exceptions import ToolError | |
| repo = _get_repo() | |
| conv = repo.view(id) | |
| if conv is None: | |
| raise ToolError(f"Conversation not found: {id}") |
| # Incremental: skip if page exists and is newer than conversation update | ||
| if incremental and page_path.exists(): | ||
| if conv_idx.updated_at: | ||
| try: | ||
| from datetime import datetime | ||
|
|
||
| file_mtime = datetime.fromtimestamp(page_path.stat().st_mtime) | ||
| conv_updated = datetime.fromisoformat(conv_idx.updated_at) | ||
| if file_mtime > conv_updated: | ||
| generated += 1 | ||
| continue | ||
| except (ValueError, OSError): | ||
| pass # Parse/stat error — rebuild this page |
There was a problem hiding this comment.
Incremental rebuild compares a naive local file_mtime (datetime.fromtimestamp) to conv_idx.updated_at parsed from a timezone-less string. Since updated_at strings are derived from possibly tz-aware datetimes earlier, this can cause incorrect skip/rebuild decisions across timezones/DST. Prefer comparing epoch seconds (page_path.stat().st_mtime vs conversation.updated_at.timestamp()) or ensure both values are timezone-aware UTC before comparing.
| server = _build_server() | ||
| # Get the tool function from the server | ||
| search_fn = server._tool_manager._tools["search"].fn | ||
| result = search_fn(query="hello", limit=10) |
There was a problem hiding this comment.
These tests reach into FastMCP private internals (server._tool_manager._tools[...]). Private attributes are not API-stable and may break on SDK upgrades. Prefer exercising the public MCP call surface (or expose the tool callables explicitly from polylogue.mcp.server for testing) so the tests validate behavior without depending on internal manager structures.
There was a problem hiding this comment.
Actionable comments posted: 18
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@nixos-modules/sync.nix`:
- Around line 7-8: Rename or document the service to avoid confusion between the
option name and the command: either change the Nix option and service
identifiers from options.services.polylogue-sync to
options.services.polylogue-run (and update any related unit/service names and
documentation) or add a clear comment/docstring next to the enable option
explaining that the service runs "polylogue run --watch" despite the
"polylogue-sync" name; update any README or module description text accordingly
so users understand the naming discrepancy.
In `@polylogue/cli/query.py`:
- Around line 896-903: The provider color is being added as literal markup text;
instead append the provider string using the Text.append style parameter instead
of inline markup. Locate the header Text construction (variables: title, pc from
provider_color, header, conv.provider, conv.display_date) and replace the append
that currently adds f" [{pc.hex}]{conv.provider}[/{pc.hex}]" with a call that
appends the provider text (including the leading spaces) and passes style=pc.hex
so the color is applied correctly.
In `@polylogue/lib/timestamps.py`:
- Around line 35-41: The branch that treats numeric strings as epoch seconds
should be reordered so ISO 8601 parsing runs first: call
datetime.fromisoformat(value) (catching ValueError) before the numeric-epoch
block that checks value.replace(".", "").isdigit(); if fromisoformat succeeds
return that datetime, otherwise fall back; also tighten the epoch heuristic in
the fallback (e.g., require 10-digit seconds or 13-digit milliseconds) when
using datetime.fromtimestamp(float(value)) to avoid misclassifying compact ISO
strings like "20250101"; update the logic around the variable value and the
calls to datetime.fromisoformat and datetime.fromtimestamp accordingly.
In `@polylogue/mcp/server.py`:
- Around line 164-175: Rename the get_conversation parameter that currently
shadows the builtin id to a clearer name (e.g., conversation_id or convo_id) and
update all uses inside the function (the signature of get_conversation, the
docstring arg name, the repo.view(id) call, and the error message interpolation
and return) to use the new identifier; ensure references to _get_repo(), conv,
and _conversation_to_full_dict(conv) remain unchanged and the mcp.tool()
decorator is preserved.
In `@polylogue/rendering/core.py`:
- Around line 260-288: format_conversation_markdown currently skips messages
with empty or whitespace-only text before checking attachments, which drops
attachment-only messages; change the logic in the loop over conv.messages
(inside format_conversation_markdown) to defer the continue until after the
attachments check or explicitly handle attachment-only messages by moving the
"if hasattr(msg, 'attachments') and msg.attachments" block above the empty-text
continue so that messages with no text but with attachments still get rendered
(e.g., emit the role/timestamp and the "**Attachments:**" line) rather than
being skipped.
In `@polylogue/schemas/schema_inference.py`:
- Around line 467-469: The legacy file deletion at legacy_path.unlink() should
be best-effort: wrap the unlink call in a try/except that catches OSError (and
subclasses) so a failure to remove the legacy file does not abort the run; on
exception, swallow it or emit a non-fatal warning (using the module logger if
available) that includes the exception message and the legacy_path, then
continue. Ensure you modify the block around legacy_path, output_dir and
provider so the new .gz schema write is not impacted by unlink failures.
In `@polylogue/site/builder.py`:
- Around line 869-885: The incremental freshness check is comparing page file
mtime against conv_idx.updated_at (a display string), causing wrong skips;
change to store and use a raw timestamp/datetime for comparisons (e.g.,
conv_idx.updated_at_raw or conv_idx.updated_ts as an ISO/epoch datetime) in the
block around page_path.stat() and datetime.fromisoformat so you compare proper
datetimes/epochs, and only use conv_idx.updated_at as a formatted display string
in templates; also update the else branch so absence of a raw timestamp does not
permanently skip rebuilding (treat missing raw timestamp as stale so page
rebuilds).
- Around line 243-250: The Pagefind UI block is always emitted but should only
be rendered when search is enabled and the configured provider is Pagefind;
update the template emission in builder.py so that the div and the PagefindUI
script block (the element selector "#search" and the new PagefindUI(...)
initialization) are wrapped in a conditional checking the site's search config
(the same condition used by _generate_search_index()) and only included if
provider == "pagefind" and enable_search is True; also replace the hard-coded
"/_pagefind/..." asset URLs with deployment-safe relative paths or the site's
static URL helper so the pagefind UI loads from the correct base rather than
root.
In `@polylogue/sources/parsers/chatgpt.py`:
- Around line 196-198: The code only sets conv_meta["is_archived"] when
is_archived is True, losing explicit False; change the branch so that when
payload.get("is_archived") exists and is a bool you assign
conv_meta["is_archived"] = is_archived (i.e., preserve both True and False)
instead of only setting it for True; update the logic around the is_archived
local variable where payload is read so the metadata retains the boolean value.
In `@polylogue/sources/parsers/codex.py`:
- Around line 91-96: The code calls CodexRecord.model_validate(record.payload)
without handling validation failures, so a malformed session meta can raise and
abort parsing; wrap the inner validation in a try/except catching
ValidationError (from pydantic or the validation lib used) around
CodexRecord.model_validate(record.payload), and only set session_git and
session_instructions if validation succeeds—on ValidationError just skip
enrichment (leave session_git/session_instructions unchanged) and continue
parsing.
In `@polylogue/sources/parsers/drive.py`:
- Around line 147-156: The current creation of content_blocks flattens each
gem.extract_content_blocks() item to only {"type","text"} and filters out blocks
with empty text, which loses per-block metadata (e.g., CODE.language,
FILE.inline-data) and drops non-text blocks; instead, serialize each cb
preserving all its fields (or call its dict/serialization method) rather than
constructing a new {"type","text"} map, do not filter out blocks solely because
text is empty (so FILE/inline-data blocks remain), and still normalize the type
into a string (use cb.type.value if present) — update the logic around
content_blocks and the fallback that sets meta["content_blocks"] so the richer
block properties are retained.
In `@polylogue/sources/providers/gemini.py`:
- Around line 240-248: The current code appends inline code execution outputs
using ContentType.TOOL_RESULT (in the codeExecutionResult handling), which
causes Message.is_tool_use() to classify entire assistant turns with any normal
text as tool-only and therefore hide them from
without_noise()/substantive_only(); change the block type from
ContentType.TOOL_RESULT to a distinct type (e.g., ContentType.INLINE_TOOL_RESULT
or ContentType.TOOL_RESULT_INLINE) when creating the ContentBlock for
self.codeExecutionResult, and update the Message.is_tool_use() logic (and any
filters used by without_noise()/substantive_only()) to treat this new
inline-tool block type as non-noise so inline execution output does not suppress
regular assistant text.
In `@polylogue/storage/backends/sqlite.py`:
- Around line 118-128: The _update_ref_counts function is performing one UPDATE
per attachment_id which is slow for large batches; change it to execute a single
UPDATE that sets attachments.ref_count = (SELECT COUNT(*) FROM attachment_refs
WHERE attachment_refs.attachment_id = attachments.attachment_id) with a WHERE
attachment_id IN (...) clause using the attachment_ids set; build the parameter
placeholders from attachment_ids and call conn.execute once (still
parameterized) so attachments and attachment_refs are updated in one pass.
In `@polylogue/storage/search_providers/sqlite_vec.py`:
- Around line 161-168: The CREATE VIRTUAL TABLE for message_embeddings hardcodes
embedding size as float[1024], which will break when
_get_embeddings()/self.dimension uses a different output dimension; update the
schema creation in sqlite_vec.py to use the configured dimension
(self.dimension) instead of 1024 when building the vec0(...) column type and
recreate or migrate the table accordingly so inserts/queries match the
provider's embedding size; locate the CREATE VIRTUAL TABLE statement that
defines message_embeddings and substitute the hardcoded float[1024] with the
dynamic dimension from the provider initialization (the same value used by
_get_embeddings()).
- Around line 319-320: The provider-filtered search can hit "no such table:
message_embeddings" because query_by_provider() doesn't call the schema gate;
update query_by_provider() to call self._ensure_tables() at the start (same
pattern used in the generic search paths) so the message_embeddings table is
created before any SELECTs; make the same change wherever query_by_provider() is
invoked or any provider-filtered search path exists to ensure the schema is
initialized before access.
In `@polylogue/templates/style.css`:
- Around line 208-240: The h1 gradient in the `@media` (prefers-color-scheme:
light) block is unscoped and applies regardless of the document theme; scope it
to the light theme by targeting the light theme selector (e.g.,
:root:not([data-theme="dark"]) h1 or [data-theme="light"] h1) inside the media
query so the linear-gradient styles only apply when both the OS prefers light
and the page theme is light; update the h1 rule accordingly near the existing
:root:not([data-theme="dark"]) block to ensure the dark theme is never affected.
In `@tests/test_mcp_server.py`:
- Around line 1043-1088: The test currently swallows both exception and
non-exception paths; change test_search_error_cases so each branch asserts an
expected outcome: for case_type == "invalid_since" wrap the call to
server._tool_manager._tools["search"].fn(**args) in pytest.raises(ValueError)
when you expect an exception, and if no exception is raised parse the returned
JSON and assert it contains an "error" key and that the error message contains
the error_keyword; similarly for the other branch (e.g., "invalid_limit_type")
use pytest.raises(TypeError) where appropriate or else parse the JSON and assert
"error" in parsed and error_keyword is present; keep use of _build_server,
make_mock_filter and patched ConversationFilter the same but replace the
try/except pass blocks with these explicit assertions.
In `@tests/test_query_execution.py`:
- Around line 893-894: The test loops use the builtin name `id` as a loop
variable (e.g., "for id in expected_ids: assert id in rendered"), which shadows
Python's id(); rename the loop variable to a non-builtin name such as
`expected_id` (or `eid`) and update all usages in those loops (references to
`id` in asserts) — apply the same rename for the other occurrences tied to
`expected_ids` at the other two locations so `expected_id` is used consistently
instead of `id`.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: d85c2511-5a7f-4804-8e4d-d7bb157fcf40
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock,!**/*.lock
📒 Files selected for processing (59)
.gitignoreREADME.mddocs/providers/chatgpt.mddocs/providers/claude-ai.mddocs/providers/claude-code.mddocs/providers/gemini.mddocs/providers/openai-codex.mdflake.nixnixos-modules/polylogue.nixnixos-modules/sync.nixpolylogue/cli/commands/auth.pypolylogue/cli/helpers.pypolylogue/cli/query.pypolylogue/health.pypolylogue/lib/filters.pypolylogue/lib/models.pypolylogue/lib/security.pypolylogue/lib/theme.pypolylogue/lib/timestamps.pypolylogue/lib/viewports.pypolylogue/mcp/server.pypolylogue/pipeline/services/ingestion.pypolylogue/rendering/core.pypolylogue/rendering/renderers/html.pypolylogue/schemas/__init__.pypolylogue/schemas/claude_code_records.pypolylogue/schemas/common.pypolylogue/schemas/schema_inference.pypolylogue/schemas/unified.pypolylogue/schemas/validator.pypolylogue/site/builder.pypolylogue/sources/parsers/base.pypolylogue/sources/parsers/chatgpt.pypolylogue/sources/parsers/claude.pypolylogue/sources/parsers/codex.pypolylogue/sources/parsers/drive.pypolylogue/sources/providers/gemini.pypolylogue/sources/source.pypolylogue/storage/backends/async_sqlite.pypolylogue/storage/backends/sqlite.pypolylogue/storage/repository.pypolylogue/storage/search.pypolylogue/storage/search_cache.pypolylogue/storage/search_providers/sqlite_vec.pypolylogue/storage/store.pypolylogue/templates/index.htmlpolylogue/templates/modern.htmlpolylogue/templates/style.csspolylogue/ui/facade.pypolylogue/ui/tui/css/styles.tcsspolylogue/ui/tui/screens/browser.pypolylogue/ui/tui/screens/dashboard.pypyproject.tomltests/test_helpers_print_summary.pytests/test_mcp_server.pytests/test_provider_models.pytests/test_query_execution.pytests/test_schema_inference.pytests/test_sqlite_vec.py
💤 Files with no reviewable changes (5)
- polylogue/rendering/renderers/html.py
- polylogue/ui/tui/css/styles.tcss
- polylogue/schemas/unified.py
- polylogue/schemas/common.py
- polylogue/schemas/claude_code_records.py
| options.services.polylogue-sync = { | ||
| enable = lib.mkEnableOption "Polylogue sync --watch service"; | ||
| enable = lib.mkEnableOption "Polylogue run --watch service"; |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider renaming the service for clarity.
The service is now named polylogue-sync but runs polylogue run --watch. This may cause confusion for users. Consider whether a future rename to polylogue-run would be appropriate, or document this naming discrepancy.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@nixos-modules/sync.nix` around lines 7 - 8, Rename or document the service to
avoid confusion between the option name and the command: either change the Nix
option and service identifiers from options.services.polylogue-sync to
options.services.polylogue-run (and update any related unit/service names and
documentation) or add a clear comment/docstring next to the enable option
explaining that the service runs "polylogue run --watch" despite the
"polylogue-sync" name; update any README or module description text accordingly
so users understand the naming discrepancy.
| title = conv.display_title or conv.id | ||
| pc = provider_color(conv.provider) | ||
| header = Text() | ||
| header.append(title, style="bold") | ||
| if conv.display_date: | ||
| header.append(f" {conv.display_date.strftime('%Y-%m-%d %H:%M')}", style="dim") | ||
| header.append(f" [{pc.hex}]{conv.provider}[/{pc.hex}]") | ||
| console.print(header) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
python -m pip install --quiet rich >/dev/null
python - <<'PY'
from rich.text import Text
t = Text()
t.append("[`#10a37f`]chatgpt[/#10a37f]")
print("append_plain:", t.plain)
print("append_spans:", t.spans)
parsed = Text.from_markup("[`#10a37f`]chatgpt[/#10a37f]")
print("from_markup_plain:", parsed.plain)
print("from_markup_spans:", parsed.spans)
PYRepository: Sinity/polylogue
Length of output: 187
🏁 Script executed:
cd polylogue/cli && wc -l query.pyRepository: Sinity/polylogue
Length of output: 73
🏁 Script executed:
cd polylogue/cli && sed -n '890,910p' query.pyRepository: Sinity/polylogue
Length of output: 659
🏁 Script executed:
# Search for provider_color function definition
rg "def provider_color" polylogue/Repository: Sinity/polylogue
Length of output: 130
🏁 Script executed:
# Check the ProviderColor class and provider_color function
rg "class ProviderColor|def provider_color" polylogue/lib/theme.py -A 10Repository: Sinity/polylogue
Length of output: 771
🏁 Script executed:
# Check if there are other examples of styling in this file
rg "header.append|Text\(\)" polylogue/cli/query.py -B 2 -A 2Repository: Sinity/polylogue
Length of output: 420
Apply the provider color via style, not inline markup text.
header is a Text object, so line 902 appends the literal string [#hex]provider[/#hex] instead of parsing it. The provider label will render with brackets rather than the intended color.
Proposed fix
- header.append(f" [{pc.hex}]{conv.provider}[/{pc.hex}]")
+ header.append(f" {conv.provider}", style=pc.hex)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli/query.py` around lines 896 - 903, The provider color is being
added as literal markup text; instead append the provider string using the
Text.append style parameter instead of inline markup. Locate the header Text
construction (variables: title, pc from provider_color, header, conv.provider,
conv.display_date) and replace the append that currently adds f"
[{pc.hex}]{conv.provider}[/{pc.hex}]" with a call that appends the provider text
(including the leading spaces) and passes style=pc.hex so the color is applied
correctly.
| # Check if it looks like an epoch (all digits, possibly with decimal). | ||
| # Realistic epoch range: 1970-01-02 through ~2100 (86400 to 4102444800). | ||
| # Values below 86400 (like "2025") would be misinterpreted as year strings. | ||
| if value.replace(".", "").isdigit(): | ||
| return datetime.fromtimestamp(float(value), tz=timezone.utc) | ||
| epoch_f = float(value) | ||
| if epoch_f >= 86400: | ||
| return datetime.fromtimestamp(epoch_f, tz=timezone.utc) |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
In Python's datetime module, does datetime.fromisoformat accept compact ISO forms like "20250101" or "20250101T120000"? Please cite official Python docs/examples.
💡 Result:
Yes. datetime.datetime.fromisoformat() accepts the basic/compact ISO 8601 forms (no dashes/colons), including:
- Date only:
YYYYMMDD(e.g.,20111104) →datetime(2011, 11, 4, 0, 0)[1] - Date + time:
YYYYMMDDThhmmss(e.g.,20111104T000523) →datetime(2011, 11, 4, 0, 5, 23)[1]
So your examples "20250101" and "20250101T120000" are accepted in the same way (as shown by the official docs’ examples of YYYYMMDD and YYYYMMDDThhmmss) [1].
Note: the docs also state this broader ISO 8601 acceptance was expanded in Python 3.11; earlier versions only supported formats emitted by date.isoformat() / datetime.isoformat() [1].
Sources:
[1] Python docs — datetime.datetime.fromisoformat() examples and version note (shows 20111104 and 20111104T000523) https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat
🏁 Script executed:
# First, let's locate and examine the timestamps.py file
find . -name "timestamps.py" -type fRepository: Sinity/polylogue
Length of output: 89
🏁 Script executed:
# Read the file to see the current implementation around lines 35-41
cat -n ./polylogue/lib/timestamps.py | head -50Repository: Sinity/polylogue
Length of output: 2153
🏁 Script executed:
# Check Python version requirements
fd -e "setup.py" -e "pyproject.toml" -e "requirements.txt" -e ".python-version" | head -10Repository: Sinity/polylogue
Length of output: 42
🏁 Script executed:
# Check root directory for Python version config files
ls -la | grep -E "setup|pyproject|requirements|.python"Repository: Sinity/polylogue
Length of output: 126
🏁 Script executed:
# Check the pyproject.toml for Python version requirements
cat pyproject.tomlRepository: Sinity/polylogue
Length of output: 4028
🏁 Script executed:
# Check if there are any tests for the parse_timestamp function
find . -name "*.py" -path "*/test*" -exec grep -l "parse_timestamp" {} \;Repository: Sinity/polylogue
Length of output: 138
🏁 Script executed:
# Check the test files for parse_timestamp tests
cat -n ./tests/test_core.py | grep -A 30 "parse_timestamp"Repository: Sinity/polylogue
Length of output: 5342
🏁 Script executed:
# Find the parametrize decorator for test_parse_timestamp_formats
cat -n ./tests/test_core.py | sed -n '1250,1290p'Repository: Sinity/polylogue
Length of output: 2163
🏁 Script executed:
# Check the complete test case parameters to see if there are any compact ISO tests
cat -n ./tests/test_core.py | sed -n '1268,1285p'Repository: Sinity/polylogue
Length of output: 1101
🏁 Script executed:
# Let's verify the actual behavior with a test script
python3 << 'EOF'
from datetime import datetime, timezone
# Test 1: Can Python 3.10+ parse compact ISO dates?
test_compact = "20250101"
test_compact_with_time = "20250101T120000"
print(f"Python version check:")
import sys
print(f" Python: {sys.version}")
print(f"\nTest 1: fromisoformat with compact forms")
try:
result = datetime.fromisoformat(test_compact)
print(f" '{test_compact}' -> {result} ✓ SUPPORTED")
except ValueError as e:
print(f" '{test_compact}' -> ValueError: {e} ✗ NOT SUPPORTED")
try:
result = datetime.fromisoformat(test_compact_with_time)
print(f" '{test_compact_with_time}' -> {result} ✓ SUPPORTED")
except ValueError as e:
print(f" '{test_compact_with_time}' -> ValueError: {e} ✗ NOT SUPPORTED")
print(f"\nTest 2: Current code behavior with '20250101'")
value = "20250101"
if value.replace(".", "").isdigit():
epoch_f = float(value)
if epoch_f >= 86400:
result = datetime.fromtimestamp(epoch_f, tz=timezone.utc)
print(f" Treated as epoch: {epoch_f} -> {result}")
print(f" This is WRONG - should be 2025-01-01")
print(f"\nTest 3: Numeric value check")
print(f" '20250101' as float: {float('20250101')}")
print(f" Is >= 86400? {float('20250101') >= 86400} (yes, so treated as epoch)")
EOFRepository: Sinity/polylogue
Length of output: 542
🏁 Script executed:
# Check if there's any Python version checking in the timestamps module
cat -n ./polylogue/lib/timestamps.pyRepository: Sinity/polylogue
Length of output: 3235
🏁 Script executed:
# Verify Python 3.10 support for compact ISO forms
python3 << 'EOF'
import sys
print(f"Python {sys.version}")
# According to web search, compact forms supported in Python 3.11+
# Let's check what the docs say about version requirements
from datetime import datetime
test_cases = [
"20250101",
"20250101T120000",
]
print("\nTesting compact ISO forms in current Python:")
for test in test_cases:
try:
result = datetime.fromisoformat(test)
print(f" '{test}' -> {result} ✓")
except ValueError as e:
print(f" '{test}' -> ValueError ✗")
# The web search result states: "this broader ISO 8601 acceptance was expanded in Python 3.11"
# This means Python 3.10 does NOT support compact forms
EOFRepository: Sinity/polylogue
Length of output: 245
Move ISO 8601 parsing before epoch numeric parsing to correctly handle compact date formats.
The current epoch-first approach misclassifies compact ISO dates like "20250101" and "20250101T120000" as epoch seconds. Since datetime.fromisoformat() supports these compact formats in Python 3.11+ (and the project requires Python ≥3.10), parsing should attempt ISO formats first, falling back to epoch only for truly numeric-looking timestamps.
Current behavior example: "20250101" is treated as epoch 20250101.0 seconds → 1970-08-23 (incorrect; should be 2025-01-01).
The proposed reordering is safe across Python versions:
- Python 3.11+: Compact ISO forms parse correctly via
fromisoformat() - Python 3.10: Compact ISO forms raise
ValueErrorinfromisoformat(), falling back to epoch parsing (no regression)
Consider also refining the epoch heuristic to be stricter (e.g., requiring 10 or 13 digits for sec/ms timestamps) rather than accepting any numeric string ≥ 86400.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/lib/timestamps.py` around lines 35 - 41, The branch that treats
numeric strings as epoch seconds should be reordered so ISO 8601 parsing runs
first: call datetime.fromisoformat(value) (catching ValueError) before the
numeric-epoch block that checks value.replace(".", "").isdigit(); if
fromisoformat succeeds return that datetime, otherwise fall back; also tighten
the epoch heuristic in the fallback (e.g., require 10-digit seconds or 13-digit
milliseconds) when using datetime.fromtimestamp(float(value)) to avoid
misclassifying compact ISO strings like "20250101"; update the logic around the
variable value and the calls to datetime.fromisoformat and
datetime.fromtimestamp accordingly.
| @mcp.tool() | ||
| def get_conversation(id: str) -> str: | ||
| """Get a conversation by ID (supports prefix matching). Returns full message content. | ||
|
|
||
| Args: | ||
| id: Conversation ID or unique prefix | ||
| """ | ||
| repo = _get_repo() | ||
| conv = repo.view(id) | ||
| if conv is None: | ||
| return json.dumps({"error": f"Conversation not found: {id}"}) | ||
| return json.dumps(_conversation_to_full_dict(conv), indent=2) |
There was a problem hiding this comment.
Rename id parameter to avoid shadowing Python builtin.
The parameter name id shadows the Python builtin id() function. While this won't cause runtime issues in this context, it's a best practice violation.
Proposed fix
`@mcp.tool`()
- def get_conversation(id: str) -> str:
+ def get_conversation(conversation_id: str) -> str:
"""Get a conversation by ID (supports prefix matching). Returns full message content.
Args:
- id: Conversation ID or unique prefix
+ conversation_id: Conversation ID or unique prefix
"""
repo = _get_repo()
- conv = repo.view(id)
+ conv = repo.view(conversation_id)
if conv is None:
- return json.dumps({"error": f"Conversation not found: {id}"})
+ return json.dumps({"error": f"Conversation not found: {conversation_id}"})
return json.dumps(_conversation_to_full_dict(conv), indent=2)📝 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.
| @mcp.tool() | |
| def get_conversation(id: str) -> str: | |
| """Get a conversation by ID (supports prefix matching). Returns full message content. | |
| Args: | |
| id: Conversation ID or unique prefix | |
| """ | |
| repo = _get_repo() | |
| conv = repo.view(id) | |
| if conv is None: | |
| return json.dumps({"error": f"Conversation not found: {id}"}) | |
| return json.dumps(_conversation_to_full_dict(conv), indent=2) | |
| `@mcp.tool`() | |
| def get_conversation(conversation_id: str) -> str: | |
| """Get a conversation by ID (supports prefix matching). Returns full message content. | |
| Args: | |
| conversation_id: Conversation ID or unique prefix | |
| """ | |
| repo = _get_repo() | |
| conv = repo.view(conversation_id) | |
| if conv is None: | |
| return json.dumps({"error": f"Conversation not found: {conversation_id}"}) | |
| return json.dumps(_conversation_to_full_dict(conv), indent=2) |
🧰 Tools
🪛 Ruff (0.15.9)
[error] 165-165: Function argument id is shadowing a Python builtin
(A002)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/mcp/server.py` around lines 164 - 175, Rename the get_conversation
parameter that currently shadows the builtin id to a clearer name (e.g.,
conversation_id or convo_id) and update all uses inside the function (the
signature of get_conversation, the docstring arg name, the repo.view(id) call,
and the error message interpolation and return) to use the new identifier;
ensure references to _get_repo(), conv, and _conversation_to_full_dict(conv)
remain unchanged and the mcp.tool() decorator is preserved.
| for msg in conv.messages: | ||
| role = (msg.role.value if hasattr(msg.role, "value") else str(msg.role)) if msg.role else "unknown" | ||
| text = msg.text or "" | ||
|
|
||
| if not text.strip(): | ||
| continue | ||
|
|
||
| lines.append(f"## {role}") | ||
| if hasattr(msg, "timestamp") and msg.timestamp: | ||
| lines.append(f"_{msg.timestamp}_") | ||
| lines.append("") | ||
|
|
||
| # Wrap raw JSON in code blocks | ||
| stripped = text.strip() | ||
| if (stripped.startswith("{") and stripped.endswith("}")) or ( | ||
| stripped.startswith("[") and stripped.endswith("]") | ||
| ): | ||
| try: | ||
| parsed = json.loads(stripped) | ||
| text = f"```json\n{json.dumps(parsed, indent=2)}\n```" | ||
| except json.JSONDecodeError: | ||
| pass | ||
|
|
||
| lines.append(text) | ||
| lines.append("") | ||
|
|
||
| if hasattr(msg, "attachments") and msg.attachments: | ||
| lines.append(f"**Attachments:** {len(msg.attachments)}") | ||
| lines.append("") |
There was a problem hiding this comment.
Don't skip attachment-only messages in format_conversation_markdown().
The early continue runs before the attachment block, so messages with empty text but non-empty attachments disappear entirely in this new formatter. The existing _format_markdown() path preserves those messages, so this introduces a rendering regression.
Suggested fix
for msg in conv.messages:
role = (msg.role.value if hasattr(msg.role, "value") else str(msg.role)) if msg.role else "unknown"
text = msg.text or ""
+ msg_attachments = getattr(msg, "attachments", None) or []
- if not text.strip():
+ if not text.strip() and not msg_attachments:
continue
lines.append(f"## {role}")
if hasattr(msg, "timestamp") and msg.timestamp:
lines.append(f"_{msg.timestamp}_")
@@
- if hasattr(msg, "attachments") and msg.attachments:
- lines.append(f"**Attachments:** {len(msg.attachments)}")
+ if msg_attachments:
+ lines.append(f"**Attachments:** {len(msg_attachments)}")
lines.append("")📝 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.
| for msg in conv.messages: | |
| role = (msg.role.value if hasattr(msg.role, "value") else str(msg.role)) if msg.role else "unknown" | |
| text = msg.text or "" | |
| if not text.strip(): | |
| continue | |
| lines.append(f"## {role}") | |
| if hasattr(msg, "timestamp") and msg.timestamp: | |
| lines.append(f"_{msg.timestamp}_") | |
| lines.append("") | |
| # Wrap raw JSON in code blocks | |
| stripped = text.strip() | |
| if (stripped.startswith("{") and stripped.endswith("}")) or ( | |
| stripped.startswith("[") and stripped.endswith("]") | |
| ): | |
| try: | |
| parsed = json.loads(stripped) | |
| text = f"```json\n{json.dumps(parsed, indent=2)}\n```" | |
| except json.JSONDecodeError: | |
| pass | |
| lines.append(text) | |
| lines.append("") | |
| if hasattr(msg, "attachments") and msg.attachments: | |
| lines.append(f"**Attachments:** {len(msg.attachments)}") | |
| lines.append("") | |
| for msg in conv.messages: | |
| role = (msg.role.value if hasattr(msg.role, "value") else str(msg.role)) if msg.role else "unknown" | |
| text = msg.text or "" | |
| msg_attachments = getattr(msg, "attachments", None) or [] | |
| if not text.strip() and not msg_attachments: | |
| continue | |
| lines.append(f"## {role}") | |
| if hasattr(msg, "timestamp") and msg.timestamp: | |
| lines.append(f"_{msg.timestamp}_") | |
| lines.append("") | |
| # Wrap raw JSON in code blocks | |
| stripped = text.strip() | |
| if (stripped.startswith("{") and stripped.endswith("}")) or ( | |
| stripped.startswith("[") and stripped.endswith("]") | |
| ): | |
| try: | |
| parsed = json.loads(stripped) | |
| text = f" |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/rendering/core.py` around lines 260 - 288,
format_conversation_markdown currently skips messages with empty or
whitespace-only text before checking attachments, which drops attachment-only
messages; change the logic in the loop over conv.messages (inside
format_conversation_markdown) to defer the continue until after the attachments
check or explicitly handle attachment-only messages by moving the "if
hasattr(msg, 'attachments') and msg.attachments" block above the empty-text
continue so that messages with no text but with attachments still get rendered
(e.g., emit the role/timestamp and the "**Attachments:**" line) rather than
being skipped.
| conn.execute(""" | ||
| CREATE VIRTUAL TABLE IF NOT EXISTS message_embeddings USING vec0( | ||
| message_id TEXT PRIMARY KEY, | ||
| embedding float[1024], | ||
| +provider_name TEXT, | ||
| +conversation_id TEXT | ||
| ) | ||
| """) |
There was a problem hiding this comment.
Use the configured embedding dimension in the vec0 schema.
Line 164 hardcodes float[1024], but _get_embeddings() can request a different output_dimension via self.dimension. A provider initialized with dimension != 1024 will generate vectors that no longer match the table schema and will fail at insert/query time.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/search_providers/sqlite_vec.py` around lines 161 - 168, The
CREATE VIRTUAL TABLE for message_embeddings hardcodes embedding size as
float[1024], which will break when _get_embeddings()/self.dimension uses a
different output dimension; update the schema creation in sqlite_vec.py to use
the configured dimension (self.dimension) instead of 1024 when building the
vec0(...) column type and recreate or migrate the table accordingly so
inserts/queries match the provider's embedding size; locate the CREATE VIRTUAL
TABLE statement that defines message_embeddings and substitute the hardcoded
float[1024] with the dynamic dimension from the provider initialization (the
same value used by _get_embeddings()).
| self._ensure_tables() | ||
|
|
There was a problem hiding this comment.
Apply the new schema gate to query_by_provider() too.
Lines 319 and 412 add _ensure_tables() for the generic paths, but query_by_provider() still reads message_embeddings without it. Provider-filtered search on a brand-new database can still raise no such table: message_embeddings.
Also applies to: 412-413
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/search_providers/sqlite_vec.py` around lines 319 - 320, The
provider-filtered search can hit "no such table: message_embeddings" because
query_by_provider() doesn't call the schema gate; update query_by_provider() to
call self._ensure_tables() at the start (same pattern used in the generic search
paths) so the message_embeddings table is created before any SELECTs; make the
same change wherever query_by_provider() is invoked or any provider-filtered
search path exists to ensure the schema is initialized before access.
| /* Light Mode */ | ||
| [data-theme="light"] { | ||
| --bg-primary: #ffffff; | ||
| --bg-secondary: #f9fafb; | ||
| --bg-elevated: #f3f4f6; | ||
| --text-primary: #111827; | ||
| --text-secondary: #4b5563; | ||
| --accent: #4f46e5; | ||
| --accent-glow: rgba(79, 70, 229, 0.2); | ||
| --border: #e5e7eb; | ||
| --glass: rgba(0, 0, 0, 0.03); | ||
| --glass-border: rgba(0, 0, 0, 0.08); | ||
| } | ||
|
|
||
| @media (prefers-color-scheme: light) { | ||
| :root:not([data-theme="dark"]) { | ||
| --bg-primary: #ffffff; | ||
| --bg-secondary: #f9fafb; | ||
| --bg-elevated: #f3f4f6; | ||
| --text-primary: #111827; | ||
| --text-secondary: #4b5563; | ||
| --accent: #4f46e5; | ||
| --accent-glow: rgba(79, 70, 229, 0.2); | ||
| --border: #e5e7eb; | ||
| --glass: rgba(0, 0, 0, 0.03); | ||
| --glass-border: rgba(0, 0, 0, 0.08); | ||
| } | ||
|
|
||
| h1 { | ||
| background: linear-gradient(to bottom right, #111827, #4b5563); | ||
| -webkit-background-clip: text; | ||
| -webkit-text-fill-color: transparent; | ||
| } |
There was a problem hiding this comment.
Scope the light-mode h1 override to the actual light theme.
The darker title gradient only exists under prefers-color-scheme: light, and it is unscoped. That means data-theme="light" still uses the white-on-light gradient when the OS prefers dark, while data-theme="dark" still gets the light-mode title colors when the OS prefers light.
Suggested fix
[data-theme="light"] {
--bg-primary: `#ffffff`;
--bg-secondary: `#f9fafb`;
--bg-elevated: `#f3f4f6`;
--text-primary: `#111827`;
--text-secondary: `#4b5563`;
--accent: `#4f46e5`;
--accent-glow: rgba(79, 70, 229, 0.2);
--border: `#e5e7eb`;
--glass: rgba(0, 0, 0, 0.03);
--glass-border: rgba(0, 0, 0, 0.08);
}
+
+[data-theme="light"] h1 {
+ background: linear-gradient(to bottom right, `#111827`, `#4b5563`);
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+}
`@media` (prefers-color-scheme: light) {
:root:not([data-theme="dark"]) {
--bg-primary: `#ffffff`;
--bg-secondary: `#f9fafb`;
--bg-elevated: `#f3f4f6`;
--text-primary: `#111827`;
--text-secondary: `#4b5563`;
--accent: `#4f46e5`;
--accent-glow: rgba(79, 70, 229, 0.2);
--border: `#e5e7eb`;
--glass: rgba(0, 0, 0, 0.03);
--glass-border: rgba(0, 0, 0, 0.08);
}
- h1 {
+ :root:not([data-theme="dark"]) h1 {
background: linear-gradient(to bottom right, `#111827`, `#4b5563`);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
-
- .user-avatar {
- background: var(--accent);
- color: white;
- }
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/templates/style.css` around lines 208 - 240, The h1 gradient in the
`@media` (prefers-color-scheme: light) block is unscoped and applies regardless of
the document theme; scope it to the light theme by targeting the light theme
selector (e.g., :root:not([data-theme="dark"]) h1 or [data-theme="light"] h1)
inside the media query so the linear-gradient styles only apply when both the OS
prefers light and the page theme is light; update the h1 rule accordingly near
the existing :root:not([data-theme="dark"]) block to ensure the dark theme is
never affected.
| @pytest.mark.parametrize( | ||
| "case_type,args,error_keyword,assertion_desc", | ||
| SEARCH_ERROR_CASES, | ||
| ) | ||
| def test_search_error_cases( | ||
| self, | ||
| case_type, | ||
| args, | ||
| error_keyword, | ||
| assertion_desc, | ||
| ): | ||
| """Search handles invalid parameters.""" | ||
| from polylogue.mcp.server import _build_server | ||
|
|
||
| if case_type == "invalid_since": | ||
| with patch("polylogue.mcp.server._get_repo") as mock_get_repo: | ||
| mock_repo = MagicMock() | ||
| mock_get_repo.return_value = mock_repo | ||
|
|
||
| with patch("polylogue.lib.filters.ConversationFilter") as MockFilter: | ||
| MockFilter.return_value = make_mock_filter(since=ValueError("Invalid date")) | ||
|
|
||
| server = _build_server() | ||
| # Tool should raise or return error dict | ||
| try: | ||
| result = server._tool_manager._tools["search"].fn(**args) | ||
| # If no exception, check result contains error info | ||
| parsed = json.loads(result) | ||
| # Tools that catch errors may return dict with error key | ||
| except ValueError: | ||
| pass # Expected for invalid date | ||
| else: | ||
| with patch("polylogue.mcp.server._get_repo") as mock_get_repo: | ||
| mock_repo = MagicMock() | ||
| mock_get_repo.return_value = mock_repo | ||
|
|
||
| with patch("polylogue.lib.filters.ConversationFilter") as MockFilter: | ||
| MockFilter.return_value = make_mock_filter(results=[]) | ||
|
|
||
| server = _build_server() | ||
| # For invalid_limit_type, tool should handle gracefully | ||
| try: | ||
| result = server._tool_manager._tools["search"].fn(**args) | ||
| parsed = json.loads(result) | ||
| except (TypeError, ValueError): | ||
| pass # Expected for invalid limit type |
There was a problem hiding this comment.
Make the invalid-parameter tests assert an outcome.
These branches currently pass on both the exception path and the non-exception path, so the cases stay green if bad inputs are ignored, silently clamped, or correctly rejected. Please assert the contract you actually want for each case instead of swallowing both outcomes.
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 1044-1044: Wrong type passed to first argument of pytest.mark.parametrize; expected tuple
Use a tuple for the first argument
(PT006)
[warning] 1051-1051: Unused method argument: error_keyword
(ARG002)
[warning] 1052-1052: Unused method argument: assertion_desc
(ARG002)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_mcp_server.py` around lines 1043 - 1088, The test currently
swallows both exception and non-exception paths; change test_search_error_cases
so each branch asserts an expected outcome: for case_type == "invalid_since"
wrap the call to server._tool_manager._tools["search"].fn(**args) in
pytest.raises(ValueError) when you expect an exception, and if no exception is
raised parse the returned JSON and assert it contains an "error" key and that
the error message contains the error_keyword; similarly for the other branch
(e.g., "invalid_limit_type") use pytest.raises(TypeError) where appropriate or
else parse the JSON and assert "error" in parsed and error_keyword is present;
keep use of _build_server, make_mock_filter and patched ConversationFilter the
same but replace the try/except pass blocks with these explicit assertions.
| for id in expected_ids: | ||
| assert id in output | ||
| assert id in rendered |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify builtin-shadowing patterns in Python loops.
rg -nP --type=py '\bfor\s+id\s+in\b'Repository: Sinity/polylogue
Length of output: 296
🏁 Script executed:
cat -n tests/test_query_execution.py | sed -n '870,920p'Repository: Sinity/polylogue
Length of output: 2555
Rename loop variable to avoid builtin shadowing (Ruff A001).
Line 893 uses id as a loop variable, which shadows Python's builtin id() and fails Ruff linting.
Proposed fix
- for id in expected_ids:
- assert id in rendered
+ for expected_id in expected_ids:
+ assert expected_id in renderedNote: The same issue appears at lines 877 and 910 and should also be fixed.
📝 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.
| for id in expected_ids: | |
| assert id in output | |
| assert id in rendered | |
| for expected_id in expected_ids: | |
| assert expected_id in rendered |
🧰 Tools
🪛 Ruff (0.15.9)
[error] 893-893: Variable id is shadowing a Python builtin
(A001)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_query_execution.py` around lines 893 - 894, The test loops use the
builtin name `id` as a loop variable (e.g., "for id in expected_ids: assert id
in rendered"), which shadows Python's id(); rename the loop variable to a
non-builtin name such as `expected_id` (or `eid`) and update all usages in those
loops (references to `id` in asserts) — apply the same rename for the other
occurrences tied to `expected_ids` at the other two locations so `expected_id`
is used consistently instead of `id`.
Rewrite the MCP server to use the official `mcp` FastMCP SDK for
protocol compliance, centralize theming across all output surfaces,
and expand metadata extraction from all four provider parsers.
MCP server (polylogue/mcp/server.py):
- Replace hand-rolled JSON-RPC dispatch with FastMCP tool/resource/prompt
decorators for standards-compliant server implementation
- Expose tools (search, list_conversations, get_conversation, stats),
resources (polylogue://stats, conversations, conversation/{conv_id}),
and prompts (analyze_errors, summarize_week, extract_code)
- Remove 1000-char message truncation in _conversation_to_full_dict
- Lazy repository singleton via _get_repo() avoids startup cost
Theme system (polylogue/lib/theme.py):
- New centralized palette with ProviderColor and RoleColor dataclasses
carrying CSS helper methods for hex/rgb output
- PROVIDER_COLORS maps provider names to brand colors; ROLE_COLORS for
user/assistant/system/tool
- DARK_THEME and LIGHT_THEME token dictionaries for consistent UI
- rich_theme_styles() for Rich Theme integration; css_variables() for
HTML template injection
Filter pipeline (polylogue/lib/filters.py):
- Extract _apply_common_filters(), _apply_sort_generic(),
_fetch_generic(), _execute_pipeline() as generic methods
- Eliminates ~200 lines of duplicated filter/sort/sample/limit logic
between Conversation and ConversationSummary code paths
Provider extraction enhancements:
- ChatGPT: model_slug, citations, code_execution, thinking content
blocks, gizmo metadata, is_archived, end_turn
- Claude Code: cwd, gitBranch, version, model, token_usage per message;
working_directories and models_used aggregated at conversation level
- Claude AI: typed extraction via ClaudeAIConversation.model_validate()
with fallback to untyped path on validation failure
- Codex: session-level git context and system instructions in provider_meta
- Gemini: typed GeminiMessage extraction covering finishReason,
thinkingBudget, safetyRatings, grounding, branch topology, executable
code, code execution results, errorMessage, isEdited
Static site builder (polylogue/site/builder.py):
- Markdown rendering with PygmentsHighlighter and MarkdownRenderer
- Pagefind search UI wired into index template
- Incremental page generation via mtime comparison skips unchanged files
- Light-mode CSS variables and @media prefers-color-scheme support
Storage backends:
- Share SCHEMA_DDL and _VEC0_DDL constants between sync and async backends
- Extract _row_get() and _update_ref_counts() as shared helpers
- Fix vector search ranking: use min() for distance (lower=more similar)
instead of max() for score, remove incorrect reverse=True from sort
Bug fixes:
- Timestamp parsing: reject values below 86400 as epoch seconds to avoid
misinterpreting year-like integers (e.g. "2025")
- Gemini detection: add content-based check for chunkedPrompt field in
detect_provider() for direct file uploads
- Source iteration: iter_source_conversations delegates to
iter_source_conversations_with_raw(capture_raw=False), removing ~160
lines of duplicated iteration logic
Cleanup:
- Delete polylogue/schemas/claude_code_records.py and common.py
- Remove GitOperation, FileChange, SubagentSpawn from models.py
- Switch provider schemas to gzip-compressed .schema.json.gz
- Consolidate tests from 60+ files to focused set; add mcp dependency
|
@codex review |
💡 Codex Reviewpolylogue/polylogue/site/builder.py Line 811 in fb6b57c Store a machine-precision timestamp for Initialize sqlite-vec tables in ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Summary
I replaced the hand-rolled MCP server with a FastMCP-based implementation, moved color/theme decisions into a shared module, and expanded the provider extraction layer so Polylogue keeps far more of the source metadata without flattening everything to text. That feature work also gave me an excuse to remove duplicated filter/storage plumbing, package compressed schemas for drift validation, wire schema validation into ingestion, add Pagefind-backed site search, and fix the vector-distance ordering bug that could return worse matches ahead of better ones. The branch looks broad because the user-facing parts depend on that cleanup: once the filter pipeline, row mapping, and theme tokens were shared, the MCP/site/parser changes stopped needing one-off implementations in four places. The most important outcome is not only "Polylogue talks FastMCP now"; it is that the archive becomes a much richer, more faithful substrate for downstream tools. MCP clients, static-site consumers, and provider-aware analysis code now see data that previously disappeared during normalization.
Motivation
There were three separate ceilings I wanted to break through here.
The first was protocol and integration. The existing MCP server worked, but it was still a hand-rolled JSON-RPC surface with custom dispatch, custom error handling, and a partial imitation of what the official SDK already knows how to do. That creates maintenance work for no real benefit. If Polylogue is going to expose tools, resources, and prompts as an MCP server, it should do so through the supported FastMCP interface rather than preserving a homegrown protocol layer.
The second was metadata fidelity. Polylogue already did a good job preserving core message text across providers, but it still left a lot of useful source data on the floor: ChatGPT citations and tool execution context, Claude Code cwd/git/model/token usage, Gemini safety/grounding/code execution state, Codex session context, and typed Claude AI records. For an archive project, flattening that metadata away is not neutral. It narrows what later analysis can ask.
The third was surface consistency. Color choices, CSS tokens, row-mapping helpers, filter pipelines, site rendering decisions, and schema assets were all slightly duplicated. That duplication was making it harder to add richer MCP/site/parser behavior without copying more code into more places.
Changes grouped by concern
FastMCP migration
The center of the branch is
polylogue/mcp/server.py. I replaced the manual request-dispatch path with a FastMCP server built from decorators for tools, resources, and prompts. That gives Polylogue a standards-aligned construction path instead of another layer of custom JSON-RPC glue.Conceptually, the old code looked like this:
The new shape is closer to:
That shift matters for three reasons:
Removed the 1000-character message truncation from full conversation resources. Truncation made sense when the server surface was mostly a quick inspection aid, but it is the wrong default once MCP clients are consuming Polylogue as an archive backend.
Richer provider extraction
A lot of the branch value is in the parser/provider layer.
For ChatGPT I keep model slug, citations, code-execution details, thinking content blocks, gizmo metadata, archived state, and end-turn markers. For Claude Code I extract cwd, git branch, version, model, and token-usage information per message, then aggregate working directories and models at the conversation level. Claude AI gets a typed parsing path through
ClaudeAIConversation.model_validate()with fallback to the older untyped route when validation fails. Codex picks up session-level git context and system instructions. Gemini gets a typed extraction path that keeps finish reason, thinking budget, safety ratings, grounding metadata, branch topology, executable code, execution results, error messages, and edit markers.This is the part of the branch where "archive fidelity" becomes concrete. None of that data is decorative. It is exactly the context downstream analysis and tooling would want once the archive stops being just a text dump.
Shared theme system
polylogue/lib/theme.pyis new and intentionally central. Before this branch, provider colors and role colors were effectively scattered across CLI formatting, HTML output, static site templates, and TUI code. That made it much harder to keep the surfaces visually consistent.The new module defines provider and role color dataclasses, shared theme dictionaries, and helpers for both Rich and CSS output. That lets the CLI and site speak the same visual language without duplicating the token definitions.
Used the same pass to improve actual rendering surfaces:
prefers-color-schemesupportThe theme system is the glue that makes those changes coherent rather than ornamental.
Filter, storage, and ranking cleanup
The feature work depended on simplifying some internals first.
In
polylogue/lib/filters.pyI genericized the dual conversation/summary paths so they share common filter application, fetch logic, sort logic, and pipeline execution. That removes a class of drift where one path would pick up a bug fix or a behavior change and the other would not.In the SQLite backends I pulled common row mappers and vec-table DDL into shared helpers/constants, then reused them from both sync and async code. Corrected the vector ranking behavior. Similarity was effectively being ordered in the wrong direction by taking the wrong aggregate and reversing the sort. The new path treats lower distance as more similar and ranks accordingly.
There is also a small but important timestamp fix here: values below
86400are no longer treated as epoch seconds automatically. That avoids misreading year-like values such as"2025"as timestamps.Static site and schema validation
The site builder picks up three meaningful improvements:
Delegated source iteration through
iter_source_conversations_with_raw(capture_raw=False)so the two iteration modes stop diverging.On the validation side, provider schemas are compressed
*.schema.json.gzassets that ship with the package, andSchemaValidatoris wired into ingestion. That moves schema drift checking from a "developer convenience" status into a real packaged capability.Testing
The branch updates and expands coverage in the places the behavior changed:
tests/test_mcp_server.pyfor the FastMCP-based surfaceThe important thing is that the tests now reflect the richer contract. For example, they do not just ask whether a provider message has text; they ask whether the source metadata that makes the message analyzable survives extraction.
Notes
There are some real API and packaging changes here. The hand-rolled MCP helpers are no longer the primary construction path, some dead model helpers were removed, and schema assets ship compressed. I have documented those as API changes rather than pretending this is a drop-in internal refactor.
Did not try to make the branch "small" by splitting the cleanup from the features. That would have obscured the dependency chain. The FastMCP migration, richer extraction, shared theming, packaged schemas, and site work all got easier and safer once the duplicated filter/storage/theme plumbing was gone. Keeping them together makes the architectural move much clearer to review.