Skip to content

feat: implement multi-agent repository analysis integration#5

Open
skyfire707 wants to merge 1 commit into
nitininhouse:mainfrom
skyfire707:feat/multi-agent-integration
Open

feat: implement multi-agent repository analysis integration#5
skyfire707 wants to merge 1 commit into
nitininhouse:mainfrom
skyfire707:feat/multi-agent-integration

Conversation

@skyfire707

@skyfire707 skyfire707 commented Jun 2, 2026

Copy link
Copy Markdown

This PR implements the multi-agent analysis system as requested in #4.

Agents Implemented

  • CodeQualityAgent - analyzes code quality and security
  • CompatibilityAgent - analyzes user compatibility for trip matching
  • EngagementAgent - analyzes community engagement patterns

Integration Engine

  • MultiAgentIntegrationEngine with conflict resolution
  • Weighted data fusion from multiple agents
  • Unified health scoring and categorized recommendations

API Endpoints

  • POST /api/multi-agent-analysis/
  • GET /api/agents/health/

Closes #4

Summary by Sourcery

Implement a multi-agent analysis system and expose unified analysis and health check APIs.

New Features:

  • Add multi-agent analysis engine integrating code quality, compatibility, and engagement agents into a unified report.
  • Introduce API endpoints to trigger multi-agent analysis and to query agent health status.

Enhancements:

  • Wire existing user, trip, request, notification, and successful trip data into the new analysis agents for richer insights.

@vercel

vercel Bot commented Jun 2, 2026

Copy link
Copy Markdown

@skyfire707 is attempting to deploy a commit to the nitininhouse's projects Team on Vercel.

A member of the Team first needs to authorize it.

@sourcery-ai

sourcery-ai Bot commented Jun 2, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implements a multi-agent analysis subsystem with three domain-specific agents (code quality, compatibility, engagement), an integration engine that fuses and reconciles their outputs into a unified health report, and exposes this functionality via new DRF API endpoints and URL routes, including an agent health check.

Sequence diagram for multi-agent analysis API request

sequenceDiagram
    actor Client
    participant MultiAgentAnalysisView
    participant CodeQualityAgent
    participant CompatibilityAgent
    participant EngagementAgent
    participant MultiAgentIntegrationEngine

    Client->>MultiAgentAnalysisView: POST /api/multi-agent-analysis/
    MultiAgentAnalysisView->>CodeQualityAgent: analyze
    CodeQualityAgent-->>MultiAgentAnalysisView: code_output

    MultiAgentAnalysisView->>CompatibilityAgent: analyze
    CompatibilityAgent-->>MultiAgentAnalysisView: compatibility_output

    MultiAgentAnalysisView->>EngagementAgent: analyze
    EngagementAgent-->>MultiAgentAnalysisView: engagement_output

    MultiAgentAnalysisView->>MultiAgentIntegrationEngine: add_agent_output(code_output)
    MultiAgentAnalysisView->>MultiAgentIntegrationEngine: add_agent_output(compatibility_output)
    MultiAgentAnalysisView->>MultiAgentIntegrationEngine: add_agent_output(engagement_output)

    MultiAgentAnalysisView->>MultiAgentIntegrationEngine: integrate
    MultiAgentIntegrationEngine-->>MultiAgentAnalysisView: unified_report

    MultiAgentAnalysisView-->>Client: 200 OK (report)
Loading

File-Level Changes

Change Details Files
Expose new multi-agent analysis and agent health APIs and clean up URL imports/usages.
  • Imports new multi-agent views (MultiAgentAnalysisView, AgentHealthCheckView) into the main urls module.
  • Replaces some view imports with direct function references to avoid using the module namespace for get_similar_users.
  • Adds URL patterns for POST /api/multi-agent-analysis/ and GET /api/agents/health/ while keeping JWT refresh and existing endpoints intact.
trip/trip/urls.py
Introduce a reusable multi-agent integration engine that standardizes agent outputs, performs weighted fusion, resolves conflicts, and produces a unified health report.
  • Defines agent priority weights and severity scores for conflict resolution and ranking.
  • Normalizes heterogeneous agent outputs into a common schema, aggregates findings/metrics/recommendations with per-agent weights and confidences, and deduplicates/sorts entries.
  • Implements recommendation conflict resolution by category with priority/confidence weighting and complementary merging, and consolidates overlapping findings by issue key with highest weighted severity retained.
  • Computes an overall health score and rating from issue severities, structures top findings, metrics summary, prioritized recommendations, an agent contribution breakdown, and generates a conflict resolution log.
