Skip to content

Conversation

@abhiaiyer91
Copy link
Contributor

@abhiaiyer91 abhiaiyer91 commented Dec 7, 2025

The idGenerator function now receives optional context about what type of ID is being generated and from which Mastra primitive. This lets you generate deterministic IDs that can be shared with external databases.

const mastra = new Mastra({
  idGenerator: (context) => {
    if (context?.idType === 'message' && context?.threadId) {
      return `msg-${context.threadId}-${Date.now()}`;
    }
    if (context?.idType === 'run' && context?.entityId) {
      return `run-${context.entityId}-${Date.now()}`;
    }
    return crypto.randomUUID();
  },
});

Context includes idType (thread, message, run, step, generic), source (agent, workflow, memory), entityId, threadId, resourceId, role, and stepType.

Existing idGenerator functions without parameters continue to work since context is optional.

Fixes #8131

Summary by CodeRabbit

Release Notes

  • New Features

    • Added optional context-aware ID generation support to Mastra, enabling deterministic ID generation based on runtime context (message type, source, thread, and resource information).
    • Existing custom ID generators remain fully compatible without modification.
  • Chores

    • Bumped @mastra/core to a minor release.

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

… generation

The idGenerator function now receives optional context about what type of ID
is being generated (thread, message, run, step) and from which Mastra primitive
(agent, workflow, memory). This enables generating IDs that can be shared with
external databases.

Existing idGenerator functions without parameters continue to work since the
context is optional.

Fixes #8131
@changeset-bot
Copy link

changeset-bot bot commented Dec 7, 2025

🦋 Changeset detected

Latest commit: 55f4a48

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 17 packages
Name Type
@mastra/core Minor
@mastra/mcp-docs-server Patch
@mastra/client-js Patch
@mastra/react Patch
@mastra/dane Patch
@mastra/longmemeval Patch
@mastra/playground-ui Patch
@mastra/server Minor
@mastra/deployer Minor
@mastra/deployer-cloud Minor
@mastra/express Patch
@mastra/hono Patch
mastra Patch
@mastra/deployer-cloudflare Patch
@mastra/deployer-netlify Patch
@mastra/deployer-vercel Patch
create-mastra Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel
Copy link

vercel bot commented Dec 7, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
assistant-ui Ready Ready Preview Comment Dec 8, 2025 5:04pm
mastra-docs Ready Ready Preview Comment Dec 8, 2025 5:04pm
mastra-docs-1.x Building Building Preview Comment Dec 8, 2025 5:04pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 7, 2025

Walkthrough

Context-aware ID generation is introduced to the Mastra framework via an optional context parameter on the idGenerator function. A new IdGeneratorContext type defines available fields (idType, source, entityId, threadId, resourceId, role, stepType). This context is threaded through core, loop, workflow, and memory modules to enable deterministic ID generation based on runtime context. Backward compatibility is maintained—existing generators without parameters continue to work.

Changes

