Skip to content

refactor(mcp): sink analysis primitives into insights/ + api facade - #2612

Merged
Sinity merged 6 commits into
masterfrom
refactor/mcp/sink-analysis-into-insights
Jul 9, 2026
Merged

Sinity merged 6 commits into
masterfrom
refactor/mcp/sink-analysis-into-insights

Conversation

@Sinity

@Sinity Sinity commented Jul 9, 2026 •

Copy link
Copy Markdown
Owner

Summary

Moves 7 analysis primitives (correlate_sessions, find_similar_sessions's metadata lane, aggregate_sessions, workflow_shape_distribution, find_abandoned_sessions, tool_call_latency_distribution, compare_sessions) out of the MCP-only surface (mcp/server_insight_tools.py) into insights/ + the async Polylogue facade, so CLI/library callers can reach the same math the MCP tools use.

Problem

server_insight_tools.py implemented analysis math directly in the MCP surface — Pearson correlation, a weighted similarity heuristic, GROUP-BY aggregation + severity-rank ordering + ISO-week bucketing, nearest-rank percentile computation, and per-key set-diff — all unreachable from CLI/library callers.

Solution

  • insights/archive_rollups.py extended with aggregate_session_profiles_by_dimension, workflow_shape_distribution_buckets, abandoned_session_items (+ ABANDONMENT_SEVERITY_RANK), iso_week_bucket_key, and tool_call_latency_distribution_payload (reuses portfolio.py's existing _percentile nearest-rank algorithm rather than a second implementation).
  • New insights/session_analytics.py holds pearson_session_correlation, compute_metadata_similarity_candidates, build_session_comparison_row/diff_session_comparison_rows — primitives with no prior home.
  • api/insights.py gained 7 facade methods delegating to the pure functions above.
  • mcp/server_insight_tools.py shrank 1181→803 lines; the 6 MCP tools are now thin wrappers with zero residual math.

Verification

Independently re-verified (not just the authoring agent's own report):

  • Grepped server_insight_tools.py for _pearson/percentile/GROUP BY/severity_rank — zero hits beyond one comment.
  • Confirmed the 1181→803 line shrink via git show against the pre-refactor commit.
  • Read tests/unit/mcp/test_analysis_primitives_facade_parity.py directly and confirmed it genuinely proves what its docstring claims: constructs a real Polylogue facade, calls the MCP tool's handler directly (not over the wire), asserts json.loads(raw) == facade_result across all 7 primitives.
  • mypy --strict on all 4 touched production files: clean.
  • devtools test across new/rewired test files (test_archive_rollups.py, test_session_analytics.py, test_session_analytics_facade.py, test_facade_contracts.py, test_analysis_primitives_facade_parity.py, test_aggregate_sessions.py, test_session_analysis_primitives.py, test_insight_shape_tools.py): 316 passed.
  • devtools render all --check: clean (topology projection regenerated for the new module).

Ref polylogue-9e5.24.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added session analysis capabilities for grouping, distributions, comparisons, correlation, and similarity lookups.
    • Expanded MCP tools to surface the new session analytics features through the app.
  • Bug Fixes

    • Improved handling of invalid inputs and missing data across session analysis actions.
    • Fixed boundary count reporting for daemon workload probes.
    • Corrected several analytics results to use consistent calculations and filtering.
  • Tests

    • Added and updated coverage for session analytics behavior, MCP delegation, and tool parity checks.

Sinity and others added 5 commits July 9, 2026 07:33
Ref polylogue-9e5.24.

Co-Authored-By: Claude <[email protected]>
Problem: server_insight_tools.py implemented Pearson correlation, a
weighted metadata-similarity heuristic, GROUP-BY aggregation, ISO-week
bucketing, a terminal-state severity rank, nearest-rank percentile, and
per-key set-diff computation directly in the MCP surface -- unreachable
from the CLI or the Python library facade.

What changed:
- polylogue/insights/archive_rollups.py: extend the existing aggregate
  reducers with aggregate_session_profiles_by_dimension,
  workflow_shape_distribution_buckets, abandoned_session_items (+
  ABANDONMENT_SEVERITY_RANK), iso_week_bucket_key, and
  tool_call_latency_distribution_payload (reuses portfolio.py's
  _percentile nearest-rank algorithm rather than a second one).
- polylogue/insights/session_analytics.py (new): pearson_session_correlation,
  compute_metadata_similarity_candidates, build_session_comparison_row +
  diff_session_comparison_rows -- primitives with no prior insights/ home.
- polylogue/api/insights.py: PolylogueInsightsMixin gains aggregate_sessions,
  workflow_shape_distribution, find_abandoned_sessions,
  tool_call_latency_distribution, compare_sessions,
  find_similar_sessions_by_metadata, correlate_sessions -- each does the
  fetch (via list_session_profile_insights/list_session_latency_profile_insights)
  then delegates to the pure insights function, so CLI/library callers reach
  the same math MCP does.
- polylogue/mcp/server_insight_tools.py: the 6 tools (correlate_sessions,
  find_similar_sessions's metadata lane, aggregate_sessions,
  workflow_shape_distribution, find_abandoned_sessions,
  tool_call_latency_distribution, compare_sessions) are now thin wrappers
  that call the facade method and format the JSON envelope; invalid-input
  validation still raises from the shared insights functions and MCP
  catches ValueError to preserve the exact original error envelopes.
- tests/unit/api/test_facade_contracts.py: register the 7 new facade
  methods in BESPOKE_METHODS so the surface-drift gate stays green.

Ref polylogue-9e5.24

Co-Authored-By: Claude <[email protected]>
… parity

Problem: tests/unit/mcp/test_aggregate_sessions.py and
test_session_analysis_primitives.py mocked list_session_profile_insights/
get_session_profile_insight directly and relied on the MCP tool doing
GROUP BY/correlation/similarity/diff math inline. That math moved to
polylogue/insights/ + the facade in the prior commit, so those mocks no
longer exercise anything -- the MCP tool now delegates to a facade method
that never runs against a bare MagicMock.

What changed:
- tests/unit/insights/test_archive_rollups.py (new): direct tests of
  aggregate_session_profiles_by_dimension, workflow_shape_distribution_buckets,
  abandoned_session_items, iso_week_bucket_key, and
  tool_call_latency_distribution_payload -- no MCP/mock scaffolding.
- tests/unit/insights/test_session_analytics.py (new): direct tests of
  pearson_session_correlation, compute_metadata_similarity_candidates,
  build_session_comparison_row/diff_session_comparison_rows.
- tests/unit/api/test_session_analytics_facade.py (new): facade-level
  I/O-boundary contracts (full-scope fetch, not a page-size cap;
  correlate_sessions validates before fetching; compare_sessions/
  find_similar_sessions_by_metadata argument contracts).
- tests/unit/mcp/test_analysis_primitives_facade_parity.py (new): the
  concrete "no behavior change" proof -- the same fixture profiles fed
  through the real Polylogue facade method and through the MCP tool's
  underlying handler (called directly against that same instance)
  produce byte-identical JSON for all 7 sunk primitives.
- tests/unit/mcp/test_aggregate_sessions.py, test_session_analysis_primitives.py,
  test_insight_shape_tools.py: reduced to thin-wrapper/delegation tests
  (mock the facade method, assert JSON pass-through and error-envelope
  mapping) since the math they used to pin now lives elsewhere.

Ref polylogue-9e5.24

Co-Authored-By: Claude <[email protected]>
New module added by the analysis-primitives sink (polylogue-9e5.24) needs
the topology projection/status regenerated or render all --check fails.

Ref polylogue-9e5.24

Co-Authored-By: Claude <[email protected]>
Ref polylogue-9e5.24.

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 28 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5b1d6e64-bb0d-43ae-92b1-09bf319041b4

📥 Commits

Reviewing files that changed from the base of the PR and between 9ac0c0e and 254d494.

📒 Files selected for processing (1)
  • .beads/issues.jsonl
📝 Walkthrough

Walkthrough

Session analysis math (aggregation, workflow-shape distribution, abandonment detection, latency distribution, comparison, metadata similarity, correlation) is relocated from MCP tool handlers into new pure functions in polylogue/insights/session_analytics.py and polylogue/insights/archive_rollups.py, exposed via new async methods on the Polylogue insights facade, and consumed by thinned MCP handlers. Tests, docs, and issue records are updated accordingly.

Changes

Session analytics refactor

Layer / File(s) Summary
Pure session_analytics module
polylogue/insights/session_analytics.py, tests/unit/insights/test_session_analytics.py
New module adds metric validation, Pearson correlation, comparison-row building/diffing, and metadata-similarity scoring, with unit tests pinning each behavior.
Archive rollup aggregation helpers
polylogue/insights/archive_rollups.py, tests/unit/insights/test_archive_rollups.py
Adds ABANDONMENT_SEVERITY_RANK, ISO-week bucketing, dimension aggregation, workflow-shape histogram buckets, abandonment filtering, and latency distribution payload builders, all unit tested.
Polylogue insights facade methods
polylogue/api/insights.py, tests/unit/api/test_facade_contracts.py, tests/unit/api/test_session_analytics_facade.py
Adds protocol methods and async facade methods aggregate_sessions, workflow_shape_distribution, find_abandoned_sessions, tool_call_latency_distribution, compare_sessions, find_similar_sessions_by_metadata, correlate_sessions delegating to the new insights helpers, with facade contract and behavior tests.
MCP tool delegation and parity tests
polylogue/mcp/server_insight_tools.py, tests/unit/mcp/test_aggregate_sessions.py, tests/unit/mcp/test_insight_shape_tools.py, tests/unit/mcp/test_session_analysis_primitives.py, tests/unit/mcp/test_analysis_primitives_facade_parity.py
MCP tool handlers are rewritten to delegate to the Polylogue facade with ValueError→invalid_argument mapping, replacing prior in-file math; tests rewritten as thin delegation checks plus new facade/MCP parity tests.

Estimated code review effort: 4 (Complex) | ~60 minutes

Issue tracking and topology docs updates

Layer / File(s) Summary
Beads records and generated topology docs
.beads/interactions.jsonl, .beads/issues.jsonl, docs/plans/topology-target.yaml, docs/topology-status.md
Refactor issue is closed with notes, a new devtools bug for _BOUNDARY_TABLES is filed, and generated topology yaml/md are updated with new loc counts and a session_analytics.py entry.

Estimated code review effort: 1 (Trivial) | ~5 minutes

Possibly related PRs

  • Sinity/polylogue#764: Both PRs modify polylogue/mcp/server_insight_tools.py to delegate insight endpoints to the polylogue facade instead of archive operations.
  • Sinity/polylogue#1539: Both touch the tool_call_latency_distribution surface built on session latency profile insights.
  • Sinity/polylogue#1738: Both add/extend the same session-analysis primitives (aggregate_sessions, compare_sessions, find_similar_sessions, correlate_sessions) and MCP wiring.

Suggested labels: type:refactor, tool:claude

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.83% 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 concisely and accurately summarizes the refactor into shared insights modules and the API facade.
Description check ✅ Passed The description covers the required core sections and appropriately omits optional changelog/risks sections for a refactor.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/mcp/sink-analysis-into-insights

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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@polylogue/insights/archive_rollups.py`:
- Around line 328-347: Validate group_by at the start of
aggregate_session_profiles_by_dimension before iterating profiles, so an invalid
value raises ValueError even when profiles is empty; mirror the upfront checks
used by workflow_shape_distribution_buckets and abandoned_session_items, and
keep the existing supported-values error message consistent.

In `@polylogue/insights/session_analytics.py`:
- Around line 198-244: The “same origin” bonus in the session scoring logic is
comparing raw source_name values instead of normalized origins. Update the
candidate comparison in the scoring loop (around ref_source/ref_origin and
profile.source_name) to use source_name_to_origin(profile.source_name) against
ref_origin, so different source tokens that map to the same origin still receive
the origin match bonus.

In `@tests/unit/api/test_session_analytics_facade.py`:
- Around line 100-129: Add coverage in test_session_analytics_facade for the
full-scope fetch contract on the remaining analytics entrypoints, especially
tool_call_latency_distribution in the Archive/Poly facade. Mirror the existing
aggregate_sessions and correlate_sessions style by stubbing the underlying fetch
helper (for example list_session_latency_profile_insights) and asserting the
call ignores the caller’s limit and uses a full-scope query instead of a paged
one; use the tool_call_latency_distribution method name and the
list_session_latency_profile_insights symbol to locate the right spot. If
similar regressions are possible, add the same pin for find_abandoned_sessions
and workflow_shape_distribution as well.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5300bf72-afe8-40bd-ba72-139e082cad72

📥 Commits

Reviewing files that changed from the base of the PR and between 10a1212 and 9ac0c0e.

📒 Files selected for processing (16)
  • .beads/interactions.jsonl
  • .beads/issues.jsonl
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/api/insights.py
  • polylogue/insights/archive_rollups.py
  • polylogue/insights/session_analytics.py
  • polylogue/mcp/server_insight_tools.py
  • tests/unit/api/test_facade_contracts.py
  • tests/unit/api/test_session_analytics_facade.py
  • tests/unit/insights/test_archive_rollups.py
  • tests/unit/insights/test_session_analytics.py
  • tests/unit/mcp/test_aggregate_sessions.py
  • tests/unit/mcp/test_analysis_primitives_facade_parity.py
  • tests/unit/mcp/test_insight_shape_tools.py
  • tests/unit/mcp/test_session_analysis_primitives.py

Comment on lines +328 to +347
def aggregate_session_profiles_by_dimension(
profiles: Sequence[SessionProfileInsight],
group_by: str,
) -> dict[str, int]:
"""GROUP BY session count over workflow_shape / terminal_state / origin (#1691).

Raises ``ValueError`` for an unsupported ``group_by``.
"""
buckets: dict[str, int] = {}
for profile in profiles:
if group_by == "workflow_shape":
key = (profile.inference.workflow_shape if profile.inference else None) or "unknown"
elif group_by == "terminal_state":
key = (profile.inference.terminal_state if profile.inference else None) or "unknown"
elif group_by == "origin":
key = source_name_to_origin(profile.source_name)
else:
raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.")
buckets[key] = buckets.get(key, 0) + 1
return buckets

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Validate group_by before the loop to match sibling functions.

aggregate_session_profiles_by_dimension raises ValueError inside the for loop, so an empty profiles list with an invalid group_by silently returns {} instead of raising. This is inconsistent with workflow_shape_distribution_buckets (line 359–361) and abandoned_session_items (line 394–395), which both validate upfront. Downstream, the facade returns a success envelope with empty buckets for an invalid group_by when no profiles match, rather than surfacing the error.

🛡️ Proposed fix: move validation before the loop
 def aggregate_session_profiles_by_dimension(
     profiles: Sequence[SessionProfileInsight],
     group_by: str,
 ) -> dict[str, int]:
     """GROUP BY session count over workflow_shape / terminal_state / origin (`#1691`).

     Raises ``ValueError`` for an unsupported ``group_by``.
     """
+    supported = {"workflow_shape", "terminal_state", "origin"}
+    if group_by not in supported:
+        raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.")
     buckets: dict[str, int] = {}
     for profile in profiles:
         if group_by == "workflow_shape":
             key = (profile.inference.workflow_shape if profile.inference else None) or "unknown"
         elif group_by == "terminal_state":
             key = (profile.inference.terminal_state if profile.inference else None) or "unknown"
         elif group_by == "origin":
             key = source_name_to_origin(profile.source_name)
-        else:
-            raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.")
         buckets[key] = buckets.get(key, 0) + 1
     return buckets
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def aggregate_session_profiles_by_dimension(
profiles: Sequence[SessionProfileInsight],
group_by: str,
) -> dict[str, int]:
"""GROUP BY session count over workflow_shape / terminal_state / origin (#1691).
Raises ``ValueError`` for an unsupported ``group_by``.
"""
buckets: dict[str, int] = {}
for profile in profiles:
if group_by == "workflow_shape":
key = (profile.inference.workflow_shape if profile.inference else None) or "unknown"
elif group_by == "terminal_state":
key = (profile.inference.terminal_state if profile.inference else None) or "unknown"
elif group_by == "origin":
key = source_name_to_origin(profile.source_name)
else:
raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.")
buckets[key] = buckets.get(key, 0) + 1
return buckets
def aggregate_session_profiles_by_dimension(
profiles: Sequence[SessionProfileInsight],
group_by: str,
) -> dict[str, int]:
"""GROUP BY session count over workflow_shape / terminal_state / origin (`#1691`).
Raises ``ValueError`` for an unsupported ``group_by``.
"""
supported = {"workflow_shape", "terminal_state", "origin"}
if group_by not in supported:
raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.")
buckets: dict[str, int] = {}
for profile in profiles:
if group_by == "workflow_shape":
key = (profile.inference.workflow_shape if profile.inference else None) or "unknown"
elif group_by == "terminal_state":
key = (profile.inference.terminal_state if profile.inference else None) or "unknown"
elif group_by == "origin":
key = source_name_to_origin(profile.source_name)
buckets[key] = buckets.get(key, 0) + 1
return buckets
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/insights/archive_rollups.py` around lines 328 - 347, Validate
group_by at the start of aggregate_session_profiles_by_dimension before
iterating profiles, so an invalid value raises ValueError even when profiles is
empty; mirror the upfront checks used by workflow_shape_distribution_buckets and
abandoned_session_items, and keep the existing supported-values error message
consistent.

Comment on lines +198 to +244
ref_evidence = ref_profile.evidence
ref_inference = ref_profile.inference
ref_shape = ref_inference.workflow_shape if ref_inference else None
ref_source = ref_profile.source_name
ref_origin = source_name_to_origin(ref_source)
ref_date = ref_evidence.canonical_session_date if ref_evidence else None
ref_tags = set(ref_evidence.tags) if ref_evidence else set()

scored: list[tuple[int, dict[str, object]]] = []
for profile in candidates:
if profile.session_id == exclude_session_id:
continue
evidence = profile.evidence
inference = profile.inference
score = 0
reasons: list[str] = []

cand_shape = inference.workflow_shape if inference else None
if ref_shape and cand_shape == ref_shape:
score += 3
reasons.append(f"same workflow_shape: {ref_shape}")

cand_source = profile.source_name
if ref_source and cand_source == ref_source:
score += 1
reasons.append(f"same origin: {ref_origin}")

cand_date = evidence.canonical_session_date if evidence else None
if ref_date and cand_date:
try:
ref_d = date.fromisoformat(ref_date)
cand_d = date.fromisoformat(cand_date)
delta = abs((ref_d - cand_d).days)
if delta <= 3:
score += 2
reasons.append(f"within 3 days (delta={delta})")
elif delta <= 14:
score += 1
reasons.append(f"within 14 days (delta={delta})")
except (ValueError, TypeError):
pass

cand_tags = set(evidence.tags) if evidence else set()
overlap = ref_tags & cand_tags
if overlap:
score += len(overlap)
reasons.append(f"{len(overlap)} overlapping tags: {sorted(overlap)}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect source_name_to_origin to check for many-to-one mappings.
fd -e py sources.py polylogue/core
rg -n -A20 'def source_name_to_origin' polylogue/core/sources.py

Repository: Sinity/polylogue

Length of output: 1291


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- session_analytics snippet ---'
sed -n '198,244p' polylogue/insights/session_analytics.py

echo
echo '--- source_name_to_origin / related mapping ---'
sed -n '314,390p' polylogue/core/sources.py

echo
echo '--- search for origin-related comparison helpers ---'
rg -n 'provider_from_origin|source_name_to_origin|same origin|same workflow_shape|Origin\.AISTUDIO_DRIVE|_CANONICAL_ORIGIN_VALUES' polylogue/core polylogue/insights

Repository: Sinity/polylogue

Length of output: 7407


Compare origins here, not raw source_name. source_name_to_origin() already folds distinct source tokens onto the same origin, so cand_source == ref_source can miss the intended “same origin” bonus for different source names that map to one origin. Use source_name_to_origin(profile.source_name) in the comparison.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/insights/session_analytics.py` around lines 198 - 244, The “same
origin” bonus in the session scoring logic is comparing raw source_name values
instead of normalized origins. Update the candidate comparison in the scoring
loop (around ref_source/ref_origin and profile.source_name) to use
source_name_to_origin(profile.source_name) against ref_origin, so different
source tokens that map to the same origin still receive the origin match bonus.

Comment on lines +100 to +129
@pytest.mark.asyncio
async def test_correlate_sessions_validates_metrics_before_fetching(tmp_path: Path) -> None:
poly = _archive(tmp_path)
poly.list_session_profile_insights = AsyncMock(return_value=[]) # type: ignore[method-assign]

with pytest.raises(ValueError, match="Unknown metric_x"):
await poly.correlate_sessions(metric_x="favorite_color", metric_y="word_count")

poly.list_session_profile_insights.assert_not_awaited()


@pytest.mark.asyncio
async def test_compare_sessions_rejects_out_of_range_counts(tmp_path: Path) -> None:
poly = _archive(tmp_path)

with pytest.raises(ValueError, match="Need at least 2"):
await poly.compare_sessions(["only-one"])

with pytest.raises(ValueError, match="Too many"):
await poly.compare_sessions([f"c{i}" for i in range(11)])


@pytest.mark.asyncio
async def test_find_similar_sessions_by_metadata_returns_none_for_unknown_session(tmp_path: Path) -> None:
poly = _archive(tmp_path)
poly.get_session_profile_insight = AsyncMock(return_value=None) # type: ignore[method-assign]

result = await poly.find_similar_sessions_by_metadata("nonexistent")

assert result is None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Coverage gap: no full-scope-fetch pin for tool_call_latency_distribution, find_abandoned_sessions, or workflow_shape_distribution.

This module pins the "fetch full scope, not a page limit" contract only for aggregate_sessions and correlate_sessions. The same invariant matters for tool_call_latency_distribution (see the flagged issue in polylogue/api/insights.py — it currently forwards the caller's limit into the fetch query, unlike its siblings) and would have caught that regression had it existed here.

✅ Suggested additional test
`@pytest.mark.asyncio`
async def test_tool_call_latency_distribution_fetches_full_scope_not_a_page_limit(tmp_path: Path) -> None:
    poly = _archive(tmp_path)
    fetch_mock = AsyncMock(return_value=[])
    poly.list_session_latency_profile_insights = fetch_mock  # type: ignore[method-assign]

    await poly.tool_call_latency_distribution(limit=5)

    assert fetch_mock.await_args is not None
    assert fetch_mock.await_args.args[0].limit is None
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/api/test_session_analytics_facade.py` around lines 100 - 129, Add
coverage in test_session_analytics_facade for the full-scope fetch contract on
the remaining analytics entrypoints, especially tool_call_latency_distribution
in the Archive/Poly facade. Mirror the existing aggregate_sessions and
correlate_sessions style by stubbing the underlying fetch helper (for example
list_session_latency_profile_insights) and asserting the call ignores the
caller’s limit and uses a full-scope query instead of a paged one; use the
tool_call_latency_distribution method name and the
list_session_latency_profile_insights symbol to locate the right spot. If
similar regressions are possible, add the same pin for find_abandoned_sessions
and workflow_shape_distribution as well.

…nalysis-into-insights

# Conflicts:
#	.beads/interactions.jsonl
github-actions Bot pushed a commit that referenced this pull request Jul 9, 2026
@Sinity
Sinity merged commit 8813922 into master Jul 9, 2026
15 checks passed
@Sinity
Sinity deleted the refactor/mcp/sink-analysis-into-insights branch July 9, 2026 06:57
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.

1 participant