Skip to content

refactor(api): define shared query/status response envelopes (#859) - #916

Merged
Sinity merged 1 commit into
masterfrom
feature/refactor/query-contracts-859
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/refactor/query-contracts-859

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026 •

Copy link
Copy Markdown
Owner

Shared response models. Daemon HTTP uses full filter vocabulary. 19 files +435/-397.

Summary by CodeRabbit

Release Notes

  • New Features

    • Conversation listings now include pagination metadata (limit, offset, total), word counts, repository information, and feature flags (tool use, thinking, paste).
    • Error responses are now structured with detailed error messages and optional field information.
  • Bug Fixes

    • Improved session profile search accuracy and performance by refining text matching logic.
  • Chores

    • Removed unused full-text search indexes for session profile data, reducing storage overhead.

…read surfaces (#859)

Define canonical typed response models shared across daemon HTTP, MCP,
CLI, and web reader surfaces. Expand the daemon HTTP /api/conversations
endpoint to accept the full ConversationQuerySpec filter vocabulary.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 7, 2026 14:55
@Sinity
Sinity merged commit c7092fe into master May 7, 2026
@Sinity
Sinity deleted the feature/refactor/query-contracts-859 branch May 7, 2026 14:56
@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

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: 945cbd65-084d-4701-ac08-5ea2ea6d8e95

📥 Commits

Reviewing files that changed from the base of the PR and between 247cbb2 and 689f0ff.

📒 Files selected for processing (19)
  • polylogue/artifacts/runtime.py
  • polylogue/cli/shared/formatting.py
  • polylogue/daemon/http.py
  • polylogue/insights/readiness.py
  • polylogue/insights/storage.py
  • polylogue/operations/specs.py
  • polylogue/readiness/__init__.py
  • polylogue/sources/drive/auth.py
  • polylogue/storage/derived/derived_status.py
  • polylogue/storage/derived/insights.py
  • polylogue/storage/fts/sql.py
  • polylogue/storage/insights/session/runtime.py
  • polylogue/storage/insights/session/status.py
  • polylogue/storage/repair.py
  • polylogue/storage/sqlite/queries/session_insight_profile_reads.py
  • polylogue/storage/sqlite/schema_ddl_archive.py
  • polylogue/storage/sqlite/schema_ddl_insight_profiles.py
  • polylogue/surfaces/payloads.py
  • tests/unit/storage/test_backend.py

📝 Walkthrough

Walkthrough

This PR systematically removes session-profile full-text search infrastructure (four FTS tables and their triggers) while maintaining query functionality via LIKE-based filtering. Changes span schema DDL, runtime artifact graphs, readiness/repair specifications, HTTP API payloads, and test updates.

Changes

Session-Profile FTS Removal

Layer / File(s) Summary
Schema & Table Definitions
polylogue/storage/sqlite/schema_ddl_insight_profiles.py, polylogue/storage/sqlite/schema_ddl_archive.py, polylogue/insights/storage.py
Removes session_profile_*_fts virtual tables and INSERT/UPDATE/DELETE triggers. Adds FTS5 external content wiring (content='messages', content_rowid='rowid') to messages_fts. Removes three FTS tables from schema rebuild drop list.
Readiness Contracts & Status Types
polylogue/storage/insights/session/runtime.py
Removes profile_*_fts_ready literal members from SessionInsightReadyFlag. Removes eight count/duplicate fields and four readiness boolean fields from SessionInsightStatusSnapshot.
Session Insight Status SQL & Descriptors
polylogue/storage/insights/session/status.py
Removes SQL constants and SessionInsightFtsDescriptor entries for profile FTS merged/evidence/inference/enrichment. Stops assigning FTS readiness keys in status payload builder.
Artifact Graph & Operation Dependencies
polylogue/artifacts/runtime.py, polylogue/operations/specs.py
Removes four session-profile FTS nodes from RUNTIME_ARTIFACT_NODES and repair-loop wiring. Updates session_profile_results and session_enrichment_results to depend only on session_profile_rows. Removes FTS artifacts from operation consumes specs.
Readiness & Repair Specifications
polylogue/insights/readiness.py, polylogue/readiness/__init__.py, polylogue/storage/repair.py
Removes FTS-related ready flags from readiness specs. Updates repair debt logic to exclude profile FTS contributions; retains work-event inference and thread FTS.
Derived Status & Metrics
polylogue/storage/derived/derived_status.py, polylogue/storage/derived/insights.py
Removes profile FTS metrics from _session_insight_metrics(). Removes FTS statuses from build_profile_statuses().
Query Implementation
polylogue/storage/sqlite/queries/session_insight_profile_reads.py, polylogue/storage/fts/sql.py
Replaces FTS-table JOINs with LIKE-based filtering on text columns (evidence_search_text, inference_search_text, enrichment_search_text, search_text). Switches messages_fts rebuild from manual INSERT to FTS5 rebuild command.

HTTP API Response Enhancements

Layer / File(s) Summary
Surface Payload Models
polylogue/surfaces/payloads.py
Adds ConversationFlagsPayload (tool_use, thinking, paste flags), extends ConversationListRowPayload with repo, cwd_display, flags. Introduces error/diagnostic models: QueryErrorPayload, QueryMissReasonPayload, QueryMissDiagnosticsPayload. Adds response envelopes: ConversationListResponse, ConversationDetailResponse, FacetTimeRange, FacetsResponse.
HTTP Handlers & Error Handling
polylogue/daemon/http.py
Updates daemon_safe_handler to emit structured QueryErrorPayload JSON. Adds query parameter helpers: _build_query_spec_params(), _extract_repo(), _extract_cwd(), _get_bool(). Refactors conversation listing to use spec-driven params, pagination (limit/offset), optional query-miss diagnostics. Expands message/conversation payloads with message_type, word_count, metadata fields.

Supporting Changes

Layer / File(s) Summary
Configuration & Type Handling
polylogue/cli/shared/formatting.py, polylogue/sources/drive/auth.py
Updates plain_forced_by_env() to use load_polylogue_config().force_plain directly with truthiness coercion. Casts drive path config values to str with type ignores in credential/token resolution.
Test Fixture Updates
tests/unit/storage/test_backend.py
Updates test_fts_triggers_restored_before_commit schema inserts to include version column. Adds test_fts_triggers_restored_after_exception_during_ingest to verify FTS index sync after exception-driven trigger restoration.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Sinity/polylogue#749: Both PRs modify session-insight status/readiness/FTS machinery in polylogue/storage/insights/session/ and related readiness/repair modules.
  • Sinity/polylogue#687: Both PRs update archive-derived status builders and metrics in polylogue/storage/derived/ modules.

Suggested labels

area:storage, area:schema, area:api, area:cli, type:refactor, type:test

Poem

🐰 The FTS tables fade away,
LIKE patterns light the path today,
Where profiles once through indexes soared,
Now simple text-search shall be poured.
API blooms with richer tales—
repo and cwd set new sails! 🎉

✨ 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/refactor/query-contracts-859

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

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: 689f0ff546

ℹ️ 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".

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors/aligns API surface payloads by introducing shared query/status response envelopes, expanding daemon HTTP query parameter support toward the canonical ConversationQuerySpec vocabulary, and simplifying some storage/indexing internals (notably removing session-profile FTS tables and switching message FTS rebuild to the FTS5 rebuild command with an external-content table).

Changes:

  • Add shared surface payload models for query errors, list/detail envelopes, facets envelopes, and query-miss diagnostics; extend conversation list rows with repo/cwd/flags metadata.
  • Update daemon HTTP list/facets handlers to build canonical query specs from query-string params and return richer response shapes (items/total/limit/offset + optional diagnostics).
  • Remove session-profile FTS schema + readiness/repair plumbing; adjust session profile “search” to use LIKE over stored search text; update message FTS DDL to external-content mode and change rebuild SQL.

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tests/unit/storage/test_backend.py Updates archive inserts for new version column; adds new regression test around FTS trigger restoration on ingest exceptions.
polylogue/surfaces/payloads.py Adds shared response envelopes (errors, list/detail, facets, diagnostics) and extends conversation list row payload.
polylogue/storage/sqlite/schema_ddl_insight_profiles.py Removes session-profile FTS virtual tables/triggers from insight profile DDL.
polylogue/storage/sqlite/schema_ddl_archive.py Adjusts messages FTS virtual table to use external content (content='messages').
polylogue/storage/sqlite/queries/session_insight_profile_reads.py Replaces session-profile FTS MATCH queries with LIKE over *_search_text columns.
polylogue/storage/repair.py Removes session-profile FTS artifacts from repair counting logic.
polylogue/storage/insights/session/status.py Removes session-profile FTS status counts/descriptors/ready flags.
polylogue/storage/insights/session/runtime.py Removes session-profile FTS counters/ready flags from status snapshot types.
polylogue/storage/fts/sql.py Updates FTS table DDL to external-content and switches rebuild SQL to INSERT ... VALUES('rebuild').
polylogue/storage/derived/insights.py Removes derived status entries for session-profile FTS artifacts.
polylogue/storage/derived/derived_status.py Removes session-profile FTS metrics from derived-status aggregation.
polylogue/sources/drive/auth.py Adds type-check suppression for TOML/env-config string path resolution.
polylogue/readiness/init.py Removes readiness artifacts related to removed session-profile FTS tables.
polylogue/operations/specs.py Updates operation artifact dependencies to remove session-profile FTS artifacts.
polylogue/insights/storage.py Removes dropped insight tables from rebuild list (session-profile FTS family).
polylogue/insights/readiness.py Simplifies readiness specs/artifact mapping after session-profile FTS removal.
polylogue/daemon/http.py Adopts shared error envelope; expands list/facets query parsing toward ConversationQuerySpec; enriches list/detail outputs.
polylogue/cli/shared/formatting.py Switches plain-mode forcing to typed config property force_plain.
polylogue/artifacts/runtime.py Removes session-profile FTS artifact nodes and updates path dependencies accordingly.

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


# After exception + restore, triggers should be active
conn.execute(
"INSERT INTO messages(message_id, conversation_id, role, text, provider_name) VALUES(?,?,?,?,?)",
Comment on lines +1625 to +1640
# After exception + restore, triggers should be active
conn.execute(
"INSERT INTO messages(message_id, conversation_id, role, text, provider_name) VALUES(?,?,?,?,?)",
("m2", "c1", "assistant", "after exception", "test"),
)
conn.commit()

# FTS should have both messages (the original m1 via repair,
# and m2 via active trigger after restore)
from polylogue.storage.fts.fts_lifecycle import ensure_fts_index_sync

ensure_fts_index_sync(conn)
conn.execute("INSERT INTO messages_fts(messages_fts) VALUES('rebuild')")

count = conn.execute("SELECT COUNT(*) FROM messages_fts").fetchone()[0]
assert count == 2, f"Expected 2 FTS entries after exception recovery, got {count}"
Comment thread polylogue/daemon/http.py
Comment on lines +138 to +140
val = handler._get_param(params, key)
if val is not None:
spec_params[key] = val
Comment thread polylogue/daemon/http.py
Comment on lines +82 to +93
def _extract_repo(provider_meta: dict[str, object] | None) -> str | None:
if provider_meta is None:
return None
repo = provider_meta.get("repo") or provider_meta.get("repository") or provider_meta.get("git_repo")
return str(repo) if repo else None


def _extract_cwd(provider_meta: dict[str, object] | None) -> str | None:
if provider_meta is None:
return None
cwd = provider_meta.get("cwd") or provider_meta.get("working_directory") or provider_meta.get("cwd_display")
return str(cwd) if cwd else None
Comment thread polylogue/daemon/http.py
Comment on lines 639 to +652
stats = await poly.stats()
tags = await poly.list_tags()
scoped_to_query = bool(query_params)

return {
"scoped_to_query": scoped_to_query,
"providers": stats.providers,
"tags": tags,
"repos": {},
"cwd_prefixes": {},
"message_types": {},
"action_types": {},
"has_flags": {},
"time_range": None,
return configured

env_path = load_polylogue_config().get("drive_credentials_path") or str(drive_credentials_path())
env_path = load_polylogue_config().get("drive_credentials_path") or str(drive_credentials_path()) # type: ignore[arg-type]
Sinity added a commit that referenced this pull request May 7, 2026
Closes #859. CLI, MCP, daemon HTTP, and the dynamic web reader
should adapt the same archive/query/status contracts; the code
was close but the envelope spine was not yet complete. CLI and
MCP already shared `ConversationQuerySpec` through their
respective `query_contracts.py`, but daemon HTTP
`/api/conversations` only parsed a small subset of filter params.

- `polylogue/operations/specs.py`,
  `polylogue/insights/{readiness,storage}.py`,
  `polylogue/readiness/__init__.py`: shared response envelope
  models adopted by all read surfaces.
- `polylogue/daemon/http.py`: daemon `/api/conversations` and
  related endpoints now use the full filter vocabulary instead
  of a hand-shaped subset.
- `polylogue/cli/shared/formatting.py`: shared formatter consumes
  the new envelope so CLI output stays in sync with the typed
  contract.
- 19 files across the read surfaces touched, +435/-397 net.

Refs #859
Sinity added a commit that referenced this pull request May 7, 2026
Closes #859. CLI, MCP, daemon HTTP, and the dynamic web reader
should adapt the same archive/query/status contracts; the code
was close but the envelope spine was not yet complete. CLI and
MCP already shared `ConversationQuerySpec` through their
respective `query_contracts.py`, but daemon HTTP
`/api/conversations` only parsed a small subset of filter params.

- `polylogue/operations/specs.py`,
  `polylogue/insights/{readiness,storage}.py`,
  `polylogue/readiness/__init__.py`: shared response envelope
  models adopted by all read surfaces.
- `polylogue/daemon/http.py`: daemon `/api/conversations` and
  related endpoints now use the full filter vocabulary instead
  of a hand-shaped subset.
- `polylogue/cli/shared/formatting.py`: shared formatter consumes
  the new envelope so CLI output stays in sync with the typed
  contract.
- 19 files across the read surfaces touched, +435/-397 net.

Refs #859
@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.

  • 72.F064 / P1: fixed-already at the checked revision: polylogue/storage/derived/derived_status.py:185-198 now derives retrieval metrics from profile_rows, which session_insight_metrics emits at :139. The removed profilefts keys are no longer read, so the stated KeyError is absent.
  • 72.F085 / P1: stale at the checked revision: polylogue/storage/insights/session/runtime.py was deleted in b7d83e1 (chore: Merge the insights packages into ordinary layering and delete de… (chore: Merge the insights packages into ordinary layering and delete de… #4614)); the cited code no longer exists at 5ebcfe5.

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