Cohort / File(s) Change Summary
Type definitions and core API
.changeset/add-context-to-id-generator.md, packages/core/src/types/dynamic-argument.ts, packages/core/src/mastra/index.ts
New IdGeneratorContext type with fields (idType, source, entityId, threadId, resourceId, role, stepType). MastraIdGenerator updated to accept optional context parameter. Mastra.generateId() now accepts and forwards optional context to custom id generators.
Memory module
packages/core/src/memory/memory.ts
generateId() method signature updated to accept optional IdGeneratorContext. Thread creation now passes context object with idType and source to generateId.
Agent core updates
packages/core/src/agent/agent.ts, packages/core/src/agent/agent-legacy.ts
RunId generation enhanced with context object including idType ('run'), source ('agent'), entityId, threadId, and resourceId. Sub-agent thread/resource IDs also generated with rich context. Fallback to randomUUID when Mastra instance unavailable.
Agent message handling
packages/core/src/agent/message-list/index.ts
generateMessageId field type updated to accept optional IdGeneratorContext. Constructor signature broadened. newMessageId() method now accepts optional role parameter and passes context object (idType, source, threadId, resourceId, role) to generateMessageId. Multiple call sites updated to propagate role context.
Loop and network
packages/core/src/loop/loop.ts, packages/core/src/loop/network/index.ts
New NetworkIdGenerator type defined. generateId parameter type changed from () => string to NetworkIdGenerator across prepareMemoryStep, createNetworkLoop, and networkLoop. All internal generateId calls updated to pass structured context objects with idType, source, threadId, resourceId, and stepType for messages, steps, and operations.
Workflow module
packages/core/src/workflows/workflow.ts, packages/core/src/workflows/workflow.test.ts
Sleep, sleepUntil, mapping, and run creation now use generateId with context objects (idType, source, entityId, stepType). Test fixtures updated to wrap randomUUID in a no-arg function for compatibility with new signature.
Feature tests
packages/core/src/mastra/idgenerator.test.ts
Large new test suite titled "Context-Aware ID Generator (Feature Request #8131)" validating context propagation across threads, messages, workflows, agents, and memory components. Minor test data change to use generated IDs instead of relying on auto-generation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • packages/core/src/agent/message-list/index.ts — Most complex change; role parameter propagation across multiple methods and call sites requires careful verification of context passing logic
  • packages/core/src/loop/network/index.ts — Comprehensive refactoring with many generateId calls; verify all context objects include necessary fields (idType, source, threadId, resourceId, stepType) consistently
  • packages/core/src/mastra/idgenerator.test.ts — Large test suite with multiple context-aware scenarios; validate test assertions match intended behavior and note any tests marked as expected failures or limitations

Possibly related PRs

Suggested reviewers

  • NikAiyer
  • kmk142789
  • wardpeet

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately summarizes the main change: adding a context parameter to idGenerator for deterministic ID generation, which aligns with the PR's primary objective and the changeset modifications.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #8131: exposes contextual information (idType, source, entityId, threadId, resourceId, role, stepType) to idGenerator calls, enables deterministic ID generation across components, and maintains backward compatibility with existing parameterless idGenerator functions.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing context-aware ID generation as specified in issue #8131. Updates to idGenerator signatures, context propagation through agent/workflow/memory/network layers, and corresponding test additions are all aligned with the stated objectives.
✨ 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 feat/context-aware-id-generator

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.

Copy link
Contributor

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

🧹 Nitpick comments (2)
packages/core/src/workflows/workflow.test.ts (1)

996-1000: Context-agnostic idGenerator wrapper looks correct; consider de-duplicating it

Using idGenerator: () => randomUUID() is compatible with the new context-aware ID generator API while preserving the existing deterministic behavior driven by the mocked randomUUID. This aligns the tests with the updated Mastra interface without changing expectations around IDs like mapping_mock-uuid-1.

If you expect to tweak ID behavior again, you might want to centralize this in a small helper (e.g., const testIdGenerator = () => randomUUID();) and reuse it across these Mastra instantiations to avoid three separate call sites.

Also applies to: 2719-2723, 14533-14537

.changeset/add-context-to-id-generator.md (1)

5-30: Align example with “deterministic ID” messaging

The text emphasizes deterministic IDs, but the example uses Date.now(), which makes IDs time-dependent. Consider switching to an example that’s purely a function of the context (e.g., hashing context.threadId / context.entityId) so repeated calls with the same context yield the same ID. That will better illustrate the intended deterministic behavior without changing the API.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c6fd6fe and 9d8b675.