trip/tripmates/agents/integration_engine.py
Add DRF API views to run the full multi-agent pipeline against live data and to report agent health status.
  • Implements MultiAgentAnalysisView that instantiates CodeQualityAgent, CompatibilityAgent, and EngagementAgent, loads real DB data into the latter two, runs analyze() on each, and passes results to MultiAgentIntegrationEngine to build a unified report.
  • Loads users, personas, trips, requests, successful trips, and notifications from the database and converts them into simple dict structures expected by the agents.
  • Returns structured success/error responses with timestamps, and exposes the endpoints without authentication to facilitate external evaluation.
  • Implements AgentHealthCheckView that returns a static list of available agents, their status, and descriptions.
trip/tripmates/views_agents.py
Implement a code quality analysis agent that scans the repository for basic security, quality, and maintainability signals.
  • Walks the repo to collect Python files (excluding common noise directories) and tracks total file count and lines of code.
  • Performs regex-based checks for hardcoded secrets, DEBUG=True in Django settings, bare except clauses, and TODO/FIXME-style comments, adding appropriately categorized findings.
  • Performs a CSRF-related security scan for csrf_exempt usage without permission_classes and summarizes these as a single high-severity finding if found.
  • Aggregates counts of security, code-quality, and maintenance issues into metrics and derives recommendations based on those metrics plus generic testing/validation advice, returning a standardized agent output payload.
trip/tripmates/agents/code_analyzer.py
Implement a compatibility analysis agent that evaluates user persona/trip data to infer compatibility and adoption patterns.
  • Analyzes distributions of user travel frequency, trip preferences, and destination preferences from in-memory user persona data and stores them in metrics.
  • Computes solo vs group trip ratios and basic trip statistics, then calculates simple pairwise compatibility scores between users based on matching preference fields, retaining the top matches.
  • Derives findings about solo-travel dominance, lack of trips vs users, and insufficient data scenarios, and exposes metrics including top match candidates.
  • Generates product-level recommendations such as group trip incentives, onboarding improvements, and ML-based compatibility/messaging enhancements, returning a standardized agent output payload.
trip/tripmates/agents/compatibility_analyzer.py
Implement an engagement analysis agent that inspects request, trip success, and notification patterns.
  • Analyzes request statuses to compute acceptance/decline/pending counts and rates, and derives basic success metrics tying successful trips back to request volume.
  • Analyzes notification read vs unread counts to compute engagement rates.
  • Generates findings for low or unusually high request acceptance and low notification read rates, categorized by engagement/notifications with severities tied to thresholds.
  • Returns consolidated metrics and a set of engagement-focused recommendations (better matching, notification optimization, gamification, success stories) in the standardized agent output schema.
trip/tripmates/agents/engagement_analyzer.py
Wire up the new agents into a cohesive package for import.
  • Exports CodeQualityAgent, CompatibilityAgent, EngagementAgent, and MultiAgentIntegrationEngine from the agents package via all for clean imports in views.
  • Adds a descriptive module docstring summarizing the purpose of the multi-agent system.
trip/tripmates/agents/__init__.py

Assessment against linked issues

Issue Objective Addressed Explanation
#4 Implement a unified multi-agent analysis system that successfully combines inputs from 3+ specialized agents into a single pipeline.
#4 Standardize agent outputs and provide a data fusion mechanism that aggregates findings, metrics, and recommendations into a coherent unified analysis report.
#4 Implement conflict resolution logic to handle conflicting agent recommendations and findings in the unified report.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

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

Hey - I've found 4 issues, and left some high level feedback:

  • The MultiAgentAnalysisView is exposed with AllowAny and executes a full repo scan and multiple DB queries on each request; consider restricting access or adding rate limiting/feature flagging to avoid potential abuse and performance degradation.
  • In MultiAgentAnalysisView.post, the broad except Exception as e returns str(e) directly to clients; consider logging the detailed error server-side and returning a generic error message in the response to avoid leaking internal details.
  • The CodeQualityAgent walks the entire repo from . and only skips a few directories; consider allowing a configurable root path and/or an ignore list (e.g., virtualenvs, large vendor dirs) to prevent unnecessary scanning and long-running requests.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `MultiAgentAnalysisView` is exposed with `AllowAny` and executes a full repo scan and multiple DB queries on each request; consider restricting access or adding rate limiting/feature flagging to avoid potential abuse and performance degradation.
- In `MultiAgentAnalysisView.post`, the broad `except Exception as e` returns `str(e)` directly to clients; consider logging the detailed error server-side and returning a generic error message in the response to avoid leaking internal details.
- The `CodeQualityAgent` walks the entire repo from `.` and only skips a few directories; consider allowing a configurable root path and/or an ignore list (e.g., virtualenvs, large vendor dirs) to prevent unnecessary scanning and long-running requests.

## Individual Comments

### Comment 1
<location path="trip/tripmates/agents/compatibility_analyzer.py" line_range="31-33" />
<code_context>
+            "recommendations": self._generate_recommendations()
+        }
+    
+    def _analyze_user_profiles(self):
+        """Analyze user persona distribution."""
+        if not self.users_data:
+            return
+        
</code_context>
<issue_to_address>
**issue (bug_risk):** Potential AttributeError when `users_data` is empty because `self.metrics` is never initialized.

