@mastra/factory: a card move during the work-item feed load is not re-checked before the abort, the notice, and the first kickoff send
What happens
In invokeSkill dispatch, the dispatcher checks that the kickoff still applies (kickoffLanded() and kickoffStale(), added by #25277) and then loads the work-item feed with withWorkItemFeed. That load is an async storage read. After it resolves, the dispatcher runs session.abort() when the decision has cancelInFlight, posts the precedingMessage notice, and sends the first kickoff, with no second applicability check. If the card leaves its phase while the feed is loading, all three side effects still happen for a card that has already moved on. The decision then completes as succeeded.
A concrete stock case: the Review board's reviewPullRequest returns cancelInFlight: true when a card re-enters review from review (a new push during an in-flight review). If that card moves out of Reviewing while the re-review decision is loading its feed, for example to Done on a merge, the dispatcher still aborts the in-flight review run and sends the re-review kickoff for a card that is no longer in Reviewing. Stock boards do not set precedingMessage; the notice leg applies to boards that do.
Expected
The applicability checks run again after the feed load and before the abort, the notice, and the first send. A card that moved during the load settles without aborting a run, posting a notice, or sending its kickoff, the same way it does when the move is observed before the load or after a deliver.
Reproduction
Stock @mastra/factory 0.18.0 with @mastra/libsql, stock Work board, a synthetic session, and a feedReader whose read blocks until the test moves the card. The feedReader option is the dispatcher's own injection point.
// Repro: a card move during the work-item feed load is not re-checked before the
// abort, the preceding notice, or the first kickoff send.
// Stock @mastra/factory 0.18.0, stock Work board, synthetic session.
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import test from 'node:test';
import { createBoardRegistry } from '@mastra/factory/boards';
import { FactoryDecisionDispatcher } from '@mastra/factory/rules/dispatcher';
import { WorkItemsStorage } from '@mastra/factory/storage/domains/work-items/base';
import { FactoryProjectsStorage } from '@mastra/factory/storage/domains/projects/base';
import { LibSQLFactoryStorage } from '@mastra/libsql';
const boards = createBoardRegistry(); // stock Work + Review boards
function deferred() {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
}
test('a card move during feed loading does not block the abort, the notice, or the first send', async t => {
const storage = new LibSQLFactoryStorage({ id: randomUUID(), url: ':memory:' });
t.after(() => storage.close());
const workItems = storage.registerDomain(new WorkItemsStorage());
const projects = storage.registerDomain(new FactoryProjectsStorage());
await Promise.all([workItems.ensureReady(), projects.ensureReady()]);
const orgId = randomUUID();
const userId = randomUUID();
const project = await projects.create({ orgId, userId, input: { name: 'Feed load' } });
const scope = { orgId, factoryProjectId: project.id };
const item = (await workItems.upsert({ ...scope, userId, input: { title: 'Card', board: 'work', stages: ['intake'] } })).item;
const address = { sessionId: randomUUID(), threadId: randomUUID(), resourceId: randomUUID() };
// Synthetic session that records aborts, notices, and kickoff sends. A run is in flight.
const subscribers = new Set();
const sends = [];
const aborts = [];
const notices = [];
const session = {
mode: { get: () => 'core' }, state: { get: () => ({}) }, model: { get: () => 'synthetic' },
identity: { getId: () => address.sessionId, getOwnerId: () => userId }, getWorkspace: () => undefined,
stream: { isActive: () => true }, abort: () => { aborts.push('abort'); },
sendNotificationSignal: notice => { notices.push(notice); return { accepted: Promise.resolve({ action: 'wake' }) }; },
thread: { requireId: () => address.threadId, switch: async () => {}, listActiveMessages: async () => [],
getSetting: async () => [], setSetting: async () => {} },
subscribe: callback => { subscribers.add(callback); return () => subscribers.delete(callback); },
sendSignal: signal => {
sends.push(signal.id);
queueMicrotask(() => {
for (const notify of [...subscribers]) notify({ type: 'agent_start' });
for (const notify of [...subscribers]) notify({ type: 'message_start', message: { id: signal.id } });
for (const notify of [...subscribers]) notify({ type: 'agent_end', reason: 'complete' });
});
return { accepted: Promise.resolve({ action: 'wake' }) };
},
};
async function enter(stage, decisionOptions) {
const before = await workItems.get({ orgId, id: item.id });
const id = randomUUID();
const role = boards.get('work').roleForPhase(stage);
const result = await workItems.commitTransition({ ...scope, workItemId: item.id,
expectedRevision: before.revision, destinationStage: stage, actorId: userId,
ingress: { identity: id, triggerType: 'human', transitionId: id },
configVersion: 'test', causalChain: [], consentedBy: userId,
evaluation: { outcome: 'accepted', decisions: decisionOptions && role
? [{ type: 'invokeSkill', role, prompt: 'Kickoff', idempotencyKey: id, ...decisionOptions }] : [] },
});
assert.equal(result.result.status, 'accepted');
return (await workItems.listDeferredDecisions(orgId, project.id)).find(d => d.idempotencyKey === id);
}
// The decision carries cancelInFlight (the stock Review re-review shape) plus a preceding notice.
const decision = await enter('planning', { cancelInFlight: true, precedingMessage: 'Now planning' });
await storage.ops.insertOne('factory_run_bindings', {
id: randomUUID(), org_id: orgId, factory_project_id: project.id, work_item_id: item.id,
role: 'plan', thread_id: address.threadId, resource_id: address.resourceId, session_id: address.sessionId,
branch: 'test', status: 'active', created_at: new Date(), revoked_at: null,
});
const current = await workItems.get({ orgId, id: item.id });
await workItems.update({ orgId, id: item.id, userId, patch: { sessions: {
...current.sessions, plan: { ...address, branch: 'test', startedBy: userId },
} } });
const loading = deferred();
const release = deferred();
const dispatcher = new FactoryDecisionDispatcher({ storage: workItems, boards,
controller: { getSessionByResource: async () => session, listActiveThreadRuns: () => [{ threadId: address.threadId }] },
transitionService: { transition: async () => { throw new Error('unexpected transition'); } },
isAutoRunEnabled: async () => false,
// A slow feed read; the dispatcher accepts feedReader as an option.
feedReader: { readRunContext: async () => { loading.resolve(); await release.promise; return null; } },
});
const run = dispatcher.runOnce();
await loading.promise; // the dispatcher is inside withWorkItemFeed, past the kickoffStale check
await enter('execute'); // the card leaves Planning during the feed load
release.resolve();
await run;
await dispatcher.stop();
const result = await workItems.getDeferredDecision(orgId, project.id, decision.id);
console.log('aborts=%d notices=%d sends=%d status=%s', aborts.length, notices.length, sends.length, result.status);
assert.equal(aborts.length, 1, 'the in-flight run was aborted after the card moved');
assert.equal(notices.length, 1, 'the preceding notice was posted after the card moved');
assert.equal(sends.length, 1, 'the kickoff was sent after the card moved');
assert.equal(result.status, 'succeeded');
});Run from a directory where @mastra/[email protected], @mastra/[email protected], @mastra/[email protected] and zod are installed:
node --test feed-load-stale-send.test.mjsOutput:
# aborts=1 notices=1 sends=1 status=succeeded
ok 1 - a card move during feed loading does not block the abort, the notice, or the first sendThe card is in execute before the abort, the notice and the send happen, and the decision still ends succeeded. The same script gives the same output on 0.17.2.
Affected versions
@mastra/factory0.18.0 andmainat 0b9e7bc: the applicability checks run before the feed load and not after it.- Open PR #25550 makes a stale kickoff settle as
supersededinstead ofsucceeded, but keeps the check before the feed load only, so this window stays open. - 0.17.2 has the same sequence after the feed load.
Suspected cause
mastracode/factory/src/rules/dispatcher.ts at 0b9e7bc:
- applicability checks, before the feed load: https://github.com/mastra-ai/mastra/blob/0b9e7bc0839bcec59f9eaa014c759ae935454c45/mastracode/factory/src/rules/dispatcher.ts#L1000-L1001
- feed load: https://github.com/mastra-ai/mastra/blob/0b9e7bc0839bcec59f9eaa014c759ae935454c45/mastracode/factory/src/rules/dispatcher.ts#L1003-L1007
- abort, preceding notice and first send with no re-check: https://github.com/mastra-ai/mastra/blob/0b9e7bc0839bcec59f9eaa014c759ae935454c45/mastracode/factory/src/rules/dispatcher.ts#L1008-L1070
Suggested fix
Run kickoffLanded() and kickoffStale() again after withWorkItemFeed resolves, before the abort, the notice and the first send, and settle without sending when either is true.
Source: mastra-ai/mastra