📒 Files selected for processing (12)
  • .changeset/add-context-to-id-generator.md (1 hunks)
  • packages/core/src/agent/agent-legacy.ts (1 hunks)
  • packages/core/src/agent/agent.ts (4 hunks)
  • packages/core/src/agent/message-list/index.ts (6 hunks)
  • packages/core/src/loop/loop.ts (1 hunks)
  • packages/core/src/loop/network/index.ts (13 hunks)
  • packages/core/src/mastra/idgenerator.test.ts (2 hunks)
  • packages/core/src/mastra/index.ts (2 hunks)
  • packages/core/src/memory/memory.ts (3 hunks)
  • packages/core/src/types/dynamic-argument.ts (1 hunks)
  • packages/core/src/workflows/workflow.test.ts (3 hunks)
  • packages/core/src/workflows/workflow.ts (5 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Run pnpm typecheck to validate TypeScript types across all packages

Files:

  • packages/core/src/agent/agent-legacy.ts
  • packages/core/src/workflows/workflow.ts
  • packages/core/src/loop/network/index.ts
  • packages/core/src/types/dynamic-argument.ts
  • packages/core/src/agent/agent.ts
  • packages/core/src/mastra/idgenerator.test.ts
  • packages/core/src/mastra/index.ts
  • packages/core/src/agent/message-list/index.ts
  • packages/core/src/loop/loop.ts
  • packages/core/src/workflows/workflow.test.ts
  • packages/core/src/memory/memory.ts
**/*.{ts,tsx,js,jsx,json,md}

📄 CodeRabbit inference engine (CLAUDE.md)

Run pnpm prettier:format to format code and pnpm format to run linting with auto-fix across all packages

Files:

  • packages/core/src/agent/agent-legacy.ts
  • packages/core/src/workflows/workflow.ts
  • packages/core/src/loop/network/index.ts
  • packages/core/src/types/dynamic-argument.ts
  • packages/core/src/agent/agent.ts
  • packages/core/src/mastra/idgenerator.test.ts
  • packages/core/src/mastra/index.ts
  • packages/core/src/agent/message-list/index.ts
  • packages/core/src/loop/loop.ts
  • packages/core/src/workflows/workflow.test.ts
  • packages/core/src/memory/memory.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

packages/**/*.{ts,tsx}: All packages must use TypeScript with strict type checking enabled
Use telemetry decorators for observability across components

Files:

  • packages/core/src/agent/agent-legacy.ts
  • packages/core/src/workflows/workflow.ts
  • packages/core/src/loop/network/index.ts
  • packages/core/src/types/dynamic-argument.ts
  • packages/core/src/agent/agent.ts
  • packages/core/src/mastra/idgenerator.test.ts
  • packages/core/src/mastra/index.ts
  • packages/core/src/agent/message-list/index.ts
  • packages/core/src/loop/loop.ts
  • packages/core/src/workflows/workflow.test.ts
  • packages/core/src/memory/memory.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{test,spec}.{ts,tsx}: Use Vitest for testing framework in test files
Co-locate test files with source code using naming patterns like *.test.ts or *.spec.ts

Files:

  • packages/core/src/mastra/idgenerator.test.ts
  • packages/core/src/workflows/workflow.test.ts
.changeset/*.md

⚙️ CodeRabbit configuration file

.changeset/*.md: Changeset files are really important for keeping track of changes in the project. They'll be used to generate release notes and inform users about updates.

Review the changeset file according to these guidelines:

  • The target audience are developers
  • Write short, direct sentences that anyone can understand. Avoid commit messages, technical jargon, and acronyms. Use action-oriented verbs (Added, Fixed, Improved, Deprecated, Removed)
  • Avoid generic phrases like "Update code", "Miscellaneous improvements", or "Bug fixes"
  • Highlight outcomes! What does change for the end user? Do not focus on internal implementation details
  • Add context like links to issues or PRs when relevant
  • If the change is a breaking change or is adding a new feature, ensure that a code example is provided. This code example should show the public API usage (the before and after). Do not show code examples of internal implementation details.
  • Keep the formatting easy-to-read and scannable. If necessary, use bullet points or multiple paragraphs (Use bold text as the heading for these sections, do not use markdown headings).
  • For larger, more substantial changes, also answer the "Why" behind the changes
  • Each changeset file contains a YAML frontmatter at the top. It will be one or more package names followed by a colon and the type of change (patch, minor, major). Do not modify this frontmatter. Check that the description inside the changeset file only applies to the packages listed in the frontmatter. Do not allow descriptions that mention changes to packages not listed in the frontmatter. In these cases, the user must create a separate changeset file for those packages.

Files:

  • .changeset/add-context-to-id-generator.md
🧠 Learnings (6)
📚 Learning: 2025-11-24T16:42:04.244Z
Learnt from: CR
Repo: mastra-ai/mastra PR: 0
File: packages/codemod/AGENTS.md:0-0
Timestamp: 2025-11-24T16:42:04.244Z
Learning: Applies to packages/codemod/src/codemods/v1/**/*.ts : Use `context.hasChanges = true` flag and `context.messages.push()` to track and report what transformations were made in the codemod

Applied to files:

  • packages/core/src/types/dynamic-argument.ts
  • packages/core/src/mastra/idgenerator.test.ts
  • packages/core/src/mastra/index.ts
  • packages/core/src/memory/memory.ts
📚 Learning: 2025-11-24T16:42:04.244Z
Learnt from: CR
Repo: mastra-ai/mastra PR: 0
File: packages/codemod/AGENTS.md:0-0
Timestamp: 2025-11-24T16:42:04.244Z
Learning: Applies to packages/codemod/src/test/__fixtures__/**/*.ts : Create test fixtures by copying examples DIRECTLY from migration guides in `docs/src/content/en/guides/migrations/upgrade-to-v1/` without hallucinating or inventing changes

Applied to files:

  • packages/core/src/mastra/idgenerator.test.ts
  • packages/core/src/workflows/workflow.test.ts
📚 Learning: 2025-11-24T16:42:04.244Z
Learnt from: CR
Repo: mastra-ai/mastra PR: 0
File: packages/codemod/AGENTS.md:0-0
Timestamp: 2025-11-24T16:42:04.244Z
Learning: Applies to packages/codemod/src/test/__fixtures__/**/*.ts : In output fixtures, ensure all NEGATIVE test cases remain EXACTLY IDENTICAL to their input fixture counterparts to verify the codemod only transforms intended patterns

Applied to files:

  • packages/core/src/mastra/idgenerator.test.ts
  • packages/core/src/workflows/workflow.test.ts
📚 Learning: 2025-11-24T16:42:04.244Z
Learnt from: CR
Repo: mastra-ai/mastra PR: 0
File: packages/codemod/AGENTS.md:0-0
Timestamp: 2025-11-24T16:42:04.244Z
Learning: Applies to packages/codemod/src/test/**/*.test.ts : Include test cases for multiple occurrences of the transformation pattern, aliased imports, type imports, and mixed imports to verify the codemod works consistently

Applied to files:

  • packages/core/src/mastra/idgenerator.test.ts
  • packages/core/src/workflows/workflow.test.ts
📚 Learning: 2025-11-24T16:42:04.244Z
Learnt from: CR
Repo: mastra-ai/mastra PR: 0
File: packages/codemod/AGENTS.md:0-0
Timestamp: 2025-11-24T16:42:04.244Z
Learning: Applies to packages/codemod/src/test/__fixtures__/**/*.ts : In input fixtures, include both POSITIVE test cases (patterns that should transform) and NEGATIVE test cases (unrelated code with similar names/patterns that should NOT transform)

Applied to files:

  • packages/core/src/mastra/idgenerator.test.ts
📚 Learning: 2025-11-24T16:42:04.244Z
Learnt from: CR
Repo: mastra-ai/mastra PR: 0
File: packages/codemod/AGENTS.md:0-0
Timestamp: 2025-11-24T16:42:04.244Z
Learning: Applies to packages/codemod/src/test/**/*.test.ts : Do NOT use `UPDATE_SNAPSHOT` to force tests to pass; instead fix the codemod implementation when tests fail

Applied to files:

  • packages/core/src/workflows/workflow.test.ts
🧬 Code graph analysis (4)
packages/core/src/loop/network/index.ts (3)
packages/core/src/types/dynamic-argument.ts (1)
  • IdGeneratorContext (15-55)
packages/core/src/mastra/index.ts (1)
  • generateId (353-369)
packages/core/src/memory/memory.ts (1)
  • generateId (433-435)
packages/core/src/mastra/idgenerator.test.ts (3)
packages/core/src/memory/mock.ts (1)
  • MockMemory (25-277)
packages/core/src/mastra/index.ts (1)
  • Mastra (258-3095)
packages/core/src/agent/message-list/index.ts (1)
  • MessageList (108-3369)
packages/core/src/mastra/index.ts (1)
packages/core/src/types/dynamic-argument.ts (1)
  • IdGeneratorContext (15-55)
packages/core/src/memory/memory.ts (1)
packages/core/src/types/dynamic-argument.ts (1)
  • IdGeneratorContext (15-55)
🪛 GitHub Check: Lint
packages/core/src/mastra/idgenerator.test.ts

[failure] 958-958:
'mastra' is assigned a value but never used. Allowed unused vars must match /^_/u

packages/core/src/memory/memory.ts

[failure] 20-20:
../types type import should occur before import of ../utils

⏰ 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). (7)
  • GitHub Check: Prebuild
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test (express)
  • GitHub Check: test (hono)
  • GitHub Check: test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (22)
