Skip to content

chore: update dependencies and refactor code#33

Merged
ssdeanx merged 1 commit intomainfrom
develop
Dec 11, 2025
Merged

chore: update dependencies and refactor code#33
ssdeanx merged 1 commit intomainfrom
develop

Conversation

@ssdeanx
Copy link
Owner

@ssdeanx ssdeanx commented Dec 11, 2025

  • Updated package dependencies in package.json to the latest versions, including:

    • "@ai-sdk/react": "^2.0.111"
    • "@mastra/ai-sdk": "^1.0.0-beta.8" to "^1.0.0-beta.9"
    • "@mastra/client-js": "^1.0.0-beta.10" to "^1.0.0-beta.11"
    • "@mastra/core": "^1.0.0-beta.10" to "^1.0.0-beta.11"
    • "@mcpc-tech/acp-ai-provider": "^0.1.31" to "^0.1.34"
    • "@openrouter/ai-sdk-provider": "^1.5.2" to "^1.5.3"
    • "ai": "^5.0.108" to "^5.0.109"
    • "framer-motion": "^12.23.25" to "^12.23.26"
    • "lucide-react": "^0.556.0" to "^0.559.0"
    • "motion": "^12.23.25" to "^12.23.26"
    • "@types/node": "^24.10.2" to "^25.0.0"
  • Refactored acpAgent to use pgMemory and pgQueryTool instead of MongoDB tools.

  • Removed unused scorer toolCallAppropriatenessScorer from weather-agent.

  • Updated MongoDB configuration to support PgVector and improved tracing with OpenTelemetry.

  • Enhanced error handling and tracing in various tools (e.g., fs, jwt-auth, pdf, code analysis).

  • Cleaned up commented-out code and improved readability in multiple files.

  • Adjusted the changelog workflow to comment out the delay function for better performance.

- Updated package dependencies in package.json to the latest versions, including:
  - "@ai-sdk/react": "^2.0.111"
  - "@mastra/ai-sdk": "^1.0.0-beta.8" to "^1.0.0-beta.9"
  - "@mastra/client-js": "^1.0.0-beta.10" to "^1.0.0-beta.11"
  - "@mastra/core": "^1.0.0-beta.10" to "^1.0.0-beta.11"
  - "@mcpc-tech/acp-ai-provider": "^0.1.31" to "^0.1.34"
  - "@openrouter/ai-sdk-provider": "^1.5.2" to "^1.5.3"
  - "ai": "^5.0.108" to "^5.0.109"
  - "framer-motion": "^12.23.25" to "^12.23.26"
  - "lucide-react": "^0.556.0" to "^0.559.0"
  - "motion": "^12.23.25" to "^12.23.26"
  - "@types/node": "^24.10.2" to "^25.0.0"

- Refactored acpAgent to use pgMemory and pgQueryTool instead of MongoDB tools.
- Removed unused scorer toolCallAppropriatenessScorer from weather-agent.
- Updated MongoDB configuration to support PgVector and improved tracing with OpenTelemetry.
- Enhanced error handling and tracing in various tools (e.g., fs, jwt-auth, pdf, code analysis).
- Cleaned up commented-out code and improved readability in multiple files.
- Adjusted the changelog workflow to comment out the delay function for better performance.
Copilot AI review requested due to automatic review settings December 11, 2025 05:56
@continue
Copy link

continue bot commented Dec 11, 2025

All Green - Keep your PRs mergeable

Learn more

All Green is an AI agent that automatically:

✅ Addresses code review comments

✅ Fixes failing CI checks

✅ Resolves merge conflicts

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Sorry @ssdeanx, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@coderabbitai
Copy link

coderabbitai bot commented Dec 11, 2025

Summary by CodeRabbit

Release Notes

  • Chores

    • Updated dependencies to latest versions, including @AI-SDK, Mastra, and provider packages.
    • Removed unused scorers and disabled telemetry setup.
    • Disabled webpack memory optimizations and bundle analyzer features.
  • Bug Fixes

    • Enhanced error handling and tracing across multiple tools with improved exception recording and status reporting.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

This PR disables telemetry features in configuration, migrates the ACP agent from MongoDB to PostgreSQL-backed vector tooling, removes certain evaluation scorers, updates OpenTelemetry tracing patterns across multiple tools, and bumps dependency versions.

Changes

Cohort / File(s) Summary
Telemetry Disablement
instrumentation.ts, next.config.ts
Comments out NodeSDK initialization, webpack memory optimizations, and bundle analyzer integration; disables telemetry setup without replacing active logic.
Configuration & Sampling
src/mastra/index.ts
Removes completenessScorer and toolCallAppropriatenessScorer; comments out ALWAYS sampling configuration.
Database Backend Migration
src/mastra/agents/acpAgent.ts
Migrates from mongoMemory to pgMemory; replaces mongoQueryTool with pgQueryTool; updates MONGODB_PROMPT to PGVECTOR_PROMPT; removes toxicity scorer.
Tracing Infrastructure Refactor
src/mastra/config/mongodb.ts
Replaces legacy TracingContext-based spans with OpenTelemetry tracer; removes tracingContext parameter from processDocument, storeDocumentEmbeddings, and querySimilarDocuments.
OpenTelemetry Tracing in Tools
src/mastra/tools/code-analysis.tool.ts, diff-review.tool.ts, jwt-auth.tool.ts, pdf.ts
Adds span creation, attributes, exception recording, and status codes; imports SpanStatusCode; wraps execution in try-catch for error handling.
Tool Execution & Signature Updates
src/mastra/tools/code-chunking.ts, fs.ts
Migrates code-chunking from context-based to inputData-based signatures; adds tracer spans and stricter AST node handling; replaces fs synchronous calls with async promises.
Error Handling Improvement
src/mastra/tools/serpapi-search.tool.ts
Extracts error message to variable for consistent reuse in logging and user-facing output.
Scorer Cleanup
src/mastra/agents/weather-agent.ts, src/mastra/scorers/weather-scorer.ts
Removes toolCallAppropriatenessScorer and completenessScorer exports and configurations.
Workflow & Minor Updates
src/mastra/workflows/changelog.ts, src/mastra/mcp/prompts.ts, src/mastra/mcp/resources.ts
Removes delay import/call; minor formatting/spacing adjustments with no functional impact.
Dependency Updates
package.json
Bumps @ai-sdk, @mastra, @types/node, @openrouter/ai-sdk-provider, framer-motion, lucide-react, and related packages to newer versions; adds octokit.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Areas requiring extra attention:
    • src/mastra/config/mongodb.ts: Verify tracing refactor correctness and that removed tracingContext parameters don't break existing call sites.
    • src/mastra/agents/acpAgent.ts: Confirm MongoDB→PostgreSQL migration is complete and PGVECTOR_PROMPT is properly defined.
    • src/mastra/tools/code-chunking.ts: Review complex AST node handling with typedNode shim and verify chunk metadata extraction across all language paths.
    • src/mastra/tools/fs.ts: Validate async/await conversion and ensure file operation error handling remains intact.

Possibly related PRs

Poem

🐰 A rabbit hops through the vector fields,
From MongoDB to PostgreSQL it yields,
Telemetry dims, but tracing stays bright,
With OpenTelemetry's spangled light,
Tools now dance with async grace!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'chore: update dependencies and refactor code' is relevant to the changeset, covering the main updates in package.json and multiple refactoring activities across the codebase.
Description check ✅ Passed The description is well-related to the changeset, detailing specific dependency updates and refactoring changes including acpAgent migration, scorer removal, OpenTelemetry tracing improvements, and code cleanup.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch develop

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.

@github-actions
Copy link

🤖 Hi @ssdeanx, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @ssdeanx, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on a significant maintenance and refactoring effort, primarily updating numerous project dependencies to their latest versions to ensure stability and leverage new features. A key architectural change involves migrating the "acpAgent" from MongoDB to a PostgreSQL/PgVector backend, offering greater flexibility in data storage. Additionally, the PR streamlines the codebase by removing unused components and enhances the application's observability through a standardized OpenTelemetry tracing implementation across several core tools, providing more robust error handling and performance insights.

