Repository navigation
refactor(surfaces): route read adapters through shared archive API (#860) - #1109
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 (11)
✨ 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 |
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.
New operation mixins (extracted into their own modules to stay under the
operations/archive.py file-size budget):
- ArchiveMutationsMixin in polylogue/operations/mutations.py wraps every
tag/metadata/mark/annotation/view/recall-pack/workspace write.
- ArchiveCompletionMixin in polylogue/operations/completion_aggregates.py
exposes typed list_session_repo_names/list_session_cwd_prefixes/
list_action_tool_names aggregates for CLI completions.
Adds a static architecture test
(tests/unit/architecture/test_surface_storage_boundary.py) that walks
every module under polylogue/{cli,mcp,api}/ and asserts no module
imports from polylogue.storage.repository outside a documented
allow-list of seam files (api/__init__.py, api/archive.py, api/ingest.py,
cli/shared/types.py, mcp/server.py, mcp/server_context_tools.py).
Ref #860
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2b41667 to
fbb7219
Compare
…xin (#862) (#1112) ## Summary Routes the seven remaining surface-side mutation paths through the shared `ArchiveMutationsMixin` contract introduced in #1109, completing the cross-surface centralization tracked by #862. Adds typed result models (`MetadataMutationResult`, `DeleteConversationResult`, `BulkTagMutationResult`) and a single source of truth for metadata key validation. ## Problem Audit of master left seven divergences where CLI, MCP, and daemon surfaces still bypassed the operation mixin: 1. `polylogue/cli/query_actions.py::apply_modifiers` set metadata via `repo.update_metadata` directly, skipping the conversation-existence check. 2. `polylogue/mcp/server_mutation_tools.py::bulk_tag_conversations` called `tag_store.bulk_add_tags` directly with inline 100/20 batch caps duplicated outside the operation layer. 3. `polylogue/mcp/server_mutation_tools.py::delete_metadata` called `tag_store.delete_metadata` directly with no resolution through the facade. 4. `polylogue/mcp/server_mutation_tools.py::delete_conversation` mapped `bool -> "deleted"/"not_found"` inside the surface; nothing guaranteed every adapter would do that the same way. 5. `polylogue/cli/query_actions.py::delete_conversations` called `repo.delete_conversation` directly without facade resolution or idempotency contract. 6. Metadata key validation (empty/whitespace, 200-char limit) was inline in MCP `set_metadata` only — every other surface relied on storage-layer behavior. 7. `polylogue/daemon/http.py::_handle_reset` had a latent async bug: the synchronous `_do_reset` callback called the async `poly.delete_conversation` and returned the coroutine into a JSON encode path, never deleting anything. ## Solution - **`polylogue/operations/mutations.py`**: extended `ArchiveMutationsMixin` with resolve-aware typed-result entrypoints — `set_metadata_validated`, `delete_metadata_validated`, `delete_conversation_safe`, `bulk_tag_conversations` — plus the centralized `_validate_metadata_key` helper and a `MetadataKeyValidationError` exception. The previous bool-returning methods stay as low-level delegates. - **`polylogue/surfaces/payloads.py`**: added typed `MetadataMutationResult`, `DeleteConversationResult`, `BulkTagMutationResult`, and `validate_metadata_key` / `METADATA_KEY_MAX_LENGTH` constants. - **`polylogue/api/archive.py`**: `Polylogue.delete_conversation`, `update_metadata`, the new `set_metadata`, `delete_metadata`, `delete_conversation_safe`, and `bulk_tag_conversations` all route through the mixin. - **`polylogue/cli/query_actions.py`**: `apply_modifiers` metadata writes go through `env.polylogue.set_metadata`; `delete_conversations` calls `env.polylogue.delete_conversation_safe`. Custom-repo escape hatches preserved for test/batch tools. - **`polylogue/mcp/server_mutation_tools.py`**: bulk tagging, set/delete metadata, and delete-conversation tools route through the facade and the typed results; key validation runs at the surface boundary before opening the facade so unit tests can exercise the rejection path without standing up an archive. - **`polylogue/daemon/http.py`**: `_handle_reset` now awaits `delete_conversation_safe` through the existing `_sync_run` async bridge and removes the obsolete `_get_or_create_polylogue` helper. - **`tests/unit/operations/test_mutations.py`** (new): 17 tests covering every (mutation, exists/missing, validation) pair on top of a real SQLite archive built via `ConversationBuilder`. - **`tests/unit/mcp/test_tool_contracts.py`**, **`tests/infra/mcp.py`**: refreshed mocks to track the new facade-typed return values. - **`tests/property/test_filter_chain_laws.py`**: fix for an inherited property-test failure (provider filter replaces prior provider rather than intersecting, so the monotonicity law required tightening to an impossible provider on disagreement). Surfaced by `devtools verify` before this PR could be merged. ## Verification ``` $ devtools verify --quick total_duration_s: 20.22, exit_code: 0 $ devtools verify --all "name": "pytest full", "exit": 0, "count": 7268, "passed": 7266, "xfailed": 2 total_duration_s: 101.93, exit_code: 0 $ pytest tests/unit/operations/test_mutations.py 17 passed in 8.13s ``` Closes #862 Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…1115) ## Summary CLI polish pass for #958 covering two concrete user-visible behaviors: NO_COLOR support and graceful narrow-terminal output. The existing completions surface (`polylogue/cli/shell_completion_values.py`, last revised by #1109) already covers the issue's dynamic-completer acceptance criteria — provider names, conversation IDs, tags, repo, cwd-prefix, tool names — so this PR does not touch it. ## Problem - The CLI honored `POLYLOGUE_FORCE_PLAIN` but ignored the cross-tool `NO_COLOR` convention (https://no-color.org/). Downstream pipelines setting `NO_COLOR=1` still got ANSI escape codes in any TTY path. - `output_summary_list` and `output_search_hits` built fixed-shape Rich tables (ID/Date/Provider/Title/Msgs[/Match]) with a 63-char title budget, regardless of terminal width. At narrow widths (≤60 columns) the table overflowed; at the 40-column edge it became unreadable. ## Solution `polylogue/cli/shared/formatting.py`: - New `no_color_requested()` honors the `NO_COLOR` env var per the no-color.org spec (presence of any non-empty value = no color). - `should_use_plain()` now bridges `NO_COLOR` to plain mode, matching the user-visible effect ("no color in output") without touching `polylogue/ui/` (owned by another lane). Documented as a deliberate short-form: true color-suppression-without-layout-drop would require flipping `no_color=False` in `polylogue/ui/facade.py`. `polylogue/cli/query_output.py`: - New `_summary_list_layout(width)`, `_search_hit_layout(width)`, `_title_budget(width)` helpers pin a deterministic wide(≥80)/mid(≥60)/narrow(≥40)/sub-narrow column selection. - `output_summary_list` and `output_search_hits` consult `env.ui.console.width` and assemble columns/rows from the selected set; below 40 columns we fall back to a single `title` column rather than letting Rich wrap. `tests/unit/cli/test_color_and_layout.py`: - Pins `NO_COLOR` detection semantics (presence vs empty), the `should_use_plain` bridge, end-to-end `polylogue list` byte-level ANSI absence under `NO_COLOR=1`, the layout column sets at every breakpoint, and the title-budget monotonicity contract. Out of scope (deferred to follow-ups): - True color-only-no-layout-drop under `NO_COLOR` (requires `polylogue/ui/facade.py` edit; ui/ is owned by another lane). - TUI/textual color discipline (#958 explicitly excludes the TUI). - Standardizing short flag aliases across all subcommands (separate ergonomics pass). ## Verification ``` nix develop -c devtools verify --quick # all 16 steps green nix develop -c pytest tests/unit/cli/ -q # 1088 passed, 1 xfailed ``` The new contracts (`test_color_and_layout.py`) cover both behaviors: 13 tests, all pinned to public-observable surfaces (env var, exit codes, column-set tuples, title-budget integers). Ref #958 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Removes 25+ direct
RepositoryWriteMixinimports frompolylogue/api/archive.pyand the three remaining raw-SQL completion callbacks frompolylogue/cli/shell_completion_values.py. Both surfaces now route through typedArchiveOperationsmethods. A new static architecture test pins the boundary so future surface modules cannot reintroduce direct imports ofpolylogue.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:polylogue/api/archive.py— every tag/metadata/mark/annotation/view/recall-pack/workspace mutator didfrom polylogue.storage.repository.archive.repository_writes import RepositoryWriteMixin; store: RepositoryWriteMixin = self.repositoryinline (25 occurrences). The publicPolyloguefacade was a thin wrapper around the repository write surface rather than a consumer of operations.polylogue/cli/shell_completion_values.py—complete_repo_values,complete_cwd_prefix_values, andcomplete_tool_valuesopened a read connection and ran raw SQL againstsession_profiles/action_eventsbecause noArchiveOperationsaggregate read existed for those columns. The file's own header documented this as a known gap awaiting refactor(mutations): centralize tag metadata and delete contracts #862 or a successor.Bypass inventory (this PR):
api/archive.pyadd_tag/remove_tagcasttoRepositoryWriteMixinops.add_tag/ops.remove_tagapi/archive.pyget_metadata/update_metadata/delete_metadataops.get_metadata/ops.update_metadata/ops.delete_metadataapi/archive.pyadd_mark/remove_mark/list_marksops.add_mark/ops.remove_mark/ops.list_marksapi/archive.pysave_annotation/get_annotation/list_annotations/delete_annotationops.*methodsapi/archive.pysave_view/get_view/get_view_by_name/list_views/delete_viewops.*methodsapi/archive.pysave_recall_pack/get_recall_pack/list_recall_packs/delete_recall_packops.*methodsapi/archive.pysave_workspace/get_workspace/list_workspaces/delete_workspaceops.*methodsapi/archive.py_ArchiveOperationsSurfacelocal ProtocolArchiveOperationsdirectly (with# type: ignore[override]no longer needed)cli/shell_completion_values.pycomplete_repo_valuessession_profiles.repo_names_jsonops.list_session_repo_names(prefix=…)cli/shell_completion_values.pycomplete_cwd_prefix_valuessession_profiles.evidence_payload_json $.cwd_pathsops.list_session_cwd_prefixes(prefix=…)cli/shell_completion_values.pycomplete_tool_valuesaction_events.normalized_tool_nameops.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 refactor(api): formalize shared read-surface contracts (#859) #1099 explicitly chose not to refactor server wiring.polylogue/mcp/server_context_tools.pycast("ConversationRepository", hooks.get_query_store())— used forget_action_events_batch, which has noArchiveOperationsequivalent 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) —ArchiveMutationsMixinwith thin async methods wrapping every write surface previously imported inline byapi/archive.py. Each method delegates toRepositoryWriteMixinvia a localized import so callers never touch the storage package.polylogue/operations/completion_aggregates.py(new, 124 LOC) —ArchiveCompletionMixinwith three typed read aggregates (list_session_repo_names,list_session_cwd_prefixes,list_action_tool_names) and aCompletionAggregatevalue type. SQL stays inside the operation boundary; the CLI surface receives typedlist[CompletionAggregate].polylogue/operations/archive.py— composes both new mixins intoArchiveOperationsand re-exportsCompletionAggregate. Net change: 1144 LOC → 1149 LOC (was 1554 LOC before the extraction) — under the 1200 ceiling indocs/plans/file-size-budgets.yamlwithout raising the budget.polylogue/api/archive.py— every mutator now readsawait self.operations.foo(...)instead ofawait store.foo(...). The local_ArchiveOperationsSurfaceProtocol (a hand-curated stub ofArchiveOperationscovering ~25 methods) is deleted; the property type is nowArchiveOperationsdirectly. Net: 1087 LOC → 779 LOC.polylogue/cli/shell_completion_values.py— drops thesqlite3+open_read_connectionimports, deletes_fetch_rows, replaces_rows_to_completion_itemswith a typed_aggregates_to_itemshelper, rewrites the three remaining completion callbacks to route through_with_operations. Header comment updated to reflect that all archive-backed completions now go throughArchiveOperations.tests/unit/architecture/test_surface_storage_boundary.py(new) — walks every.pyfile underpolylogue/{cli,mcp,api}/, parses imports withast, fails any module that imports frompolylogue.storage.repositoryoutside the documented allow-list. Includes a companion test ensuring the allow-list does not contain stale entries (each allowed file must still importstorage.repository, otherwise it should be removed).tests/unit/cli/test_command_aux_runtime.py— updates the completion-callback test to mocklist_session_repo_names/list_session_cwd_prefixes/list_action_tool_nameson theArchiveOperationsstub instead of patching the removed_fetch_rows. Drops the no-longer-relevanttest_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.71snix 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 filesnix develop -c devtools verify --quick—exit_code: 0after rebuilding.cache/site(inherited from master; same condition called out in PR refactor(api): formalize shared read-surface contracts (#859) #1099)nix develop -c devtools verify-topology—realized=740 declared=740 blocking=Falseafterdevtools build-topology-projectionregistered the two new operation modules.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_backendand the remaining type-only references stay as documented allow-list entries.Ref #860