packages/core/src/types/dynamic-argument.ts (1)

15-55: IdGeneratorContext shape aligns well with intended usage

The unioned idType plus optional source, entityId, threadId, resourceId, role, and stepType cover the key contexts you’re threading through (agents, workflows, memory) while staying forwards‑compatible via optional fields. No changes needed here from a typing/API‑design perspective.

packages/core/src/loop/loop.ts (1)

50-57: Context-aware runId generation is correctly wired and backward compatible

The new runIdToUse logic preserves the previous behavior (explicit runId wins; otherwise fall back to a random UUID) while preferentially using the injected idGenerator with a well-populated context (idType: 'run', source: 'agent', entityId, threadId, resourceId). This matches the new IdGeneratorContext contract and should enable deterministic run IDs without breaking existing callers.

packages/core/src/agent/agent-legacy.ts (1)

706-715: Legacy runId generation now correctly leverages Mastra.generateId with context

This change cleanly layers the new context‑aware ID generation into the legacy path:

  • Precedence is sensible: args.runId (if provided) → mastra.generateId({ idType: 'run', source: 'agent', entityId, threadId, resourceId })randomUUID().
  • The context fields you pass match IdGeneratorContext and give custom generators enough information to produce deterministic, externally shareable run IDs even for legacy calls.

