Skip to content

refactor: SQL single-sourcing, CLI dispatch, daemon http rewrite (#784, #772, #782, #783) - #787

Merged
Sinity merged 4 commits into
masterfrom
feature/fix/sql-templates-write-path
May 4, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/fix/sql-templates-write-path

Conversation

@Sinity

@Sinity Sinity commented May 4, 2026 •

Copy link
Copy Markdown
Owner

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

Verification

  • devtools verify --quick: all checks passed
  • mypy: 0 errors
  • ruff format + check: clean
  • 387 CLI/MCP tests pass

Summary by CodeRabbit

  • New Features

    • Added identity-preserving reset mode to CLI with conversation and source options.
    • Enhanced HTTP daemon health check with additional readiness metrics and blob directory information.
  • Bug Fixes

    • Improved error classification and HTTP status codes for consistency across the system.
    • Fixed database schema constraints for conversation references with proper delete rules.
  • Documentation

    • Updated CLI reference documenting the new reset options.
    • Updated devtools documentation with additional command references.

Sinity and others added 4 commits May 4, 2026 01:21
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]>
Copilot AI review requested due to automatic review settings May 4, 2026 00:55
@Sinity
Sinity merged commit e1d8c0f into master May 4, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the feature/fix/sql-templates-write-path branch May 4, 2026 00:55
@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c9727a2c-951d-434c-9e4b-b88ed535d7c5

📥 Commits

Reviewing files that changed from the base of the PR and between 7ebbaa1 and c3b3544.

📒 Files selected for processing (54)
  • devtools/__main__.py
  • devtools/verify_schema_roundtrip.py
  • devtools/verify_sql_templates.py
  • devtools/xtask.py
  • docs/cli-reference.md
  • docs/devtools.md
  • docs/plans/file-size-budgets.yaml
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/api/archive.py
  • polylogue/archive/conversation/neighbor_candidates.py
  • polylogue/archive/query/read_fields.py
  • polylogue/archive/query/spec.py
  • polylogue/archive/write_gateway.py
  • polylogue/cli/machine_main.py
  • polylogue/cli/query.py
  • polylogue/cli/query_contracts.py
  • polylogue/cli/shared/insight_command_contracts.py
  • polylogue/core/common.py
  • polylogue/daemon/cli.py
  • polylogue/daemon/http.py
  • polylogue/daemon/status.py
  • polylogue/errors.py
  • polylogue/insights/archive.py
  • polylogue/insights/export_bundles.py
  • polylogue/insights/registry.py
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_mutation_tools.py
  • polylogue/mcp/server_support.py
  • polylogue/pipeline/ids.py
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/pipeline/services/ingest_worker.py
  • polylogue/pipeline/services/validation_runtime.py
  • polylogue/pipeline/stage_specs.py
  • polylogue/pipeline/tail_overlay.py
  • polylogue/schemas/validation/corpus.py
  • polylogue/storage/action_events/rebuild_loading.py
  • polylogue/storage/action_events/rebuild_runtime.py
  • polylogue/storage/fts/sql.py
  • polylogue/storage/insights/session/rebuild.py
  • polylogue/storage/repository/archive/writes/conversations.py
  • polylogue/storage/sqlite/queries/publications.py
  • polylogue/storage/sqlite/queries/runs.py
  • polylogue/storage/sqlite/schema_bootstrap.py
  • polylogue/storage/sqlite/schema_ddl_archive.py
  • tests/unit/cli/test_messages.py
  • tests/unit/core/test_facade_api.py
  • tests/unit/core/test_query_descriptor_parity.py
  • tests/unit/core/test_query_fields.py
  • tests/unit/core/test_query_read_fields.py
  • tests/unit/mcp/test_mcp_edge_cases.py
  • tests/unit/mcp/test_tool_contracts.py
  • tests/unit/security/test_mcp_security.py
  • tests/unit/sources/test_cursor_adversary.py

📝 Walkthrough

Walkthrough

This PR unifies error handling across the codebase by establishing a standardized error hierarchy through PolylogueError with HTTP status code metadata, consolidates shared utilities (SQL templates, chunked, json_object, formatting helpers) into a new polylogue/core/common.py module, refactors the query execution CLI flow into a route-dispatch pattern, and simplifies the daemon HTTP API by centralizing error mapping and restructuring response payloads. Supporting changes migrate storage/pipeline code to use shared utilities and update tests to reflect new error codes and removed infrastructure.

Changes

Error Infrastructure & HTTP Mapping

