Skip to content

refactor(surfaces): route read adapters through shared archive API (#860) - #1109

Merged
Sinity merged 1 commit into
masterfrom
feature/refactor/surface-routing-via-facade
May 16, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/refactor/surface-routing-via-facade

Conversation

@Sinity

@Sinity Sinity commented May 16, 2026

Copy link
Copy Markdown
Owner

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 refactor(mutations): centralize tag metadata and delete contracts #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 refactor(api): formalize shared read-surface contracts (#859) #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 refactor(api): formalize shared read-surface contracts (#859) #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

@coderabbitai

coderabbitai Bot commented May 16, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 39 minutes and 21 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5f228da7-f465-411b-804e-4d73c6a147d9

📥 Commits

Reviewing files that changed from the base of the PR and between ad5ada2 and fbb7219.

📒 Files selected for processing (11)
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/api/__init__.py
  • polylogue/api/archive.py
  • polylogue/cli/shell_completion_values.py
  • polylogue/operations/__init__.py
  • polylogue/operations/archive.py
  • polylogue/operations/completion_aggregates.py
  • polylogue/operations/mutations.py
  • tests/unit/architecture/test_surface_storage_boundary.py
  • tests/unit/cli/test_command_aux_runtime.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/surface-routing-via-facade

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.

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]>
@Sinity
Sinity force-pushed the feature/refactor/surface-routing-via-facade branch from 2b41667 to fbb7219 Compare May 16, 2026 23:53
@Sinity
Sinity merged commit 9c30160 into master May 16, 2026
3 checks passed
@Sinity
Sinity deleted the feature/refactor/surface-routing-via-facade branch May 16, 2026 23:53
Sinity added a commit that referenced this pull request May 17, 2026
…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]>
Sinity added a commit that referenced this pull request May 17, 2026
…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]>
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.

refactor(surfaces): route read adapters through shared archive APIs

1 participant