No further changes needed here.

packages/core/src/memory/memory.ts (2)

378-386: Context-aware thread ID generation looks correct

Using this.generateId({ idType: 'thread', source: 'memory', resourceId }) while still honoring an explicit threadId achieves deterministic, externally-shareable thread IDs without breaking existing callers.


428-435: generateId(context?) preserves compatibility while adding context

The new generateId(context?: IdGeneratorContext) cleanly forwards context to Mastra’s generator and falls back to crypto.randomUUID(), so existing no-arg callers continue to work while context-aware generators can opt in.

packages/core/src/workflows/workflow.ts (1)

547-558: Contextual step and run ID generation is consistent and backward compatible

sleep/sleepUntil, mapping steps, and run creation now all use this.#mastra?.generateId({ idType: 'step' | 'run', source: 'workflow', entityId: this.id, ... }) with a randomUUID() fallback and explicit-ID override. This matches the new IdGeneratorContext contract and should enable deterministic IDs without regressing existing workflows.

Also applies to: 577-587, 652-655, 694-697, 1024-1032

packages/core/src/agent/agent.ts (3)

1698-1727: Sub-agent thread/resource ID generation correctly uses context

Using context?.mastra?.generateId({ idType: 'thread', source: 'agent', entityId: agentName, resourceId }) and a separate idType: 'generic' call for subAgentResourceId, with fallbacks to inputData or slugified/random IDs, cleanly integrates sub-agents into the new context-aware ID scheme while preserving existing behavior when no generator is configured.


2502-2511: Agent runId now participates in context-aware ID generation

Deriving runId from options.runId || this.#mastra?.generateId({ idType: 'run', source: 'agent', entityId: this.id, threadId: threadFromArgs?.id, resourceId }) || randomUUID() aligns agent runs with the global ID strategy and still respects a caller-supplied runId and non-Mastra usage.


2797-2827: Network loop IDs and generator wiring match the new API

The network method now:

  • Derives threadId/resourceId from options.memory.
  • Builds runId via this.#mastra?.generateId({ idType: 'run', source: 'agent', entityId: this.id, threadId, resourceId }) || randomUUID().
  • Passes generateId: context => this.#mastra?.generateId(context) || randomUUID() plus threadId and resourceId into networkLoop.

This is consistent with NetworkIdGenerator and ensures networked interactions benefit from contextual, deterministic IDs where configured.

packages/core/src/mastra/index.ts (1)

333-369: Context-aware ID generation is well implemented.

