Skip to content

refactor(mutations): centralize tag metadata and delete contracts #862

Closed

Description

@Sinity

Problem

Polylogue treats user metadata, tags, and conversation deletion as surface-level mutations in several places. The behavior is not consistently expressed as one archive operation contract.

Current audit evidence:

  • Python API mutation helpers live in polylogue/api/archive.py and reach into repository/write mixins directly:
    • delete_conversation() uses self.filter().id(...).delete().
    • add_tag() / remove_tag() / get_metadata() / update_metadata() cast the repository to RepositoryWriteMixin.
  • CLI query mutations apply metadata and tags through the query execution store / repository protocol directly:
    • polylogue/cli/query_actions.py:apply_modifiers()
    • polylogue/cli/query_actions.py:delete_conversations()
  • MCP mutation tools mix paths:
    • add_tag, remove_tag, set_metadata, and delete_conversation mostly call Polylogue.
    • bulk_tag_conversations calls hooks.get_tag_store().bulk_add_tags() directly.
    • delete_metadata resolves via query store and deletes via tag store directly.
  • Daemon HTTP reset/delete path calls poly.delete_conversation() through a hand-shaped reset endpoint:
    • polylogue/daemon/http.py:_handle_reset()
  • Tag listing already has API/MCP/CLI surfaces, but mutation result semantics, idempotency, confirmation/safety, and bulk behavior are not centralized.

This matters because tags/metadata are explicitly user-owned archive state and are excluded from content hash. They need stable semantics across surfaces without binding every adapter to repository implementation details.

Scope

Define a shared user-mutation operation contract for tags, metadata, and conversation deletion.

Likely files:

  • polylogue/api/archive.py
  • polylogue/operations/archive.py or a dedicated mutation operations module
  • polylogue/cli/query_actions.py
  • polylogue/cli/query.py
  • polylogue/cli/commands/tags.py
  • polylogue/mcp/server_mutation_tools.py
  • polylogue/mcp/payloads.py
  • polylogue/daemon/http.py if reset/delete stays exposed there
  • polylogue/protocols.py
  • polylogue/storage/repository/archive/repository_writes.py
  • tests/unit/core/test_facade_api.py
  • tests/unit/cli/test_query_exec*.py
  • tests/unit/mcp/test_tool_contracts.py
  • storage tag/metadata/delete tests where operation behavior depends on repository guarantees

Implementation shape

  • Add typed request/result models or simple dataclasses for:
    • add/remove tag;
    • bulk add tags;
    • set/delete metadata;
    • delete conversation.
  • Define idempotency semantics explicitly:
    • adding an existing tag;
    • removing a missing tag;
    • setting the same metadata value;
    • deleting an already-missing conversation.
  • Keep user metadata out of content hash; this issue should reinforce that boundary rather than changing archive content identity.
  • Move API helpers to ArchiveOperations / mutation operations first, then adapt CLI/MCP/daemon surfaces.
  • Preserve surface-specific confirmation UX in CLI/MCP, but make the actual mutation result shape shared.
  • Decide whether bulk operations return applied_count, per-item results, or both, and make CLI/MCP/API consistent enough for agents to reason about partial success.
  • Avoid a generic CRUD abstraction. The contract should be archive-specific and small.

Non-goals

Dependencies and coordination

Acceptance criteria

  • API, CLI query modifiers, MCP mutation tools, and daemon delete/reset path all use a shared mutation operation or explicitly documented adapter exception.
  • Mutation result semantics are tested for idempotency and not-found behavior.
  • Bulk tag behavior is defined and tested consistently enough that applied_count / per-item success cannot be misread by an agent or caller.
  • CLI/MCP safety confirmations remain surface concerns, but the underlying delete result contract is shared.
  • No changed surface adds new direct RepositoryWriteMixin, TagStore, or repository mutation access unless it is the operation boundary or an explicitly justified adapter exception.
  • User metadata/tag changes remain excluded from content hash and do not trigger re-import/replacement semantics.

Verification

Focused checks while iterating:

  • pytest tests/unit/core/test_facade_api.py tests/unit/cli/test_query_exec.py tests/unit/cli/test_query_exec_laws.py tests/unit/mcp/test_tool_contracts.py -q
  • storage tag/metadata/delete tests when repository behavior changes
  • rg -n "RepositoryWriteMixin|bulk_add_tags|add_tag\(|remove_tag\(|update_metadata\(|delete_conversation\(|delete_metadata" polylogue/api polylogue/cli polylogue/mcp polylogue/daemon polylogue/operations tests/unit
  • devtools verify-layering --json if import-boundary rules change
  • devtools render-all --check if CLI/MCP docs/generated references change
  • devtools verify --quick, then full devtools verify before PR readiness unless using chore(backlog): daemon-first execution graph after #847 #852's intermediate/draft override

Refs #852 #841 #859 #819 #860 #861