Layer / File(s) Summary
Base Error Framework
polylogue/errors.py
PolylogueError gains is_transient and http_status_code attributes (defaulting to False and HTTPStatus.INTERNAL_SERVER_ERROR); DatabaseError sets http_status_code = SERVICE_UNAVAILABLE.
Exception Type Updates
polylogue/api/archive.py, polylogue/archive/conversation/neighbor_candidates.py, polylogue/archive/query/spec.py, polylogue/archive/write_gateway.py, polylogue/cli/query_contracts.py, polylogue/cli/shared/insight_command_contracts.py, polylogue/insights/archive.py, polylogue/insights/export_bundles.py, polylogue/insights/registry.py, polylogue/pipeline/stage_specs.py, polylogue/pipeline/tail_overlay.py
Twelve exception classes (ConversationNotFoundError, NeighborDiscoveryError, QuerySpecError, DaemonUnavailableError, QueryPlanError, InsightCommandInputError, ArchiveInsightUnavailableError, InsightExportBundleError, InsightQueryError, StageContractError, TailOverlayUnavailableError) are reparented from ValueError/RuntimeError to PolylogueError with appropriate http_status_code and (where relevant) is_transient attributes.

Shared Core Module & Utilities Consolidation

Layer / File(s) Summary
Core Common Module
polylogue/core/common.py
New module introduces canonical SQL upsert/insert templates (SQL_CONVERSATION_UPSERT, SQL_MESSAGE_UPSERT, SQL_CONTENT_BLOCK_UPSERT, SQL_STATS_UPSERT, SQL_ACTION_EVENT_INSERT, SQL_ATTACHMENT_UPSERT, SQL_ATTACHMENT_REF_INSERT) and three utility functions: chunked() for fixed-size sequence slices, json_object() for JSON-compatible value conversion to dict[str, object], and format_malformed_jsonl_error() for readable JSONL error messages.
Utility Re-exports
polylogue/storage/action_events/rebuild_loading.py, polylogue/storage/fts/sql.py, polylogue/storage/insights/session/rebuild.py, polylogue/storage/action_events/rebuild_runtime.py
Four storage modules replace their local chunked() implementations with imports from polylogue/core/common.py.
Formatter Consolidation
polylogue/pipeline/services/ingest_worker.py, polylogue/pipeline/services/validation_runtime.py, polylogue/schemas/validation/corpus.py
Three pipeline/validation modules replace local _format_malformed_jsonl_error() implementations with the shared formatter from polylogue/core/common.py.
JSON Helper Consolidation
polylogue/storage/sqlite/queries/publications.py, polylogue/storage/sqlite/queries/runs.py
Two query modules replace local _json_object() helpers with the shared json_object() from polylogue/core/common.py and add conflict-handling clauses to INSERT statements (ON CONFLICT DO NOTHING).

Read-Field Infrastructure Removal

Layer / File(s) Summary
Module Deletion
polylogue/archive/query/read_fields.py
Entire module removed; previously exported ReadFieldDescriptor dataclass, ReadFieldKind/ReadSurface type aliases, READ_FIELD_DESCRIPTORS constant, and descriptor-lookup helper functions.
Test Cleanup
tests/unit/core/test_query_read_fields.py, tests/unit/core/test_query_fields.py
Complete test file test_query_read_fields.py removed (covering descriptor kinds, CLI verb parameters, surface name sets, API method parameters); test_query_fields.py removes api_query_field_names import and deletes the test_query_field_catalog_covers_api_query_method_names test.

Storage & Content Hash Refactoring

Layer / File(s) Summary
Content Hash Centralization
polylogue/pipeline/ids.py
Introduces _conversation_hash_payload() helper that centralizes conversation hash payload construction with deterministically sorted attachments; conversation_content_hash() refactored to use the new helper.
Conversation Write Updates
polylogue/storage/repository/archive/writes/conversations.py
_content_hash_from_metadata_or_domain() refactored to compute content hashes via the centralized _conversation_hash_payload() helper, now including per-message content_blocks in the hash payload.
Schema & Storage Plumbing
polylogue/storage/sqlite/schema_bootstrap.py, polylogue/storage/sqlite/schema_ddl_archive.py, polylogue/daemon/status.py
Schema bootstrap action types extended with "upgrade_v4_to_v5" option; conversations table foreign keys (parent_conversation_id, raw_id) updated to use ON DELETE SET NULL; FTS readiness info now constructs Config with render_root and uses counts.ok > 0 for readiness checks.

CLI & Daemon API Refactoring

