Repository navigation
refactor: SQL single-sourcing, CLI dispatch, daemon http rewrite (#784, #772, #782, #783) - #787
Conversation
Rebase 11 orphan error classes onto PolylogueError with is_transient and http_status_code classification. Fix MCP _safe_call to use integer JSON-RPC error codes and honest Callable[[], None] -> str | None overload. Add except Exception safety net in CLI human mode. Remove dead read_fields.py module and associated test. Co-Authored-By: Claude Opus 4.7 <[email protected]>
, #783, #786) Replace _execute_query_plan 226-line if/elif chain with dispatch table and independently testable route handlers. Rewrite daemon http.py with safe_handler decorator for PolylogueError-aware HTTP status codes, route dispatch, and structured CORS/error handling. Add is_transient and http_status_code to PolylogueError base class. Co-Authored-By: Claude Opus 4.7 <[email protected]>
…es (#784, #772) Create polylogue/core/common.py with canonical SQL templates and merged utilities (chunked, json_object, format_malformed_jsonl_error). Consolidate content hash through pipeline/ids.py. Add FK ON DELETE SET NULL, ON CONFLICT clauses, dead async variant cleanup. Linter at devtools/verify_sql_templates.py guards against SQL/function duplication. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Fix mypy errors in pipeline/ids.py, verify_sql_templates.py, and conversations.py. Add common.py to topology-target.yaml. Bump ingest_batch.py file budget to 1350 (pending Slice G split). Fix daemon cli.py reference to removed make_daemon_api_server. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (54)
📝 WalkthroughWalkthroughThis PR unifies error handling across the codebase by establishing a standardized error hierarchy through ChangesError Infrastructure & HTTP Mapping
Shared Core Module & Utilities Consolidation
Read-Field Infrastructure Removal
Storage & Content Hash Refactoring
CLI & Daemon API Refactoring
Tests & Type Annotations
Documentation & Configuration
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related issues
Possibly related PRs
Suggested labels
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Review rate limit: 0/1 reviews remaining, refill in 60 minutes.Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c3b3544c75
ℹ️ 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".
There was a problem hiding this comment.
Pull request overview
Wave 1 of the May 2026 execution plan: consolidates error handling + classification, single-sources key SQLite SQL/templates and shared utilities, refactors CLI query routing into dispatchable handlers, and rewrites the daemon HTTP API/error handling to reduce duplicated boilerplate and improve discrimination.
Changes:
- Introduces
PolylogueErrorclassification (is_transient,http_status_code) and rebases previously orphaned errors onto it; updates MCP error code handling and_safe_calltyping. - Adds
polylogue/core/common.pyas a central home for shared SQL templates/utilities and addsdevtools/verify_sql_templates.pyto prevent drift/duplication. - Refactors daemon HTTP routing + safety handling and restructures CLI query execution into a route→handler dispatch table; updates schema/bootstrap and tests/docs accordingly.
Reviewed changes
Copilot reviewed 54 out of 54 changed files in this pull request and generated 10 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/unit/sources/test_cursor_adversary.py | Minor assertion formatting change. |
| tests/unit/security/test_mcp_security.py | Updates MCP error-code expectations; asserts non-None _safe_call result. |
| tests/unit/mcp/test_tool_contracts.py | Removes unused import. |
| tests/unit/mcp/test_mcp_edge_cases.py | Updates MCP error-code expectations; asserts non-None _safe_call result. |
| tests/unit/core/test_query_read_fields.py | Removes read-field descriptor tests (module removed). |
| tests/unit/core/test_query_fields.py | Removes API query-field coverage test tied to removed surface inventory. |
| tests/unit/core/test_query_descriptor_parity.py | Tightens typing for a local set. |
| tests/unit/core/test_facade_api.py | Updates facade stats call to archive.stats(). |
| tests/unit/cli/test_messages.py | Refactors test helper object creation for readability. |
| polylogue/storage/sqlite/schema_ddl_archive.py | Adds ON DELETE SET NULL to conversation parent/raw references. |
| polylogue/storage/sqlite/schema_bootstrap.py | Adds v4→v5 upgrade path and cleans imports/statement formatting. |
| polylogue/storage/sqlite/queries/runs.py | Reuses shared json_object and adds ON CONFLICT DO NOTHING for run inserts. |
| polylogue/storage/sqlite/queries/publications.py | Reuses shared json_object and adds ON CONFLICT DO NOTHING for publication inserts. |
| polylogue/storage/repository/archive/writes/conversations.py | Routes conversation content-hash payload building through shared ids helpers. |
| polylogue/storage/insights/session/rebuild.py | Re-exports canonical chunked from core common module. |
| polylogue/storage/fts/sql.py | Re-exports canonical chunked from core common module. |
| polylogue/storage/action_events/rebuild_runtime.py | Switches to canonical chunked import. |
| polylogue/storage/action_events/rebuild_loading.py | Re-exports canonical chunked from core common module. |
| polylogue/schemas/validation/corpus.py | Reuses shared malformed-JSONL error formatter. |
| polylogue/pipeline/tail_overlay.py | Rebases TailOverlayUnavailableError onto PolylogueError with classification. |
| polylogue/pipeline/stage_specs.py | Rebases StageContractError onto PolylogueError with status classification. |
| polylogue/pipeline/services/validation_runtime.py | Reuses shared malformed-JSONL error formatter. |
| polylogue/pipeline/services/ingest_worker.py | Reuses shared malformed-JSONL error formatter. |
| polylogue/pipeline/services/ingest_batch.py | Reorders imports and adds detailed post-commit side-effects rationale comment. |
| polylogue/pipeline/ids.py | Extracts shared _conversation_hash_payload helper for cross-path hashing consistency. |
| polylogue/mcp/server_support.py | Implements integer JSON-RPC internal error code; fixes overload return types; broadens error-json extras typing. |
| polylogue/mcp/server_mutation_tools.py | Adds typing suppression for payload conversion call. |
| polylogue/mcp/payloads.py | Broadens MCP error code field type to allow ints. |
| polylogue/insights/registry.py | Rebases InsightQueryError onto PolylogueError with status classification. |
| polylogue/insights/export_bundles.py | Rebases InsightExportBundleError onto PolylogueError. |
| polylogue/insights/archive.py | Rebases ArchiveInsightUnavailableError onto PolylogueError with transient/503 classification. |
| polylogue/errors.py | Adds base error classification fields and uses HTTPStatus defaults. |
| polylogue/daemon/status.py | Updates readiness probe config fields and readiness computation. |
| polylogue/daemon/http.py | Rewrites HTTP routing/handlers with a decorator-based safety wrapper and simplified handler bodies. |
| polylogue/daemon/cli.py | Updates daemon API server construction to use exported handler/server types. |
| polylogue/core/common.py | Adds canonical shared SQL templates and common utility functions (chunked/json_object/error formatting). |
| polylogue/cli/shared/insight_command_contracts.py | Rebases InsightCommandInputError onto PolylogueError with 400 classification. |
| polylogue/cli/query_contracts.py | Rebases QueryPlanError onto PolylogueError with 400 classification. |
| polylogue/cli/query.py | Replaces large route if/elif chain with a dispatch table + extracted route handler functions. |
| polylogue/cli/machine_main.py | Adds a catch-all exception safety net in machine entry flow. |
| polylogue/archive/write_gateway.py | Rebases DaemonUnavailableError onto PolylogueError with transient/503 classification. |
| polylogue/archive/query/spec.py | Rebases QuerySpecError onto PolylogueError with 400 classification. |
| polylogue/archive/query/read_fields.py | Removes read-field descriptor registry module. |
| polylogue/archive/conversation/neighbor_candidates.py | Rebases NeighborDiscoveryError onto PolylogueError with 400 classification. |
| polylogue/api/archive.py | Rebases ConversationNotFoundError onto PolylogueError with 404 classification; removes unnecessary ignores. |
| docs/topology-status.md | Updates generated topology status summary and lists TBD routing cell. |
| docs/plans/topology-target.yaml | Removes routing entry for deleted read_fields; adds routing entry for new core/common.py. |
| docs/plans/file-size-budgets.yaml | Adjusts pipeline/services LOC budget. |
| docs/devtools.md | Adds new devtools commands to generated reference list. |
| docs/cli-reference.md | Updates reset command help output formatting and options list. |
| devtools/xtask.py | Tightens local variable typing for parsed task fields. |
| devtools/verify_sql_templates.py | Adds linter enforcing SQL single-sourcing and duplicated function-body detection. |
| devtools/verify_schema_roundtrip.py | Cleans up typing ignores around optional imports. |
| devtools/main.py | Exposes main via __all__. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| messages_payload: list[dict[str, JSONValue]] = [] | ||
| for message in conversation.messages: | ||
| messages_payload.append( | ||
| { | ||
| "id": str(message.id), | ||
| "role": str(message.role), | ||
| "text": _normalize_hash_value(message.text), | ||
| "timestamp": _normalize_hash_value(message.timestamp.isoformat() if message.timestamp else None), | ||
| } | ||
| ) | ||
| attachments_payload = sorted( | ||
| [ | ||
| { | ||
| "id": _normalize_hash_value(attachment.id), | ||
| "message_id": _normalize_hash_value(message.id), | ||
| "name": _normalize_hash_value(attachment.name), | ||
| "mime_type": _normalize_hash_value(attachment.mime_type), | ||
| "size_bytes": _normalize_hash_value(attachment.size_bytes), | ||
| } | ||
| for message in conversation.messages | ||
| for attachment in message.attachments | ||
| ], | ||
| key=lambda item: ( | ||
| str(item.get("message_id") or ""), | ||
| str(item.get("id") or ""), | ||
| str(item.get("name") or ""), | ||
| ), | ||
| ) | ||
| return hash_payload( | ||
| { | ||
| "title": _normalize_hash_value(conversation.title), | ||
| "created_at": _normalize_hash_value( | ||
| conversation.created_at.isoformat() if conversation.created_at else None | ||
| ), | ||
| "updated_at": _normalize_hash_value( | ||
| conversation.updated_at.isoformat() if conversation.updated_at else None | ||
| ), | ||
| "messages": messages_payload, | ||
| "attachments": attachments_payload, | ||
| msg_entry: dict[str, JSONValue] = { | ||
| "id": str(message.id), | ||
| "role": str(message.role), | ||
| "text": _normalize_for_hash(message.text), | ||
| "timestamp": _normalize_for_hash(message.timestamp.isoformat() if message.timestamp else None), | ||
| } |
| class MCPErrorPayload(SurfacePayloadModel): | ||
| error: str | ||
| code: str | None = None | ||
| code: int | str | None = None |
| return { | ||
| "id": str(conv.id), | ||
| "title": conv.title, | ||
| "provider": str(conv.provider) if conv.provider else None, | ||
| "created_at": conv.created_at.isoformat() if conv.created_at else None, | ||
| "updated_at": conv.updated_at.isoformat() if conv.updated_at else None, | ||
| "messages": [ | ||
| { | ||
| "id": str(msg.id), | ||
| "role": str(msg.role), | ||
| "text": msg.text, | ||
| "timestamp": msg.timestamp.isoformat() if msg.timestamp else None, | ||
| } | ||
| for msg in conv.messages | ||
| ], | ||
| "total": len(conv.messages), | ||
| } |
| async def _do_list(self, poly: Polylogue, limit: int, provider: str | None, since: str | None) -> object: | ||
| summaries = await poly.list_conversations(provider=provider, limit=limit) | ||
| hits: list[dict[str, object]] = [] | ||
| for summary in summaries: | ||
| hits.append( | ||
| { | ||
| "id": str(summary.id), | ||
| "title": summary.display_title, | ||
| "provider": str(summary.provider) if summary.provider else None, | ||
| "created_at": summary.created_at.isoformat() if summary.created_at else None, | ||
| "updated_at": summary.updated_at.isoformat() if summary.updated_at else None, | ||
| "message_count": getattr(summary, "message_count", None), | ||
| } | ||
| ) | ||
| return {"hits": hits, "total": len(hits)} |
| attachments_payload.append( | ||
| { | ||
| "id": _normalize_for_hash(attachment.id), | ||
| "message_id": _normalize_for_hash(message.id), | ||
| "name": _normalize_for_hash(attachment.name), | ||
| "mime_type": _normalize_for_hash(attachment.mime_type), | ||
| "size_bytes": _normalize_for_hash(attachment.size_bytes), | ||
| } | ||
| ) |
| # Files that are allowed to import the canonical SQL templates. | ||
| # All other files must NOT define SQL with matching semantics. | ||
| _SQL_TEMPLATE_SOURCES = frozenset( | ||
| { | ||
| "polylogue/core/common.py", | ||
| "polylogue/pipeline/services/ingest_batch.py", | ||
| "polylogue/storage/sqlite/queries/conversations_writes.py", | ||
| "polylogue/storage/sqlite/queries/message_query_writes.py", | ||
| "polylogue/storage/sqlite/queries/attachment_content_blocks.py", | ||
| "polylogue/storage/sqlite/queries/attachment_mutations.py", | ||
| "polylogue/storage/sqlite/queries/action_events.py", | ||
| "polylogue/storage/sqlite/queries/stats.py", | ||
| "polylogue/storage/action_events/rebuild_sql.py", |
| INSERT OR IGNORE INTO attachment_refs ( | ||
| ref_id, attachment_id, conversation_id, message_id, provider_meta | ||
| ) VALUES (?, ?, ?, ?, ?) |
| def _list(poly: Polylogue) -> object: | ||
| return asyncio.run(self._do_list(poly, limit, provider, since)) | ||
|
|
||
| result = self._sync_run(_list) | ||
| self._send_json(HTTPStatus.OK, result) |
|
|
||
| cfg = Config(archive_root=archive_root(), render_root=render_root(), sources=[]) | ||
| report = get_readiness(cfg, deep=False, probe_only=False) | ||
| quick_check_ok = report.counts().ok > 0 |
| from polylogue.paths import archive_root, render_root | ||
| from polylogue.readiness import get_readiness | ||
|
|
||
| cfg = Config(archive_root=archive_root()) | ||
| cfg = Config(archive_root=archive_root(), render_root=render_root(), sources=[]) | ||
| report = get_readiness(cfg, deep=False, probe_only=False) | ||
| counts = report.counts() | ||
| return { | ||
| "messages_ready": report.ok, | ||
| "action_events_ready": report.ok, | ||
| "messages_ready": counts.ok > 0, | ||
| "action_events_ready": counts.ok > 0, | ||
| } |
#772, #782, #783) (#787) ## Summary Wave 1 of the May 2026 ambitious execution plan. Three slices merged into one PR. ## Problem - 11 error classes bypassed PolylogueError, breaking top-level error handling - Sync/async SQL paths had 5+ WHERE clause divergences - 6 utility functions duplicated across 3+ modules each - CLI query routing was a 226-line if/elif chain (9 routes) - Daemon http.py had 10 broad except blocks, undefined function, no error discrimination - MCP tools never set isError=True, error codes were strings not JSON-RPC integers ## Solution - **#786**: Rebased 11 orphan errors onto PolylogueError with is_transient/http_status_code classification. Fixed MCP isError + integer codes. Added except Exception safety net in CLI human mode. - **#784**: Created polylogue/core/common.py with canonical SQL templates and merged utilities (chunked, json_object, format_malformed_jsonl_error). Added verify_sql_templates.py linter. - **#772**: Content hash single-sourced through pipeline/ids.py. FK ON DELETE actions. ON CONFLICT clauses on publications/runs. Removed 355 lines of duplicated SQL. - **#782**: Replaced _execute_query_plan if/elif chain with dict-based dispatch + 10 independently testable handler functions. - **#783**: Rewrote daemon http.py with @daemon_safe_handler decorator (10 except Exception → 2), route dispatch, proper CORS headers, fixed undefined _get_or_create_polylogue. ## Verification - devtools verify --quick: all checks passed - mypy: 0 errors - ruff format + check: clean - 387 CLI/MCP tests pass --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Wave 1 of the May 2026 ambitious execution plan. Three slices merged into one PR.
Problem
Solution
Verification
Summary by CodeRabbit
New Features
Bug Fixes
Documentation