Skip to content

feat: add neighbor candidate discovery (#364) - #364

Merged
Sinity merged 2 commits into
masterfrom
feature/feat/neighbor-candidates
Apr 22, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/feat/neighbor-candidates

Conversation

@Sinity

@Sinity Sinity commented Apr 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds explainable neighboring-conversation discovery for known conversation IDs and fuzzy query seeds. The new polylogue neighbors CLI command and neighbor_candidates MCP tool return ranked candidates with explicit reasons such as same title, nearby time, shared attachment identity, query match, source-content search, and body content similarity.

Problem

Closes #220. Polylogue had canonical exact-ID retrieval and archival dedupe primitives, but users had no durable way to inspect nearby or near-duplicate candidates when several conversations looked plausible from title/date summaries alone. That pushed duplicate-like exploration into ad hoc search instead of an explainable retrieval surface.

Solution

  • Added polylogue/lib/neighbor_candidates.py as the shared selector and evidence model.
  • Wired ArchiveOperations.neighbor_candidates() so surfaces share one substrate implementation.
  • Added root CLI command polylogue neighbors with plain and JSON output.
  • Added MCP tool neighbor_candidates plus shared CLI/MCP payload models.
  • Updated generated CLI/proof/reference surfaces for the new command.
  • Added tests for same-title-different-body candidates, nearby similar content, content-similar candidates outside the time window, query-seeded candidates, CLI JSON output, MCP payloads, command registration, and terminal help snapshots.
  • Added committed showcase help baselines for the new command after remote showcase-verify exposed the missing baseline.

Verification

ruff check polylogue/lib/neighbor_candidates.py polylogue/operations/archive.py polylogue/surface_payloads.py polylogue/mcp/payloads.py polylogue/mcp/server_tools.py polylogue/cli/commands/neighbors.py polylogue/cli/click_command_registration.py tests/unit/core/test_neighbor_candidates.py tests/unit/cli/test_neighbors_command.py tests/unit/mcp/test_tool_contracts.py tests/infra/mcp.py
mypy polylogue/lib/neighbor_candidates.py polylogue/operations/archive.py polylogue/surface_payloads.py polylogue/mcp/payloads.py polylogue/mcp/server_tools.py polylogue/cli/commands/neighbors.py tests/unit/core/test_neighbor_candidates.py tests/unit/cli/test_neighbors_command.py tests/unit/mcp/test_tool_contracts.py tests/infra/mcp.py
pytest -q tests/unit/core/test_neighbor_candidates.py tests/unit/cli/test_neighbors_command.py tests/unit/mcp/test_tool_contracts.py
devtools render-all --check
pytest -q tests/unit/cli/test_click_app.py::TestCliMetadata::test_all_subcommands_registered tests/unit/cli/test_terminal_snapshots.py::TestHelpOutput::test_help_output_snapshot tests/unit/cli/test_terminal_snapshots.py::TestTerminalDimensions::test_help_at_narrow_width tests/unit/cli/test_terminal_snapshots.py::TestTerminalDimensions::test_help_at_wide_width
devtools verify
devtools verify-showcase
pytest -q --ignore=tests/integration
devtools verify --quick

devtools verify finished with verify: all checks passed before the showcase baseline follow-up. After refreshing baselines, devtools verify-showcase reported All baselines match, direct pytest reported 5108 passed in 173.83s, and the pre-push hook ran devtools verify --quick with verify: all checks passed.

Summary by CodeRabbit

  • New Features

    • Added polylogue neighbors command to discover and display conversations similar to a target or matching a query, with detailed explainable reasoning for candidate matches.
  • Documentation

    • Updated documentation and CLI help to reflect the new neighbors command and its configuration options.
  • Tests

    • Added test coverage for the new neighbors command and discovery functionality.

Problem: exact-id lookup and search results could identify canonical conversations, but did not expose an explainable way to inspect likely neighboring or near-duplicate candidates around a known conversation or fuzzy query.

What changed: added the shared neighbor-candidate selector, reason model, archive operation, CLI command, MCP tool, JSON payloads, generated surfaces, and coverage for same-title, nearby-time, shared-query, and content-similar evidence.

Verification: devtools verify.

Closes #220
@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

A new feature for discovering neighboring or near-duplicate conversations has been added. It includes a core discovery library with ranking and explainability, CLI and MCP surfaces, payload serialization, and comprehensive test coverage across command, core logic, and MCP tool validation.

Changes

Cohort / File(s) Summary
Core neighbor discovery logic
polylogue/lib/neighbor_candidates.py
New 567-line module implementing conversation neighbor discovery with explainable ranking. Defines domain models (NeighborReason, ConversationNeighborCandidate, NeighborDiscoveryRequest, NeighborDiscoveryError) and async discovery algorithm using multiple strategies: title matching, time-window proximity, attachment identity, and content-based similarity scoring with configurable thresholds.
Surface payload serialization
polylogue/surface_payloads.py, polylogue/mcp/payloads.py
Added ConversationNeighborReasonPayload and ConversationNeighborCandidatePayload classes with conversion methods. Extended MCP payload layer with MCPConversationNeighborCandidateListPayload wrapper and builder function for serializing candidate lists.
Operations/archive integration
polylogue/operations/archive.py
Added async neighbor_candidates() method to ArchiveSearchMixin that calls the discovery library and augments results with message counts via batch fetch.
CLI command
polylogue/cli/click_command_registration.py, polylogue/cli/commands/neighbors.py
Registered new top-level neighbors command. Implementation validates input (requires --id or --query), runs discovery via run_coroutine_sync, handles NeighborDiscoveryError, and renders output in JSON or plain-text with explainability reasons per candidate.
MCP tool integration
polylogue/mcp/server_tools.py
Added new neighbor_candidates tool accepting optional id/query, provider, limit, and window_hours. Returns JSON payload using the new payload builder with limit clamping.
Documentation
docs/cli-reference.md, docs/test-quality-workflows.md, docs/verification-catalog.md
Updated CLI reference with new neighbors command entry. Updated test-quality workflow counts (237→238 scenarios, 132→133 inferred exercises) and added help-neighbors exercise entry. Updated verification catalog snapshot counts: subjects 9033→9034, obligations 9112→9115, with new command subject entry.
Test baselines and snapshots
tests/baselines/showcase/help-*.txt, tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
Added new help-neighbors.txt baseline documenting command options. Updated CLI help snapshot to include neighbors command in main commands list.
Command integration tests
tests/unit/cli/test_click_app.py, tests/unit/cli/test_neighbors_command.py
Added "neighbors" to expected subcommands registry. New test module validates neighbors_command with mocked neighbor_candidates calls, verifies JSON/plain output, and ensures proper error handling when neither --id nor --query is provided.
Core discovery tests
tests/unit/core/test_neighbor_candidates.py
New async test module covering four scenarios: same-title-different-body within window (verifies same_title reason), nearby-time with content similarity (verifies ranking and reason kinds), content-similar candidate outside time window (verifies content_search reason), and query-based discovery with provider filter.
MCP tool contract tests
tests/infra/mcp.py, tests/unit/mcp/test_tool_contracts.py
Added "neighbor_candidates" to expected MCP tool names. Updated mock helper with AsyncMock returning empty list. New test validates MCP tool surface returns candidate reasons and verifies the async call signature.

Sequence Diagram(s)

sequenceDiagram
    participant User as User/CLI
    participant CLI as neighbors_command
    participant Ops as ArchiveSearchMixin
    participant Lib as discover_neighbor_candidates
    participant Store as ConversationStore
    participant Output as JSON/Text Renderer

    User->>CLI: neighbors --id target --query ...
    CLI->>CLI: Validate (--id or --query)
    CLI->>Ops: neighbor_candidates(conversation_id, query, ...)
    Ops->>Lib: discover_neighbor_candidates(request)
    
    Lib->>Store: Load target conversation (if id given)
    Lib->>Store: List candidates by title/time/attachments/search
    Lib->>Lib: Score candidates (same_title, nearby_time, content_similarity)
    Lib->>Lib: Sort by rank & recency
    Lib-->>Ops: List[ConversationNeighborCandidate]
    
    Ops->>Store: Batch fetch message counts for candidates
    Ops-->>CLI: Candidates with message counts
    
    CLI->>Output: Serialize to JSON or plain-text
    Output-->>User: Formatted neighbor results with reasons
Loading
sequenceDiagram
    participant MCP as MCP Client
    participant Tool as neighbor_candidates Tool
    participant Server as mcp_server
    participant Ops as Archive Operations
    participant Payload as Payload Builder

    MCP->>Tool: Call with id/query params
    Tool->>Server: Invoke within MCP context
    Server->>Ops: neighbor_candidates(id, query, limit, window_hours)
    Ops-->>Server: List[ConversationNeighborCandidate]
    Server->>Payload: conversation_neighbor_candidate_list_payload(candidates)
    Payload->>Payload: Convert to MCPConversationNeighborCandidatePayload[]
    Payload-->>Server: MCPConversationNeighborCandidateListPayload
    Server-->>Tool: JSON serialized payload
    Tool-->>MCP: {"root": [neighbor_candidate, ...]}
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

The review requires careful attention to: (1) the discovery algorithm's multi-strategy candidate ranking and scoring logic (567 lines), (2) proper validation and error handling in the CLI command, (3) correct payload serialization across surface/MCP layers, (4) integration between operations and the library, and (5) verification that test coverage validates core heuristics (same-title, proximity, content similarity). The changes are heterogeneous across multiple subsystems but follow consistent patterns.

Suggested labels

type:feat, area:cli, area:storage, area:pipeline, area:docs, type:test

Poem

🐰 Neighbors all around us hide,
Now discovered side by side—
Same title, time, or matching seed,
Ranked and reasoned for your read!
Near-duplicates no longer lost,
Just explain the why and cost! 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add neighbor candidate discovery' directly and accurately summarizes the main addition of a new neighbor discovery feature with CLI and MCP support.
Description check ✅ Passed The PR description follows the template with all required sections (Summary, Problem, Solution, Verification) completed with detailed, specific information about the implementation.
Linked Issues check ✅ Passed All coding requirements from issue #220 are met: neighbor discovery implementation, explainable reasons, CLI and MCP surfaces, and comprehensive tests covering required scenarios.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the neighbor discovery feature: core library, operations, surfaces (CLI/MCP), payloads, tests, and documentation. No unrelated modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/neighbor-candidates

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 changed the title feat: add neighbor candidate discovery feat: add neighbor candidate discovery (#364) Apr 22, 2026

@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: 5644280158

ℹ️ 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/lib/neighbor_candidates.py Resolved
Problem: adding the root neighbors command changed the deterministic tier-0 showcase help surface and introduced a new help exercise without a committed baseline.

What changed: refreshed the showcase baselines so help-main includes neighbors and help-neighbors records the command-specific help output.

Verification: devtools verify-showcase; pytest -q --ignore=tests/integration.

Refs #220
@Sinity
Sinity merged commit d837ab1 into master Apr 22, 2026
10 of 14 checks passed
@Sinity
Sinity deleted the feature/feat/neighbor-candidates branch April 22, 2026 18:59
@Sinity
Sinity requested a review from Copilot May 1, 2026 00:44
@Sinity
Sinity requested review from Copilot and removed request for Copilot May 1, 2026 01:05
Sinity added a commit that referenced this pull request May 7, 2026
## Summary

Adds explainable neighboring-conversation discovery for known conversation IDs and fuzzy query seeds. The new `polylogue neighbors` CLI command and `neighbor_candidates` MCP tool return ranked candidates with explicit reasons such as same title, nearby time, shared attachment identity, query match, source-content search, and body content similarity.

## Problem

Closes #220. Polylogue had canonical exact-ID retrieval and archival dedupe primitives, but users had no durable way to inspect nearby or near-duplicate candidates when several conversations looked plausible from title/date summaries alone. That pushed duplicate-like exploration into ad hoc search instead of an explainable retrieval surface.

## Solution

- Added `polylogue/lib/neighbor_candidates.py` as the shared selector and evidence model.
- Wired `ArchiveOperations.neighbor_candidates()` so surfaces share one substrate implementation.
- Added root CLI command `polylogue neighbors` with plain and JSON output.
- Added MCP tool `neighbor_candidates` plus shared CLI/MCP payload models.
- Updated generated CLI/proof/reference surfaces for the new command.
- Added tests for same-title-different-body candidates, nearby similar content, content-similar candidates outside the time window, query-seeded candidates, CLI JSON output, MCP payloads, command registration, and terminal help snapshots.
- Added committed showcase help baselines for the new command after remote `showcase-verify` exposed the missing baseline.

## Verification

```text
ruff check polylogue/lib/neighbor_candidates.py polylogue/operations/archive.py polylogue/surface_payloads.py polylogue/mcp/payloads.py polylogue/mcp/server_tools.py polylogue/cli/commands/neighbors.py polylogue/cli/click_command_registration.py tests/unit/core/test_neighbor_candidates.py tests/unit/cli/test_neighbors_command.py tests/unit/mcp/test_tool_contracts.py tests/infra/mcp.py
mypy polylogue/lib/neighbor_candidates.py polylogue/operations/archive.py polylogue/surface_payloads.py polylogue/mcp/payloads.py polylogue/mcp/server_tools.py polylogue/cli/commands/neighbors.py tests/unit/core/test_neighbor_candidates.py tests/unit/cli/test_neighbors_command.py tests/unit/mcp/test_tool_contracts.py tests/infra/mcp.py
pytest -q tests/unit/core/test_neighbor_candidates.py tests/unit/cli/test_neighbors_command.py tests/unit/mcp/test_tool_contracts.py
devtools render-all --check
pytest -q tests/unit/cli/test_click_app.py::TestCliMetadata::test_all_subcommands_registered tests/unit/cli/test_terminal_snapshots.py::TestHelpOutput::test_help_output_snapshot tests/unit/cli/test_terminal_snapshots.py::TestTerminalDimensions::test_help_at_narrow_width tests/unit/cli/test_terminal_snapshots.py::TestTerminalDimensions::test_help_at_wide_width
devtools verify
devtools verify-showcase
pytest -q --ignore=tests/integration
devtools verify --quick
```

`devtools verify` finished with `verify: all checks passed` before the showcase baseline follow-up. After refreshing baselines, `devtools verify-showcase` reported `All baselines match`, direct pytest reported `5108 passed in 173.83s`, and the pre-push hook ran `devtools verify --quick` with `verify: all checks passed`.

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **New Features**
  * Added `polylogue neighbors` command to discover and display conversations similar to a target or matching a query, with detailed explainable reasoning for candidate matches.

* **Documentation**
  * Updated documentation and CLI help to reflect the new neighbors command and its configuration options.

* **Tests**
  * Added test coverage for the new neighbors command and discovery functionality.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@Sinity

Sinity commented Sep 30, 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.

feat: add neighboring and near-duplicate conversation discovery

1 participant