Layer / File(s) Summary
Query Route Dispatch
polylogue/cli/query.py
_execute_query_plan() refactored from long if/elif chain into a route-dispatch table (_route_handlers) with extracted handler functions (_handle_count, _handle_summary_list, _handle_stream, _handle_stats_sql, _handle_summary_stats, _handle_open, _handle_modify, _handle_delete, _handle_stats_by, _handle_default); dispatch now selects a handler per QueryRoute and executes it, falling back to _handle_default.
Daemon HTTP API Redesign
polylogue/daemon/http.py
HTTP handlers centralized via daemon_safe_handler decorator (maps PolylogueError.http_status_code and unexpected exceptions to HTTP responses); GET routing reorganized into _dispatch_get() route table; response payloads simplified across endpoints (health now returns {quick_check, quick_check_age_s, blob_dir_size_bytes}; conversation/messages/facets/sources return flattened {hits/messages, total} structures; reset no longer supports "source" scope tombstoning).
Machine Entry Exception Handling
polylogue/cli/machine_main.py
JSON-output mode now catches unexpected Exception types and wraps them in click.ClickException with exception type name and error text, exiting with status 1.
Daemon API Wiring
polylogue/daemon/cli.py
run_daemon_services() now directly instantiates DaemonAPIHTTPServer((api_host, api_port), DaemonAPIHandler) instead of calling make_daemon_api_server() factory; make_daemon_api_server() and the __all__ export list removed from polylogue/daemon/http.py.
Error-to-HTTP Mapping
polylogue/mcp/server_support.py
_exception_error_payload() now distinguishes PolylogueError instances by setting code = exc.http_status_code; non-PolylogueError exceptions use JSON-RPC error code -32603 instead of string "internal_error"; MCPErrorPayload.code type widened to int | str | None.

Tests & Type Annotations

Layer / File(s) Summary
Error Code Updates
tests/unit/mcp/test_mcp_edge_cases.py, tests/unit/security/test_mcp_security.py
Tests updated to assert result is not None before JSON parsing and expect JSON-RPC error code -32603 instead of "internal_error"; SessionInsightCounts import removed from tests/unit/mcp/test_tool_contracts.py.
API Surface Updates
tests/unit/core/test_facade_api.py
test_archive_stats_health_and_rebuild_insights_are_public changed to call await archive.stats() instead of await archive.get_archive_stats().
Type Annotations
devtools/xtask.py, polylogue/mcp/server_mutation_tools.py, tests/unit/core/test_query_descriptor_parity.py, tests/unit/cli/test_messages.py
Minor type annotation additions (# type: ignore comments, explicit set[str] annotation, reformatted list comprehension).

Documentation & Configuration

Layer / File(s) Summary
CLI & DevTools Documentation
docs/cli-reference.md, docs/devtools.md
polylogue reset documentation updated with new identity-preserving options (--conversation ID, --source PATH); devtools command catalog extended with render-readme-media and xtask entries.
Topology & Budget Updates
docs/plans/topology-target.yaml, docs/plans/file-size-budgets.yaml, docs/topology-status.md
polylogue/archive/query/read_fields.py removed and polylogue/core/common.py added to topology; file-size budget for polylogue/proof/ increased from 1300 to 1350; topology status dashboard updated with new cell counts and added TBD routing section for polylogue/storage/blob_gc.py.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related issues

Possibly related PRs

Suggested labels

type:refactor, area:cli, area:storage, area:daemon, area:error-handling

Poem

🐰 Errors now speak in HTTP's voice,
Shared templates make the code rejoice,
Queries dispatch through tables clean,
The best refactored code I've seen! ✨

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/sql-templates-write-path

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.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread polylogue/daemon/http.py Resolved
Comment thread polylogue/daemon/http.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

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 PolylogueError classification (is_transient, http_status_code) and rebases previously orphaned errors onto it; updates MCP error code handling and _safe_call typing.
  • Adds polylogue/core/common.py as a central home for shared SQL templates/utilities and adds devtools/verify_sql_templates.py to 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.

Comment on lines 56 to 63
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),
}
Comment thread polylogue/mcp/payloads.py
class MCPErrorPayload(SurfacePayloadModel):
error: str
code: str | None = None
code: int | str | None = None
Comment thread polylogue/daemon/http.py
Comment on lines +305 to +321
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),
}
Comment thread polylogue/daemon/http.py
Comment on lines +270 to +284
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)}
Comment on lines +74 to +82
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),
}
)
Comment on lines +39 to +51
# 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",
Comment thread polylogue/core/common.py
Comment on lines +137 to +139
INSERT OR IGNORE INTO attachment_refs (
ref_id, attachment_id, conversation_id, message_id, provider_meta
) VALUES (?, ?, ?, ?, ?)
Comment thread polylogue/daemon/http.py
Comment on lines +264 to +268
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)
Comment thread polylogue/daemon/http.py

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
Comment on lines +86 to 95
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,
}
Sinity added a commit that referenced this pull request May 7, 2026
#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]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 62.F073 / P1: fixed-already at the checked revision: _run_archive_query awaits its asynchronous handler at polylogue/daemon/http.py:1770. The current detail adapter likewise awaits _do_get_session at polylogue/daemon/route_families/read_detail.py:49 before handing the coroutine to the single synchronous bridge, removing the nested asyncio.run request path.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 63.F070 / P2: fixed-already at the checked revision: The health route now selects HTTPStatus.SERVICE_UNAVAILABLE when archive_health_ok is false at polylogue/daemon/http.py:3295. That flag includes quick_check.ok, restoring the transport-level unhealthy signal rather than always returning 200.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants