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

23,235 commits

Author SHA1 Message Date
mastra-platform[bot]
566e2081d3
Fix transcript gap ordering when answered suspension prompts are removed (#30163) 2026-11-11 21:03:05 -08:00
Abhi Aiyer
c1fb13f325
fix(agent-controller): resume reopened approvals with request context (#30159)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 20:57:46 -08:00
mastra-platform[bot]
a2998f4084
test(storage): verify rollback reporters settle before client release (#30160)
## Summary
- Make PostgreSQL pooled/pinned and DSQL pooled async rollback reporter
tests assert that reporting finishes before transaction settlement and
pooled release.
- Use plain async reporters to catch unhandled promise rejections rather
than `vi.fn` wrappers.

## Test plan
- PostgreSQL transaction tests: 18 passed; DSQL transaction tests: 9
passed.
- Both package TypeScript checks, targeted Oxlint, Prettier and `git
diff --check` passed.
- Confirmed the changed tests fail against the parent of merged #30157:
PG 2 failures, DSQL 1 failure (plus unhandled rejections).

Follow-up to #30157; test-only correction to the regression coverage for
its already-merged implementation.

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

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

ELI5: The change makes the database tests check the right order of
events. A rollback error must be reported before the database connection
is released and before the transaction ends. The tests now fail if that
order is wrong.

## Summary

This change updates two test files for the rollback reporter behavior in
PostgreSQL and DSQL transaction clients. It changes test code only. No
production code changes.

Diff stats: 2 files changed, 33 insertions, 9 deletions.

### `stores/dsql/src/storage/client.tx-serialize.test.ts`

- The reporter is now a plain async function, not a `vi.fn` wrapper.
- The reporter stores the error it receives.
- The reporter waits 10 ms, records `reported`, and then throws `async
logger failed`.
- The test mocks `client.release` to record `released`.
- The test records `tx-settled` after the transaction call rejects with
the original error.
- Assertions:
  - The reporter received `rollbackError`.
  - `client.release` was called with `true`.
  - The event order is `['reported', 'released', 'tx-settled']`.

### `stores/pg/src/storage/client.tx-serialize.test.ts`

- The same reporter change applies to the shared async rollback reporter
test.
- For the pooled case (`kind === 'pool'`):
  - `client.release` records `released`.
  - Assertions check that `client.release` was called with `true`.
  - The event order is `['reported', 'released', 'tx-settled']`.
- For the pinned case:
  - No release tracking is added.
  - Assertions check that `adapter.shouldDestroyClient` is `true`.
  - The event order is `['reported', 'tx-settled']`.

## Not verified

- The PR reports test runs, type checks, lint, and format checks. I did
not run them. Their results are not available from this review.
- The PR reports that the changed tests fail against the parent of the
referenced prior change. I did not verify this. It is not available from
this review.

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

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 20:50:47 -08:00
mastra-platform[bot]
6f7eb696e9
fix(core): keep sub-agent snapshots out of the durable replay cache (#29151)
> Opened by @wardpeet

Fixes #29035 (follow-up to #24160).

## Summary
When a `DurableAgent` or `EventedAgent` delegates to a sub-agent, the
sub-agent's chunks are forwarded on the run stream inside `tool-output`
/ `workflow-step-output`. Each nested `step-start`, `step-finish` and
`finish` carries the sub-agent's full prompt, message history and
cumulative steps. `CachingPubSub` stored them as-is in the run's 24h
replay cache, so about 80 KB of real content grew to about 2.2 MB per
run.

Main already slims these chunks for the plain `Agent` publisher
(#29965). The durable engines were left out because their callers read
their own run back from the same topic, so slimming the published event
would change what the caller sees on `fullStream`.

## Changes
- `events/topics.ts`: new `toCachedLogFrame(topic, event)`, next to
`cachedLogTtlMs`. For `chunk` events on agent stream topics it returns a
copy with `slimNestedAgentChunks` applied. Everything else is returned
by reference.
- `events/caching-pubsub.ts`: `publish` stores `toCachedLogFrame(topic,
fullEvent)` in the cache log. Live subscribers still receive `fullEvent`
unchanged.
- So a durable or evented caller streaming its own run gets the same
full nested chunks as a plain `Agent` caller, and only the cached copy
is slimmed. Top-level chunks (#28674) and data written by tools are
cached unchanged. The sub-agent's usage, tool identity and `producedAt`
are kept.
- `agent-stream-log.scenario.test.ts`: "keeps a delegated agent's prompt
off the log" now runs as `it` on every engine. On main it is `it.fails`
on the durable engines.
- New tests:
`agent/durable/__tests__/delegated-chunk-snapshots-durable.test.ts`.
They check that live subscribers get the chunk as published and the
cache gets the slimmed copy, and that a real delegation's caller still
sees nested `messages`.
- Changeset: `@mastra/core` patch.

**Known limit:** a cross-process live transport (for example Redis
pub/sub) still carries the full delegated chunk while the run is live.
This PR fixes the persisted growth reported in #29035, not live message
size.

## Verification (head `31247785`)
| Check | Result | Tests |
|---|---|---|
| `parity-sub-agent-delegation.scenario.test.ts` (raised in review) | ✅
Passed | durable + evented |
| `agent-stream-log.scenario.test.ts` | ✅ Passed | 40 passed |
| New tests | ✅ Passed | 5 passed (×2 storage projects) |
| `src/events/**` + the above | ✅ Passed | 24 files, 392 passed |
| `src/agent/streams`, `src/stream`, `background-tasks/manager`, durable
`running-snapshot-request-echo`, `run-local-topics-not-cached`,
`resumable-streams`, `cache-ttl`, `durable-agent-delegation`,
`durable-shared-bus`, `parity` | ✅ Passed | 40 files, 667 passed |
| `tsc --noEmit` (no errors in `src/events` or new test), oxlint,
prettier | ✅ Clean | |

**Regression proof:** with only the `toCachedLogFrame` call reverted in
`caching-pubsub.ts`, 3 of the 5 new tests fail, and the scenario test
fails on the durable and evented engines. The negative controls still
pass.

**Not run:** a full `packages/core` suite and the reporter's repro repo.

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

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

**ELI5:** When an AI helper agent works for another agent, it sends back
a lot of extra data. This change stores a smaller copy of that data in
the replay log, so the log uses less space. Live viewers still get the
full data.

## Summary

This change reduces the size of delegated sub-agent chunks in the
durable run-stream replay cache. It does not change the events that live
subscribers receive.

## Changes by file

- `packages/core/src/events/topics.ts`: Adds the exported function
`toCachedLogFrame<E extends { type: string; data?: unknown }>(topic:
string, event: E): E`. For `chunk` events on `agent.stream.` topics, it
calls `slimNestedAgentChunks` on `event.data`. If the data does not
change, it returns the original event. If the data changes, it returns a
shallow copy with the new data. All other events and topics pass through
unchanged.
- `packages/core/src/events/caching-pubsub.ts`: The cached publish path
passes `toCachedLogFrame(topic, fullEvent)` to `listPushIndexed`. It no
longer stores `fullEvent` directly. The indexed append and cache TTL are
unchanged. Cache errors are still logged. Live delivery still occurs
without an index.
-
`packages/core/src/agent/durable/__tests__/delegated-chunk-snapshots-durable.test.ts`
(+277): Adds regression tests. Cached history must omit nested snapshot
fields (`request`, `inputMessages`, `messages`, `output.steps`,
`metadata.request`). Cached history must keep usage, tool identity, and
other fields. Live events, top-level agent chunks, and tool-authored
output must stay unchanged. A delegation test checks that nested
step-start and finish chunks appear in history without snapshot fields,
and that nested finish usage remains.
-
`packages/core/src/loop/test-utils/aimock/scenarios/agent-stream-log.scenario.test.ts`
(+31/−39): The delegated-agent prompt-logging scenario no longer runs as
an expected failure for durable engine variants. It now runs as a normal
test for every engine. It checks that the delegated response appears in
the parent run log and that the writer instructions marker does not.
- `.changeset/slim-delegated-durable-chunks.md` (+5): Adds a patch
changeset for `@mastra/core`. It states that cached delegated chunks
omit the sub-agent prompt, message history, and steps. It also states
that callers streaming their own run still receive full chunks, and that
sub-agent usage is still reported.

Totals: 5 files changed, +334 and −41 lines. No exported declarations
change, except the new `toCachedLogFrame` export in `topics.ts`.

## Relation to linked issue `#29035`

- The issue asks that chunks sent to the durable run stream and stored
in the replay cache be sanitized. It also asks that nested delegated
`tool-output` chunks be included.
- This change sanitizes only the cached copy. Events published to the
durable run stream remain unsanitized.
- Therefore, this change addresses replay-cache growth only. It does not
meet the issue's requirement for the run-stream path.
- The optional list-size cap on `MastraServerCache` or
`RedisServerCache` is not part of this change.

## Test status

- The author reports passing results at head `973766a4`: 5 tests in
`delegated-chunk-snapshots-durable.test.ts` and 40 tests in
`agent-stream-log.scenario.test.ts`.
- The author reports that the full `packages/core` suite was not run.
- The external reproduction repository was not run.
- These results were not verified in this review.

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

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 20:31:18 -08:00
Damien Schneider
6937417bd4
fix(factory): ⌘K reads the clicked card by its id, and three search fixes (#30154)
**─────── TLDR ───────**
> ⌘K now reads the card you click by its id before starting it, and
three smaller search bugs are fixed.

Copilot reviewed #30081 after it merged and left six findings. Four are
about the palette and are fixed here, one commit each. The CLI one is
#30153, and the sixth was declined on the PR.

### Behavior changed

clicking a listed card the search would no longer return, because a more
recently updated card took its place among the 20
&nbsp;&nbsp;├─ **was** — "This card no longer exists", nothing started
&nbsp;&nbsp;└─ **now** — the card is read by its id and its session
starts

Retry after the board cards failed to load, when the intake has no
candidate
&nbsp;&nbsp;├─ **was** — the failure notice stayed up for good
&nbsp;&nbsp;└─ **now** — only the reads that failed are asked again, and
the notice goes

typing a source label such as "review" with more than 20 intake items
&nbsp;&nbsp;├─ **was** — the item matching by its label could miss the
20 looked up, and its row never showed
&nbsp;&nbsp;└─ **now** — the 20 are ranked on the same text the rows are
filtered on

typing the number of a card that has no key and no GitHub source
&nbsp;&nbsp;├─ **was** — the server found the card, the palette then hid
its row
&nbsp;&nbsp;└─ **now** — the row shows

the list route asked for `?workItemId=<id>`
&nbsp;&nbsp;└─ **new** — the cards with those ids and no other; an id no
card has is left out, and a board cursor (`since`) sent with it is
ignored, as on the other narrowed lists

### Shape changed

| | | |
|---|---|---|
| **+** | `workItemId` on `workItemListQuerySchema` | repeatable, 100
ids at most, refused with any other filter |
| **+** | `cardsWithIds` | beside `cardsFiledFrom` in
`work-item-selection.ts` |
| **~** | `useBoardRuns({ refetchItems })` | now given the id of the
card clicked |
| **~** | `useGlobalSearchWorkItems.refetch` | one card by its id, no
longer both lists |
| **+** | `candidateSearchValue` | one home for the text a candidate row
is filtered and ranked on |
| **+** | `searchedNumber` | the number the server's search reads,
mirrored for the row |

what callers can now ask
&nbsp;&nbsp;&nbsp;&nbsp;`GET …/work-items?workItemId=<id>` · `mastra api
factory work-item list` can pass it once #30153 is in

### Decisions

- **a filter on the list route, not `GET /work-items/:id`** — a server
older than the filter ignores it and sends the whole board, which still
holds the card; a new route would answer 404 there and read as "deleted"
- **not the listed copy as a fallback** — starting a run on an id the
server no longer has creates the card again (`prepareRunStart`), so a
deleted card would come back; the fresh read decides, and a deleted card
still gets the toast
- **the board page keeps refetching its list on a click** — it moves to
the same read with the board page's own PR

### Gain

A click in ⌘K asks for one card instead of two lists.

### Watch

> [!WARNING]
> <mark>Until a server with `workItemId` is deployed, each click on a
card in ⌘K downloads the whole board.</mark> It still finds the card
there, so the click works, only slower.

on merge: `main` with #30099 is merged in and the CLI route metadata
regenerated. #30097 regenerates the same file, so whichever merges
second runs `pnpm --filter @mastra/factory
generate:api-cli-route-metadata` again.

### Not verified

- [ ] against a deployed Factory or Postgres — the route tests run on
the in-memory harness, the palette tests against stubbed routes
- [ ] in a real browser — the palette tests run in jsdom

---

> ██████████████████ **tests** `+273 −5` — 65% of the additions
> ███████ **source** `+110 −25`
> █ **generated** `+18 −2`
> █ **changeset** `+16`
> █ **docs** `+2 −2`

---------

Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
2026-11-11 20:30:15 -08:00
dane-ai-mastra[bot]
055a8c3b82 chore: version packages 2026-11-12 04:17:40 +00:00
mastra-platform[bot]
a0cd52cdc1
refactor(core): extract shared observe() fullStream detach wrapper (#30111)
> Opened by @wardpeet

## Result: Approved — c2acf6499e

The three duplicated `fullStream` detach wrappers are now one shared
`detachFullStreamOnEnd` helper. The extraction is complete,
behavior-preserving, and covered by the helper's own tests plus the
COR-1525 end-to-end regression.

### Checks on this head

| Check | Result | Tests |
| --- | --- | --- |
| Diff against base `9efd1ea8` | ✅ Passed | 1 focused commit, 8 files,
+186/−90 |
| Only one copy of the wrapper remains | ✅ Passed | helper only;
`agent.ts:12426`, `durable-agent.ts:5942`,
`create-inngest-agent.ts:2303` all call the helper |
| Removed inline wrapper matches helper body | ✅ Passed |
byte-identical, modulo `this` typing |
| `@mastra/core` typecheck (`pnpm check`) | ✅ Passed | 0 errors |
| `@mastra/inngest` typecheck (`tsc --noEmit -p tsconfig.json`) | ✅
Passed | 0 errors |
| Lint (`oxlint --type-aware`, changed files) | ✅ Passed | 0 warnings, 0
errors |
| New unit test `observe-full-stream.test.ts` | ✅ Passed | 4 tests × 2
vitest projects |
| `@mastra/core` durable suite (`src/agent/durable/`) | ✅ Passed | 3989
passed, 4 skipped; crash-recovery 20/20 with a raised heap (see note) |
| Inngest observe e2e (COR-1525 regression) | ✅ Passed | replays a
finished run through `observe(runId).fullStream` |
| Inngest unit `create-inngest-agent.test.ts` | ✅ Passed | 117 passed |

Note: the heavy `durable-agent-crash-recovery.test.ts` aborts one worker
on the sandbox's default Node heap limit; the same abort reproduces at
the base commit, and the file passes 20/20 with
`NODE_OPTIONS=--max-old-space-size=6144`. Environmental, not caused by
this change.

### Follow-ups

- `packages/core/src/agent/durable/observe-full-stream.test.ts`: the
end-path test counts `detach` calls but does not assert it is not called
before the source ends; an earlier assertion would tighten the contract.
- `packages/core/src/agent/durable/observe-full-stream.test.ts`: the
structural `FakeObserverOutput` stands in for the real
`MastraModelOutput`; real-path coverage is the COR-1525 Inngest e2e, so
this is proportionate.

### Adversarial check

Strongest case for request changes: the extraction silently altered
behavior (the wrapper's `this` receiver or the `ReadableStream`
constructor). It fails: the removed inline code is byte-identical to the
helper body, both instantiate the global `ReadableStream` (the
`node:stream/web` import is type-only), and the destructurable-proxy
path is exercised green by the COR-1525 e2e on this head.

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

## ELI5

When an observer watches an agent's output stream, it must stop watching
at the right time. This PR moves that stop logic into one shared helper.
Both the core agent and the durable agent now use it. The Inngest
package keeps its own copy, because it can run with older core versions
that lack the helper.

## Overview

The PR extracts the `fullStream` detach wrapper from `Agent.observe()`
and `DurableAgent.observe()` into a shared helper,
`detachFullStreamOnEnd`, in `@mastra/core`. The helper is exported from
the durable-agent module. The `@mastra/inngest` package keeps its
wrapper inline, with a comment that explains why.

Diff scope: 7 files changed, 196 lines added, 60 lines removed.

## Changes

- **`packages/core/src/agent/durable/observe-full-stream.ts`** (+58):
Adds `detachFullStreamOnEnd(output, detach)`. It wraps the output's
inherited `fullStream` getter in a lazy stream. The wrapper calls the
original getter with the output as receiver and forwards chunks. It
calls `detach` when the reader reaches the end, when a read errors, or
when the consumer cancels. Cancellation forwards the cancel reason to
the underlying reader.
- **`packages/core/src/agent/durable/observe-full-stream.test.ts`**
(+109): Adds tests for chunk forwarding and detach on source end. It
also covers read-error propagation, cancellation reason forwarding, and
an inherited getter called through a proxy.
- **`packages/core/src/agent/durable/index.ts`** (+4): Re-exports
`detachFullStreamOnEnd` with a comment about use by integrations outside
core.
- **`packages/core/src/agent/agent.ts`** (+2/-30): `Agent.observe()`
calls the helper. The inline `fullStream` wrapper is removed.
- **`packages/core/src/agent/durable/durable-agent.ts`** (+2/-30):
`DurableAgent.observe()` calls the helper. Its custom `fullStream`
wrapper is removed.
- **`workflows/inngest/src/durable-agent/create-inngest-agent.ts`**
(+5): Adds a comment explaining why the `fullStream` detach logic stays
inline. The declared `@mastra/core` peer range includes versions that do
not export `detachFullStreamOnEnd`. No runtime behavior changes.
- **`.changeset/observe-full-stream-helper-core.md`** (+16): Adds a
patch changeset for `@mastra/core`. It documents the helper and states
that existing `observe()` behavior is unchanged.

## Public API

- Added: `detachFullStreamOnEnd<TOutput>(output:
FullStreamOutput<TOutput>, detach: () => void): void`, exported from the
durable-agent module in `@mastra/core`.
- No other exported declarations change.

## Testing

Results below come from the PR author. This summary did not rerun them.

- Typechecks pass for `@mastra/core` and `@mastra/inngest`.
- Lint passes on changed files.
- Four helper tests pass in each of two Vitest projects.
- The durable suite reports 3,989 passing tests and 4 skipped.
- `create-inngest-agent.test.ts` reports 117 passing tests.
- The crash-recovery test passes 20/20 with
`NODE_OPTIONS=--max-old-space-size=6144`. Under the sandbox's default
heap limit, one worker aborts. The same abort occurs at the base commit.
- The COR-1525 end-to-end regression replays a finished run through
`observe(runId).fullStream`.

## Known gaps

- The helper's end-path test does not assert that `detach` is not called
before the source ends.
- The test's structural `FakeObserverOutput` does not match the real
`MastraModelOutput`.
<!-- 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: NikAiyer <nick.aiyer@gmail.com>
2026-11-11 20:11:53 -08:00
Leo
d7fa57619b
fix(core): keep sub-agents streaming after a durable resume with a request context (#29616)
## Summary

A `DurableAgent` run started with `stream()` stopped streaming its
sub-agents after a resume that passed a `requestContext`. On a warm
resume with a request context, the run's tools are rebuilt, and the
rebuild picked `generate` whenever `closeOnSuspend` was set.
`closeOnSuspend` is also a `stream()` option, and `resumeStream()` (so
`approveToolCall()` too) always sets it, so `agent-<name>` delegation
tools ran the sub-agent through `generate` and its chunks never reached
the stream as `tool-output`.

The fix records the method that started the run on the run registry
entry and rebuilds for that method. The same line in the Inngest durable
agent gets the same change.

The same hunk restores a second outcome: tool calls that a delegated
sub-agent makes on durable and evented runs report `subagent_tool_end`
again. The agent controller emits
`subagent_tool_start`/`subagent_tool_end` only while it reads the
sub-agent's stream (`agent-controller/tools.ts`) and uses
`subagent_tool_end` to set the tracked call's status
(`agent-controller/session.ts`), so while the delegation tool was built
for `generate` those rows never got a status or result. That is why the
`it.fails` pins on the durable and evented `delegated` cases in
`controller-tool-errors.scenario.test.ts` are removed; the changeset
says so too.

```diff
 // prepareForDurableExecution
 registryEntry = {
   tools,
   requestTools: tools,
+  methodType,            // 'stream' or 'generate', from the call that started the run
   ...
 }

 // warm resume with requestContext / delegation / hooks
 getToolsForExecution({
   ...
-  methodType: resolvedOptions.closeOnSuspend ? 'generate' : 'stream',
+  methodType: entry.methodType ?? 'stream',
 })
```

## Evidence

New shared aimock scenario
`packages/core/src/loop/test-utils/aimock/scenarios/subagent-resume-streaming.scenario.test.ts`.
A lead agent with a suspending `ask_user` tool and a sub-agent `helper`
(with its own tool) talk to a real OpenAI provider pointed at the aimock
HTTP server. The lead suspends, is resumed, then delegates to `helper`.
Each case checks that `helper`'s `tool-call`, `tool-result` and
`text-delta` chunks arrive on the resumed stream as `tool-output`, and
that every `helper` model request was a streaming request. Cases:

- `resumeStream()` with a `requestContext` (the #29436 path)
- `resumeStream()` without one (control)
- durable only: `resume()` with `requestContext` and `closeOnSuspend:
true`, as in the issue's repro
- durable only: a `generate()` run resumed with `resumeGenerate()` still
runs the sub-agent through `generate` (non-streaming requests)

- **Before (origin/main):** normal, durable, evented: `Tests 4 failed |
6 passed | 4 skipped (16)`. The 4 failures are the request-context cases
on durable and evented: `expected [] to deeply equal ArrayContaining
["tool-call","tool-result","text-delta"]`.
  **After:** `Tests  10 passed | 4 skipped (16)`.
- **Inngest engine** (real dev server,
`AIMOCK_SCENARIOS='subagent-resume-streaming' pnpm --dir
workflows/inngest test:aimock`): with the Inngest line reverted, `2
failed | 2 passed (4)`, the same two request-context cases. With the
fix: `4 passed (4)`.
- Neighbouring tests, unchanged and green (`Tests 130 passed | 3
expected fail | 11 skipped`): `durable-agent-resume-request-context`,
`durable-agent-request-context`, `durable-agent-delegation`,
`durable-agent-generate`, and the `request-context-resume`,
`supervisor-suspension`, `supervisor-delegation-generate`,
`parity-sub-agent-suspend`, `parity-sub-agent-delegation`,
`subagent-auto-resume`, `resume-stream` scenarios.
- `tsc --noEmit -p tsconfig.build.json` for core, `tsc --noEmit` for
`@mastra/inngest`, oxlint on the touched files and prettier on the
changed files all pass.
- `controller-tool-errors.scenario.test.ts` pinned its durable and
evented `delegated` cases with `it.fails` because those delegations
emitted no `subagent_tool_end`. This fix makes them pass (CI reported
`Expect test to fail` on all 14), so the marker is removed: `Tests 84
passed (84)`.

Not covered: a cold resume (registry entry gone, rebuilt from storage)
still calls `prepare()` with the default `stream`, so a `generate()` run
resumed in another process gets stream-built tools. That was already the
case before this PR, and the tools still work under `resumeGenerate()`,
so it is left as-is.

## Merge Danger

**Door:** two-way. A one-field registry change plus two one-line
call-site changes, all easy to revert.

**Blast radius:** warm `DurableAgent`, `EventedAgent` and Inngest
durable resumes that pass a `requestContext`, `delegation` or `hooks`.
One behavior change to know about: `resumeGenerate()` on a run started
with `stream()` now rebuilds its tools for `stream`, matching the first
segment and the no-context resume. Other open PRs touch
`durable-agent.ts` / `types.ts` (#28283, #28530, #29036, #29282,
#27522), but none changes these lines.

Closes #29436

## Council review

Rounds: 2

| Seat | Round 1 | Round 2 |
| --- | --- | --- |
| Claude Opus 5.5 | not run | 9/10 (Correctness 9, Tests 9, Scope 10,
Code quality 9) |
| GPT-6.1 Sol | 9/10 (Correctness 9, Tests 9, Scope 10, Code quality 9)
| 9/10 (Correctness 9, Tests 9, Scope 10, Code quality 9) |
| Grok 4.7 | empty seat | empty seat |

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
When a paused run continues, it should keep working the way it started.
This change makes sub-agents keep sending progress updates after a
streamed run resumes. This holds even when the resume includes a
`requestContext` or `closeOnSuspend`.

## Summary
- Store the original method type (`stream` or `generate`) on each run
registry entry when the run is prepared.
- On warm resume, rebuild request-scoped tools with the stored method
type. If no method type is stored, use `stream`. Stop inferring the
method from `closeOnSuspend`.
- Apply the same change to the Inngest durable agent resume path.
- Add an AIMock scenario test for sub-agent streaming after resume, with
and without a request context. The test also checks that resumed
`generate()` runs make non-streaming helper requests.
- Remove the `it.fails` markers from the delegated-tool tests for the
durable and evented engines. These tests now run as ordinary tests.
- Add patch changesets for `@mastra/core` and `@mastra/inngest`. The
changesets reference issue `#29436`.

Scope:
- Cold resumes, which rebuild the run from storage, are not changed.
They still default to `stream`, including for a run that started with
`generate()`.

Test and CI results: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:23:12 -05:00
Damien Schneider
b9610409ab
perf(factory): send an open board only the cards that changed (#30099)
Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 18:27:47 -08:00
mastra-platform[bot]
b1948fb073
fix(storage): await rollback diagnostics before releasing clients (#30157) 2026-11-11 18:18:44 -08:00
Leo
efc1fe40ba
fix(core): drop supervisor reasoning from delegated sub-agent context (#29620)
## Summary

A supervisor on Claude with extended thinking could not delegate after
its first step in a run. Anthropic rejected every such delegation with
"`thinking` or `redacted_thinking` blocks in the latest assistant
message cannot be modified". Delegation forwards the supervisor's
messages to the sub-agent with tool calls and tool messages removed, but
it kept their reasoning parts. So the sub-agent got the supervisor's
signed thinking with no `tool_use` beside it, and `@ai-sdk/anthropic`
merged the now-adjacent assistant steps into one message.
`stripParentToolParts` in `@mastra/core` now removes reasoning parts
from forwarded assistant messages along with tool calls. It keeps their
text and still drops messages left empty.

```diff
 stripParentToolParts(messages)
   drop tool messages and the OM continuation hint
   for each assistant message
-    remove tool-call parts
+    remove tool-call and reasoning parts   // text stays
     drop the message if nothing is left
```

Why drop all forwarded reasoning, not only the reasoning in messages
that lost a tool call? The narrower rule (the one
`removeWorkingMemoryToolInvocationParts` uses for working-memory calls)
still fails here. Take an earlier turn recalled from memory, `[thinking,
text, tool_use] → tool_result → [thinking, text]`. After stripping it
reaches Anthropic as one merged message, `[text, thinking, text]`, with
signed thinking in the middle. The forwarded context always ends in the
delegation prompt (a user message, never a tool-use continuation), so no
provider needs thinking blocks in it. This is also the workaround the
issue suggests.

## Evidence

New scenario
`packages/core/src/loop/test-utils/aimock/scenarios/delegation-signed-reasoning.scenario.test.ts`
runs on the normal, durable, evented and fs engines. Both agents use the
real `@ai-sdk/anthropic` provider against AIMock's Messages endpoint,
and the assertions read the raw request body the sub-agent sends. No
real Anthropic calls are made. The five cases:

1. Think and call `get_time`, then delegate. The sub-agent request has
no `thinking`/`redacted_thinking` without a `tool_use`, and none of the
supervisor's signatures.
2. Text in the tool step survives; its thinking does not.
3. Two runs on one `MockMemory` thread. The recalled turn's signed
thinking (tool step and final answer) is gone, and its text is kept.
4. OpenAI supervisor with unsigned reasoning in history. `messageFilter`
receives text-only assistant messages.
5. `messageFilter` input carries no reasoning.

- **Before** (origin/main `agent.ts`): `Tests 20 failed (20)`. The
sub-agent body carried the supervisor's step-1 signed thinking and
redacted thinking:
  ```
+ { "data": "redacted-supervisor-step-1", "type": "redacted_thinking" },
+ { "signature": "sig-supervisor-step-1", "thinking": "First I need the
current time.", "type": "thinking" },
  ```
  **After:** `Tests 20 passed (20)`.
- The narrower "drop reasoning only where tool calls were removed"
version fails cases 3 and 4 (8 of 20), which is why the final rule drops
all forwarded reasoning.
- Existing delegation and history tests still pass: `subagent.test.ts`,
`subagent-duplicate-prompt.test.ts`, `src/agent/__tests__/delegation*`,
the `delegation-message-filter`, `delegation-parent-context`,
`supervisor-message-history`, `parity-sub-agent-delegation` and
`supervisor-delegation-generate` scenarios, and
`provider-history-compat.test.ts`: 234 passed, 2 skipped.
- `tsc --noEmit -p tsconfig.build.json` and `oxlint --type-aware` on the
changed files pass.

Not checked: a live Anthropic or Bedrock request (AIMock does not
enforce Anthropic's thinking rule, so the tests assert it directly), and
the Inngest engine.

## Merge Danger

**Door:** two-way. One filter in one private method; reverting it
restores the old forwarded context.

**Blast radius:** context forwarded to every delegated sub-agent, on
every provider. Sub-agents and `messageFilter` no longer see the
supervisor's reasoning parts; its text, user messages and system
messages are unchanged. The `iteration` value passed to delegation hooks
is unchanged: it is still counted on the parent context with reasoning
kept.

Provider-executed tool results (`tool-result` parts inside assistant
messages, such as Anthropic web search) are now stripped by main
(#30134) at the same filter; after merging main, the filter drops tool
calls, tool results and reasoning.

Closes #29276

## Council review

| Round | Sol (GPT-6.1 Sol): correctness / tests / scope / quality |
Opus (Claude Opus 5.5): correctness / tests / scope / quality | Grok 4.7
|
|---|---|---|---|
| 1 | 9 / 8 / 10 / 9 | not run (Sol first) | empty seat |
| 2 | 9 / 8 / 10 / 9 | not run (Sol first) | empty seat |
| 3 | 9 / 9 / 10 / 10 | not run (Sol first) | empty seat |
| 4 | 9 / 9 / 10 / 9 | 8 / 9 / 10 / 8 | empty seat |
| 5 | 10 / 9 / 10 / 9 | 9 / 9 / 9 / 9 | empty seat |

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

When a supervisor agent asks a helper agent to do work, it now leaves
out the supervisor's reasoning notes. Those notes can make the AI
provider reject the request. The helper still receives the supervisor's
text replies.

## Changes

- `stripParentToolParts` removes assistant `reasoning` parts along with
`tool-call` parts from the context forwarded to a delegated sub-agent.
- Assistant text parts are kept. Assistant messages with no content left
are dropped.
- Delegation computes its `iteration` value from the original parent
context. A new helper, `countParentAssistantSteps`, counts assistant
messages. It skips `om-continuation` messages and messages whose array
content holds only `tool-call` or `tool-result` parts. Removing
reasoning does not change the reported iteration.
- Added AIMock delegation scenario tests in
`delegation-signed-reasoning.scenario.test.ts`. They cover signed
reasoning, unsigned reasoning from another provider, and signed
reasoning recalled from memory. They check that forwarded context
excludes reasoning, signatures, and redacted thinking, and that text and
prompts remain. They also check that the `messageFilter` input has no
reasoning and that the reported iteration is unchanged.
- Added a patch changeset for `@mastra/core`.
- User and system messages are not changed by this PR. The
`messageFilter` input keeps its other message types.

## Validation

Test and check results: not available. The PR description reports
passing scenario and existing delegation tests, plus type-check and lint
results. These were not confirmed on the current head. Live Anthropic
and Bedrock requests and the Inngest engine were not tested.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:08:32 -05:00
Abhi Aiyer
3dbe6f4314
fix(agent-controller): restore stored tool suspensions (#30132)
## Problem
When the server process that parked a run on a tool question (for
example `submit_plan`) goes away, the run stays suspended in storage.
Approving the plan later was rejected with `{ok:false,
reason:"no_pending_suspension"}` because claiming only looked in memory.
The Factory UI treated that 200 as success, so "Approve & build" did
nothing and the card kept offering buttons. Seen in prod on thread
`f82402a7` (plan waiting about 14h).

## Changes
- **core:** `Session.restoreStoredToolSuspension(toolCallId, runId?)`
registers a suspension that exists only in storage. It only does this
when exactly one stored suspended run on the active thread matches the
tool call id, and it skips approval prompts.
- **server:** the tool-suspension route restores the stored suspension
before claiming it. The claim stays synchronous.
- **factory-ui:** reply mutations now reject `ok:false` acks and show an
error toast. The respond mutation refetches the session. The transcript
only resolves a prompt once the reply was actually delivered.

## Tests
- `session-stored-suspension-after-restart.test.ts`: park on one
controller, then approve from a second controller that shares storage.
Fails before the fix. A negative case covers unknown calls and
mismatched runs.
- `useRespondSuspensionRejected.msw.test.tsx`: an `ok:false` ack fails
the mutation. Fails before the fix.
- core agent-controller 1021/1021, server agent-controller 104/104,
factory-ui chat/hooks 616/616, typecheck clean.


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

**ELI5:** When an AI agent asks a question and waits for an answer, the
server can restart before the user replies. The reply used to fail
because the server only checked memory. Now the server loads the waiting
question from storage, so the reply works. The user interface also shows
an error when a reply is rejected.

## Overview

This change fixes replies to tool prompts after the process that parked
the run has stopped. Before this change, the claim step checked only
in-memory suspensions. A reply could return `{ ok: false, reason:
"no_pending_suspension" }`. Factory UI treated that response as success,
so the prompt buttons stayed visible.

The change also keeps prompt cards in sync across windows. When a tool
call completes, the matching approval or suspension card clears in every
window.

## Changes

**Core (`packages/core/src/agent-controller/session.ts`)**
- Adds `Session.restoreStoredToolSuspension(toolCallId?: string, runId?:
string): Promise<void>`.
- Returns without a storage lookup when the tool-call ID is missing, the
suspension is already resolvable, or no thread is active.
- Searches suspended runs in storage for the active thread and resource.
It checks each configured agent, reads 100 runs per page, and reads at
most 10 pages per agent.
- Optionally filters by `runId`. Matches only non-approval tool calls
that have the requested ID and a tool name.
- Stops scanning an agent on the no-storage error. Propagates other
lookup errors.
- Registers the suspension and caches its owning agent only when exactly
one match exists and no concurrent restore occurred.

**Server (`packages/server/src/server/handlers/agent-controller.ts`)**
- If `session.restoreStoredToolSuspension` is available, the
tool-suspension route awaits it with `toolCallId` and `runId`. It then
claims the suspension. If the method is not available, the route claims
directly.
- Rejected claims return `{ ok: false, reason }`. Accepted claims are
acknowledged, and the suspension response runs in the background.

**Factory UI**
- `useAgentControllerRunMutations.ts`:
- Validates tool approval and suspension acknowledgments with
`requireAccepted`. A rejected acknowledgment throws the new
`RejectedReplyError`.
- Adds `isEndedPrompt(error: unknown): boolean`. It returns true for
rejections with reason `no_pending_suspension`.
  - Both mutations report errors in a toast.
- Suspension-reply errors invalidate the session query. Successful
mutations also invalidate it.
- `Transcript.tsx`: Resolves a prompt after a successful mutation. On
rejection, resolves the prompt only when `isEndedPrompt` returns true.
Otherwise, leaves it unresolved.
- `services/transcript.ts`:
- On a `tool_end` event, updates the tool result. Removes only the
approval or suspension prompt with the matching `toolCallId`.
- Omits persisted prompts for tool calls in terminal states (`result`,
`output-error`, or `output-denied`).
- During server-window reconciliation, removes prompts for terminal tool
calls. Updates matching assistant tool invocations from persisted
terminal parts.

**Changeset (`.changeset/stale-plan-approval.md`)**
- Declares patch releases for `@mastra/core` and `@mastra/server`.

**Channels test
(`packages/core/src/channels/__tests__/agent-controller-channels.test.ts`)**
- The allow/deny policy test sets `deployTool` permission in
`onSessionStart`. It no longer sets the permission on a manually created
session. It reads the session after inbound processing.

**Tests**
-
`packages/core/src/agent-controller/__tests__/session-stored-suspension-after-restart.test.ts`
(new, +169): Covers approval from a second controller that shares
storage. Covers an unknown tool call, a call tied to a different run,
and the 10-page limit.
-
`mastracode/factory-ui/src/hooks/__tests__/useRespondSuspensionRejected.msw.test.tsx`
(new, +45): Mocks a `no_pending_suspension` rejection. Asserts an error
whose message indicates the prompt is no longer waiting. Asserts that
`isEndedPrompt` classifies only that rejection reason as an ended
prompt.
-
`mastracode/factory-ui/src/ui/domains/chat/services/__tests__/transcript.test.ts`
(+57): Covers persisted prompt visibility. A prompt stays visible while
its tool call has no result. It is hidden when a later message or
refetched window includes the result. A `tool_end` event clears only the
prompt with the matching `toolCallId`.
- `mastracode/web/e2e/web/approval-other-window.scenario.test.ts` (new,
+130): End-to-end scenarios for prompts in two windows. After a response
settles, approval, plan-suspension, and `ask_user` cards clear from the
non-answering window. Approval cards clear from the answering window.
Unanswered cards stay in both windows.
- `mastracode/web/e2e/web/fixtures/approval-other-window.json` (new,
+104): Fixture for the end-to-end scenarios. Defines six `gpt-5.4-mini`
interactions: write-file approve and decline, plan approve and revise,
and an `ask_user` prompt.

## Scope

- 12 files changed, 663 lines added, 30 lines removed.
- Added declarations:
- `Session.restoreStoredToolSuspension` (method,
`packages/core/src/agent-controller/session.ts`)
- `RejectedReplyError` (class) and `isEndedPrompt` (function) in
`mastracode/factory-ui/src/hooks/useAgentControllerRunMutations.ts`

## Test results

The author reports these results. This review did not run them:
- Core agent-controller: 1021/1021 passed.
- Server agent-controller: 104/104 passed.
- Factory UI chat and hooks: 616/616 passed.
- Typecheck: clean.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-11 18:05:50 -08:00
mastra-platform[bot]
743a02786e
feat(valkey): identify Mastra-created clients with a clientInfoTag (#30156) 2026-11-11 17:57:11 -08:00
mastra-platform[bot]
ce631e94c6
fix(storage): prevent poisoned PostgreSQL transactions from returning to the pool (#30144) 2026-11-11 17:55:44 -08:00
Ward Peeters
d432f1ea67
feat(factory-ui): pick a route's repository, team or project from the project's own (#29982)
## Summary

An intake route with `source.repository equals mastra` never matches. On
GitHub the value is `owner/repo` (`mastra-ai/mastra`), and the route
editor gave no hint of that. Now you pick the value from the project's
own sources:

- **Searchable list of the project's sources.** In Settings › Work
Intake, the value of **Repository, team or project** is a combobox. It
lists the project's linked repositories (`owner/repo` on GitHub,
`group/project` on GitLab), then the team keys of the Linear teams and
projects bound to it, then the keys of its bound Jira projects. All of
this comes from data the UI already loads (`/web/factory/projects`,
`/web/intake/bindings`, `/web/linear/{projects,teams}`,
`/web/jira/projects`), and the Linear and Jira lists are only fetched
when the project has a binding for them. No new endpoint.
- **Narrowed by provider.** When the condition's own AND group, or an
AND group around it, limits `source.integration` or `source.provider`
with **is** or **is any of**, only those providers' values are offered.
A limit in an OR group doesn't count, since a card meets only one
branch. A key two providers share (Linear and Jira `ENG`) shows once.
- **Free typing still works.** The search box offers `Use "<text>"` for
any value not in the list, after the suggestions it matches, so typing
`mastra` and pressing Enter picks `mastra-ai/mastra`; with no match it's
the only option. The control is the same before and after suggestions
load, so a value being typed is kept. Saved values that aren't listed
still show. With **is any of** / **is none of** you can pick several.
The empty trigger reads `owner/repo, ENG, PLAT`. A project with nothing
to suggest gets the same picker with an empty list.
- **Bare-name warning.** When every card a condition tests must come
from GitHub or GitLab (the same AND-group limits as the narrowing, from
one shared helper) and the condition requires a repository with no `/`
(**is**, or any value of **is any of**), the editor shows "GitHub
repositories are owner/repo, such as mastra-ai/mastra." (or the GitLab
equivalent). **contains** / **is not** / **is none of** stay quiet,
since those can still match.
- **README:** the `source.repository` row gives each provider's exact
format and says the comparison ignores case. incident.io items have none
(test `source.provider equals incidentio`), and manual cards have no
`source.*` facts (test `source.kind not_exists`).

`main` replaced the playground-ui `RuleBuilder` in this editor with
factory-ui's own condition rows (#29978). The earlier playground-ui
`examples` placeholder change and its changeset are therefore gone, and
this PR only touches factory-ui and the Factory README.

## Screenshots

<img width="1280" height="900" alt="repository-picker-desktop"
src="https://github.com/user-attachments/assets/60483565-0a47-4ded-88b8-d74f4cfc3da2"
/>

This image predates 7fa791378d, where `Use "mastra"` moved below the
matches. The refreshed shot, with `mastra-ai/mastra` highlighted first
and `Use "mastra"` last, is
`.pr-review/29982/repository-picker-desktop.png`.


The API answers Factory project routes only for a signed-in user in an
organization, and the only local providers for that are WorkOS or the
platform, both remote. So the API calls for the screenshots were
answered in the browser from the same fixtures the MSW tests use, not
from a local API and database.

## Test plan

- [x] Written failing first (MSW, `IntakeRoutesSection`): suggestions
come from the project's repositories and Linear/Jira keys, and picking
`acme/app` saves `source.repository equals acme/app`; typing `acme/next`
saves it as is, and **is any of** saves `in ['ENG', 'PLAT']`; a GitLab
provider condition beside it leaves only `acme/platform/api`; a bare
GitHub name shows the warning
- [x] Written failing first (unit, `rules.test.ts`): the warning reads
only **is** / **is any of**, and inherited keys like `constructor` give
no format
- [x] Written failing first (MSW): typing `mastra` + Enter saves
`mastra-ai/mastra`, offered before `Use "mastra"`; a value typed before
the project's sources arrive is kept and saved
- [x] Written failing first (unit): an OR of GitHub and a repository
doesn't warn; a GitHub limit carries into a nested OR of repositories;
Linear and Jira `ENG` show once
- [x] Unit `sourceSuggestions.test.ts`: suggestion order, deduping,
other projects' bindings ignored, provider limits
- [x] factory-ui: typecheck 0, lint 0/0, oxfmt, `test:unit` 660 passed,
`IntakeRoutesSection` MSW 32 passed. Settings MSW 348 passed / 10 failed
(OMSection 9, MemorySettings 1), and those also fail on main


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

**ELI5:** When a user writes a rule for a repository, team, or project,
the editor now shows the expected format. It also suggests real values
from the project and warns when a GitHub or GitLab repository name is
missing its owner.

## Overview

This change improves value entry for the "Repository, team or project"
field in the Factory intake route editor. It adds:

- Format placeholders for the field.
- Suggestions from the project's linked repositories and its bound
Linear and Jira sources.
- Free-text entry alongside suggestions.
- Suggestions that narrow when a neighboring AND condition limits
`source.integration` or `source.provider`.
- A warning for GitHub or GitLab repository names without an owner.
- README and changeset updates that document `source.repository`
formats.

## Changes by area

**Rule hint logic (`rules.ts`)**
- Adds `Limit`, `andLimits`, `limitedProviders`, and `repositoryHint`.
- `andLimits` passes an AND group's rows to nested groups as inherited
limits. OR groups add no inherited limits.
- `limitedProviders` collects string values from `equals` and `in`
limits on `source.provider` or `source.integration`. It trims and
lowercases the values. It intersects multiple limits. It returns
`undefined` when no applicable limit exists.
- `repositoryHint` returns a GitHub or GitLab format hint only when:
- The condition requires a nonblank `source.repository` value without
`/`.
  - Every provider allowed by the applicable limits is GitHub or GitLab.
- Otherwise, the function searches for another hint. It returns
`undefined` if none applies.
- The warning applies only to `is` (`equals`) and to each value of `is
any of` (`in`). It does not apply to `contains`, `is not`, or `is none
of`.
- Repository format lookup uses a `Map`. Tests check that `constructor`,
`toString`, and `__proto__` return `undefined`.

**Source suggestions (`sourceSuggestions.ts`,
`useSourceSuggestions.ts`)**
- `SourceOption` is a suggestion type with a `provider` field.
- `sourceSuggestions(...)` builds suggestions from repositories,
bindings, Linear projects and teams, and Jira projects. Repository
options default to the `github` provider.
- Suggestions are deduplicated by provider and case-insensitive value.
- `narrowSuggestions(...)` filters provider-tagged suggestions to the
allowed providers. It keeps untagged options. It always deduplicates by
case-insensitive value across providers.
- `useSourceSuggestions(factoryProjectId)` loads the project and its
intake bindings. It enables Linear queries when the project is bound to
Linear. It enables Jira queries when the project is bound to Jira.

**Editor components**
- `conditionFields.ts` adds `VALUE_PLACEHOLDERS`. It sets the
`source.repository` placeholder to `owner/repo, ENG, PLAT`. The
repository field uses text operators unless `strict` is `true`.
- `ConditionRows.tsx`:
  - Shows repository guidance from `repositoryHint`.
  - Passes inherited AND limits through nested groups and rows.
  - Narrows suggestions with those limits.
- Renders `OpenValues` for non-strict fields with suggestions that do
not use free-text operators. Users can type values beside suggestions.
  - Keeps selected values that are no longer offered.
  - Treats an empty suggestion list as no list.
- Keeps the picker mounted while suggestions load, so typed drafts
remain.
- Shows "Use `<text>`" after matching suggestions. Enter selects a match
when one exists.
- `IntakeRoutesSection.tsx` passes a `sources: SourceOption[]` prop
through `RouteList`, `RouteCard`, `NewRoute`, and `RouteConditions`.

**Tests and mocks**
- `rules.test.ts` covers hint and no-hint cases, inherited keys, and
`in` conditions.
- `sourceSuggestions.test.ts` covers ordering, deduplication, binding
scope, and provider narrowing.
- `IntakeRoutesSection.msw.test.tsx` adds project-source fixtures. It
covers listed and typed values, multiple values, provider-based
narrowing, and the owner warning.
- `msw-server.ts` returns an empty `bindings` list for
`*/web/intake/bindings` requests.

**Documentation**
- `mastracode/factory/README.md` documents `source.repository` as
case-insensitive. It gives provider examples:
  - GitHub: `owner/repo`.
  - GitLab: the full project path, including subgroups.
  - Linear: the team key.
  - Jira: the project key.
  - incident.io items: use `source.provider equals incidentio`.
  - Manual cards: use `source.kind not_exists`.
- A patch changeset for `@mastra/factory` describes the same behavior.

## Scope

- The diff touches 12 files: 778 lines added and 25 removed.

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

- The author reports that Factory UI typecheck returns 0 and lint
returns 0 errors and 0 warnings.
- The author reports 660 passing unit tests (`test:unit`).
- The author reports 32 passing `IntakeRoutesSection` MSW tests.
- The author reports 348 passing and 10 failing Settings MSW tests. The
failures are 9 in OMSection and 1 in MemorySettings. The author states
the same 10 failures occur on `main`.
- The author reports that the tests for these changes were written to
fail first.
- CI results for the current head: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 02:16:40 +01:00
Ward Peeters
e60ea1f681
fix(factory): rebuild environment templates on push for Platform GitHub (#30135)
Factories connected to GitHub through Mastra Platform never rebuilt
their sandbox template on push, even with build-on-push turned on.
Sessions kept starting from whatever template was built last, so they
spent time fetching and checking out weeks of commits (and
`last_push_build_at` stayed null).

On the Platform lane GitHub events only reach Factory through the
polling event worker. The worker's integration context was built without
the `onRepositoryPush` hook (only the routes context had it), so
`GithubRules` dropped every default-branch push. This passes the hook
into the worker context too:

```ts
// factory.ts, integration worker context
...(this.#environmentBuilds ? { onRepositoryPush: this.#environmentBuilds.onRepositoryPush } : {}),
```

The new test in `event-worker.lifecycle.test.ts` boots a real
`MastraFactory` with `PlatformGithubIntegration`, polls a `push` event
from a stubbed Platform event log, and checks that the build starts,
`lastPushBuildAt` is recorded and the active template is pinned to the
new head. It fails without the fix and passes with it on both LibSQL and
Postgres 16 (`FACTORY_TEST_STORAGE_BACKEND=postgres`).


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

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

ELI5: When someone pushes new code to a Factory's GitHub repository, the
Factory now rebuilds its sandbox template. New sessions then start from
the latest code, not an old copy.

## Summary

This PR fixes build-on-push for Factories connected to GitHub through
Mastra Platform. Platform GitHub events reach Factory through the
polling event worker. That worker did not receive the `onRepositoryPush`
hook, so default-branch pushes did not trigger an environment build.

## Changes

- `mastracode/factory/src/factory.ts`: When `#environmentBuilds` exists,
`MastraFactory.prepare()` adds `onRepositoryPush` to the integration
context used to build each ready integration's workers. When no
environment build runner exists, the property is omitted. The change is
two added lines, placed beside the existing optional
`sourceControlOwnerId: 'github'` entry.
- `mastracode/factory/src/integrations/platform/github/event-worker.ts`:
Comments only. They now describe default-branch pushes as triggering
environment-template rebuilds, and they name
`GithubRules.onRepositoryPush` as the hand-off. The comments no longer
refer to base-checkpoint rebuilds or `withBaseCheckpointWebhookTrigger`.
No executable behavior changed.
-
`mastracode/factory/src/integrations/platform/github/event-worker.lifecycle.test.ts`:
Adds 143 lines. The test adds PostgreSQL test-storage support and a mock
sandbox that records build starts and returns a ready template. It
configures a project for push builds with a 60-minute debounce, links
its default-branch repository, and polls a stubbed GitHub push event. It
checks that the project is marked as having a push build, that an
environment build starts, and that the resulting template becomes active
with the pushed commit SHA recorded as the repository head. Cleanup
closes storage and stops workers.
- `.changeset/free-horses-grin.md`: Adds a patch changeset for
`@mastra/factory`.

## Test results

The author reports that the new test fails without the change and passes
with it. The author reports this on LibSQL and on Postgres 16 with
`FACTORY_TEST_STORAGE_BACKEND=postgres`. This review did not run the
tests. CI status is not available.

## Diff scope

4 files changed, 153 lines added, 3 lines removed.

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

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 02:15:50 +01:00
Dane - AI (Mastra)
c014d187bb
chore(deps): update docker images (major) (#19788) 2026-11-11 17:08:49 -08:00
Anurag Ojha
7c40bc84b6
fix(react): load the Studio review queue page by page (#29291)
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-11 17:06:48 -08:00
mastra-platform[bot]
5e3c087082
fix(core): strip provider-executed tool results from delegated sub-agent context (#30134) 2026-11-11 17:06:26 -08:00
mastra-platform[bot]
53b9bf64ba
fix(core): accept null optional fields in strict structured output on durable, evented and Inngest agents (#30136) 2026-11-11 17:05:45 -08:00
Damien Schneider
ddf1c08cf6
perf(factory): ⌘K asks the server for matching cards instead of downloading the board (#30081)
Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 16:40:22 -08:00
Dane - AI (Mastra)
a8130955fe
chore(deps): update cgr.dev/chainguard/minio docker digest to db3f583 (#30139) 2026-11-11 16:35:27 -08:00
Caleb Barnes
fd139c9a14
test(core): fix channel approval-card tests broken by per-thread permission rules (#30137)
Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 16:30:17 -08:00
mastra-platform[bot]
2d4284603a
Fix MCP core compatibility, Windows browser paths, and AI SDK tool titles (#30125) 2026-11-11 15:45:01 -08:00
mastra-platform[bot]
834c0c5635
fix(factory): honor board triage routes and return labeled cards to Intake (#30100) 2026-11-11 15:43:56 -08:00
Caleb Barnes
9497c2edfb
test(mastracode): make schedules multi-line e2e scenario independent of the clock (#30128)
## Summary

The `schedules-multiline-prompt` TUI e2e scenario failed depending on
the time of day. The `/schedules` picker cuts each row off at the dialog
width, and the row label's length changes with the clock: the next-fire
time includes a date when it falls on another day, and the countdown
(`in 5s` vs `in 59m 59s`) changes width. When the label got long enough,
the end of the schedule summary was cut off and the "whole summary is
visible on one row" check failed. This happened on `main` and on
unrelated PRs.

The scenario now resizes the terminal to 160 columns, which leaves room
for the longest possible label plus the full summary. The test still
proves the same things: each schedule takes exactly one row while
arrowing through the picker, rows aren't duplicated or wrapped, and the
whole summary is visible. A summary with line breaks would still split
the row at any width. No product code changes.

## Test plan

- [x] Reproduced the failure by running the scenario with
`MC_E2E_COLUMNS=114`: the summary was cut off the same way it was in CI.
- [x] With the fix, the scenario passes at `MC_E2E_COLUMNS` 80, 114 and
120.
- [x] `schedules-multiline-prompt` and `schedules-command` passed 5 runs
in a row.
- [x] `pnpm --filter ./mastracode/tui lint` and `check` pass, and `oxfmt
--check` is clean.

Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 00:35:51 +01:00
mastra-platform[bot]
8ea9c0e552
fix(factory): surface incomplete working-phase runs instead of marking them successful (#30101) 2026-11-11 15:14:17 -08:00
mastra-platform[bot]
b75348adbd
docs: redirect commonly hallucinated docs URLs to real pages (#30126) 2026-11-11 16:07:08 -07:00
mastra-platform[bot]
0fe65182d8
docs(evals): link datasets, experiments, and the eval loop from the Evals overview (#30124) 2026-11-11 16:06:03 -07:00
mastra-platform[bot]
064c1ff2e2
docs: redirect /docs/agents/mcp-guide to the MCP page (#30122) 2026-11-11 15:48:19 -07:00
mastra-platform[bot]
f5c7626fe7
docs(mcp): link runtime-tools example to durable agents and background tasks (#30120) 2026-11-11 15:41:02 -07:00
mastra-platform[bot]
4e028252d1
docs(sandbox): clarify that LocalSandbox workingDirectory doesn't copy the project (#30119) 2026-11-11 15:34:29 -07:00
mastra-platform[bot]
edb61ca939
docs(workspace): explain provider requirement when indexing supplied text (#30117) 2026-11-11 15:21:52 -07:00
dane-ai-mastra[bot]
9e82af0237
chore: version packages (alpha) (#30074)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-11 14:21:14 -08:00
Abhi Aiyer
4884ee08a0
fix(agent-controller): answer parked tool approvals when the permission rules allow or deny them (#30114)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 14:18:01 -08:00
mastra-platform[bot]
056d35d943
Enforce JSON Schema formats in MCP tool validation (#30113) 2026-11-11 14:16:55 -08:00
Caleb Barnes
7f0d2fd4b6
feat(core): trace agent setup before the first model call (#30002)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 14:14:09 -08:00
mastra-platform[bot]
4cfa256801
feat(coding-agent): link Linear issues with Fixes lines in PR descriptions (#30112) 2026-11-11 15:13:23 -07:00
mastra-platform[bot]
8e26648e8b
docs(schedules): explain that workers must be running for schedules to fire (#30116) 2026-11-11 15:03:55 -07:00
Caleb Barnes
0b3514eb8a
fix(code-sdk): keep schedule summaries on one line (#30108)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 13:57:39 -08:00
mastra-platform[bot]
38327de07a
Avoid Event-Loop Stalls in Instruction Lookup (#30104) 2026-11-11 13:54:28 -08:00
Abhi Aiyer
1689ce38e1
perf(agent-controller): read only the newest page when listing threads with a limit (#30090)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-11 13:53:07 -08:00
Lennart
f3f304bc1f
docs(mastracode): fix goal continuation, ResolutionPolicy, and mode default models (#30103)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 14:34:41 -07:00
mastra-platform[bot]
3ca0af7cf4
docs: show how to save audit records with agent tool hooks (#30106) 2026-11-11 14:08:30 -07:00
Lennart
fdd242c2a4
chore(ci): remove 2027dev evals workflow (#30107)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 14:08:09 -07:00
Caleb Barnes
9efd1ea8df
fix(factory): report a missing schedule cron as null (#30098)
Schedules can now be one-off runs with no cron expression (#25131), so
`schedule.cron` is optional. The Factory environment build schedule view
still assigned it to a `string | null` field, which fails the
`@mastra/factory` typecheck on `main`.

The view now reports a missing cron as `null`, the same as when there is
no schedule.

## Test plan
- [x] `tsc --noEmit` in `mastracode/factory` passes (fails on `main` at
`build-schedule.ts:68`)
- [x] `vitest run src/environment`: 61 passed

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

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

## ELI5

When a schedule has no cron expression, Factory now returns `null`
instead of an invalid missing value. This supports one-off schedules and
matches the declared output type.

## Changes

- Updated `toView` to map an undefined `schedule.cron` to `null`.
- Added a patch changeset for `@mastra/factory`.

## Testing

Not available.

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

Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 13:37:55 -07:00
Caleb Barnes
47dfae5d3a
fix(factory): mint GitHub tokens ten repositories at a time (#30093)
## Summary

A Factory with more than ten repositories asked GitHub for one token per
repository every time a session started or an environment built, because
one token can name at most ten repositories. Rebuilds and a handful of
sessions together ran into the per-installation token limit, and a
failed request quietly left that repository unsynced.

- Sessions, environment builds and branch-head lookups now request
access for each group of up to ten repositories once, and serve every
repository in the group from that token. Eleven repositories need two
tokens instead of eleven. The group token stays with those callers; a
lookup for a single repository still gets a token for that repository
only.
- Minted access is reused for 20 minutes instead of 5. Sessions replace
their `GH_TOKEN` after 30 minutes instead of 45, so a reused token is
never close to GitHub's 60-minute expiry.
- If a group can't be granted, each repository falls back to its own
token as before.

## Test plan

- [x] New: the Platform GitHub integration serves an eleven-repository
environment from two token requests (twelve without this change)
- [x] New: a group mint returns each repository's access under the group
token, and a later single-repository lookup still gets a
single-repository token
- [x] New: `groupedRepositoryAccess` falls back to per-repository tokens
when a group can't be granted or the group request fails
- [x] Updated token refresh tests for the 30-minute refresh
- [x] `@mastra/factory` tests, typecheck, oxlint and oxfmt pass


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

## ELI5

Factory now requests shared GitHub tokens for groups of up to ten
repositories. This reduces token requests while preserving
individual-token fallback when group access is unavailable.

## Changes

- Added grouped repository access with deduplication and shared
in-flight requests.
- Added a 60-second cooldown after failed or unavailable group requests.
- Applied grouped access to environment builds, branch-head resolution,
and workspace setup.
- Extended the version-control contract for multi-repository access.
- Increased repository-access token reuse from 5 to 20 minutes.
- Updated session `GH_TOKEN` refresh from 45 to 30 minutes.
- Added tests for batching, fallback, cooldowns, cache expiry, and token
refresh.
- Added a patch changeset for `@mastra/factory`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 13:37:35 -07:00
Leo
eb683b45fe
fix(core): find channel tool approvals older than the newest 50 messages (#29618)
## Description

### Summary

After an `AgentChannels` rebuild (the `channelConfig` pattern) or a bot
restart, the new instance has no card cache, so a click on Approve/Deny
looks up the pending approval in Memory. That lookup read only the
newest 50 messages. An approval followed by a longer thread was silently
ignored (`No pending approval found`) while its metadata still existed.
The same window also hid the user turn that triggered the tool, so the
requester check was skipped and anyone could answer the card.

The lookup in `packages/core/src/channels/agent-channels.ts` now reads
history newest-first, 50 messages per page, and only on a cache miss:

```diff
 on approval click, card not in cache
-  read newest 50 messages
-  find pending entry for toolCallId, else "No pending approval found"
+  for each page of 50, newest first
+    pending entry for toolCallId found  -> keep reading until its user turn is complete
+    assistant message carrying the tool call, no entry -> already answered, stop
+    no more messages -> stop
+  recover requester from that user turn (ambiguous turn -> no one may answer)
```

Storage can't filter on the nested
`pendingToolApprovals[...].toolCallId` (the `listMessages` metadata
filter is shallow scalar only), so this pages rather than querying.
Earlier pages are dropped and `includeTotal: false` skips the count
query. Both approval writers (`tool-call-step.ts` and the durable
`tool-call.ts`) store the entry on the newest assistant message carrying
the tool call, which is what makes the "already answered" stop safe.

The scan runs before the requester check, so its result is cached per
card (thread, card message, toolCallId) to stop repeat clicks from
forcing repeat scans (Superagent finding):

- Pending and answered results are kept for 10 minutes, unknown cards
for 60 seconds. At most 1000 entries per instance; concurrent clicks on
one card share one read.
- Core decides whether a second answer applies:
`approveToolCall`/`declineToolCall` claim the suspended run atomically
(`AGENT_RESUME_ALREADY_CLAIMED` for the loser) and hand it back if the
resumed run fails before it starts. The channel only reads core's resume
errors by `MastraError` id: a finished, aborted or no-longer-waiting run
marks the card answered, so later clicks neither resume nor read
history; a resume already in progress is ignored quietly. While one
click edits the card and dispatches, other clicks on that card on the
same instance are ignored.
- No hard page cap: a cap would strand approvals behind it again. The
cache bounds the cost instead, to one scan per card per window.

### Evidence

New colocated test
`packages/core/src/channels/__tests__/agent-channels-approval-history.test.ts`
follows the issue's steps: a real `Mastra` + `InMemoryStore`, a mapped
thread, an `AgentChannels` rebuilt from `channelConfig` with the same
adapter and StateAdapter, and clicks through the real Chat
`processAction`. Only the dispatch boundary is recorded, via the
documented subclass hooks.

- **Before** (fix reverted to `origin/main`'s `agent-channels.ts`):
`Tests 7 failed | 3 passed (10)`. Failures: approval 60 back not
dispatched, approval 400 back not dispatched, wrong user could approve
when the requester's message was outside the window, two-author turn
could still be answered (whole and split across pages), and an answered
card read the full thread. The 3 passing are controls (recent approval,
`toolApprovers: 'anyone'`, unknown id).
  **After:** `Tests 10 passed (10)`.
- Existing channel tests (`src/channels/**`, 13 files): `616 passed`.
`oxlint --type-aware --deny-warnings` and `oxfmt --check` are clean on
changed files. `tsc --noEmit` shows no errors under `src/channels/`.
- Mutation checks: removing either stop condition, or checking
"answered" before the pending entry, fails at least one of the new
tests.
- Not tested: storage adapters other than in-memory (paging relies on
standard `page`/`hasMore`), or a live channel transport or LLM resume.

Lookup cache follow-up (same test file, 12 more tests, storage reads
counted with a spy on the real `InMemoryStore.listMessages`):

- **Before** (`e37d64d`): `Tests 9 failed | 11 passed (20)`. A
non-requester clicking a 400-message-deep card 11 times caused 99 reads
instead of 9; repeated clicks on an unknown or answered card read the
thread every time (45 vs 9); 3 simultaneous clicks read it 3 times; the
requester could answer the same card twice.
**After:** `Tests 22 passed (22)`. Each card is read once; the requester
can still approve after a non-requester was rejected; a failed resume
leaves the card usable; an approval saved after a miss is found once the
60-second window passes; a reused tool call id on a new card or in
another thread gets its own lookup; a claim survives the resumed run
reseeding its card and cache eviction.
- Channel tests (`src/channels/**`, 16 files): `645 passed`. `oxlint
--type-aware` and `oxfmt --check` clean on changed files; `tsc` shows no
errors in the changed files.

Resume follow-up (`5ef5b4a..aaa7eec`). An independent review of
`5ef5b4a` found that its channel-level "claim once" step blocked a valid
card for 10 minutes when the resumed run failed after dispatch returned,
and that a card answered on another instance was retried with an error
post on every click (`AGENT_RESUME_NO_SNAPSHOT_FOUND` was matched by
message text). The claim is removed, because core already prevents a
double answer, and resume errors are classified by id. The new tests
drive a real `Agent` with a mock model, an approval-gated tool,
`MockMemory` and `InMemoryStore`, with no dispatch override.

- **Before** (`5ef5b4a`'s `agent-channels.ts`): `stops resuming an
approval that another instance already answered` fails (2
`approveToolCall` calls for 2 clicks, error posted) and `lets the
requester approve again when the resumed run fails before it starts`
fails (run back to `suspended`, the second click never reached core,
refund never ran).
**After:** both pass. Other new tests: concurrent Approve+Approve and
Approve+Deny on one instance dispatch once and edit the card once; the
same click on two instances runs the refund once (core refuses the
second with `AGENT_RESUME_ALREADY_CLAIMED`, no error posted); a card
whose run now waits on a newer approval, a stashed card, and
DurableAgent finished-run errors are each resumed once and then cached
as answered; a core durability timeout leaves the card answerable.
- Core: `AGENT_RESUME_TOOL_CALL_NOT_SUSPENDED` now carries
`details.timedOut: true` only when the 30-second durability wait ran out
(new test in `tool-approval-large-snapshot.test.ts` fails without it). A
`DurableAgent` resume of a run with no stored snapshot throws
`MastraError` `AGENT_RESUME_NO_SNAPSHOT_FOUND` instead of a plain
`Error`; the message is unchanged.
- `src/channels/**` plus the core approval and durable resume tests (20
files): `774 passed`. The new approval tests passed 5 of 5 repeat runs.
`oxfmt --check` and `oxlint --deny-warnings` are clean on changed files;
`tsc --noEmit` shows no errors in changed files. Not tested:
`durable-agent-evented-two-process.test.ts`, which needs a built `dist`
and times out the same way without these changes.

Stale card follow-up (`aaa7eec..393e75e`). An independent review found
that a card whose run/tool target was remembered (from the lookup cache
or because this instance posted the card) could outlive its approval:
another instance answers it, the same run then suspends on a second
refund, and a late click on the first card reached `DurableAgent`, which
accepted the stale target and ran the second refund. Before resuming
from a remembered target, the channel now does one read of the thread's
suspended runs (`Agent.listSuspendedRuns`, no history scan). If the run
is suspended only on other tool calls, the card is cached as answered
and nothing is resumed or posted. A run that isn't suspended at all is
still left to core's resume, so a fast click before the suspension is
saved keeps working. `AgentControllerChannels` is skipped because its
session gate already checks this.

- **Before** (`aaa7eec`): the 4 new `ignores a stale card once the run
waits on a newer approval` cases (real `Agent` and real `DurableAgent`,
history lookup and posted card, no `approveToolCall`/`declineToolCall`
mocks) fail. With `DurableAgent` the stale click resumed the run and
refunds became `[10, 20]`. With `Agent` it reached core and was refused
(`AGENT_RESUME_TOOL_CALL_NOT_SUSPENDED`).
**After:** stale clicks reach no resume, refunds stay `[10]`, the second
card then approves normally (`[10, 20]`). 4 of 4 pass, 5 of 5 repeat
runs.
- `src/channels/**` (16 files): `655 passed`. `oxfmt --check` and
`oxlint --deny-warnings` clean on changed files; `tsc` shows no errors
in `agent-channels.ts` or the approval-history test.

### Merge Danger

**Door:** two-way. Only a read path changes; nothing new is persisted.

**Blast radius:** channel tool-approval clicks that miss the in-memory
card cache. The first click on a card whose tool call appears nowhere in
the thread reads the whole thread in pages of 50; later clicks on that
card reuse the result. Repeat clicks on an answered card are now ignored
instead of posting an error each time. Two core errors change shape (see
Evidence): a new `details.timedOut` flag, and the durable missing-run
error gains an id. Code matching the durable error by message still
works.

**Known gap, not in this PR:** the card is edited to Approved/Denied
before core claims the run, as on `main`. A click from a stale client
(the first click's edit removes the buttons) or from another instance at
the same moment can still relabel a card whose run another click already
resumed. Execution is not affected. Fixing it means moving the decision
edit into the resumed stream's render path after core accepts it. Cache
entries are per instance, so each instance in a multi-instance
deployment does its own first read.

**Known gap, not in this PR:** the MySQL and MongoDB `listMessages`
adapters order by `createdAt` with no id tie-breaker (Postgres has one),
so messages with identical timestamps at a page boundary could be
skipped. That predates this PR and affects every paginated caller; it
needs a store-level fix.

**Known gap, not in this PR:** an approval is matched by tool call id.
If two runs in one thread reuse the same id, a click on the older card
can resolve to the newer run's pending entry. `main` matches the same
way; binding each card to its run needs a stored card-to-run link and is
a separate change.

**First-click race (fixed in d986fc9):** a first click's history scan
can read pages written before another instance answered the card. Every
target, not only a remembered one, is now checked against the run's
current suspension (one `listSuspendedRuns` read) before resuming. New
tests serve the scan a pre-answer history snapshot: before the fix a
DurableAgent resumed the newer approval and an Agent reached core;
after, neither click resumes. Channels suite 677/677.

**Overlap:** #29197 also edits `agent-channels.ts`, but in the
render-context code (around `_buildRenderContext`). This diff only
touches the approval-lookup branch of the action handler, so they
shouldn't conflict textually.

## Related issue(s)

Closes #29186

## 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

## Council review

Rounds: 4

| Seat | Round 1 | Round 2 | Round 3 | Round 4 |
| --- | --- | --- | --- | --- |
| Claude Opus 5.5 | not run | 8.5/10 | 9/10 (Tests 8, Code quality 8) |
9/10 |
| GPT-6.1 Sol | 9/10 | 9/10 | 9/10 | 9.5/10 |
| Grok 4.7 | empty seat | empty seat | empty seat | empty seat |

Lookup cache follow-up, GPT-6.1 Sol (Correctness / Tests / Scope / Code
quality): round 1 6/7/10/7, round 2 6/7/10/7, round 3 8/8/10/8. Each
round's findings were fixed; the round 3 finding (cross-thread
invalidation) was fixed after the last round with a regression test.

Resume follow-up, GPT-6.1 Sol: round 1 7/8/10/8, round 2 7/8/10/8, round
3 8/8/10/8. All findings fixed except the stale-client card relabel
above, which the round 3 review agreed not to block on (same as `main`).
The round 3 finding (DurableAgent errors not recognized) was fixed after
the last round with tests.

Stale card follow-up, GPT-6.1 Sol: round 1 9/9/10/9, no P1 or P2.

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

If the bot restarts, it can search older conversation history to find an
approval request. The person who started the request can answer it,
unless the channel allows anyone to respond.

## Summary

- When an approval card is not in memory, `AgentChannels` searches
Memory history newest-first in pages of 50.
- The search continues until it finds the tool call, confirms that the
approval was answered, or reaches the end of history.
- The lookup recovers the requester from the initiating user turn.
Ambiguous turns cannot be answered unless `toolApprovers` is `'anyone'`.
- Lookup results are cached per thread, card, and tool-call ID.
Concurrent clicks share one lookup.
- Missing results expire after 60 seconds. Pending and answered results
expire after 10 minutes.
- Approval actions ignore answered cards and prevent concurrent actions
on the same card.
- A late click on an answered card does not resume a different approval
on a `DurableAgent`.
- Before resuming a remembered approval, `AgentChannels` checks whether
the run is suspended on a different tool call.
- Resume errors distinguish completed, missing, aborted, and in-progress
runs.
- Timed-out suspension checks include `details.timedOut: true`.
- A `DurableAgent` resume without a stored snapshot throws `MastraError`
with ID `AGENT_RESUME_NO_SNAPSHOT_FOUND`.
- Added tests for history recovery, requester authorization, repeated
and concurrent clicks, cache expiry, stale cards, and resume outcomes.
- Added a patch changeset for `@mastra/core`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com>
2026-11-11 15:18:00 -05:00
mastra-platform[bot]
259f142f46
fix(pg): support scalar and nested operators in vector elemMatch filters (#30095) 2026-11-11 11:31:00 -08:00
Michael 'Misha' Nightingale
0da9a5275d
fix(observability): redact span errors on traces that hide input or output (#29716)
## Description

`tracingOptions.hideInput` / `hideOutput` clear span input and output at
export, but `exportSpan()` passed `errorInfo` through untouched. Error
messages, the stack header (which repeats the message) and error details
often quote exactly the data the flags are meant to hide. Examples: a
tool throwing `Invalid IBAN: <the user's IBAN>`, or a provider that
refuses a prompt and echoes it back in its response body. This applies
to every span type, not just scorers. It came up in review of #29174
([comment](https://github.com/mastra-ai/mastra/pull/29174#discussion_r4444454609)).

On a trace that sets either flag, the exported error now keeps what
identifies it and drops the text:

```json
// Before
{ "name": "Error", "message": "Invalid IBAN: DE89370400440532013000",
  "stack": "Error: Invalid IBAN: DE89370400440532013000\n    at validate (tools/iban.ts:12:11)" }

// After
{ "name": "Error", "message": "[REDACTED]",
  "stack": "Error: [REDACTED]\n    at validate (tools/iban.ts:12:11)" }
```

`id`, `name`, `domain`, `category` and the stack frames are kept. From
`details`, only the provider fields that `apiCallErrorDetails` already
sanitizes are kept (`statusCode`, `url`, `isRetryable`), so
`responseBody` and free-form `MastraError.details` are dropped. Either
flag triggers this, because an error can quote either side. The
redaction happens at export, next to the existing input/output check, so
all exporters and bridges get it and the live span keeps the real error
for in-process use (metrics status, span processors). Traces without the
flags are unchanged.

New integration test
(`observability/mastra/src/hidden-trace-errors.integration.test.ts`)
runs a real agent, Observability instance and TestExporter. It covers a
tool error and a provider API error under `hideInput` only and
`hideOutput` only, plus unhidden controls and stack-header edge cases.
All four hidden-trace cases fail on `main`.

Two open questions for reviewers: should we keep a small allowlist of
id-like `MastraError.details` keys (`agentName`, `toolId`, `runId`)
instead of dropping them all? And are we fine with `error.message`
grouping in Datadog-style dashboards showing `[REDACTED]` for hidden
traces?

After #29174 merges, a failing scorer step on a hidden trace is covered
by this same rule. I'll add that case to the scorer redaction test once
both have landed.

## Related issue(s)

Follow-up to #29174.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)

## Checklist

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


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

## ELI5

When a trace hides input or output, this change also hides secrets in
exported errors. It preserves safe error identity and relevant stack
frames without exposing hidden data.

## Changes

- Redacts exported error messages and stack headers as `[REDACTED]`.
- Applies redaction when `hideInput` or `hideOutput` is enabled.
- Preserves error identity fields and safely correlated stack frames.
- Omits free-form error details from redacted exports.
- Replaces unsupported stack formats with a redacted header.
- Leaves live errors and unhidden traces unchanged.
- Uses wrapped error causes when capturing stack information.
- Adds integration tests for tool errors, provider errors, wrapped
causes, and stack edge cases.
- Adds a patch changeset for `@mastra/observability`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Ehindero Israel <iehindero419@stu.ui.edu.ng>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 20:17:20 +01:00