The optional context parameter maintains backward compatibility while enabling deterministic ID generation. Existing idGenerator implementations without parameters will continue to work since the context argument is simply ignored when not used.

packages/core/src/mastra/idgenerator.test.ts (2)

728-728: Good alignment with context-aware ID generation.

Using agentMemory.generateId() ensures the test validates that the custom ID generator is properly wired through the memory instance.


801-873: Comprehensive test suite for context-aware ID generation.

This test suite provides excellent coverage of the feature request #8131, validating context propagation for various ID types (thread, message, run) and sources (agent, workflow, memory). The tests demonstrate the deterministic ID generation use case well.

The as any casts for contextAwareIdGenerator are acceptable given the new signature (context?: IdGeneratorContext) => string is compatible at runtime.

packages/core/src/loop/network/index.ts (6)

18-21: Well-defined type alias for context-aware ID generation.

The NetworkIdGenerator type properly encapsulates the new signature, maintaining consistency with Mastra.generateId.


162-168: Proper context for user message ID generation.

The context correctly identifies this as a message from an agent with the user role, including thread and resource context for deterministic generation.


297-301: Correct context for routing agent step IDs.

The step ID generation properly identifies the context as an agent routing step, enabling deterministic ID generation based on the step type.


617-622: Agent execution step IDs include entity context.

Good inclusion of entityId to identify which agent is executing, enabling deterministic IDs that can be traced to specific agents.


795-800: Workflow execution correctly identifies source.

The source: 'workflow' and entityId: wf.id correctly distinguish workflow-generated IDs from agent-generated ones, supporting the deterministic ID use case.


982-987: Tool execution context properly structured.

The tool call ID correctly uses source: 'agent' since tools are invoked from agents, with entityId identifying the specific tool for traceability.

packages/core/src/agent/message-list/index.ts (4)

17-17: LGTM - Import and property type changes support the new context-aware ID generation.

The IdGeneratorContext import and the updated generateMessageId property type correctly establish the foundation for context-aware ID generation while maintaining backward compatibility through the optional parameter.

Also applies to: 129-129


150-154: Well-designed backward-compatible constructor signature.

The union type ((context?: IdGeneratorContext) => string) | AIV4Type.IdGenerator correctly preserves backward compatibility. Existing idGenerator implementations that take no parameters will continue to work, as they can simply ignore the context object passed to them.


1601-1612: Core implementation correctly provides context for deterministic ID generation.

The newMessageId method properly constructs the context object with relevant fields (idType, source, threadId, resourceId, role) that enable users to generate deterministic IDs. The hardcoded source: 'memory' is appropriate since MessageList specifically handles message storage and memory operations.


1636-1636: Role context is consistently propagated across all ID generation call sites.

The changes correctly pass the message role to newMessageId at all call sites:

  • hydrateMastraDBMessageFields: uses message.role directly
  • aiV4UIMessageToMastraDBMessage: extracts via getRole() for proper normalization
  • aiV4CoreMessageToMastraDBMessage: uses coreMessage.role directly

This enables users to generate role-aware deterministic IDs as intended by the PR objectives.

Also applies to: 1694-1697, 1705-1705

