Repository navigation
refactor(mutations): centralize tag/metadata/delete result envelopes (#862) - #893
Conversation
Problem: MCP mutation tools had three different conversation-not-found patterns, no shared result shape, and no idempotency signaling. add_tag always returned status="ok" even when the tag was already present. Solution: - Define MutationResultPayload (status, detail, affected_count, skipped_count, tag, key) as the shared mutation result envelope - Thread repository write signals: add_tag/remove_tag/delete_metadata/ update_metadata now return bool indicating actual change - Unify conversation resolution via _resolve_or_error helper - Add idempotent status codes: unchanged/not_found/deleted/ok - Add 6 mutation OperationSpec entries (mutate-add-tag through mutate-delete-conversation) Files: payloads.py, server_mutation_tools.py, repository_writes.py, metadata.py, api/archive.py, specs.py Ref #862 Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Warning Rate limit exceeded
To continue reviewing without waiting, purchase usage credits 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 (6)
✨ 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: e600dfa0dc
ℹ️ 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".
There was a problem hiding this comment.
Pull request overview
This PR centralizes tag/metadata/conversation-delete mutation contracts across MCP/API/repository layers by introducing a shared mutation result envelope and propagating idempotency signals (e.g., “unchanged”, “not_found”) up from repository writes.
Changes:
- Introduces
MutationResultPayloadfor mutation responses and migrates MCP mutation tools to use it. - Updates repository metadata/tag write helpers to return
boolindicating whether a mutation actually changed state. - Adds new mutation
OperationSpecentries describing these mutation operations and their effects.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
polylogue/storage/repository/archive/writes/metadata.py |
Makes metadata read/modify/write report whether a write occurred. |
polylogue/storage/repository/archive/repository_writes.py |
Propagates bool change signals for tag/metadata mutations through repository write mixin methods. |
polylogue/operations/specs.py |
Registers new mutation operation specs for tags/metadata/delete. |
polylogue/mcp/server_mutation_tools.py |
Switches MCP mutation tools to MutationResultPayload and adds a shared conversation resolution helper. |
polylogue/mcp/payloads.py |
Adds the shared MutationResultPayload envelope. |
polylogue/api/archive.py |
Simplifies tag mutation helpers and makes update_metadata return idempotency (bool). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| async def _metadata_read_modify_write( | ||
| self, | ||
| conversation_id: str, | ||
| mutator: Callable[[JSONDocument], bool], | ||
| ) -> None: | ||
| await metadata_read_modify_write(self._backend, conversation_id, mutator) | ||
| ) -> bool: | ||
| return await metadata_read_modify_write(self._backend, conversation_id, mutator) | ||
|
|
||
| async def update_metadata(self, conversation_id: str, key: str, value: JSONValue) -> None: | ||
| async def update_metadata(self, conversation_id: str, key: str, value: JSONValue) -> bool: | ||
| def _set(meta: JSONDocument) -> bool: | ||
| if key in meta and meta[key] == value: | ||
| return False | ||
| meta[key] = value | ||
| return True | ||
|
|
||
| await self._metadata_read_modify_write(conversation_id, _set) | ||
| return await self._metadata_read_modify_write(conversation_id, _set) | ||
|
|
||
| async def delete_metadata(self, conversation_id: str, key: str) -> None: | ||
| async def delete_metadata(self, conversation_id: str, key: str) -> bool: | ||
| def _delete(meta: JSONDocument) -> bool: | ||
| if key in meta: | ||
| del meta[key] | ||
| return True | ||
| return False | ||
|
|
||
| await self._metadata_read_modify_write(conversation_id, _delete) | ||
| return await self._metadata_read_modify_write(conversation_id, _delete) | ||
|
|
| @mcp.tool() | ||
| async def bulk_tag_conversations(conversation_ids: list[str], tags: list[str]) -> str: | ||
| async def run() -> str: | ||
| if not conversation_ids: | ||
| return hooks.error_json("bulk_tag_conversations requires at least one conversation_id") | ||
| if not tags: | ||
| return hooks.error_json("bulk_tag_conversations requires at least one tag") | ||
| if len(conversation_ids) > 100: | ||
| return hooks.error_json("bulk_tag_conversations supports at most 100 conversation_ids") | ||
| if len(tags) > 20: | ||
| return hooks.error_json("bulk_tag_conversations supports at most 20 tags") | ||
| tag_store = hooks.get_tag_store() | ||
| applied_count = await tag_store.bulk_add_tags(conversation_ids, tags) | ||
| skipped_count = len(conversation_ids) - applied_count | ||
| return hooks.json_payload( | ||
| MCPRootPayload( | ||
| root={ | ||
| "status": "ok", | ||
| "conversation_count": len(conversation_ids), | ||
| "tag_count": len(tags), | ||
| "applied_count": applied_count, | ||
| } | ||
| ) | ||
| MutationResultPayload( | ||
| status="ok", | ||
| conversation_count=len(conversation_ids), | ||
| tag_count=len(tags), | ||
| affected_count=applied_count, | ||
| skipped_count=skipped_count, | ||
| ), | ||
| exclude_none=True, | ||
| ) |
| from polylogue.mcp.server_support import _get_polylogue | ||
|
|
||
| poly = _get_polylogue() |
| async def _resolve_or_error( | ||
| hooks: ServerCallbacks, conversation_id: str | ||
| ) -> tuple[str | None, str | None]: | ||
| """Resolve a conversation ID, returning the canonical ID or an error JSON.""" | ||
| resolved = await hooks.get_query_store().resolve_id(conversation_id, strict=True) | ||
| if not resolved: | ||
| return None, hooks.error_json("conversation not found", conversation_id=conversation_id) | ||
| return resolved, None | ||
|
|
||
|
|
||
| def register_mutation_tools(mcp: FastMCP, hooks: ServerCallbacks) -> None: | ||
| @mcp.tool() | ||
| async def add_tag(conversation_id: str, tag: str) -> str: | ||
| async def run() -> str: | ||
| from polylogue.api.archive import ConversationNotFoundError | ||
|
|
||
| resolved, err = await _resolve_or_error(hooks, conversation_id) | ||
| if err: | ||
| return err | ||
| assert resolved is not None # _resolve_or_error contract | ||
| poly = hooks.get_polylogue() | ||
| try: | ||
| await poly.add_tag(conversation_id, tag) | ||
| except ConversationNotFoundError: | ||
| return hooks.error_json("conversation not found", conversation_id=conversation_id) | ||
| was_added = await poly.add_tag(resolved, tag) | ||
| return hooks.json_payload( |
| class MutationResultPayload(SurfacePayloadModel): | ||
| """Shared result envelope for tag, metadata, and delete mutations. | ||
|
|
||
| Carries idempotent status codes, context fields, and bulk-operation | ||
| counts so that CLI, MCP, API, and daemon surfaces all expose the | ||
| same mutation contract shape. | ||
| """ | ||
|
|
||
| status: str | ||
| """``ok``, ``deleted``, ``not_found``, ``unchanged``, or ``partial``.""" | ||
|
|
||
| conversation_id: str | None = None | ||
| detail: str | None = None | ||
| """Machine-readable detail: ``already_present``, ``tag_not_present``, | ||
| ``key_not_found``, ``value_unchanged``, ``conversation_not_found``.""" | ||
|
|
||
| affected_count: int | None = None | ||
| skipped_count: int | None = None | ||
| tag: str | None = None | ||
| key: str | None = None | ||
| conversation_count: int | None = None | ||
| tag_count: int | None = None | ||
| applied_count: int | None = None | ||
|
|
| name="mutate-bulk-tag-conversations", | ||
| kind=OperationKind.MAINTENANCE, | ||
| description="Apply tags to multiple conversations in one transaction. Returns affected and skipped counts.", | ||
| consumes=("conversation_tags",), | ||
| produces=("conversation_tags",), | ||
| path_targets=("tag-mutation-loop",), | ||
| code_refs=( | ||
| "polylogue.storage.repository.archive.repository_writes.RepositoryWriteMixin.bulk_add_tags", | ||
| "polylogue.mcp.server_mutation_tools.bulk_tag_conversations", | ||
| ), | ||
| surfaces=("mcp", "api"), | ||
| mutates_state=True, | ||
| idempotent=True, | ||
| effects=("DbRead", "DbWrite"), | ||
| ), | ||
| OperationSpec( | ||
| name="mutate-set-metadata", | ||
| kind=OperationKind.MAINTENANCE, | ||
| description="Set a metadata key on one conversation. Idempotent — returns unchanged when the value matches.", | ||
| consumes=("conversation_metadata",), | ||
| produces=("conversation_metadata",), | ||
| path_targets=("metadata-mutation-loop",), | ||
| code_refs=( | ||
| "polylogue.storage.repository.archive.repository_writes.RepositoryWriteMixin.update_metadata", | ||
| "polylogue.api.archive.PolylogueArchiveMixin.update_metadata", | ||
| "polylogue.mcp.server_mutation_tools.set_metadata", | ||
| ), | ||
| surfaces=("facade", "mcp", "api"), | ||
| mutates_state=True, | ||
| idempotent=True, | ||
| effects=("DbRead", "DbWrite"), | ||
| ), | ||
| OperationSpec( | ||
| name="mutate-delete-metadata", | ||
| kind=OperationKind.MAINTENANCE, | ||
| description="Delete a metadata key from one conversation. Idempotent — returns not-found when the key is absent.", | ||
| consumes=("conversation_metadata",), | ||
| produces=("conversation_metadata",), | ||
| path_targets=("metadata-mutation-loop",), | ||
| code_refs=( | ||
| "polylogue.storage.repository.archive.repository_writes.RepositoryWriteMixin.delete_metadata", | ||
| "polylogue.mcp.server_mutation_tools.delete_metadata", | ||
| ), | ||
| surfaces=("mcp", "api"), | ||
| mutates_state=True, |
Closes #862. MCP mutation tools had three different conversation-not-found patterns, no shared result shape, and no idempotency signaling — `add_tag` always returned `status="ok"` so callers could not distinguish "newly added" from "already there". - `polylogue/mcp/payloads.py`: adds `MutationResultPayload` with `status` (`ok`/`deleted`/`not_found`/`unchanged`/ `partial`), `detail` (machine-readable, e.g. `already_present`), `affected_count`, `skipped_count`, `tag`, `key`. - `polylogue/storage/repository/archive/writes/metadata.py`: `metadata_read_modify_write` returns `bool`. - `polylogue/storage/repository/archive/repository_writes.py`: `add_tag`, `remove_tag`, `delete_metadata`, `update_metadata` return `bool` indicating whether an actual change occurred. - `polylogue/api/archive.py`: `add_tag` / `remove_tag` use the repository return values; `update_metadata` returns `bool`. - `polylogue/mcp/server_mutation_tools.py`: all seven mutation tools return `MutationResultPayload`; unified `_resolve_or_error` helper for conversation resolution. - `polylogue/operations/specs.py`: six new `OperationSpec` entries (`mutate-add-tag` … `mutate-delete-conversation`). Refs #862
Direct, no-PR. Larger cleanup batch after the multi-PR merge wave landed mismatches between the agent-authored PRs. - `polylogue/protocols.py`: `TagStore` protocol return types switch from `None` to `bool` for `add_tag`, `remove_tag`, `update_metadata`, `delete_metadata`, matching the idempotency contract introduced in PR #893 (#862). - `polylogue/archive/session/{documents,models}.py`: adds the per-tool timing fields to `SessionProfileDocument` TypedDict so PR #895's timing additions roundtrip through the TypedDict consumers. - `polylogue/daemon/{health,notifications,status}.py`: fixes the circular import between `status.py` and `health.py` introduced by PR #898; tightens generic dict-type parameters in `notifications.py`. - `polylogue/storage/insights/session/profiles.py`: replaces `dict()` calls with literal `{}` where mypy's inference preferred the literal. - `polylogue/mcp/server_mutation_tools.py`: keyword-arg fixups for the `MutationResultPayload` envelope from PR #893. Refs #830, #862, #895
Closes #862. MCP mutation tools had three different conversation-not-found patterns, no shared result shape, and no idempotency signaling — `add_tag` always returned `status="ok"` so callers could not distinguish "newly added" from "already there". - `polylogue/mcp/payloads.py`: adds `MutationResultPayload` with `status` (`ok`/`deleted`/`not_found`/`unchanged`/ `partial`), `detail` (machine-readable, e.g. `already_present`), `affected_count`, `skipped_count`, `tag`, `key`. - `polylogue/storage/repository/archive/writes/metadata.py`: `metadata_read_modify_write` returns `bool`. - `polylogue/storage/repository/archive/repository_writes.py`: `add_tag`, `remove_tag`, `delete_metadata`, `update_metadata` return `bool` indicating whether an actual change occurred. - `polylogue/api/archive.py`: `add_tag` / `remove_tag` use the repository return values; `update_metadata` returns `bool`. - `polylogue/mcp/server_mutation_tools.py`: all seven mutation tools return `MutationResultPayload`; unified `_resolve_or_error` helper for conversation resolution. - `polylogue/operations/specs.py`: six new `OperationSpec` entries (`mutate-add-tag` … `mutate-delete-conversation`). Refs #862
Direct, no-PR. Larger cleanup batch after the multi-PR merge wave landed mismatches between the agent-authored PRs. - `polylogue/protocols.py`: `TagStore` protocol return types switch from `None` to `bool` for `add_tag`, `remove_tag`, `update_metadata`, `delete_metadata`, matching the idempotency contract introduced in PR #893 (#862). - `polylogue/archive/session/{documents,models}.py`: adds the per-tool timing fields to `SessionProfileDocument` TypedDict so PR #895's timing additions roundtrip through the TypedDict consumers. - `polylogue/daemon/{health,notifications,status}.py`: fixes the circular import between `status.py` and `health.py` introduced by PR #898; tightens generic dict-type parameters in `notifications.py`. - `polylogue/storage/insights/session/profiles.py`: replaces `dict()` calls with literal `{}` where mypy's inference preferred the literal. - `polylogue/mcp/server_mutation_tools.py`: keyword-arg fixups for the `MutationResultPayload` envelope from PR #893. Refs #830, #862, #895
|
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
Centralize mutation result contracts for tags, metadata, and conversation deletion. Define a shared
MutationResultPayloadenvelope with idempotent status codes, unify conversation-not-found patterns, and surface write signals through the repository layer.Problem
MCP mutation tools had three different conversation-not-found patterns, no shared result shape, and no idempotency signaling.
add_tagalways returnedstatus="ok"even when the tag was already present — callers could not distinguish "newly added" from "already there."Solution
polylogue/mcp/payloads.py: AddMutationResultPayloadwithstatus(ok/deleted/not_found/unchanged/partial),detail(machine-readable likealready_present),affected_count,skipped_count,tag,keypolylogue/storage/repository/archive/writes/metadata.py:metadata_read_modify_writereturnsboolpolylogue/storage/repository/archive/repository_writes.py:add_tag,remove_tag,delete_metadata,update_metadataall returnbool— whether actual change occurredpolylogue/api/archive.py: Simplifyadd_tag/remove_tagto use direct repository returns;update_metadatareturnsboolfor idempotencypolylogue/mcp/server_mutation_tools.py: All 7 mutation tools useMutationResultPayload; unified_resolve_or_errorhelper for conversation resolution; idempotent status codespolylogue/operations/specs.py: 6 newOperationSpecentries (mutate-add-tagthroughmutate-delete-conversation)Verification
Deferred to wave batch per #852 policy.
Ref #862