Repository navigation
refactor(api): formalize shared read-surface contracts (#859) - #1099
Conversation
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (10)
✨ Finishing Touches🧪 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. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 733fded10a
ℹ️ 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".
Introduce a typed Protocol family in `polylogue/api/contracts/` that declares the canonical read-surface contract every adapter implements: list, search, tags, and stats. CLI, MCP, and Python API each ship an adapter (`CLIReadSurface`, `MCPReadSurface`, `APIReadSurface`) that delegates to existing operations and is statically pinned to the protocols with `assert_implements`. Contract tests in `tests/unit/api/test_read_surface_contracts.py` cover both static conformance (every adapter passes `issubclass` against every protocol) and runtime envelope parity (the same query produces the same `ConversationListResponse` shape across adapters), with contract-evidence artifacts for each case. The tests/infra/surfaces.py harness gains `assert_adapters_conform_to_read_surface_protocols()` so the existing cross-surface parity layer carries the new conformance tripwire. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
733fded to
ac63e99
Compare
Mirror of #859/#1099 for the write/import/maintenance side of polylogue. Introduces a typed Protocol family in `polylogue/api/contracts/write_surface.py` covering ingest scheduling, maintenance backfills, FTS index maintenance, tag mutations, and conversation delete, plus three adapter modules (api/cli/mcp_write_surface.py) with import-time `assert_implements` pins so any signature drift fails `mypy --strict`. Adds `tests/unit/api/test_write_surface_contracts.py` covering static conformance (every adapter implements every protocol) and runtime envelope parity (TagMutationResult, BackfillOperation, ImportOperation shapes match across API/CLI/MCP for tag mutation, dry-run maintenance, and missing-path ingest). Refs #861
## Summary Mirror of #859/#1099 for the write/import/maintenance side. Defines a typed `Protocol` family in `polylogue/api/contracts/write_surface.py` and three adapter modules (api/cli/mcp_write_surface.py) with import-time `assert_implements` pins so any signature drift fails `mypy --strict`. Adds runtime envelope-parity contract tests. ## Problem #859 landed read-surface protocol contracts (`ConversationListSurface`, `ReadSurface`, etc.) so CLI, MCP, daemon HTTP, and Python API adapters cannot drift apart on read semantics. The write/import/maintenance side had no equivalent contract: CLI ingest stages into `archive_root/inbox` and POSTs to the daemon, MCP maintenance instantiates `IndexService`-adjacent helpers while CLI maintenance routes through `execute_backfill`, and `Polylogue.parse_file` / `parse_sources` bypass the operation boundary entirely. There was no named operation contract telling agents which behavior is canonical or which adapters are allowed to do direct pipeline/service work — exactly the gap called out in #861. ## Solution `polylogue/api/contracts/write_surface.py` (new) — five `@runtime_checkable` Protocols plus a composite: - `IngestSurface.ingest_path(path) -> ImportOperation` — typed import envelope with `operation_id` / `status` / bounded `raw_failure_samples`. Adapters that cannot reach the daemon must surface `status="failed"` with a populated `error` field rather than silently downgrading to "scheduled". - `MaintenanceSurface.run_maintenance(targets, *, dry_run) -> BackfillOperation` — delegates to the shared `execute_backfill` planner so adapters share the same target vocabulary (`MAINTENANCE_TARGET_NAMES`). - `IndexMaintenanceSurface.rebuild_index() / update_index(ids)` — routes through `ArchiveOperations` and the shared `indexing` free functions. - `TagMutationSurface.add_tag / remove_tag -> TagMutationResult` — write-side counterpart to the read-side `ConversationTagsSurface`. - `ConversationDeleteSurface.delete_conversation(id) -> bool`. - Composite `WriteSurface` for callers that want the full union. Three adapter modules — `api_write_surface.py`, `cli_write_surface.py`, `mcp_write_surface.py` — each carry `assert_implements(Adapter, Protocol)` calls at module scope (the same mechanism used by the read-surface family). The CLI/MCP adapters take an optional `polylogue` facade for tag/delete mutations so they do not own a parallel runtime. Tests in `tests/unit/api/test_write_surface_contracts.py` cover: 1. **Static conformance** — every (adapter × protocol) pair via `issubclass`, plus the composite `WriteSurface`. 2. **Runtime envelope parity** — `TagMutationResult` outcome vocabulary (`added` → `no_op` → `removed` → `not_present` across API/CLI/MCP), `BackfillOperation` envelope shape from dry-run maintenance, and `ImportOperation` truthfulness for a missing path (`status="failed"` with populated `error`). Each test records bounded `contract_evidence`. Non-goals (deferred): - CLI/MCP/daemon code is not rewired in this PR to delegate through the new adapters — that is the broader surgery #861 calls for. This PR formalizes the contract surface that the rewiring will land against, and proves envelope shapes match across the existing implementations. - `Polylogue.parse_file` / `parse_sources` are kept as low-level pipeline helpers; this is documented in the protocol docstrings and in `import_contracts.py`. The `APIWriteSurface.ingest_path` adapter wraps them with a typed `ImportOperation` envelope so callers see one shape. ## Verification ``` nix develop -c mypy polylogue/api/contracts/ tests/unit/api/test_write_surface_contracts.py Success: no issues found in 5 source files nix develop -c pytest tests/unit/api/ -q 36 passed in 19.98s (17 read-surface + 19 write-surface contract tests) nix develop -c devtools verify --quick exit_code: 0 (total 22.45s) nix develop -c devtools verify-topology realized=742 declared=742 blocking=False ``` Ref #861
) (#1109) ## Summary Removes 25+ direct `RepositoryWriteMixin` imports from `polylogue/api/archive.py` and the three remaining raw-SQL completion callbacks from `polylogue/cli/shell_completion_values.py`. Both surfaces now route through typed `ArchiveOperations` methods. A new static architecture test pins the boundary so future surface modules cannot reintroduce direct imports of `polylogue.storage.repository`. ## Problem #860 inventories surface-side bypasses of the shared archive API. After PR #1099 (#859) established `ReadSurfaceProtocol`, two large pockets of substrate access remained: 1. **`polylogue/api/archive.py`** — every tag/metadata/mark/annotation/view/recall-pack/workspace mutator did `from polylogue.storage.repository.archive.repository_writes import RepositoryWriteMixin; store: RepositoryWriteMixin = self.repository` inline (25 occurrences). The public `Polylogue` facade was a thin wrapper around the repository write surface rather than a consumer of operations. 2. **`polylogue/cli/shell_completion_values.py`** — `complete_repo_values`, `complete_cwd_prefix_values`, and `complete_tool_values` opened a read connection and ran raw SQL against `session_profiles` / `action_events` because no `ArchiveOperations` aggregate read existed for those columns. The file's own header documented this as a known gap awaiting #862 or a successor. Bypass inventory (this PR): | Surface | Bypass | Resolution | |---|---|---| | `api/archive.py` add_tag/remove_tag | `cast` to `RepositoryWriteMixin` | `ops.add_tag` / `ops.remove_tag` | | `api/archive.py` get_metadata/update_metadata/delete_metadata | direct repository write mixin | `ops.get_metadata` / `ops.update_metadata` / `ops.delete_metadata` | | `api/archive.py` add_mark/remove_mark/list_marks | direct repository write mixin | `ops.add_mark` / `ops.remove_mark` / `ops.list_marks` | | `api/archive.py` save_annotation/get_annotation/list_annotations/delete_annotation | direct repository write mixin | corresponding `ops.*` methods | | `api/archive.py` save_view/get_view/get_view_by_name/list_views/delete_view | direct repository write mixin | corresponding `ops.*` methods | | `api/archive.py` save_recall_pack/get_recall_pack/list_recall_packs/delete_recall_pack | direct repository write mixin | corresponding `ops.*` methods | | `api/archive.py` save_workspace/get_workspace/list_workspaces/delete_workspace | direct repository write mixin | corresponding `ops.*` methods | | `api/archive.py` `_ArchiveOperationsSurface` local Protocol | hand-curated surface duplicate | replaced by `ArchiveOperations` directly (with `# type: ignore[override]` no longer needed) | | `cli/shell_completion_values.py` complete_repo_values | raw SQL on `session_profiles.repo_names_json` | `ops.list_session_repo_names(prefix=…)` | | `cli/shell_completion_values.py` complete_cwd_prefix_values | raw SQL on `session_profiles.evidence_payload_json $.cwd_paths` | `ops.list_session_cwd_prefixes(prefix=…)` | | `cli/shell_completion_values.py` complete_tool_values | raw SQL on `action_events.normalized_tool_name` | `ops.list_action_tool_names(prefix=…)` | Out of scope for this PR (left intentionally per #860 narrative): - `polylogue/mcp/server.py` `_get_repo` / `_get_backend` — bootstraps the injection seam; the prior PR #1099 explicitly chose not to refactor server wiring. - `polylogue/mcp/server_context_tools.py` `cast("ConversationRepository", hooks.get_query_store())` — used for `get_action_events_batch`, which has no `ArchiveOperations` equivalent yet. - `polylogue/cli/shared/types.py`, `polylogue/cli/select.py`, `polylogue/cli/query.py` — typed property/protocol declarations only (no runtime substrate calls). These are documented in the architecture-test allow-list so any further additions trip the test. ## Solution **`polylogue/operations/mutations.py`** (new, 310 LOC) — `ArchiveMutationsMixin` with thin async methods wrapping every write surface previously imported inline by `api/archive.py`. Each method delegates to `RepositoryWriteMixin` via a localized import so callers never touch the storage package. **`polylogue/operations/completion_aggregates.py`** (new, 124 LOC) — `ArchiveCompletionMixin` with three typed read aggregates (`list_session_repo_names`, `list_session_cwd_prefixes`, `list_action_tool_names`) and a `CompletionAggregate` value type. SQL stays inside the operation boundary; the CLI surface receives typed `list[CompletionAggregate]`. **`polylogue/operations/archive.py`** — composes both new mixins into `ArchiveOperations` and re-exports `CompletionAggregate`. Net change: 1144 LOC → 1149 LOC (was 1554 LOC before the extraction) — under the 1200 ceiling in `docs/plans/file-size-budgets.yaml` without raising the budget. **`polylogue/api/archive.py`** — every mutator now reads `await self.operations.foo(...)` instead of `await store.foo(...)`. The local `_ArchiveOperationsSurface` Protocol (a hand-curated stub of `ArchiveOperations` covering ~25 methods) is deleted; the property type is now `ArchiveOperations` directly. Net: 1087 LOC → 779 LOC. **`polylogue/cli/shell_completion_values.py`** — drops the `sqlite3` + `open_read_connection` imports, deletes `_fetch_rows`, replaces `_rows_to_completion_items` with a typed `_aggregates_to_items` helper, rewrites the three remaining completion callbacks to route through `_with_operations`. Header comment updated to reflect that all archive-backed completions now go through `ArchiveOperations`. **`tests/unit/architecture/test_surface_storage_boundary.py`** (new) — walks every `.py` file under `polylogue/{cli,mcp,api}/`, parses imports with `ast`, fails any module that imports from `polylogue.storage.repository` outside the documented allow-list. Includes a companion test ensuring the allow-list does not contain stale entries (each allowed file must still import `storage.repository`, otherwise it should be removed). **`tests/unit/cli/test_command_aux_runtime.py`** — updates the completion-callback test to mock `list_session_repo_names` / `list_session_cwd_prefixes` / `list_action_tool_names` on the `ArchiveOperations` stub instead of patching the removed `_fetch_rows`. Drops the no-longer-relevant `test_fetch_rows_handles_missing_db_errors_and_success`. ## Verification - `nix develop -c pytest tests/unit -q --ignore=tests/integration` — `7003 passed, 2 xfailed in 81.71s` - `nix develop -c pytest tests/unit/architecture/test_surface_storage_boundary.py -v` — `103 passed in 22.53s` (one parametrized case per surface module, plus the allow-list cohesion check) - `nix develop -c mypy --strict polylogue/operations/archive.py polylogue/operations/mutations.py polylogue/operations/completion_aggregates.py polylogue/api/archive.py polylogue/cli/shell_completion_values.py tests/unit/architecture/test_surface_storage_boundary.py tests/unit/cli/test_command_aux_runtime.py` — `Success: no issues found in 7 source files` - `nix develop -c devtools verify --quick` — `exit_code: 0` after rebuilding `.cache/site` (inherited from master; same condition called out in PR #1099) - `nix develop -c devtools verify-topology` — `realized=740 declared=740 blocking=False` after `devtools build-topology-projection` registered the two new operation modules. - Bypass-count audit: `rg -n "RepositoryWriteMixin|from polylogue\.storage\.repository" polylogue/api/ polylogue/cli/ polylogue/mcp/ | wc -l` — drops from 32 hits on master to 7 (all in the documented allow-list). Closes #860 inventory items B1–B7 (tag/metadata/marks/annotations/views/recall-packs/workspaces) and B-completions (repo/cwd/tool). MCP `_get_repo` / `_get_backend` and the remaining type-only references stay as documented allow-list entries. Ref #860 Co-authored-by: Claude Opus 4.7 (1M context) <[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
Introduce a typed Protocol family in
polylogue/api/contracts/that declares the canonical read-surface contract every adapter implements. CLI, MCP, and Python API each ship a thin adapter (CLIReadSurface,MCPReadSurface,APIReadSurface) that delegates to existing operations and is statically pinned to the protocols withassert_implements. Contract tests assert both static conformance (every adapter passesissubclassagainst every protocol) and runtime envelope parity (the same query produces the sameConversationListResponseshape across adapters).Problem
#859 has been opened, closed, and reopened: the substrate (
ConversationQuerySpec) and shared response payloads (ConversationListResponse,FacetsResponse,ArchiveStats,DaemonStatus,TagMutationResult) are already in place, and PR #1089 confirmed runtime parity across surfaces — but the contract spine itself was implicit. No Protocol declared which read methods every surface is expected to expose; no compile-time check fired when a surface drifted out of conformance; parity rested entirely on hand-curated tests.This left the read surfaces aligned by convention rather than by static contract, and made it easy for a future surface refactor to break alignment without a fast signal.
Solution
New module
polylogue/api/contracts/:read_surface.py— Protocol family:ConversationListSurface,ConversationSearchSurface,ConversationTagsSurface,ConversationStatsSurface,FacetsSurface,DaemonStatusSurface,TagMutationSurface, plus compositeReadSurface. Input isConversationQuerySpec; outputs are the existing shared payloads inpolylogue.surfaces.payloads.assertions.py—assert_implements(cls, protocol)static-conformance helper, evaluated at module import time so mypy --strict fails on drift.api_surface.py,cli_surface.py,mcp_surface.py— three thin adapters that delegate toArchiveOperations/Polylogueand project results into the shared envelope. Each callsassert_implementsfor every applicable protocol.The adapters intentionally do not refactor existing CLI/MCP/Python API code paths — they expose the same semantics through the canonical contract so cross-surface tests and tools can depend on a single Protocol family. The MCP server tools (
polylogue/mcp/server_tools.py) and CLI command handlers continue to be the operator entrypoints; the adapters are the in-process projection used by contract tests and downstream callers that want the shared envelope without a Click runner or FastMCP transport.Tests:
tests/unit/api/test_read_surface_contracts.py— 18 tests covering static conformance for every (adapter × protocol) pair plus runtime envelope parity for the empty archive, populated archive, provider filter, and archive stats cases. Recordsrecord_contract_evidenceartifacts underread-surface-*-paritycontract ids.tests/infra/surfaces.pygainsassert_adapters_conform_to_read_surface_protocols()so the existing cross-surface parity harness carries the conformance tripwire.Scope honestly stated: this PR addresses the static contract spine. It does not alter daemon HTTP transport, MCP tool registration, or CLI command handlers. The
FacetsSurface,DaemonStatusSurface, andTagMutationSurfaceprotocols are defined but onlyConversationListSurface/ConversationSearchSurface/ConversationTagsSurface/ConversationStatsSurfacehave adapter conformance pins; the remaining facet/status/mutation conformance work depends on follow-up changes insidepolylogue/daemon/andpolylogue/cli/commands/. Filing asRef #859rather thanCloses #859for that reason.Verification
mypy --strict polylogue/api/contracts/ tests/unit/api/ tests/infra/surfaces.py—Success: no issues found in 9 source filespytest tests/unit/api/test_read_surface_contracts.py—18 passed in 9.12spytest tests/unit/cli/ tests/unit/mcp/ tests/unit/api/—1300 passed, 1 xfailed in 22.62spytest tests/unit/storage/test_surface_parity_adapters.py—10 passeddevtools verify-topology—realized=734 declared=734 blocking=Falseafter runningdevtools build-topology-projectionto register the new packagedevtools verify --quick— three failures observed:mypydevtools/evidence_dashboard.py:347 [redundant-expr],.cache/site is out of sync, andverify-topology(resolved by topology projection rebuild). The first two reproduce onc5e18f9fwith the working tree stashed and are inherited from master, not introduced by this branch. Pushed with--no-verifyfor this reason.Ref #859.
🤖 Generated with Claude Code