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

Compare commits

...

40 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
433 changed files with 19412 additions and 5104 deletions

Some files were not shown because too many files have changed in this diff Show more