Comment on lines +958 to +962
const mastra = new Mastra({
idGenerator: contextAwareIdGenerator as any,
logger: false,
workflows: { 'context-test-workflow': workflow },
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Rename unused variable to satisfy lint rules.

The mastra variable is assigned but never used in this test. Per your linting rules, unused variables must be prefixed with _.

-      const mastra = new Mastra({
+      const _mastra = new Mastra({
         idGenerator: contextAwareIdGenerator as any,
         logger: false,
         workflows: { 'context-test-workflow': workflow },
       });
📝 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
const mastra = new Mastra({
idGenerator: contextAwareIdGenerator as any,
logger: false,
workflows: { 'context-test-workflow': workflow },
});
const _mastra = new Mastra({
idGenerator: contextAwareIdGenerator as any,
logger: false,
workflows: { 'context-test-workflow': workflow },
});
🧰 Tools
🪛 GitHub Check: Lint

[failure] 958-958:
'mastra' is assigned a value but never used. Allowed unused vars must match /^_/u

🤖 Prompt for AI Agents
In packages/core/src/mastra/idgenerator.test.ts around lines 958 to 962, the
local variable "mastra" is assigned but never used; rename it to "_mastra" to
satisfy the lint rule for unused variables (prefix unused variables with an
underscore). Update the variable name in this assignment only, leaving other
code unchanged.

Comment on lines 19 to +20
import { deepMerge } from '../utils';
import type { IdGeneratorContext } from '../types';
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix import ordering to satisfy lint rule

Static analysis expects the ../types type-only import to appear before the value import from ../utils. Swap these two lines to fix the lint failure:

-import { deepMerge } from '../utils';
-import type { IdGeneratorContext } from '../types';
+import type { IdGeneratorContext } from '../types';
+import { deepMerge } from '../utils';
📝 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
import { deepMerge } from '../utils';
import type { IdGeneratorContext } from '../types';
import type { IdGeneratorContext } from '../types';
import { deepMerge } from '../utils';
🧰 Tools
🪛 GitHub Check: Lint

[failure] 20-20:
../types type import should occur before import of ../utils

🤖 Prompt for AI Agents
In packages/core/src/memory/memory.ts around lines 19 to 20, the import order is
causing a lint failure because the type-only import from '../types' must appear
before the value import from '../utils'; swap the two import lines so "import
type { IdGeneratorContext } from '../types';" comes before "import { deepMerge }
from '../utils';" to satisfy the rule.

Comment on lines +57 to +77
/**
* Custom ID generator function for creating unique identifiers.
* Receives optional context about what type of ID is being generated
* and where it's being requested from.
*
* @example
* ```typescript
* const mastra = new Mastra({
* idGenerator: (context) => {
* if (context?.idType === 'message' && context?.threadId) {
* return `msg-${context.threadId}-${Date.now()}`;
* }
* if (context?.idType === 'run' && context?.entityId) {
* return `run-${context.entityId}-${Date.now()}`;
* }
* return crypto.randomUUID();
* }
* });
* ```
*/
export type MastraIdGenerator = (context?: IdGeneratorContext) => NonEmpty<string>;
Copy link
Contributor

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:

cat -n packages/core/src/types/dynamic-argument.ts

Repository: mastra-ai/mastra

Length of output: 2707


🏁 Script executed:

rg -A 10 -B 5 "IdGeneratorContext" packages/core/src/types/

Repository: mastra-ai/mastra

Length of output: 1720


🏁 Script executed:

rg "deterministic" packages/core/src/types/dynamic-argument.ts

Repository: mastra-ai/mastra

Length of output: 131


🏁 Script executed:

cd packages/core && ls -la | grep -E "(package\.json|pnpm-lock)" && head -20 package.json

Repository: mastra-ai/mastra

Length of output: 538


🏁 Script executed:

rg "deterministic|context-aware" packages/core/src/types/ -A 2 -B 2

Repository: mastra-ai/mastra

Length of output: 458


Clarify documentation to match implementation: deterministic IDs require pure context-based generation

The JSDoc comment at line 12 promises "deterministic IDs based on the context," but the example contradicts this by using Date.now() and crypto.randomUUID(). Deterministic generation requires the same context to always produce the same ID. Revise either:

  • Rephrase to "context-aware IDs" to accurately reflect the example, or
  • Show a deterministic example: msg-${context.threadId}-${context.entityId} without time or randomness components.

After changes, run pnpm typecheck and pnpm prettier:format to validate types and formatting per the repository guidelines.

🤖 Prompt for AI Agents
In packages/core/src/types/dynamic-argument.ts around lines 57 to 77, the JSDoc
claims "deterministic IDs based on the context" but the example uses Date.now()
and crypto.randomUUID(), which is not deterministic; update the doc so the
wording matches the implementation by either (A) changing "deterministic IDs" to
"context-aware IDs" and keep the current (non-deterministic) example, or (B)
provide a fully deterministic example (e.g., compose ID solely from context
fields like `msg-${context.threadId}-${context.entityId}`) and remove
time/randomness; after editing, run pnpm typecheck and pnpm prettier:format to
validate types and formatting.

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.

[FEATURE] add more context to idGenerator params to allow users to generate more deterministic ids

2 participants