If `self.users_data` is empty, `_analyze_user_profiles` returns before `self.metrics` is set, but `analyze()` still calls `_analyze_trip_diversity` and `_get_findings`, which rely on `self.metrics` and will raise an `AttributeError`. Consider initializing `self.metrics = {}` in `__init__` or before the early return in `_analyze_user_profiles` to keep this path safe.
</issue_to_address>

### Comment 2
<location path="trip/tripmates/agents/compatibility_analyzer.py" line_range="47-51" />
<code_context>
+            "destination_preference_distribution": dict(dest_prefs)
+        }
+    
+    def _analyze_trip_diversity(self):
+        """Analyze trip diversity and patterns."""
+        if not self.trips_data:
+            self.metrics["total_trips"] = 0
+            self.metrics["solo_ratio"] = 0.0
+            return
+        
</code_context>
<issue_to_address>
**issue (bug_risk):** `group_ratio` is missing when there are no trips, leading to inconsistent metrics shape.

In the `not self.trips_data` branch you set `total_trips` and `solo_ratio` but omit `group_ratio`, while it’s always set in the non-empty case. This can break callers that assume `group_ratio` is always present. Please also set `group_ratio = 0.0` here to keep the metrics schema consistent.
</issue_to_address>

### Comment 3
<location path="trip/tripmates/views_agents.py" line_range="41" />
<code_context>
+    
+    Returns a unified report with consolidated insights and recommendations.
+    """
+    permission_classes = [AllowAny]  # Open for bounty evaluation
+
+    def post(self, request, *args, **kwargs):
</code_context>
<issue_to_address>
**🚨 issue (security):** Running a full repo scan and DB-wide analysis on an unauthenticated endpoint may be expensive and abusable.

This endpoint launches three agents, walks the entire repo, and loads unbounded sets of users, trips, requests, successful trips, and notifications. With `AllowAny`, anonymous clients can trigger this repeatedly, causing significant CPU and DB load. Consider tightening access (e.g., staff-only), adding rate limiting/throttling, or otherwise constraining usage to reduce abuse risk.
</issue_to_address>

### Comment 4
<location path="trip/tripmates/views_agents.py" line_range="72-75" />
<code_context>
+                            "issue": f"{len(todos)} unresolved TODO/FIXME comments"
+                        })
+                        
+            except Exception as e:
+                self.findings.append({
+                    "severity": "low",
</code_context>
<issue_to_address>
**🚨 issue (security):** Returning the raw exception message to clients may leak internal details.

Here you’re sending `str(e)` back to the client, which can leak internal details (paths, query contents, etc.). Instead, log the full exception on the server and return a generic error identifier or high-level message, keeping the existing user-facing `detail` text if needed.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +31 to +33
def _analyze_user_profiles(self):
"""Analyze user persona distribution."""
if not self.users_data:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): Potential AttributeError when users_data is empty because self.metrics is never initialized.

If self.users_data is empty, _analyze_user_profiles returns before self.metrics is set, but analyze() still calls _analyze_trip_diversity and _get_findings, which rely on self.metrics and will raise an AttributeError. Consider initializing self.metrics = {} in __init__ or before the early return in _analyze_user_profiles to keep this path safe.

Comment on lines +47 to +51
def _analyze_trip_diversity(self):
"""Analyze trip diversity and patterns."""
if not self.trips_data:
self.metrics["total_trips"] = 0
self.metrics["solo_ratio"] = 0.0

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): group_ratio is missing when there are no trips, leading to inconsistent metrics shape.

In the not self.trips_data branch you set total_trips and solo_ratio but omit group_ratio, while it’s always set in the non-empty case. This can break callers that assume group_ratio is always present. Please also set group_ratio = 0.0 here to keep the metrics schema consistent.


Returns a unified report with consolidated insights and recommendations.
"""
permission_classes = [AllowAny] # Open for bounty evaluation

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🚨 issue (security): Running a full repo scan and DB-wide analysis on an unauthenticated endpoint may be expensive and abusable.

This endpoint launches three agents, walks the entire repo, and loads unbounded sets of users, trips, requests, successful trips, and notifications. With AllowAny, anonymous clients can trigger this repeatedly, causing significant CPU and DB load. Consider tightening access (e.g., staff-only), adding rate limiting/throttling, or otherwise constraining usage to reduce abuse risk.

Comment on lines +72 to +75
except Exception as e:
return Response({
"success": False,
"error": str(e),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🚨 issue (security): Returning the raw exception message to clients may leak internal details.

Here you’re sending str(e) back to the client, which can leak internal details (paths, query contents, etc.). Instead, log the full exception on the server and return a generic error identifier or high-level message, keeping the existing user-facing detail text if needed.

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.

Multi-Agent Repository Analysis Integration

1 participant