Highlights

  • Dependency Updates: Numerous package dependencies, including "@ai-sdk/react", "@mastra/ai-sdk", "@mastra/client-js", "@mastra/core", "@mcpc-tech/acp-ai-provider", "@openrouter/ai-sdk-provider", "ai", "framer-motion", "lucide-react", "motion", and "@types/node", have been updated to their latest versions.
  • acpAgent Refactoring: The acpAgent has been refactored to transition from MongoDB-based memory and query tools to PostgreSQL/PgVector equivalents ("pgMemory" and "pgQueryTool"), enhancing database flexibility.
  • Scorer Cleanup: The unused "toolCallAppropriatenessScorer" has been removed from "weather-agent" and related configurations, streamlining the scoring logic.
  • OpenTelemetry Tracing Enhancement: Tracing implementations across various tools ("fs", "jwt-auth", "pdf", "code-analysis", "code-chunking", "diff-review", "mongodb" config) have been updated to use the standard OpenTelemetry API ("trace.getTracer", "span.setAttribute", "span.recordException", "span.setStatus") for improved observability and error handling.
  • Next.js Configuration Adjustments: Several Next.js build optimizations and bundle analysis features ("webpackMemoryOptimizations", "webpackBuildWorker", "withBundleAnalyzer") have been commented out in "next.config.ts".
  • Changelog Workflow Optimization: The "delay" function call within the changelog workflow has been commented out, potentially improving performance or responsiveness.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@github-actions
Copy link

🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details.

@greptile-apps
Copy link

greptile-apps bot commented Dec 11, 2025

Greptile Overview

Greptile Summary

Updated dependencies to latest versions and refactored codebase from MongoDB to PgVector for vector storage, with comprehensive tracing migration to OpenTelemetry's native API.

Key Changes:

  • Updated 12 package dependencies including @mastra/core (beta.10→beta.11), ai SDK (5.0.108→5.0.109), and added octokit package
  • Major refactoring: Migrated acpAgent from MongoDB tools (mongoMemory, mongoQueryTool, mongoGraphTool) to PgVector equivalents (pgMemory, pgQueryTool)
  • Tracing modernization: Replaced Mastra's custom TracingContext API with OpenTelemetry's native tracing across 5+ tools (fs.ts, jwt-auth.tool.ts, pdf.ts, code-analysis.tool.ts, mongodb.ts)
  • Enhanced error handling with proper SpanStatusCode and recordException() calls
  • Migrated fs.ts tool from synchronous file operations to async fs.promises API
  • Removed unused code: toolCallAppropriatenessScorer from weather-agent, createToxicityScorer import, and TokenLimiter processor
  • Commented out OpenTelemetry NodeSDK initialization in instrumentation.ts and rate limiting in changelog workflow

Issues Found:

  • acpAgent instructions still reference "Mongo" and mongoQueryTool despite implementation using PgVector (line 65-76 in acpAgent.ts)

Confidence Score: 4/5

  • This PR is mostly safe to merge but contains one logical inconsistency that should be addressed
  • Score reflects systematic improvements to tracing and async patterns with proper error handling, balanced against the instruction documentation mismatch in acpAgent.ts that could confuse future developers. The dependency updates are standard patch/minor version bumps. OpenTelemetry tracing being disabled in instrumentation.ts appears intentional for debugging but should be verified.
  • Pay attention to src/mastra/agents/acpAgent.ts (instruction text references old MongoDB tools), and verify that disabling OpenTelemetry in instrumentation.ts is intentional

Important Files Changed

File Analysis

Filename Score Overview
src/mastra/agents/acpAgent.ts 4/5 Refactored from MongoDB to PgVector: replaced mongoMemory/mongoQueryTool/mongoGraphTool with pgMemory/pgQueryTool, updated imports and prompts; removed unused createToxicityScorer
src/mastra/config/mongodb.ts 4/5 Migrated tracing from Mastra's TracingContext to OpenTelemetry's native tracing API; removed TokenLimiter processor; fixed memory configuration structure; standardized span error handling
src/mastra/tools/fs.ts 5/5 Migrated from sync file operations (readFileSync, writeFileSync) to async fs.promises API; updated tracing to use OpenTelemetry directly with proper error handling
instrumentation.ts 4/5 Commented out OpenTelemetry NodeSDK initialization, likely for debugging or to temporarily disable tracing

Sequence Diagram

sequenceDiagram
    participant Dev as Developer
    participant Pkg as package.json
    participant Agent as acpAgent
    participant Tools as Tools (fs, pdf, jwt-auth, code-analysis)
    participant Mongo as MongoDB Config
    participant PG as PgVector Storage
    participant OTel as OpenTelemetry

    Dev->>Pkg: Update dependencies
    Note over Pkg: @mastra/core beta.10→beta.11<br/>ai 5.0.108→5.0.109<br/>+octokit package

    Dev->>Agent: Refactor MongoDB to PgVector
    Agent->>Agent: Remove mongoMemory, mongoQueryTool, mongoGraphTool
    Agent->>PG: Add pgMemory, pgQueryTool
    Agent->>Agent: Update imports from config
    Note over Agent: Instructions still reference<br/>"Mongo" (inconsistency)

    Dev->>Tools: Migrate tracing to OpenTelemetry
    Tools->>Tools: Replace TracingContext API
    Tools->>OTel: Use trace.getTracer()
    Tools->>OTel: startSpan() with attributes
    Tools->>OTel: recordException() + setStatus()
    Note over Tools: fs.ts: sync→async promises<br/>jwt-auth, pdf, code-analysis

    Dev->>Mongo: Update mongodb.ts tracing
    Mongo->>OTel: Replace Mastra TracingContext
    Mongo->>Mongo: Remove TokenLimiter processor
    Mongo->>Mongo: Fix memory config structure
    Mongo->>OTel: Standardize span error handling

    Dev->>Agent: Clean up unused code
    Note over Agent: Remove toolCallAppropriatenessScorer<br/>Remove createToxicityScorer

    Agent->>PG: Runtime operations
    PG->>OTel: Trace vector operations
    Tools->>OTel: Trace tool executions
    OTel-->>Dev: Observability data
Loading

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Additional Comments (1)

  1. src/mastra/agents/acpAgent.ts, line 65-76 (link)

    logic: Instructions still reference "Mongo" and mongoQueryTool but implementation now uses PgVector and pgQueryTool

18 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request brings a host of valuable updates, primarily focusing on dependency upgrades and refactoring. The migration from MongoDB to PgVector in the acpAgent and the switch to standard OpenTelemetry APIs for tracing are significant improvements. While the changes are largely positive, there are several instances of commented-out code across multiple files that should be removed to enhance maintainability. Additionally, I've identified a few stylistic issues and a minor bug related to incorrect string escaping in one of the files.

content: {
type: "text",
text: `Create a new note, It is critical to provide a detailed description of each section. Ensure that each section is well-organized and easy to read. Also, include subsections for each section. Provide as much detail as possible for each section. Using this template titled \"${today}\" with sections: \"## Tasks\", \"## Specifications\", \"## Resources\", and \"## Notes\". `,
text: `Create a new note, It is critical to provide a detailed description of each section. Ensure that each section is well-organized and easy to read. Also, include subsections for each section. Provide as much detail as possible for each section. Using this template titled \\"${today}\\" with sections: \\"## Tasks\\", \\"## Specifications\\", \\"## Resources\\", and \\"## Notes\\". `,
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The double quotes in this template literal are escaped with \\", which results in a literal backslash being included in the final string (e.g., ...titled \\"2024-01-01\\"...). This is likely not the intended behavior. You can use double quotes directly within template literals without any escaping.

Suggested change
text: `Create a new note, It is critical to provide a detailed description of each section. Ensure that each section is well-organized and easy to read. Also, include subsections for each section. Provide as much detail as possible for each section. Using this template titled \\"${today}\\" with sections: \\"## Tasks\\", \\"## Specifications\\", \\"## Resources\\", and \\"## Notes\\". `,
text: `Create a new note, It is critical to provide a detailed description of each section. Ensure that each section is well-organized and easy to read. Also, include subsections for each section. Provide as much detail as possible for each section. Using this template titled "${today}" with sections: "## Tasks", "## Specifications", "## Resources", and "## Notes". `,

]; }
default:
throw new Error(`Prompt \"${name}\" not found, please check the prompt name and try again.`);
throw new Error(`Prompt \\"${name}\\" not found, please check the prompt name and try again.`);
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Similar to the issue above, the double quotes in this error message are unnecessarily escaped with \\". This will include a literal backslash in the thrown error message. Double quotes can be used directly inside template literals.

Suggested change
throw new Error(`Prompt \\"${name}\\" not found, please check the prompt name and try again.`);
throw new Error(`Prompt "${name}" not found, please check the prompt name and try again.`);

Comment on lines +68 to +71
//const withBundleAnalyzer = require('@next/bundle-analyzer')({
// enabled: process.env.ANALYZE === 'true',
//})
//module.exports = withBundleAnalyzer({})
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The withBundleAnalyzer configuration is commented out. This should be removed to avoid cluttering the configuration file with dead code.

Comment on lines +1 to +5
//import {
// NodeSDK,
// ATTR_SERVICE_NAME,
// resourceFromAttributes,
//} from "@mastra/core/telemetry/otel-vendor";
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This import block is commented out. If it's no longer needed as part of the OpenTelemetry refactoring, it should be removed to keep the code clean and improve maintainability.

serviceName: "ai",
requestContextKeys: ["userId", "environment", "tenantId"],
sampling: { type: SamplingStrategyType.ALWAYS },
//sampling: { type: SamplingStrategyType.ALWAYS },
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The sampling configuration for Langfuse is commented out. If this is not intended to be used, it should be removed to avoid confusion and keep the configuration clean.

Comment on lines +2 to +11
//import { createToolCallAccuracyScorerCode } from '@mastra/core/evals/code';
//import { createCompletenessScorer } from '@mastra/core/evals/completeness-scorer';
import { createScorer, runEvals } from '@mastra/core/evals';

export const toolCallAppropriatenessScorer = createToolCallAccuracyScorerCode({
expectedTool: 'weatherTool',
strictMode: false,
});
//export const toolCallAppropriatenessScorer = createToolCallAccuracyScorerCode({
//expectedTool: 'weatherTool',
//strictMode: false,
//});

export const completenessScorer = createCompletenessScorer();
//export const completenessScorer = createCompletenessScorer();
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

These imports and variable declarations are commented out. If these scorers are no longer needed, the corresponding code should be removed entirely to keep the codebase clean and maintainable.

Comment on lines +92 to +93
//toolCallAppropriatenessScorer,
//completenessScorer,
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

These properties in the scorers object are commented out. They should be removed if they are no longer used.


for (const symbol of symbols) {
if ((symbol.kind === 'function' || symbol.kind === 'class') && symbol.endLine) {
if ((symbol.kind === 'function' || symbol.kind === 'class') && (symbol.endLine !== null && symbol.endLine !== undefined && symbol.endLine > 0)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This check is more robust than before, but it's a bit verbose. Since null > 0 and undefined > 0 are both false, you can simplify this check to just symbol.endLine > 0 to achieve the same result with better readability.

Suggested change
if ((symbol.kind === 'function' || symbol.kind === 'class') && (symbol.endLine !== null && symbol.endLine !== undefined && symbol.endLine > 0)) {
if ((symbol.kind === 'function' || symbol.kind === 'class') && symbol.endLine > 0) {

@@ -1,4 +1,4 @@
import { delay } from '@mastra/core';
//import { delay } from '@mastra/core';
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The import for delay is commented out. This dead code should be removed for better maintainability.


if (TOKEN_LIMIT < 20000) {
await delay(60000);
//await delay(60000);
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The call to delay is commented out. As per the PR description, this was done for performance. The commented-out code should be removed to keep the codebase clean.

Suggested change
//await delay(60000);

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 21

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (14)
src/mastra/mcp/resources.ts (2)

28-39: Path traversal vulnerability: validate and sanitize URI input.

The readNoteFile function extracts the title directly from the URI without validation and uses it in file path construction. An attacker could provide a malicious URI like notes://../../../etc/passwd to access files outside the NOTES_DIR.

Apply this diff to add path validation:

 const readNoteFile = async (uri: string): Promise<string | null> => {
   const title = uri.replace("notes://", "");
+  // Prevent path traversal attacks
+  if (title.includes("..") || title.includes("/") || title.includes("\\")) {
+    console.error(`Invalid note URI: ${uri}`);
+    return null;
+  }
   const notePath = path.join(NOTES_DIR, `${title}.md`);
   try {

Alternatively, use path.basename() to ensure only the filename is extracted:

 const readNoteFile = async (uri: string): Promise<string | null> => {
-  const title = uri.replace("notes://", "");
+  const title = path.basename(uri.replace("notes://", ""));
   const notePath = path.join(NOTES_DIR, `${title}.md`);

41-48: Add TSDoc documentation for the public API.

The exported resourceHandlers is a public API but lacks documentation explaining its purpose and usage.

As per coding guidelines, add TSDoc comments:

+/**
+ * MCP server resource handlers for managing markdown note files.
+ * 
+ * @remarks
+ * Provides resource listing and content retrieval for notes stored in the local filesystem.
+ * All notes are stored as markdown files in the `notes` directory.
+ * 
+ * @example
+ * ```typescript
+ * const resources = await resourceHandlers.listResources();
+ * const content = await resourceHandlers.getResourceContent({ uri: 'notes://my-note' });
+ * ```
+ */
 export const resourceHandlers: MCPServerResources = {
   listResources: listNoteFiles,
   getResourceContent: async ({ uri }: { uri: string }) => {
instrumentation.ts (1)

10-46: Unused LangfuseExporter instance and disabled telemetry.

The exporter is instantiated but never used since the SDK setup is commented out. This creates:

  1. An unused variable that consumes resources
  2. A non-functional register() function
  3. Inconsistency with other tools in this PR that are adding OpenTelemetry spans (e.g., serpapi-search.tool.ts, jwt-auth.tool.ts)

If telemetry is intentionally disabled, either:

  • Remove the entire function body and add a comment explaining why
  • Or keep a minimal stub that clearly indicates telemetry is disabled
 export function register() {
-  const exporter = new LangfuseExporter({
-    publicKey: process.env.LANGFUSE_PUBLIC_KEY,
-    secretKey: process.env.LANGFUSE_SECRET_KEY,
-    baseUrl: process.env.LANGFUSE_BASE_URL,
-  });
-
-  //const sdk = new NodeSDK({
-  // ... commented out code ...
-  //});
-
-//  sdk.start();
+  // TODO: Telemetry temporarily disabled - spans recorded in tools will be no-ops
+  // Re-enable NodeSDK setup when ready to export traces
 }
src/mastra/tools/jwt-auth.tool.ts (1)

64-72: Error message not included in thrown error.

The errorMessage is extracted and logged but the thrown error uses a hardcoded "Unknown error" string, losing valuable debugging information.

     } catch (error) {
       const errorMessage =
         error instanceof Error ? error.message : String(error)
       log.error(`JWT verification failed: ${errorMessage}`)
       span?.recordException(new Error(errorMessage));
       span?.setStatus({ code: SpanStatusCode.ERROR, message: errorMessage });
       span?.end();
-      throw new Error('JWT verification failed: Unknown error')
+      throw new Error(`JWT verification failed: ${errorMessage}`)
     }
src/mastra/tools/pdf.ts (1)

27-28: Tool ID should follow 'namespace:toolName' format.

Per coding guidelines, tool IDs should follow the format 'namespace:toolName' (e.g., 'pdf:readPDF' or 'file:readPDF'). The current ID 'readPDF' doesn't include a namespace.

 export const readPDF = createTool({
-  id: 'readPDF',
+  id: 'file:readPDF',
   description: 'Read PDF file and extract information',
src/mastra/tools/code-analysis.tool.ts (1)

205-221: Indentation inconsistency within try block.

The code inside the try block (starting at line 211) is not indented relative to the try statement. This affects readability and doesn't match the indentation style in other tools.

src/mastra/tools/fs.ts (1)

8-9: Tool ID should follow 'namespace:toolName' format.

Per coding guidelines, tool IDs should follow the format 'namespace:toolName'. Consider renaming to 'file:fsTool' or 'fs:fileOperation'.

 export const fsTool = createTool({
-  id: 'fsTool',
+  id: 'fs:fileOperation',
   description: 'File System Tool',
src/mastra/agents/acpAgent.ts (3)

53-53: Stale MongoDB references in agent instructions.

The capabilities section still references mongoQueryTool / mongoGraphTool but the agent now uses pgQueryTool. This inconsistency will confuse the LLM about which tools are available.

   <capabilities>
-  - Query & mutate Mongo records via mongoQueryTool / mongoGraphTool (Follow Mongo rules below).
+  - Query & mutate PostgreSQL records via pgQueryTool (Follow database rules below).

65-65: Stale MongoDB reference in process instructions.

The process section still instructs to persist to "Mongo" but the storage backend is now PostgreSQL.

-     - Persist important decisions, task status, and metadata to Mongo ONLY after completion or explicit commit.
+     - Persist important decisions, task status, and metadata to PostgreSQL ONLY after completion or explicit commit.

69-78: Rename <mongo_rules> section and update tool references.

The section name and content still reference MongoDB despite using PGVECTOR_PROMPT and PostgreSQL tools. The mongoQueryTool reference on line 76 should be updated to pgQueryTool.

-  <mongo_rules>
+  <pg_rules>
   - Use ${PGVECTOR_PROMPT} to format queries/updates and avoid any unstructured updates.
-  - Persist "decisions" and "task changes" to collection: acp_tasks, with schema: {taskId, title, status, createdBy, modifiedBy, timestamp, actionLog}.
+  - Persist "decisions" and "task changes" to table: acp_tasks, with schema: {taskId, title, status, createdBy, modifiedBy, timestamp, actionLog}.
   - Write to memory only after the task is validated.
-  </mongo_rules>
+  </pg_rules>

   <tools_usage>
-  - Always do a read with mongoQueryTool before mutating.
+  - Always do a read with pgQueryTool before mutating.
src/mastra/config/mongodb.ts (3)

84-91: Index config type mismatch between actual config and log statement.

The actual config uses type: 'hnsw' with hnsw options, but the log statement on lines 116-119 incorrectly logs type: 'flat' with ivf options. This inconsistency makes debugging difficult.

Update the log statement (lines 103-130) to match the actual configuration:

             indexConfig: {
-                type: 'flat',
+                type: 'hnsw',
                 metric: 'cosine',
-                ivf: { lists: 4000 }, // Adjust list count based on your needs
+                hnsw: {
+                    m: 16,
+                    efConstruction: 200,
+                },
             }

127-127: Same inverted logic issue in log statement.

This mirrors the issue on line 74 - the log shows generateTitle will be true when THREAD_GENERATE_TITLE is not 'true'.


202-254: Tracing implementation is correct but uses unnecessary optional chaining.

The span is always defined from tracer.startSpan(), so optional chaining (span?.) is unnecessary. While harmless, it adds noise.

-    span?.setAttribute('chunksCount', chunks.length);
-    span?.setAttribute('embeddingDimension', embeddings[0]?.length || 0);
-    span?.setAttribute('processingTimeMs', processingTime);
-    span?.setAttribute('success', true);
-    span?.setAttribute('model', 'gemini-embedding-001');
-    span?.setAttribute('operation', 'document-processing');
-    span?.end();
+    span.setAttribute('chunksCount', chunks.length);
+    span.setAttribute('embeddingDimension', embeddings[0]?.length || 0);
+    span.setAttribute('processingTimeMs', processingTime);
+    span.setAttribute('success', true);
+    span.setAttribute('model', 'gemini-embedding-001');
+    span.setAttribute('operation', 'document-processing');
+    span.end();
src/mastra/tools/code-chunking.ts (1)

106-117: Simplify the endLine validation condition.

The null/undefined checks are redundant since > 0 already implies a numeric value. TypeScript will narrow the type with just the > 0 check combined with typeof or a simpler truthy check.

-          if ((symbol.kind === 'function' || symbol.kind === 'class') && (symbol.endLine !== null && symbol.endLine !== undefined && symbol.endLine > 0)) {
+          if ((symbol.kind === 'function' || symbol.kind === 'class') && typeof symbol.endLine === 'number' && symbol.endLine > 0) {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec03cfb and ce41213.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (18)
  • instrumentation.ts (2 hunks)
  • next.config.ts (2 hunks)
  • package.json (8 hunks)
  • src/mastra/agents/acpAgent.ts (5 hunks)
  • src/mastra/agents/weather-agent.ts (0 hunks)
  • src/mastra/config/mongodb.ts (12 hunks)
  • src/mastra/index.ts (3 hunks)
  • src/mastra/mcp/prompts.ts (4 hunks)
  • src/mastra/mcp/resources.ts (1 hunks)
  • src/mastra/scorers/weather-scorer.ts (2 hunks)
  • src/mastra/tools/code-analysis.tool.ts (4 hunks)
  • src/mastra/tools/code-chunking.ts (8 hunks)
  • src/mastra/tools/diff-review.tool.ts (4 hunks)
  • src/mastra/tools/fs.ts (2 hunks)
  • src/mastra/tools/jwt-auth.tool.ts (3 hunks)
  • src/mastra/tools/pdf.ts (3 hunks)
  • src/mastra/tools/serpapi-search.tool.ts (1 hunks)
  • src/mastra/workflows/changelog.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • src/mastra/agents/weather-agent.ts
🧰 Additional context used
📓 Path-based instructions (20)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)

**/*.{js,jsx,ts,tsx}: Use next/dynamic for dynamic imports to load components only when needed, improving initial load time.
Use next/image component for automatic image optimization, including lazy loading and responsive images.
Use React.memo to prevent unnecessary re-renders of components.
Use the <Link prefetch> tag to prefetch pages that are likely to be visited.
Use getServerSideProps, getStaticProps, or server components for fetching data on the server-side.
Use SWR or React Query for client-side data fetching and caching.
Use CSS Modules, Styled Components, or Tailwind CSS for component-level styling. Prefer Tailwind CSS for rapid development.
Use React Context, Zustand, Jotai, or Recoil for managing global state. Avoid Redux unless necessary.
Use react-hook-form for managing forms and validation.
Only fetch the data that is needed by the component to avoid over-fetching.
Avoid long-running synchronous operations in the main thread to prevent blocking.
Always use setState or hooks to update state instead of mutating state directly.
Include a complete dependency array in useEffect hooks to prevent unexpected behavior.
Avoid writing server-side code in client components to prevent exposing secrets or causing unexpected behavior.
Use try...catch blocks for handling errors in asynchronous operations.
Implement error boundary components using getDerivedStateFromError or componentDidCatch lifecycle methods.
Sanitize user input to prevent Cross-Site Scripting (XSS) attacks. Be especially careful when rendering HTML directly from user input.
Store authentication tokens in HTTP-only cookies or local storage securely.
Implement role-based access control to restrict access to sensitive resources.
Clean up event listeners and timers in useEffect hooks to avoid memory leaks.
Only update state when necessary to reduce the number of re-renders and improve performance.
Use immutable data structures and avoid mutating data directly to prevent unexpected...

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/mcp/resources.ts
  • instrumentation.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/scorers/weather-scorer.ts
  • src/mastra/workflows/changelog.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/index.ts
  • next.config.ts
  • src/mastra/mcp/prompts.ts
  • src/mastra/agents/acpAgent.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/tools/diff-review.tool.ts
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)

Use parameterized queries or an ORM to prevent SQL injection attacks.

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/mcp/resources.ts
  • instrumentation.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/scorers/weather-scorer.ts
  • src/mastra/workflows/changelog.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/index.ts
  • next.config.ts
  • src/mastra/mcp/prompts.ts
  • src/mastra/agents/acpAgent.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/tools/diff-review.tool.ts
src/mastra/tools/**/*.ts

📄 CodeRabbit inference engine (src/mastra/AGENTS.md)

src/mastra/tools/**/*.ts: Use the createTool pattern with Zod schemas when adding new tools under src/mastra/tools
Use explicit Zod schemas for every tool input/output

src/mastra/tools/**/*.ts: Use Zod schemas for strict validation of tool inputs and outputs in all Mastra tools
Implement tools using the createTool({ id, inputSchema, outputSchema, execute }) pattern
Organize tools into categories: Financial (Polygon, Finnhub, AlphaVantage), Research (SerpAPI, ArXiv), Data (CSV, JSON), RAG (chunking, embeddings)

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/tools/diff-review.tool.ts
src/mastra/{tools,workflows}/**/*.ts

📄 CodeRabbit inference engine (src/mastra/AGENTS.md)

Use RuntimeContext to enforce access control in tools and workflows

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/workflows/changelog.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/tools/diff-review.tool.ts
src/mastra/tools/**/*.tool.ts

📄 CodeRabbit inference engine (src/mastra/tools/AGENTS.md)

src/mastra/tools/**/*.tool.ts: Define Zod schema for inputs and outputs when creating tools
Tool IDs should follow the 'namespace:toolName' format (e.g., 'alpha-vantage:stockTool')

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/tools/diff-review.tool.ts
src/mastra/tools/**/*.{ts,tsx}

📄 CodeRabbit inference engine (src/mastra/tools/AGENTS.md)

src/mastra/tools/**/*.{ts,tsx}: All tools must include comprehensive error handling with try-catch blocks, clear error messages, and retry logic for API calls
Sanitize inputs, mask secrets in logs, and implement rate-limiting in tools
Implement caching, stream large data, and set timeouts for external API calls in tools
Add Arize spans on all tool execute functions for observability

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/tools/diff-review.tool.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Never commit API keys or secrets to the repository; use maskSensitiveMessageData() helper from src/mastra/config/pg-storage.ts when logging

**/*.{ts,tsx}: Document interface and type definitions with TSDoc comments explaining their purpose and usage context
Document interface properties with /** */ comments explaining each field's purpose and constraints
Document generic type parameters with @template tags explaining what each type parameter represents
Use type guards with comments explaining the runtime validation logic being performed
Document advanced/complex TypeScript types with explanatory comments about their purpose and use cases

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/mcp/resources.ts
  • instrumentation.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/scorers/weather-scorer.ts
  • src/mastra/workflows/changelog.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/index.ts
  • next.config.ts
  • src/mastra/mcp/prompts.ts
  • src/mastra/agents/acpAgent.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/tools/diff-review.tool.ts
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Run eslint with --max-warnings=0 on src/**/*.{ts,tsx} to enforce linting standards

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/mcp/resources.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/scorers/weather-scorer.ts
  • src/mastra/workflows/changelog.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/index.ts
  • src/mastra/mcp/prompts.ts
  • src/mastra/agents/acpAgent.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/tools/diff-review.tool.ts
**/*.{ts,tsx,js,jsx,py,java,cs,rb,go,rs,cpp,c,h,hpp,swift,kotlin,php,scala,clj,groovy,lua,sh,bash}

📄 CodeRabbit inference engine (.github/instructions/self-explanatory-code-commenting.instructions.md)

**/*.{ts,tsx,js,jsx,py,java,cs,rb,go,rs,cpp,c,h,hpp,swift,kotlin,php,scala,clj,groovy,lua,sh,bash}: Write code that speaks for itself. Comment only when necessary to explain WHY, not WHAT. Avoid obvious comments that state what the code literally does.
Avoid redundant comments that simply repeat what the code is doing
Keep comments accurate and up-to-date with code changes. Remove or update outdated comments that no longer match the implementation.
Write comments for complex business logic that explain the WHY behind specific calculations or business rules
Document non-obvious algorithms with comments explaining the algorithm choice and its reasoning
Add comments explaining what regex patterns match, especially for complex patterns
Document API constraints, rate limits, gotchas, and external dependencies with explanatory comments
Avoid commenting out dead code. Use version control instead of maintaining commented code blocks.
Do not maintain code change history or modification logs as comments. Rely on git history and commit messages instead.
Avoid decorative divider comments (e.g., lines of equals signs or asterisks) for section separation
Ensure comments are placed appropriately above or adjacent to the code they describe
Write comments using proper grammar, spelling, and professional language
Prefer self-documenting code with clear variable/function names over adding comments to explain unclear code

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/mcp/resources.ts
  • instrumentation.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/scorers/weather-scorer.ts
  • src/mastra/workflows/changelog.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/index.ts
  • next.config.ts
  • src/mastra/mcp/prompts.ts
  • src/mastra/agents/acpAgent.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/tools/diff-review.tool.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/instructions/self-explanatory-code-commenting.instructions.md)

**/*.{ts,tsx,js,jsx}: Document public APIs with TSDoc/JSDoc comments including parameter descriptions, return types, examples, and thrown exceptions
Add TSDoc comments to configuration constants and environment variables explaining their source, reasoning, or constraints
Use TSDoc annotation tags (TODO, FIXME, HACK, NOTE, WARNING, PERF, SECURITY, BUG, REFACTOR, DEPRECATED) to mark special comments
Include file headers with @fileoverview, @author, @copyright, and @license tags to document file purpose and ownership
Document function parameters with @param tags, return values with @returns tags, and exceptions with @throws tags in TSDoc comments
Use @see tags in TSDoc comments to reference related functions, methods, or documentation
Include @example tags in public API documentation with code examples showing typical usage

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/mcp/resources.ts
  • instrumentation.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/scorers/weather-scorer.ts
  • src/mastra/workflows/changelog.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/index.ts
  • next.config.ts
  • src/mastra/mcp/prompts.ts
  • src/mastra/agents/acpAgent.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/tools/diff-review.tool.ts
src/mastra/**/*

📄 CodeRabbit inference engine (src/AGENTS.md)

mastra modules can import from utils, but must not import from app or cli (except types)

Files:

  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/mcp/resources.ts
  • src/mastra/tools/pdf.ts
  • src/mastra/scorers/weather-scorer.ts
  • src/mastra/workflows/changelog.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/index.ts
  • src/mastra/mcp/prompts.ts
  • src/mastra/agents/acpAgent.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/tools/diff-review.tool.ts
src/mastra/mcp/**/*.ts

📄 CodeRabbit inference engine (src/mastra/mcp/AGENTS.md)

src/mastra/mcp/**/*.ts: Implement coordinate_a2a_task tool with parameters: task (string), taskType (enum: 'financial'|'content'|'rag'|'report'|'coordination'), workflow (enum: 'sequential'|'parallel'|'conditional'), and priority (enum: 'low'|'medium'|'high'|'urgent')
Implement list_a2a_agents tool that returns an array of 25+ available agents with names and descriptions
Implement create_a2a_workflow tool with parameters: workflowName (string), agents (array), workflowType (enum), and optional description (string)
Implement ask_a2aCoordinator tool providing direct access to the A2A coordinator agent for complex coordination tasks

Use Model Context Protocol (MCP) server implementation in src/mastra/mcp for external tool integration

Files:

  • src/mastra/mcp/resources.ts
  • src/mastra/mcp/prompts.ts
src/mastra/scorers/**/*.ts

📄 CodeRabbit inference engine (src/mastra/scorers/AGENTS.md)

src/mastra/scorers/**/*.ts: Scorers should be deterministic and avoid stochastic logic, unless the stochastic behavior is inherent to the task and explicitly tested
Follow the createScorer(...) pattern when creating scorers, define a clear judge instruction, and provide normalized input/output examples for reproducible grading
Provide clear success/failure boundaries and sample test cases with expected outputs for scorers

Implement custom evaluation metrics in src/mastra/scorers for automated quality assessment

Files:

  • src/mastra/scorers/weather-scorer.ts
src/mastra/workflows/**/*.ts

📄 CodeRabbit inference engine (src/mastra/AGENTS.md)

Add new workflow definitions under src/mastra/workflows to orchestrate multi-step flows

Use Mastra DSL for multi-step workflow definitions in src/mastra/workflows

Files:

  • src/mastra/workflows/changelog.ts
src/mastra/index.ts

📄 CodeRabbit inference engine (src/AGENTS.md)

Enforce registration pattern in mastra/index.ts for AI orchestration modules composition

Files:

  • src/mastra/index.ts
**/next.config.{js,ts}

📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)

**/next.config.{js,ts}: Integrate linting and formatting into the build process to ensure consistent code.
Analyze bundle size using tools like webpack-bundle-analyzer to identify large dependencies.
Use tree shaking to remove unused code from bundles.

Files:

  • next.config.ts
src/mastra/agents/**/*.ts

📄 CodeRabbit inference engine (src/mastra/AGENTS.md)

Add new agent definitions under src/mastra/agents that wire tools together into higher-level behaviors

Files:

  • src/mastra/agents/acpAgent.ts
src/mastra/agents/*.ts

📄 CodeRabbit inference engine (src/mastra/agents/AGENTS.md)

src/mastra/agents/*.ts: Agent file naming convention: Create agent files using kebab-case with .ts extension in /src/mastra/agents/ directory (e.g., your-agent-name.ts)
Each agent must follow the pattern: export agent as const yourAgent = new Agent({ id: 'your-agent-id', name: 'Your Agent Name', description: '...' })

Files:

  • src/mastra/agents/acpAgent.ts
src/mastra/config/**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

src/mastra/config/**/*.ts: Centralize provider clients (Google, OpenAI, Anthropic, OpenRouter) and storage configuration in src/mastra/config
Use pg-storage with PgVector for vector store functionality in the configuration
Use src/mastra/config for role hierarchy and provider client configuration

Files:

  • src/mastra/config/mongodb.ts
src/mastra/config/mongodb.ts

📄 CodeRabbit inference engine (src/mastra/config/AGENTS.md)

MongoDB configuration must provide alternative document storage capability

Files:

  • src/mastra/config/mongodb.ts
🧬 Code graph analysis (5)
src/mastra/tools/pdf.ts (1)
src/mastra/config/logger.ts (1)
  • log (14-18)
src/mastra/tools/code-chunking.ts (1)
src/mastra/config/logger.ts (1)
  • log (14-18)
src/mastra/tools/fs.ts (1)
src/mastra/config/logger.ts (1)
  • log (14-18)
src/mastra/agents/acpAgent.ts (1)
src/mastra/config/pg-storage.ts (1)
  • pgMemory (87-151)
src/mastra/config/mongodb.ts (1)
src/mastra/config/logger.ts (1)
  • log (14-18)
🪛 Biome (2.1.2)
src/mastra/tools/diff-review.tool.ts

[error] 165-165: expected , but instead found )

Remove )

(parse)


[error] 165-165: expected , but instead found ;

Remove ;

(parse)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Agent
  • GitHub Check: Codacy Security Scan
🔇 Additional comments (21)
src/mastra/tools/serpapi-search.tool.ts (1)

177-188: LGTM!

Good refactoring. Extracting errorMessage once and reusing it improves consistency and aligns with the error handling pattern used in other tools across the codebase. The span lifecycle (recordException → setStatus → end) is correctly implemented.

src/mastra/tools/jwt-auth.tool.ts (1)

37-53: LGTM!

The OpenTelemetry tracing migration is well-implemented. Span lifecycle is properly managed with appropriate attributes, error recording, and status setting. This is consistent with the tracing patterns used in other tools across the codebase.

src/mastra/tools/diff-review.tool.ts (2)

142-145: LGTM on span instrumentation.

The span attributes for metrics (additions, deletions, totalChanges) and proper span termination follow the tracing pattern established across other tools in this PR.


158-165: Error handling follows the established pattern.

The catch block properly records the exception, sets the span status to ERROR, ends the span, and rethrows the error. This aligns with the tracing conventions in other tools.

Regarding the static analysis hint: The Biome parse errors appear to be false positives - the closing }); on line 165 correctly terminates both the execute function and the createTool call.

src/mastra/tools/pdf.ts (2)

40-43: Tracing setup is correct.

The tracer initialization with descriptive name 'tools/read-pdf' and span attributes (pdfPath, service) provide good observability context.


70-81: Span lifecycle correctly handles both success and error paths.

The span attributes are set before ending on success, and on error the exception is recorded with proper status before ending. This aligns with the tracing pattern across the codebase.

src/mastra/tools/code-analysis.tool.ts (1)

295-301: Error handling follows established pattern.

The catch block correctly records the exception, sets span status to ERROR, ends the span, and rethrows the error. This is consistent with the tracing conventions in diff-review.tool.ts.

package.json (1)

49-82: Dependency updates look reasonable.

The beta version bumps for @mastra/* packages and minor/patch updates for AI SDK packages are consistent with the PR's refactoring objectives.

src/mastra/tools/fs.ts (2)

46-47: Success path span handling is correct.

The span attribute and termination are properly handled for the write/append success paths.


55-57: Error path span handling follows the established pattern.

Exception recording, status setting, and span termination are correctly implemented, consistent with other tools in this PR.

src/mastra/agents/acpAgent.ts (2)

3-6: Import changes align with PostgreSQL migration.

The imports correctly bring in pgMemory and pgQueryTool from the config, and PGVECTOR_PROMPT from @mastra/pg to support the PostgreSQL-based vector storage.


99-101: Memory and tools configuration correctly updated.

The memory and tools are now properly configured to use PostgreSQL-backed pgMemory and pgQueryTool.

src/mastra/index.ts (2)

18-18: Import updated to match reduced scorer exports.

The import correctly reflects that only translationScorer is now exported from weather-scorer.ts.


167-167: Scorer configuration updated correctly.

The scorers object now uses the reduced set of available scorers.

src/mastra/config/mongodb.ts (5)

9-10: OpenTelemetry imports added for enhanced tracing.

The imports correctly bring in trace and SpanStatusCode for creating and managing spans.


190-190: Function signature correctly simplified.

Removing the tracingContext parameter in favor of inline tracer acquisition is a cleaner approach for OpenTelemetry instrumentation.


261-266: Error handling in tracing is well-implemented.

The error path correctly records the exception, sets error status, and ends the span before re-throwing.


281-281: Function signature correctly simplified.

Consistent with processDocument, the tracingContext parameter removal is appropriate.


350-350: Function signature correctly simplified.

Consistent tracing pattern applied to querySimilarDocuments.

src/mastra/tools/code-chunking.ts (2)

10-29: LGTM!

The Zod schemas are well-structured with appropriate defaults for chunking parameters. The output schema properly documents the chunk metadata structure.


130-155: LGTM!

The MDocument fallback path correctly handles non-parseable files with proper span lifecycle management. The comment explaining the placeholder line numbers is helpful.

Comment on lines +51 to +52
// webpackMemoryOptimizations: true,
//7 webpackBuildWorker: true,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Minor typo in comment.

Line 52 has a malformed comment //7 instead of //.

  //   webpackMemoryOptimizations: true,
- //7   webpackBuildWorker: true,
+ //   webpackBuildWorker: true,
📝 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
// webpackMemoryOptimizations: true,
//7 webpackBuildWorker: true,
// webpackMemoryOptimizations: true,
// webpackBuildWorker: true,
🤖 Prompt for AI Agents
In next.config.ts around lines 51 to 52, there's a malformed comment marker
"//7" on line 52; change "//7   webpackBuildWorker: true," to use a proper
comment marker "//   webpackBuildWorker: true," so the comment is well-formed
and consistent with the surrounding comments.

Comment on lines +68 to +71
//const withBundleAnalyzer = require('@next/bundle-analyzer')({
// enabled: process.env.ANALYZE === 'true',
//})
//module.exports = withBundleAnalyzer({})
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Remove commented-out dead code.

Per coding guidelines, avoid commenting out dead code. Use version control to preserve history instead. If the bundle analyzer is no longer needed, remove these lines entirely.

-//const withBundleAnalyzer = require('@next/bundle-analyzer')({
-//  enabled: process.env.ANALYZE === 'true',
-//})
-//module.exports = withBundleAnalyzer({})
-
 const withMDX = createMDX({
🤖 Prompt for AI Agents
In next.config.ts around lines 68 to 71, remove the commented-out bundle
analyzer block (the three lines that require and invoke @next/bundle-analyzer)
because dead code should not be left commented; simply delete these commented
lines so the file contains only active code, relying on VCS history if the
analyzer is needed later.

"nanoid": "^5.1.6",
"next": "^16.0.8",
"next-themes": "^0.4.6",
"octokit": "^5.0.5",
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify octokit is used in the codebase
rg -n "from ['\"]octokit['\"]|require\(['\"]octokit['\"]" --type=ts --type=js

Repository: ssdeanx/AgentStack

Length of output: 44


🏁 Script executed:

#!/bin/bash
# Broader search for octokit anywhere in the codebase
rg -i "octokit" --type=ts --type=js --type=json

Repository: ssdeanx/AgentStack

Length of output: 9056


Remove unused octokit dependency.

The octokit package is declared in package.json but is not imported or used anywhere in the codebase. It should be removed to reduce bundle size and avoid maintaining unnecessary dependencies.

🤖 Prompt for AI Agents
In package.json around line 141, the octokit dependency is declared but unused;
remove the "octokit": "^5.0.5" entry from dependencies, then run your package
manager (npm install or yarn install) to update package-lock.json or yarn.lock,
run the test suite and a global search to confirm no imports/usages remain, and
commit the updated package.json and lockfile.

"@types/jsdom": "^27.0.0",
"@types/mdx": "^2.0.13",
"@types/node": "^24.10.2",
"@types/node": "^25.0.0",
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

@types/node 25.0.0 Node.js version compatibility what version

💡 Result:

@types/node@25.0.0 is the type package for Node.js v25 — i.e., it targets Node 25. [1][2]

Sources:

  • Mapping of @types/node versions to Node.js versions. [1]
  • Node.js v25.0.0 release. [2]

Use @types/node@^24 or update the Node.js engine requirement to >=25.

@types/node@25.0.0 targets Node.js v25, but your engine requirement (line 42) specifies >=20.9.0. The major version mismatch means the type definitions will include features and types specific to Node.js 25 that don't exist in Node.js 20. Either downgrade @types/node to ^24.x (compatible with Node.js 20) or update the engine requirement to >=25.0.0.

🤖 Prompt for AI Agents
In package.json around line 186, the dependency "@types/node": "^25.0.0" is
incompatible with the project Node engine (>=20.9.0); either change the
devDependency to "@types/node": "^24.x" to match Node 20, or update the
"engines.node" field to ">=25.0.0" to match the types package. Pick one policy:
if you want to keep running on Node 20, replace the types entry with ^24.x and
run npm/yarn install; if you want to require Node 25, update the engines.node
value to >=25.0.0 and update CI/docs accordingly.

options: {
// Message management
lastMessages: parseInt(process.env.MEMORY_LAST_MESSAGES ?? '500'),
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Inverted generateTitle logic needs correction.

The condition process.env.THREAD_GENERATE_TITLE !== 'true' causes generateTitle to be true when the env var is anything except 'true' (including when undefined), which is counterintuitive. The standard pattern for feature flags is to enable features when the env var is explicitly set to 'true'.

-        generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
+        generateTitle: process.env.THREAD_GENERATE_TITLE === 'true',
📝 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
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
generateTitle: process.env.THREAD_GENERATE_TITLE === 'true',
🤖 Prompt for AI Agents
In src/mastra/config/mongodb.ts around line 74, the generateTitle flag is
inverted because it uses process.env.THREAD_GENERATE_TITLE !== 'true', which
yields true unless the env var is exactly 'true'; change the expression to
explicitly check for 'true' (e.g., process.env.THREAD_GENERATE_TITLE === 'true')
so the feature is enabled only when the environment variable is set to 'true'.

Comment on lines +163 to +166
// Trace the exception and set status
span?.recordException(error instanceof Error ? error : new Error(String(error)));
span?.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
span?.end();
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Optional chaining on span is unnecessary.

The span variable is initialized at line 43 before the try block, so it's always defined in the catch block. The optional chaining (span?.) adds noise without benefit.

-      span?.recordException(error instanceof Error ? error : new Error(String(error)));
-      span?.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
-      span?.end();
+      span.recordException(error instanceof Error ? error : new Error(String(error)));
+      span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
+      span.end();
📝 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
// Trace the exception and set status
span?.recordException(error instanceof Error ? error : new Error(String(error)));
span?.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
span?.end();
// Trace the exception and set status
span.recordException(error instanceof Error ? error : new Error(String(error)));
span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
span.end();
🤖 Prompt for AI Agents
In src/mastra/tools/code-chunking.ts around lines 163 to 166, the catch block
uses optional chaining on span (span?.) even though span is initialized before
the try and guaranteed to be defined here; remove the optional chaining and call
span.recordException(...), span.setStatus(...), and span.end() directly so the
code is clearer and avoids unnecessary noise.

Comment on lines +53 to +57
const tracer = trace.getTracer('diff-review');
const span = tracer.startSpan('diff-review', { attributes: { filename, contextLines } });

try {

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Inconsistent span initialization and indentation.

The span is created without optional chaining on line 54, but later uses optional chaining (span?.) when setting attributes. If startSpan can return undefined, use optional chaining consistently. Also, the try block content has inconsistent indentation - the code inside should be indented relative to the try block.

     const tracer = trace.getTracer('diff-review');
-    const span = tracer.startSpan('diff-review', { attributes: { filename, contextLines } });
+    const span = tracer.startSpan('diff-review', { attributes: { filename, contextLines } });

     try {
-
-    const unifiedDiff = createPatch(
+      const unifiedDiff = createPatch(

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/mastra/tools/diff-review.tool.ts around lines 53 to 57, the span is
started without optional chaining but later accessed with span?. which is
inconsistent; either treat startSpan as always returning a Span and remove
optional chaining later, or use optional chaining consistently by changing the
start to const span = trace.getTracer('diff-review')?.startSpan(...). Also fix
the indentation of the try block body so all code inside the try is indented one
level deeper than the try line to match project style.

Comment on lines +35 to +38
case 'read': {
const readContent = await fsPromises.readFile(file, 'utf8')
return { message: readContent }
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Span is not ended on successful read path.

The read case returns early at line 37 without ending the span. This creates a resource leak in the tracing system.

         case 'read': {
           const readContent = await fsPromises.readFile(file, 'utf8')
+          span?.setAttribute('success', true);
+          span?.end();
           return { message: readContent }
         }
🤖 Prompt for AI Agents
In src/mastra/tools/fs.ts around lines 35 to 38 the read case returns early
without ending the tracing span; ensure the span is ended before returning by
either calling span.end() immediately before the return or by refactoring to
assign the read result to a variable and exit the switch so a shared
finally/cleanup can call span.end(); implement one of these so the span is
always closed on the successful read path.

Comment on lines 42 to 43
default:
return { message: 'Invalid action' }
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Span is not ended on invalid action path.

The default case returns without ending the span, creating a resource leak.

         default:
+          span?.setAttribute('success', false);
+          span?.end();
           return { message: 'Invalid action' }
📝 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
default:
return { message: 'Invalid action' }
default:
span?.setAttribute('success', false);
span?.end();
return { message: 'Invalid action' }
🤖 Prompt for AI Agents
In src/mastra/tools/fs.ts around lines 42-43, the default branch returns an
object without ending the telemetry span which leaks the span; update the
default case to call span.end() (and optionally set span.status or record an
error/message on the span) before returning the { message: 'Invalid action' } so
the span is always closed on the invalid-action path.

Comment on lines 173 to 176
if (TOKEN_LIMIT < 20000) {
await delay(60000);
//await delay(60000);
TOKEN_LIMIT = 80000;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Removing the delay may cause API rate limit issues.

The commented-out delay was likely intended to prevent hitting LLM API rate limits when TOKEN_LIMIT drops below the threshold. Without this delay, the workflow will reset the token counter and continue immediately, potentially overwhelming the API with requests.

Consider one of these alternatives:

  1. Keep the delay for rate limiting
  2. Implement exponential backoff
  3. Use a rate limiter library
  4. Add proper API rate limit handling in the agent
         if (TOKEN_LIMIT < 20000) {
-            //await delay(60000);
+            await delay(60000); // Rate limit protection
             TOKEN_LIMIT = 80000;
           }

Also restore the import:

-//import { delay } from '@mastra/core';
+import { delay } from '@mastra/core';

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/mastra/workflows/changelog.ts around lines 173-176 the temporary removal
of the delay (commented-out await delay(60000)) causes the token counter reset
to happen immediately and risks hitting LLM API rate limits; restore the
previous rate-limiting behavior by re-enabling the delay (or replace it with an
exponential backoff or a proper rate-limiter call) so TOKEN_LIMIT is not
immediately increased, and re-add the missing import for the delay/rate-limiter
utility at the top of the file; ensure the chosen approach logs/backoffs on
repeated triggers and does not block the event loop unnecessarily.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This pull request updates multiple dependencies to their latest versions and performs a significant architectural refactoring from MongoDB to PgVector storage, while also standardizing OpenTelemetry tracing implementation across the codebase. The changes include improvements to error handling, migration to async file operations, and removal of unused scorer functionality.

Key Changes

  • Dependency Updates: Updated 15+ packages including core Mastra packages (beta.10 → beta.11), AI SDK packages, and various UI libraries
  • Storage Migration: Refactored acpAgent from MongoDB (mongoMemory, mongoQueryTool) to PgVector (pgMemory, pgQueryTool) with corresponding prompt updates
  • Tracing Standardization: Migrated from Mastra's custom AISpanType to standard OpenTelemetry APIs across all tools, using trace.getTracer(), span.recordException(), and SpanStatusCode

Reviewed changes

Copilot reviewed 18 out of 19 changed files in this pull request and generated 18 comments.

Show a summary per file
File Description
package.json Updated 15 dependencies to latest versions including Mastra core packages, AI SDK, UI libraries, and type definitions
package-lock.json Lock file updates reflecting all package version changes
src/mastra/workflows/changelog.ts Commented out delay function and import, potentially impacting rate limiting
src/mastra/tools/serpapi-search.tool.ts Added proper error message handling before logging
src/mastra/tools/pdf.ts Migrated to OpenTelemetry standard tracing with improved error handling
src/mastra/tools/jwt-auth.tool.ts Refactored tracing to use OpenTelemetry APIs with proper exception recording
src/mastra/tools/fs.ts Converted from sync to async file operations and updated tracing implementation
src/mastra/tools/diff-review.tool.ts Added OpenTelemetry tracing with comprehensive error handling
src/mastra/tools/code-chunking.ts Added tracing, improved type safety, and verbose null checking for endLine
src/mastra/tools/code-analysis.tool.ts Wrapped execution in try-catch with proper error tracing
src/mastra/scorers/weather-scorer.ts Commented out unused toolCallAppropriatenessScorer and completenessScorer
src/mastra/mcp/resources.ts Added braces to if statement return (style change)
src/mastra/mcp/prompts.ts Added block scopes to case statements and single-line if statements
src/mastra/index.ts Removed unused scorers from imports and configuration, commented out sampling config
src/mastra/config/mongodb.ts Refactored to use OpenTelemetry, removed TokenLimiter, restructured memory options
src/mastra/agents/weather-agent.ts Removed toolCallAppropriatenessScorer configuration
src/mastra/agents/acpAgent.ts Migrated from MongoDB to PgVector (mongoMemory→pgMemory, mongoQueryTool→pgQueryTool)
next.config.ts Commented out webpack optimizations and bundle analyzer configuration
instrumentation.ts Commented out entire NodeSDK initialization, disabling OpenTelemetry instrumentation


if (TOKEN_LIMIT < 20000) {
await delay(60000);
//await delay(60000);
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

Commenting out the delay function can lead to rate limiting issues with the API. The delay was likely added to prevent exceeding token limits. Instead of commenting it out, consider making this configurable through an environment variable or reducing the delay duration if performance is a concern.

Copilot uses AI. Check for mistakes.
Comment on lines +35 to +38
case 'read': {
const readContent = await fsPromises.readFile(file, 'utf8')
return { message: readContent }
}
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

This change replaces synchronous file operations with async operations, which is good. However, for the 'read' case, wrapping the return in a block creates unnecessary scope. The block is only needed if you're declaring variables that might conflict with other case statements. Consider removing the braces for the return statement to maintain consistency with the other cases.

Suggested change
case 'read': {
const readContent = await fsPromises.readFile(file, 'utf8')
return { message: readContent }
}
case 'read':
const readContent = await fsPromises.readFile(file, 'utf8')
return { message: readContent }

Copilot uses AI. Check for mistakes.

for (const symbol of symbols) {
if ((symbol.kind === 'function' || symbol.kind === 'class') && symbol.endLine) {
if ((symbol.kind === 'function' || symbol.kind === 'class') && (symbol.endLine !== null && symbol.endLine !== undefined && symbol.endLine > 0)) {
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

The condition check has been made more verbose but it's checking for the same condition multiple times. The expression (symbol.endLine !== null && symbol.endLine !== undefined && symbol.endLine > 0) can be simplified to (symbol.endLine != null && symbol.endLine > 0) using loose equality which checks for both null and undefined, or even better (symbol.endLine && symbol.endLine > 0) if 0 is also an invalid value.

Suggested change
if ((symbol.kind === 'function' || symbol.kind === 'class') && (symbol.endLine !== null && symbol.endLine !== undefined && symbol.endLine > 0)) {
if ((symbol.kind === 'function' || symbol.kind === 'class') && (symbol.endLine != null && symbol.endLine > 0)) {

Copilot uses AI. Check for mistakes.
serviceName: "ai",
requestContextKeys: ["userId", "environment", "tenantId"],
sampling: { type: SamplingStrategyType.ALWAYS },
//sampling: { type: SamplingStrategyType.ALWAYS },
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

The sampling configuration for Langfuse has been commented out. This means all traces will be sent regardless of the sampling strategy. If this is intentional to collect all traces, it should be explicitly set rather than commented out. If it's temporary for debugging, consider using an environment variable to control this behavior.

Suggested change
//sampling: { type: SamplingStrategyType.ALWAYS },
sampling: {
type: process.env.LANGFUSE_SAMPLING_STRATEGY === "NEVER"
? SamplingStrategyType.NEVER
: process.env.LANGFUSE_SAMPLING_STRATEGY === "PROBABILISTIC"
? SamplingStrategyType.PROBABILISTIC
: SamplingStrategyType.ALWAYS
},

Copilot uses AI. Check for mistakes.
webpackMemoryOptimizations: true,
webpackBuildWorker: true,
// webpackMemoryOptimizations: true,
//7 webpackBuildWorker: true,
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

There's a typo in the comment: '//7' should be '//' without the '7'.

Suggested change
//7 webpackBuildWorker: true,
// webpackBuildWorker: true,

Copilot uses AI. Check for mistakes.
import type { UIMessage } from 'ai'
import { log } from './logger';
import { TokenLimiter } from "@mastra/memory/processors";
import z from "zod";
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

'z' is defined but never used.

Suggested change
import z from "zod";

Copilot uses AI. Check for mistakes.
import { createCompletenessScorer } from '@mastra/core/evals/completeness-scorer';
//import { createToolCallAccuracyScorerCode } from '@mastra/core/evals/code';
//import { createCompletenessScorer } from '@mastra/core/evals/completeness-scorer';
import { createScorer, runEvals } from '@mastra/core/evals';
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

'runEvals' is defined but never used.

Suggested change
import { createScorer, runEvals } from '@mastra/core/evals';
import { createScorer } from '@mastra/core/evals';

Copilot uses AI. Check for mistakes.
import { trace } from "@opentelemetry/api";
import { trace, SpanStatusCode } from "@opentelemetry/api";
import { PythonParser } from './semantic-utils'
import type { RequestContext } from '@mastra/core/request-context';
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

'RequestContext' is defined but never used.

Suggested change
import type { RequestContext } from '@mastra/core/request-context';

Copilot uses AI. Check for mistakes.
import { promises as fsPromises } from 'fs';
import { z } from 'zod';
import { log } from '../config/logger';
import type { RequestContext } from '@mastra/core/request-context';
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

'RequestContext' is defined but never used.

Suggested change
import type { RequestContext } from '@mastra/core/request-context';

Copilot uses AI. Check for mistakes.
import { log } from '../config/logger'
import { trace } from "@opentelemetry/api";
import { trace, SpanStatusCode } from "@opentelemetry/api";
import type { RequestContext } from '@mastra/core/request-context';
Copy link

Copilot AI Dec 11, 2025

Choose a reason for hiding this comment

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

'RequestContext' is defined but never used.

Suggested change
import type { RequestContext } from '@mastra/core/request-context';

Copilot uses AI. Check for mistakes.
@ssdeanx ssdeanx merged commit 3c7f62a into main Dec 11, 2025
250 of 251 checks passed
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