Skip to content

feat(insights): tool usage analytics per provider (#1133) - #1164

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/tool-usage-analytics
May 17, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/tool-usage-analytics

Conversation

@Sinity

@Sinity Sinity commented May 17, 2026

Copy link
Copy Markdown
Owner

Summary

Adds a tool_usage insight that rolls up canonical action_events into per-(provider, tool, action_kind) entries with call counts, conversation counts, distinct tool ids, and affected-path / output-text density. The same envelope carries a per-provider coverage map that distinguishes "data unavailable" (provider exposes no tool events at all) from "zero observed" so coverage gaps never collapse into silent zeros.

Closes #1133.

Problem

Per #1133 (parent #994 / W11 of #827), Polylogue had no per-tool, per-session, per-provider analytics over the canonical action-event substrate even though that substrate already carries normalized tool names, action kinds, tool ids, affected paths, and output text. Consumers wanting "which tools fire most from claude-code?" or "does my Codex session use apply_patch more than shell?" had to roll their own SQL over action_events.

The harder requirement was honesty about coverage. ChatGPT exports do not surface tool calls; aggregating a "zero" for ChatGPT next to "8,000" for Claude Code without flagging the difference would lie to readers. The issue called this out explicitly: the envelope must distinguish "data unavailable" from "zero observed".

Solution

Substrate-first, per the architecture rule (docs/architecture.md):

  • polylogue/storage/sqlite/queries/tool_usage.py — two typed TypedDict query results:
    • get_tool_usage_rows() groups by (provider, normalized_tool_name, action_kind) over action_events, summing call/conversation/message/tool-id/path/output-text counts.
    • get_tool_usage_provider_coverage_rows() left-joins conversations against action_events so every provider with at least one conversation is in the result — providers with zero events surface as action_event_count=0.

Insight model (polylogue/insights/tool_usage.py):

  • ToolUsageInsight is a single envelope returned by list_tool_usage_insights. It carries entries, provider_coverage, totals, and has_coverage_gaps.
  • ToolUsageCoverageEntry.data_available is the load-bearing flag: True iff the provider has any action-event rows.
  • extract_mcp_server() parses mcp__<server>__<tool> and stores the server segment as a first-class field on each entry. Non-MCP tools get None — the catalog stays honest.
  • build_tool_usage_insight() is a pure function so filters, sorting, MCP-server derivation, and coverage flags are unit-testable without standing up a database. Query filters narrow entries; provider_coverage stays exhaustive so a narrowed query never hides gaps.

Surfaces (all auto-wired via the registry-driven insight machinery, no per-surface boilerplate):

  • CLI: polylogue insights tool-usage with --tool, --mcp-server, --action-kind filters. Root-level --provider is inherited.
  • MCP: tool_usage tool registered automatically by server_insight_tools.register_insight_tools iterating INSIGHT_REGISTRY. Wire schema regenerated in tests/data/witnesses/mcp-tool-schemas.json.
  • Facade: Polylogue.list_tool_usage_insights(query) + sync SyncPolylogue counterpart.
  • Module-level: polylogue.operations.list_tool_usage_insights(*, services, db_path, query) for ad-hoc callers.
  • Operation spec query-tool-usage + artifact tool_usage_results + path tool-usage-query-loop registered in the runtime catalog and artifact graph; scenario coverage map points list_tool_usage_insights → query-tool-usage.

Rejected alternatives:

  • Materializing a tool_usage table behind a rebuild was rejected because action_events is already the canonical materialized substrate and the per-provider rollup is small enough to compute on read. Same shape as provider_analytics. The TOOL_USAGE_INSIGHT_VERSION field on the envelope still gives consumers a hook to invalidate caches if the aggregation contract changes.
  • A separate readiness spec was rejected for the same reason — the insight is marked readiness_exempt=True in the registry and gates on action_events indirectly through the coverage map it returns.

Verification

nix develop -c devtools verify --quick
# exit_code: 0 (mypy --strict + ruff + render-all --check + 17 manifest/topology lints all pass)

nix develop -c pytest tests/unit/insights/test_tool_usage.py
# 13 passed in 8.30s

nix develop -c pytest tests/unit/mcp tests/unit/insights tests/unit/core/test_insight_registry_runtime.py tests/unit/core/test_artifact_specs.py tests/unit/core/test_artifact_graph.py tests/unit/core/test_sync_surface_runtime.py tests/unit/cli/test_insights.py tests/unit/core/test_insight_readiness.py tests/unit/operations/test_specs.py
# 339 passed

nix develop -c mypy polylogue/insights/tool_usage.py polylogue/operations/archive.py polylogue/storage/sqlite/queries/tool_usage.py polylogue/storage/sqlite/async_sqlite_archive.py polylogue/storage/sqlite/query_store_archive.py tests/unit/insights/test_tool_usage.py
# Success: no issues found in 6 source files

Full suite (devtools verify --all) shows 9 pre-existing failures on master (message_type_backfill topology cells, test_check.py repair fixtures, terminal snapshots, scenario-coverage maintenance-target list) — unchanged on this branch; not introduced by #1133.

Test plan

  • Pure aggregation correctness: counts, sort, dedup of distinct tool ids, affected-path / output-text density.
  • Coverage-gap honesty: provider with conversations but zero action_events surfaces as data_available=False.
  • Coverage exhaustive under narrowed queries: filtering entries to one provider does NOT hide coverage gaps for other providers.
  • MCP server identity extraction from mcp__<server>__<tool> prefixes (and None for non-MCP tools and malformed prefixes).
  • End-to-end through the real SQLite backend with replace_action_events.
  • Envelope JSON serialization shape (insight_kind, materializer_version, provenance, entries, provider_coverage).
  • MCP wire-schema witness regenerated and registry classification covers the new tool.

@coderabbitai

coderabbitai Bot commented May 17, 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 16 minutes and 57 seconds before requesting another review.

You’ve run out of usage credits. Purchase more 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: 8e7fb77b-0878-44dc-80b6-b2e86c49bec3

📥 Commits

Reviewing files that changed from the base of the PR and between 6668996 and 367b559.

📒 Files selected for processing (25)
  • CHANGELOG.md
  • docs/cli-reference.md
  • docs/library-api.md
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • docs/verification-catalog.md
  • polylogue/api/insights.py
  • polylogue/api/sync/insights.py
  • polylogue/artifacts/runtime.py
  • polylogue/insights/registry.py
  • polylogue/insights/tool_usage.py
  • polylogue/operations/__init__.py
  • polylogue/operations/archive.py
  • polylogue/operations/specs.py
  • polylogue/scenarios/execution.py
  • polylogue/storage/sqlite/async_sqlite_archive.py
  • polylogue/storage/sqlite/queries/tool_usage.py
  • polylogue/storage/sqlite/query_store_archive.py
  • tests/data/witnesses/mcp-tool-schemas.json
  • tests/unit/core/test_artifact_graph.py
  • tests/unit/core/test_artifact_specs.py
  • tests/unit/insights/test_tool_usage.py
  • tests/unit/mcp/test_envelope_contracts.py
  • tests/unit/operations/test_specs.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/tool-usage-analytics

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.

Closes #1133

Adds a `tool_usage` insight that rolls up canonical action_events into
per-(provider, tool, action_kind) entries with call counts, conversation
counts, distinct tool ids, and affected-path / output-text density. The
same envelope carries a per-provider coverage map that distinguishes
"data unavailable" (provider exposes no tool events at all) from
"zero observed" so coverage gaps never collapse into silent zeros.

Surface:

- `polylogue insights tool-usage` (CLI, with `--tool`, `--mcp-server`,
  `--action-kind` filters; root-level `--provider` inherited)
- MCP `tool_usage` tool on the standard `{items, total}` envelope
- `Polylogue.list_tool_usage_insights(query)` async facade method and
  its sync counterpart
- Operation `query-tool-usage` and artifact `tool_usage_results`
  registered in the runtime catalog / artifact graph

MCP tool names of the form `mcp__<server>__<tool>` have their server
segment extracted as a first-class `mcp_server` field, so analytics can
distinguish GitHub vs Polylogue vs Context7 MCP fanout without ad-hoc
prefix parsing in callers.

The aggregator (`build_tool_usage_insight`) is a pure function over the
two typed substrate rows so filters, coverage, and MCP-server derivation
are testable without standing up a database.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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: 5c353e390a

ℹ️ 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/insights/tool_usage.py Resolved
@Sinity
Sinity force-pushed the feature/feat/tool-usage-analytics branch from 5c353e3 to 367b559 Compare May 17, 2026 05:17
@Sinity
Sinity merged commit 7d6dd65 into master May 17, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the feature/feat/tool-usage-analytics branch May 17, 2026 05:17
@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.

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

  • 77.F045 / P2: stale at the checked revision: The analytics query now counts canonical tool-use block identities, not provider tool_id strings; a blank provider identifier is not counted as a distinct identifier by the retired expression. See polylogue/storage/sqlite/queries/tool_usage.py:106.

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(insights): tool usage analytics with explicit provider coverage

1 participant