Activity

  1. added
    type:refactor
    theme:command-surface
    phase:architecture
    area:core
    on May 6, 2026
  2. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Gap-audit split: tags/delete vs reader marks/saved views

    #867 now owns reader marks, annotations, saved views, and recall packs.

    Interpretation for #862: keep this issue focused on shared tag metadata and delete/mutation contracts. #867 should reuse the idempotency, not-found, delete-safeguard, and result-envelope conventions from #862 where they fit, but it should not hide marks/annotations/saved views inside generic tag metadata or opaque blobs.

    Refs #867 #852.

  3. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Reconnaissance Report: Centralize Tag Metadata and Delete Contracts

    Auditor: automated recon pass against polylogue/mcp/server_mutation_tools.py, polylogue/cli/commands/tags.py, polylogue/storage/repository/archive/repository_writes.py, polylogue/protocols.py, polylogue/surfaces/payloads.py. No code changes.


    Current State of Play

    Tag operations (MCP): server_mutation_tools.py registers add_tag, remove_tag, bulk_tag_conversations, list_tags:

    • add_tag and remove_tag (lines 18-57): Return MCPMutationStatusPayload(status="ok", conversation_id=..., tag=...). Use ConversationNotFoundError catch path.
    • bulk_tag_conversations (lines 60-83): Returns inline MCPRootPayload dict with status: "ok", conversation_count, tag_count, applied_count. The applied_count is the count of conversations whose tags actually changed.
    • No idempotency signal: caller cannot distinguish "tag already present" from "tag newly added" — both return status="ok".

    Metadata operations (MCP): server_mutation_tools.py registers get_metadata, set_metadata, delete_metadata:

    • get_metadata (lines 95-101): Returns MCPMetadataPayload.from_document(metadata) — a bare JSON doc, no envelope.
    • set_metadata (lines 104-126): Returns MCPMutationStatusPayload(status="ok"). Catches ConversationNotFoundError. Tries json.loads(value) for number/boolean/json parsing with silent fallback to string.
    • delete_metadata (lines 130-145): Uses resolve_id(strict=True) pattern (different from add_tag/remove_tag which use the Poly facade). Returns MCPMutationStatusPayload(status="ok"). No indication whether the key existed.

    Delete operation (MCP): server_mutation_tools.py registers delete_conversation:

    • Lines 148-171: Requires confirm=True guard. Returns MCPMutationStatusPayload(status="deleted" or "not_found"). Uses the Poly facade (_get_polylogue) rather than the consistent store pattern.

    CLI surface: cli/commands/tags.py is read-only — lists tags with optional provider/count filter. No mutation commands exist in CLI for tags or metadata.

    Underlying store (RepositoryWriteMixin): storage/repository/archive/repository_writes.py:

    • add_tag (line 136-153): False return on duplicate tag (not used by MCP adapter)
    • remove_tag (line 204-216): Mutes if tag absent
    • bulk_add_tags (line 155-202): Returns applied_count — conversations changed
    • delete_metadata (line 127-134): Mutes if key absent
    • delete_conversation (line 231-232): Delegates to delete_conversation_via_backend
    • update_metadata (line 120-125): Write-through with read-modify-write

    Inconsistency pattern:

    1. add_tag/remove_tag use Poly facade → ConversationNotFoundError catch
    2. delete_metadata uses direct resolve_id(strict=True) store access
    3. delete_conversation uses _get_polylogue() (same as Poly, but different pattern)
    4. Return payloads are ad-hoc per tool — no shared mutation result schema

    Build This

    1. Shared mutation result envelope across tag, metadata, delete:

      • One MCPMutationResult payload (extend or replace MCPMutationStatusPayload) with:
        • status: Literal["ok", "deleted", "not_found", "unchanged", "partial"]
        • conversation_id: str | None
        • detail: str | None (machine-readable detail like "already_present", "key_not_found")
        • affected_count: int | None (for bulk operations)
        • skipped_count: int | None
        • tag: str | None, key: str | None (context for single-resource ops)
      • This envelope should be the canonical mutation response shape for CLI, MCP, API, and daemon per refactor(api): define shared query/status contracts for all read surfaces #859.
    2. Idempotency semantics:

      • add_tag on already-present tag: return status="unchanged" with detail "already_present"
      • remove_tag on absent tag: return status="not_found" with detail "tag_not_present"
      • delete_metadata on absent key: return status="not_found" with detail "key_not_found"
      • delete_conversation on nonexistent: return status="not_found"
    3. Consistent conversation-not-found pattern:

      • All mutation tools should use the same resolution pattern (either resolve_id(strict=True) or Poly facade consistently).
      • Use ConversationNotFoundError for not-found with structured error envelope.
    4. CLI mutation parity (optional but recommended):

    5. Delete contract safeguards:

      • Confirm guard remains mandatory for delete_conversation.
      • Bulk delete semantics should be idempotent: deleting an already-deleted conversation returns status="not_found", not "ok".

    Do NOT Build This


    Files to Touch

    Priority File Change
    1 polylogue/surfaces/payloads.py Add shared MutationResultPayload model extending MachineSuccessPayload / SurfacePayloadModel with the fields listed above.
    2 polylogue/mcp/payloads.py Deprecate MCPMutationStatusPayload in favor of shared MutationResultPayload, or keep both with adapter.
    3 polylogue/mcp/server_mutation_tools.py Update all 7 mutation tools to use shared result envelope and idempotent status codes.
    4 polylogue/storage/repository/archive/repository_writes.py Minor — surface add_tag/remove_tag already-present signals to callers.
    5 polylogue/operations/specs.py Add OperationSpec entries for mutation operations (tag-add, tag-remove, metadata-set, metadata-delete, delete-conversation) with appropriate effects.
    6 polylogue/cli/commands/tags.py If adding CLI mutation commands (add-tag/remove-tag/set-metadata), add here.
    7 polylogue/protocols.py Possibly update TagStore protocol return types for idempotency.

    Coordination


    Focused Tests

    # Idempotency: add_tag on already-tagged conversation
    polylogue --conv chatgpt:test --add-tag test-tag
    polylogue --conv chatgpt:test --add-tag test-tag
    # Expect: second call returns status="unchanged", detail="already_present"
    
    # Delete on nonexistent
    polylogue mcp tool delete_conversation --conversation_id nonexistent:abc --confirm true
    # Expect: status="not_found"
    
    # Bulk tag with mixed present/absent
    polylogue mcp tool bulk_tag_conversations --conversation_ids '["existing:id","missing:id"]' --tags '["tag"]'
    # Expect: affected_count and skipped_count both present
    
    # Unit tests
    pytest tests/unit/mcp/ -xvs -k "mutation or tag or delete or metadata"
    # Integration
    pytest tests/integration/test_cli_tags_surface.py -xvs
    pytest tests/integration/test_mcp.py -xvs -k "tag or delete or metadata"

    Acceptance Criteria

    • Shared MutationResultPayload defines status, affected_count, skipped_count, detail, context fields
    • add_tag returns unchanged when tag already present
    • remove_tag returns not_found when tag absent or conversation not found
    • delete_metadata returns not_found when key absent
    • delete_conversation returns not_found when conversation nonexistent (not deleted)
    • All mutation tools use the same conversation resolution pattern
    • Operation specs exist for each mutation type
    • CLI/MCP/API mutation surfaces produce the same result envelope shape
    • devtools verify --quick passes; full devtools verify before PR readiness
  4. reopened this on May 7, 2026
  5. reopened this on May 7, 2026
  6. 15 remaining items

  7. reopened this on May 9, 2026
  8. Sinity commented on May 9, 2026

    @Sinity
    OwnerAuthor

    PR #978 adds the idempotency outcome field to tag mutation payloads.

    Landed:

    • outcome field on MutationResultPayload and MCPMutationStatusPayload
    • Four values: added, no_op, removed, not_present
    • Computed in MCP mutation tools, surfaced in CLI human-readable and JSON output
    • 9 focused unit tests covering all outcome paths

    Still open: shared mutation contract centralization (metadata, delete, bulk), consistent conversation-not-found patterns, operation specs — tracked in #861.

    Refs #862.

  9. Sinity commented on May 9, 2026

    @Sinity
    OwnerAuthor

    Certification — PR #978

    WORK

    Acceptance criterion (subset of #862):

    1. Idempotency outcome surfaced in mutation payload (added/no_op/removed/not_present)

    REALIZATION

    1. polylogue/mcp/payloads.py: MutationResultPayload.outcome + MCPMutationStatusPayload.outcome fields; polylogue/mcp/server_mutation_tools.py: outcome computed from add_tag/remove_tag boolean returns; polylogue/cli/commands/tags.py: CLI rendering includes outcome; test: tests/unit/mcp/test_tag_idempotency.py (9 tests × 4 outcomes + error + roundtrip)

    DECLARATION

    I declare the WORK item above to be fully realized by the matching REALIZATION entry. AC #2 of #862 (centralize mutation contract across all surfaces) is OUT OF SCOPE for this PR — tracked in #972. Verified by: pytest tests/unit/mcp/ tests/unit/cli/ tests/unit/storage/ -k tag -q → 129 passed; mypy strict: clean.

  10. Sinity commented on May 9, 2026

    @Sinity
    OwnerAuthor

    Certification — PR #991

    WORK: Centralize tag mutation operations across surfaces

    REALIZATION: polylogue/surfaces/payloads.py (shared contract) + CLI/MCP/API routing

    DECLARATION: Fully realized. Verified by pytest.

  11. Sinity commented on May 9, 2026

    @Sinity
    OwnerAuthor

    All AC satisfied. Idempotency outcome via PR #978, centralized tag operations via PR #991. Closing.

  12. Sinity commented on May 15, 2026

    @Sinity
    OwnerAuthor

    Reopened from the 2026-05-15 issue-set streamlining pass. #972 was tracking this residual indirectly; the mutation contract work belongs here. Remaining scope: shared mutation operation/result contract across CLI/API/MCP/daemon surfaces, with explicit idempotency/no-op/not-found outcomes rather than surface-local repository/tag-store calls. #978 covered part of the idempotency behavior; closeout should cite exact result envelopes and focused tests across the surfaces.

  13. reopened this on May 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:cliarea:corearea:mcpphase:architecturetheme:command-surfacetype:refactor

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions