Skip to content

refactor(mutations): centralize tag/metadata/delete result envelopes (#862) - #893

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

Sinity merged 1 commit into
masterfrom
feature/refactor/mutation-contracts-862

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026

Copy link
Copy Markdown
Owner

Summary

Centralize mutation result contracts for tags, metadata, and conversation deletion. Define a shared MutationResultPayload envelope 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_tag always returned status="ok" even when the tag was already present — callers could not distinguish "newly added" from "already there."

Solution

  • polylogue/mcp/payloads.py: Add MutationResultPayload with status (ok/deleted/not_found/unchanged/partial), detail (machine-readable like 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 all return bool — whether actual change occurred
  • polylogue/api/archive.py: Simplify add_tag/remove_tag to use direct repository returns; update_metadata returns bool for idempotency
  • polylogue/mcp/server_mutation_tools.py: All 7 mutation tools use MutationResultPayload; unified _resolve_or_error helper for conversation resolution; idempotent status codes
  • polylogue/operations/specs.py: 6 new OperationSpec entries (mutate-add-tag through mutate-delete-conversation)

Verification

Deferred to wave batch per #852 policy.

Ref #862

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]>
Copilot AI review requested due to automatic review settings May 7, 2026 08:50
@coderabbitai

coderabbitai Bot commented May 7, 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 33 seconds before requesting another review.

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 @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: 0ca88955-f527-4be3-91a8-76a7ea7e5cc8

📥 Commits

Reviewing files that changed from the base of the PR and between b0d74c5 and e600dfa.

📒 Files selected for processing (6)
  • polylogue/api/archive.py
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_mutation_tools.py
  • polylogue/operations/specs.py
  • polylogue/storage/repository/archive/repository_writes.py
  • polylogue/storage/repository/archive/writes/metadata.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/mutation-contracts-862

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.

@Sinity
Sinity merged commit 8080cea into master May 7, 2026
5 checks passed
@Sinity
Sinity deleted the feature/refactor/mutation-contracts-862 branch May 7, 2026 08:51

@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: 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".

Comment thread polylogue/mcp/server_mutation_tools.py Resolved

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 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 MutationResultPayload for mutation responses and migrates MCP mutation tools to use it.
  • Updates repository metadata/tag write helpers to return bool indicating whether a mutation actually changed state.
  • Adds new mutation OperationSpec entries 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.

Comment on lines 113 to 137
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)

Comment on lines 74 to 97
@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,
)
Comment on lines 183 to 185
from polylogue.mcp.server_support import _get_polylogue

poly = _get_polylogue()
Comment on lines +21 to 41
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(
Comment thread polylogue/mcp/payloads.py
Comment on lines +245 to +268
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

Comment on lines +596 to +640
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,
Sinity added a commit that referenced this pull request May 7, 2026
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
Sinity added a commit that referenced this pull request May 7, 2026
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
Sinity added a commit that referenced this pull request May 7, 2026
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
Sinity added a commit that referenced this pull request May 7, 2026
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
@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.

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