import { resolveRequestThinkingLevel } from '@mastra/code-sdk/agents/model'; import type { ThinkingLevel } from '@mastra/code-sdk/providers/openai-codex'; import type { MastraCodeState } from '@mastra/code-sdk/schema'; import type { MastraDBMessage, MessageList } from '@mastra/core/agent/message-list'; import type { AgentControllerRequestContext } from '@mastra/core/agent-controller'; import type { ComputeStateSignalArgs, ComputeStateSignalResult, ProcessInputArgs, ProcessInputStepArgs, Processor, } from '@mastra/core/processors'; import type { FactoryBoardEngine } from '../board-engine/engine.js'; import { boardFlow, boardForWorkItem, resolveBoardToolRule, reviewsPullRequest, workItemPhaseSemantics, } from '../boards/index.js'; import type { BoardPhaseOutcome, BoardRegistry } from '../boards/index.js'; import { workStageCarries } from '../boards/legacy-plan-role.js'; import { exitToolSucceeded, PHASE_EXIT_METADATA_KEY } from '../boards/phase-automation.js'; import { exitToolOutcome, pendingPhaseOutcome, phaseOutcomes } from '../boards/phase-outcomes.js'; import { toBoardSource } from '../boards/project-boards.js'; import type { ProjectBoardSource } from '../boards/project-boards.js'; import { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js'; import type { FactoryRunBindingRecord, WorkItemsStorage, Card } from '../storage/domains/work-items/base.js'; import { findSessionRunBinding, getFactorySessionCoordinates, getFactoryToolsRole } from './binding-context.js'; import { workItemSource } from './types.js'; import type { FactoryCommitDecision, FactoryRuleDecision, FactoryRuleJsonValue, FactoryRuleStage, FactoryToolResultRuleContext, } from './types.js'; import { assertFactoryDecisionTarget, normalizeFactoryRuleJsonValue, validateFactoryRuleDecisions, } from './validation.js'; const STATE_ID = 'factory-phase'; const RULE_TIMEOUT_MS = 5_000; const TRANSCRIPT_PAGE_SIZE = 50; const MAX_LINKED_ITEMS = 5; // Bindings read at once by a reconcile pass, which yields between them. const RECONCILE_CONCURRENCY = 4; // The full walk of every active binding behind the routine reconcile pass. const FULL_RECONCILE_INTERVAL_MS = 10 * 60_000; const yieldToEventLoop = () => new Promise(resolve => setImmediate(resolve)); function ruleStage(boards: BoardRegistry, item: Card | null | undefined): string | undefined { return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : undefined; } function itemInRuleStage(boards: BoardRegistry, item: Card | null | undefined): item is Card { return ruleStage(boards, item) !== undefined; } type PersistedMessageReader = { listMessages(input: { threadId: string; resourceId?: string; page: number; perPage: number; filter?: { dateRange?: { start?: Date } }; orderBy: { field: 'createdAt'; direction: 'ASC' }; }): Promise<{ messages: MastraDBMessage[]; hasMore: boolean }>; }; type CompletedToolResult = { assistantMessageId: string; messageCreatedAt: Date; toolCallId: string; toolName: string; input: FactoryRuleJsonValue; status: 'success' | 'error'; value: FactoryRuleJsonValue; }; function isApprovedPlanResult(result: CompletedToolResult): boolean { if (result.toolName !== 'submit_plan' || result.status !== 'success') return false; if (typeof result.value === 'string') return result.value.startsWith('Plan approved.'); if (!result.value || typeof result.value !== 'object' || Array.isArray(result.value)) return false; const content = result.value.content; return typeof content === 'string' && content.startsWith('Plan approved.'); } const STAMP_ATTEMPTS = 3; /** When the card's current visit to `stage` began, if it is in `stage` alone. */ function openEntry(item: Card, stage: string): string | undefined { if (item.stages.length !== 1 || item.stages[0] !== stage) return undefined; return item.stageHistory?.findLast(entry => entry.stage === stage && entry.exitedAt === undefined)?.enteredAt; } /** * The phase this result finishes: the card's phase whose exit tool succeeded (for `submit_plan`, * with an approved plan) in the session that works the card there. Undefined otherwise. */ function finishedPhase( boards: BoardRegistry, board: string, item: Card, role: string, toolResult: CompletedToolResult, ): string | undefined { const stage = item.stages.length === 1 ? item.stages[0]! : undefined; const definition = boards.get(board); const phase = stage === undefined ? undefined : definition?.phases[stage]; if (phase?.kind !== 'working' || phase.exitTool?.id !== toolResult.toolName) return undefined; if (toolResult.status !== 'success') return undefined; if (toolResult.toolName === 'submit_plan' && !isApprovedPlanResult(toolResult)) return undefined; // Only the session that works the card in this phase finishes it: one in another context that // still holds the card (a triage session, say) calling the same tool leaves the phase unfinished. // A Work card planned before Planning ran in the `work` context still holds its `plan` session. if (role !== phase.runner.context && workStageCarries(definition, stage!, role, undefined) !== true) { return undefined; } return stage; } type RuntimeSnapshot = { modelId: string; thinkingLevel: ThinkingLevel; }; type ActivePhaseSnapshotBase = { bindingId: string; itemId: string; revision: number; stage: FactoryRuleStage; role: string; configVersion: string; status: 'active'; }; type ActivePhaseSnapshotValue = ActivePhaseSnapshotBase & { board: string; modelId?: string; thinkingLevel?: ThinkingLevel; }; type PhaseSnapshotValue = ActivePhaseSnapshotValue | { bindingId?: string; status: 'none' }; function reviewRuntimeFromRequestContext( requestContext: ComputeStateSignalArgs['requestContext'], defaultThinkingLevel: ThinkingLevel | undefined, ): RuntimeSnapshot { if (!requestContext || typeof requestContext.get !== 'function') { throw new Error('Factory review phase requires a controller request context.'); } const context = requestContext.get<'controller', AgentControllerRequestContext>('controller'); const modelId = context?.session?.modelId.trim(); if (!modelId) { throw new Error('Factory review phase requires a selected session model.'); } return { modelId, thinkingLevel: resolveRequestThinkingLevel({ state: context?.state }, undefined, defaultThinkingLevel), }; } function workItemSourceKey(item: Card): string | null { const source = item.externalSource; return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null; } function boundedError(value: unknown): FactoryRuleJsonValue { const message = value instanceof Error ? value.message : typeof value === 'string' ? value : 'Tool execution failed.'; return { message: message.slice(0, 2_000) }; } function boundedResult(value: unknown): FactoryRuleJsonValue { try { // A result read during the run is the tool's in-memory value (submit_plan's holds undefined // fields); read it as the JSON the thread stores, so it means the same now as after the run. return normalizeFactoryRuleJsonValue(value === undefined ? null : JSON.parse(JSON.stringify(value))); } catch { return { message: 'Tool result was not serializable.' }; } } function messageParts(message: MastraDBMessage): unknown[] { const content = message.content as { parts?: unknown[]; toolInvocations?: unknown[] } | unknown[] | undefined; if (Array.isArray(content)) return content; if (Array.isArray(content?.parts)) return content.parts; return Array.isArray(content?.toolInvocations) ? content.toolInvocations : []; } function completedStepToolCallIds(steps: unknown[]): Set { const ids = new Set(); for (const rawStep of steps) { if (!rawStep || typeof rawStep !== 'object') continue; const toolResults = (rawStep as { toolResults?: unknown[] }).toolResults; if (!Array.isArray(toolResults)) continue; for (const rawResult of toolResults) { if (!rawResult || typeof rawResult !== 'object') continue; const toolCallId = (rawResult as { toolCallId?: unknown }).toolCallId; if (typeof toolCallId === 'string') ids.add(toolCallId); } } return ids; } function* completedInvocations(message: MastraDBMessage): Generator<{ invocation: Record; state: 'result' | 'error'; toolCallId: string; toolName: string; }> { if (message.role !== 'assistant') return; for (const rawPart of messageParts(message)) { if (!rawPart || typeof rawPart !== 'object') continue; const part = rawPart as Record; const invocation = part.type === 'tool-invocation' && part.toolInvocation && typeof part.toolInvocation === 'object' ? (part.toolInvocation as Record) : part; const state = invocation.state; if (state !== 'result' && state !== 'error') continue; const toolCallId = invocation.toolCallId; const toolName = invocation.toolName ?? invocation.name; if (typeof toolCallId !== 'string' || typeof toolName !== 'string') continue; yield { invocation, state, toolCallId, toolName }; } } /** Which tool calls a message holds a result for, without serializing the results. */ function completedToolCallsKey(message: MastraDBMessage): string { const keys: string[] = []; for (const { state, toolCallId } of completedInvocations(message)) keys.push(`${toolCallId}:${state}`); return keys.join('\n'); } function messageTime(message: MastraDBMessage): number { return (message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt)).getTime(); } function completedToolResults(message: MastraDBMessage): CompletedToolResult[] { const createdAt = message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt); const completed: CompletedToolResult[] = []; for (const { invocation, state, toolCallId, toolName } of completedInvocations(message)) { completed.push({ assistantMessageId: message.id, messageCreatedAt: createdAt, toolCallId, toolName: toolName.slice(0, 256), input: boundedResult(invocation.args ?? {}), status: state === 'error' ? 'error' : 'success', value: state === 'error' ? boundedError(invocation.result ?? invocation.error) : boundedResult(invocation.result), }); } return completed; } function currentCompletedToolMessage( messages: MastraDBMessage[], toolCallIds: ReadonlySet, ): MastraDBMessage | undefined { for (let index = messages.length - 1; index >= 0; index -= 1) { const message = messages[index]!; if (completedToolResults(message).some(result => toolCallIds.has(result.toolCallId))) return message; } return undefined; } /** * The tool results the step about to run follows: the latest assistant message, past any signals * after it. A run continued after a tool call (such as submit_plan's approval) carries steps * without their tool results, so the step ids alone can miss the result the agent acts on next. */ function latestToolResultMessage(messages: MastraDBMessage[]): MastraDBMessage | undefined { for (let index = messages.length - 1; index >= 0; index -= 1) { const message = messages[index]!; if ((message.role as string) === 'signal') continue; return message.role === 'assistant' && completedToolResults(message).length > 0 ? message : undefined; } return undefined; } async function phaseCacheKey( value: ActivePhaseSnapshotValue, linked: Card[], outcomes: readonly BoardPhaseOutcome[], ): Promise { const serialized = JSON.stringify({ ...value, linked: linked.map(item => [item.id, item.revision, item.stages[0]]), // A board edit can change a phase's outcomes without writing the card. ...(outcomes.length ? { outcomes: outcomes.map(({ key, label, to }) => [key, label, to]) } : {}), }); return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized))).toString( 'hex', ); } function escapeText(value: string): string { return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); } function phaseFromSignal(signal: { metadata?: Record } | undefined): PhaseSnapshotValue | undefined { return (signal?.metadata?.value as { phase?: PhaseSnapshotValue } | undefined)?.phase; } function latestPhase(args: ComputeStateSignalArgs): PhaseSnapshotValue | undefined { for (const signal of [...args.activeStateSignals].reverse()) { const phase = phaseFromSignal(signal); if (phase) return phase; } return phaseFromSignal(args.lastSnapshot); } async function withRuleTimeout(operation: Promise): Promise { let timer: ReturnType | undefined; try { return await Promise.race([ operation, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS); }), ]); } finally { if (timer) clearTimeout(timer); } } const reportedUnavailableMemorySettings = new WeakSet(); /** * Marks this run's Factory memory settings as unavailable so memory falls back * to auto, and tells the thread once per request that saved choices were not * applied. The reserved request-context key keeps clients from spoofing it. */ export function reportMemorySettingsUnavailable( requestContext: NonNullable, reason: string, ): void { requestContext.set('mastra__factoryMemorySettings', { status: 'unavailable', reason }); console.warn('[Factory Memory Settings] Failed to load settings for run', { error: reason }); if (reportedUnavailableMemorySettings.has(requestContext)) return; reportedUnavailableMemorySettings.add(requestContext); const controller = requestContext.get('controller') as | Pick, 'emitEvent'> | undefined; controller?.emitEvent?.({ type: 'error', error: new Error( 'Memory settings could not be loaded for this run, so observational memory is using Auto models and default thresholds.', ), errorType: 'factory_memory_settings_unavailable', retryable: false, }); } export class FactoryPhaseStateProcessor implements Processor<'factory-phase'> { readonly id = STATE_ID; readonly stateId = STATE_ID; /** Request contexts whose caller row is already resolved for this request. */ private readonly loadedMemorySettings = new WeakSet(); private readonly bindingReconciles = new Map>(); /** * Bindings a step ran on since they were last reconciled, or whose run was still * going then. Only these can have tool results the step hook did not see, so a * routine pass reads only them. `settled` marks one already read after its run * stopped: it gets one trailing read, for results persisted after the run ended. */ private readonly pendingReconciles = new Map(); /** Messages at each binding's cursor time already ingested, by id, with the tool calls they held results for. */ private readonly cursorBoundaries = new Map }>(); private lastFullReconcileAt: number | undefined; private readonly boards: ProjectBoardSource; constructor( private readonly options: { configVersion: string; storage: WorkItemsStorage; boards: BoardRegistry | ProjectBoardSource; loadMemorySettings?: (args: { requestContext: ProcessInputStepArgs['requestContext']; binding: FactoryRunBindingRecord | null; }) => Promise; /** The session's routed thinking default, used when the session has not picked a level. */ defaultThinkingLevel?: (requestContext: ComputeStateSignalArgs['requestContext']) => Promise; /** Called on every step of a run on an active bound thread, so an idle dispatcher reconciles its tool results. */ onBoundThreadRun?: () => void; /** Whether a run is going on this thread in this process; its binding stays due for reconcile until it stops. */ isThreadRunning?: (threadId: string) => boolean; boardEngine?: Pick; messageReader?: PersistedMessageReader; recordPullRequestProvenance?: (input: { binding: FactoryRunBindingRecord; item: Card; assistantMessageId: string; toolCallId: string; toolName: string; toolInput: FactoryRuleJsonValue; toolResult: FactoryRuleJsonValue; status: 'success' | 'error'; }) => Promise; }, ) { this.boards = toBoardSource(options.boards); } /** * Memory settings are caller state, not run state. Factory invokes this while * resolving its configured processor list, before Agent resolves dynamic * Memory and enumerates Memory's processors. This guarantees both the Memory * options and its model callbacks see the authoritative row for this * invocation. Doing this in `processInputStep` would be too late: Memory's * input-step hook runs before configured processors. */ async prepareMemorySettings(requestContext: ProcessInputArgs['requestContext']): Promise { await this.loadCallerMemorySettings(requestContext, undefined, true); } async processInput(args: ProcessInputArgs): Promise { await this.loadCallerMemorySettings(args.requestContext); return args.messageList; } async processInputStep(args: ProcessInputStepArgs): Promise { const address = getFactorySessionCoordinates(args.requestContext); let binding: FactoryRunBindingRecord | null | undefined; try { binding = address ? await this.options.storage.findRunBindingBySession(address) : undefined; } catch { await this.loadCallerMemorySettings(args.requestContext, undefined); return; } // Resumed runs skip the input-processor phase, so re-check here: it is a // no-op once `processInput` already placed the row for this request. Passing // `undefined` (not `null`) keeps the recovery lookup inside the loader, so a // recovered session reaches its project row from this hook too. await this.loadCallerMemorySettings(args.requestContext, binding); if (!binding || binding.status !== 'active') return; this.pendingReconciles.set(binding.id, { binding, settled: false }); this.options.onBoundThreadRun?.(); const completedToolCallIds = completedStepToolCallIds(args.steps); const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds); if (completedMessage) { await this.ingestMessages(binding, [completedMessage], completedToolCallIds); return; } const latest = latestToolResultMessage(args.messages); if (latest) await this.ingestMessages(binding, [latest]); } /** * Loads the caller's row once per invocation. The input hook always refreshes * it in case the controller reused a request context; later step hooks reuse * that value (`undefined` means it has not been loaded yet; `null` means an * empty row). * * The WeakSet covers loaders that do not set the context key themselves, so a * request is still loaded once. A failed load records an unavailable sentinel * (memory then runs both roles on auto with default thresholds) and is not * marked loaded so the next step can retry. */ private async loadCallerMemorySettings( requestContext: ProcessInputStepArgs['requestContext'] | ProcessInputArgs['requestContext'], binding?: FactoryRunBindingRecord | null, force = false, ): Promise { if (!requestContext || !this.options.loadMemorySettings) return; const currentSettings = requestContext.get('mastra__factoryMemorySettings') as | { status?: unknown } | null | undefined; if (force) this.loadedMemorySettings.delete(requestContext); if (!force && currentSettings !== undefined && currentSettings?.status !== 'unavailable') return; if (!force && this.loadedMemorySettings.has(requestContext)) return; try { let runBinding = binding ?? null; if (binding === undefined) { const address = getFactorySessionCoordinates(requestContext); runBinding = address ? await this.options.storage.findRunBindingBySession(address) : // Crash-recovered sessions come back with empty state, so the binding // table is the last source of the project whose row applies. Without // this the run would silently read the caller's personal row. await findSessionRunBinding(requestContext, this.options.storage); } await this.options.loadMemorySettings({ requestContext, binding: runBinding }); this.loadedMemorySettings.add(requestContext); } catch (error) { reportMemorySettingsUnavailable(requestContext, error instanceof Error ? error.message : String(error)); } } async computeStateSignal(args: ComputeStateSignalArgs): Promise { const address = getFactorySessionCoordinates(args.requestContext); if (!address) return; const binding = await this.options.storage.findRunBindingBySession(address); const prior = latestPhase(args); const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot; if (!binding) return; if (binding.status !== 'active') { if (!hasBase || prior?.status !== 'active') return; // Say where the card went, so the session stops its work instead of guessing why its phase vanished. const moved = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }); const movedBoards = moved ? await this.boards.load(binding) : undefined; const movedTo = moved && movedBoards ? ruleStage(movedBoards, moved) : undefined; const movedName = movedTo ? (movedBoards?.get(boardForWorkItem(moved!))?.phases[movedTo]?.name ?? movedTo) : undefined; return { id: STATE_ID, cacheKey: `factory:none:${prior.bindingId ?? 'revoked'}${movedTo ? `:${movedTo}` : ''}`, mode: 'snapshot', tagName: 'factory-phase', contents: movedName ? `This session no longer works its Factory card; the card is now in ${escapeText(movedName)}. Your part is done: do not continue its work here. Answer questions only.\n` : '\n', value: { phase: { status: 'none' } }, attributes: { status: 'none' }, metadata: { value: { phase: { status: 'none' } } }, }; } const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }); const boards = await this.boards.load(binding); const stage = ruleStage(boards, item); if (!item || !stage) return; // A request keeps the role it was built with: see setFactoryToolsRole. const runRole = getFactoryToolsRole(args.requestContext) ?? binding.role; const linked = await this.options.storage.listLinked({ item, limit: MAX_LINKED_ITEMS }); const board = boardForWorkItem(item); const baseValue: ActivePhaseSnapshotBase = { status: 'active', bindingId: binding.id, itemId: item.id, revision: item.revision, stage, role: runRole, configVersion: this.options.configVersion, }; const flow = boardFlow(boards.get(board)); const value: ActivePhaseSnapshotValue = reviewsPullRequest({ flow, item: { source: workItemSource(item.externalSource), workItem: item.workItem }, }) ? { ...baseValue, board, ...reviewRuntimeFromRequestContext( args.requestContext, await this.options.defaultThinkingLevel?.(args.requestContext), ), } : { ...baseValue, board }; const definition = boards.get(board); const phase = definition?.phases[stage]; // Only the session working the card in its phase reports how that phase ended. const works = phase?.kind === 'working' && (phase.runner.context === runRole || workStageCarries(definition, stage, runRole, undefined) === true); const outcomes = definition && works ? phaseOutcomes(definition, stage) : []; const cacheKey = await phaseCacheKey(value, linked, outcomes); if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey) return; const linkedText = linked.length ? `\nLinked items: ${linked.map(candidate => `${workItemSource(candidate.externalSource)} ${candidate.title}`).join('; ')}` : ''; const phaseLabel = phase?.name ?? stage; const nextText = phase ? `Next phases: ${ phase.nextPhases.length ? phase.nextPhases .map(key => `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})`) .join('; ') : 'none' }\n` : ''; const phaseName = (key: string) => escapeText(definition?.phases[key]?.name ?? key); const exitOutcome = definition && phase?.kind === 'working' ? exitToolOutcome(definition, stage) : undefined; const exitText = phase?.kind === 'working' && phase.exitTool ? `This phase ends when ${escapeText(phase.exitTool.id)} succeeds${phase.exitTool.id === 'submit_plan' ? ' with an approved plan' : ''}; until then the card stays here. ${ definition?.tools[phase.exitTool.id] ? 'Its result moves the card on.' : exitOutcome ? `Its success reports ${escapeText(exitOutcome.key)} (${escapeText(exitOutcome.label)}); Factory moves the card to ${phaseName(exitOutcome.to)} once your run ends.` : 'Then report an outcome with factory_report_outcome.' }\n` : ''; const pending = definition && outcomes.length ? pendingPhaseOutcome(definition, item) : undefined; const outcomeText = outcomes.length ? `Outcomes: ${outcomes .map(outcome => `${escapeText(outcome.key)}: ${escapeText(outcome.label)} → ${phaseName(outcome.to)}`) .join('; ')}\n` + "Report one with factory_report_outcome when this phase's work ends. Factory moves the card once your run ends; you never move it yourself.\n" + (pending ? `Reported outcome: ${escapeText(pending.outcome)} (${escapeText(pending.label)}) → ${phaseName(pending.to)}. Report again to change it.\n` : '') : ''; // Skills name phases by role in the pull request loop, never by key: this line maps them. const flowPhase = (key: string | undefined) => key ? `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})` : undefined; const completed = flow.completed?.phase; const canceled = flow.canceled?.phase === completed ? undefined : flow.canceled?.phase; const flowParts = [ definition ? `rest: ${flowPhase(definition.initialPhase)}` : undefined, flow.triage ? `triage: ${flowPhase(flow.triage)}` : undefined, flow.build ? `build: ${flowPhase(flow.build)}` : undefined, flow.selfReview ? `self-review: ${flowPhase(flow.selfReview)}` : undefined, flow.pullRequestReview ? `pull request review: ${flowPhase(flow.pullRequestReview)}` : undefined, completed ? `completed: ${flowPhase(completed)}` : undefined, canceled ? `canceled: ${flowPhase(canceled)}` : undefined, ].filter(part => part !== undefined); const flowText = flowParts.length ? `Board phases by part: ${flowParts.join('; ')}\n` : ''; // The card moved to a phase another context works; this session's tools for it are gone. const handedOnText = phase?.kind === 'working' && phase.runner.context !== runRole && // A Work card planned before Planning ran in `work` keeps its `plan` session there. workStageCarries(definition, stage, runRole, undefined) !== true ? `This card is now in ${escapeText(phaseLabel)}, which runs in the ${escapeText(phase.runner.context)} context in another session. Your part is done: do not continue its work here. Answer questions only.\n` : ''; const runtime = value.modelId && value.thinkingLevel ? { modelId: value.modelId, thinkingLevel: value.thinkingLevel } : null; const snapshotContents = `Factory ${board} phase: ${escapeText(phaseLabel)} (${escapeText(stage)})\n` + `Work item: ${escapeText(item.title)} (${item.id})\n` + `Role: ${escapeText(runRole)}\nRevision: ${item.revision}\nConfig: ${escapeText(this.options.configVersion)}\n` + (runtime ? `Runtime: model=${escapeText(runtime.modelId)}, reasoning-setting=${escapeText(runtime.thinkingLevel)}\n` : '') + (phase?.kind === 'resting' ? `This card rests in ${escapeText(phaseLabel)}: its work is paused. Answer questions; a person moves it on from the Factory board when the work should resume.\n` : '') + nextText + flowText + outcomeText + exitText + handedOnText + escapeText(linkedText).replace(/^\n/, ''); const isDelta = hasBase && prior?.status === 'active'; return { id: STATE_ID, cacheKey, mode: isDelta ? 'delta' : 'snapshot', tagName: 'factory-phase', contents: isDelta ? `Factory phase update:\n${snapshotContents}` : snapshotContents, value: { phase: value }, ...(isDelta ? { delta: { phase: value } } : {}), attributes: { status: 'active', board, stage, role: runRole, revision: item.revision, ...(runtime ?? {}), }, metadata: { value: { phase: value } }, }; } /** * The dispatcher's recurring pass. Tool results reach the card from the step hook; * this catches the ones it cannot see (results persisted after a run's last step, * or while no process was watching). Only bindings a step ran on since the last * pass can have new ones, so a routine pass reads just those. The first pass, and * one every {@link FULL_RECONCILE_INTERVAL_MS}, walks every active binding instead. */ async reconcileBoundThreads(now = Date.now()): Promise { if (!this.options.messageReader) return; if (this.lastFullReconcileAt === undefined || now - this.lastFullReconcileAt >= FULL_RECONCILE_INTERVAL_MS) { await this.reconcileAllBoundThreads(now); return; } const pending = [...this.pendingReconciles.values()]; this.pendingReconciles.clear(); await this.reconcileEntries(pending, true); } /** Walks every active binding: the boot catch-up and the safety net behind {@link reconcileBoundThreads}. */ async reconcileAllBoundThreads(now = Date.now()): Promise { if (!this.options.messageReader) return; const bindings = await this.options.storage.listActiveRunBindings(); this.lastFullReconcileAt = now; const pending = new Map(this.pendingReconciles); this.pendingReconciles.clear(); const active = new Set(bindings.map(binding => binding.id)); for (const id of this.cursorBoundaries.keys()) if (!active.has(id)) this.cursorBoundaries.delete(id); await this.reconcileEntries( bindings.map(binding => ({ binding, settled: pending.get(binding.id)?.settled ?? true })), false, ); } /** * A few bindings at a time, yielding between them: a pass is background work and * must not hold the event loop or the database for the runs it follows. A binding * that fails stays due for the next pass; the first failure is rethrown at the end. */ private async reconcileEntries( entries: Array<{ binding: FactoryRunBindingRecord; settled: boolean }>, refresh: boolean, ): Promise { let next = 0; let failure: { error: unknown } | undefined; const worker = async () => { while (next < entries.length) { const entry = entries[next++]!; try { await this.reconcileEntry(entry, refresh); } catch (error) { failure ??= { error }; if (!this.pendingReconciles.has(entry.binding.id)) this.pendingReconciles.set(entry.binding.id, entry); } await yieldToEventLoop(); } }; await Promise.all(Array.from({ length: Math.min(RECONCILE_CONCURRENCY, entries.length) }, worker)); if (failure) throw failure.error; } private async reconcileEntry( entry: { binding: FactoryRunBindingRecord; settled: boolean }, refresh: boolean, ): Promise { let binding = entry.binding; if (refresh) { // Noted at its last step; the card may have moved on and revoked it since. const current = await this.options.storage.findRunBindingById({ orgId: binding.orgId, factoryProjectId: binding.factoryProjectId, id: binding.id, }); if (current?.status !== 'active') { this.cursorBoundaries.delete(binding.id); return; } binding = current; } // Read before the transcript: a run that stops after this check gets its trailing read next pass. const running = this.options.isThreadRunning?.(binding.threadId) ?? false; await this.reconcileBinding(binding); // A step that ran meanwhile already queued it again. if (this.pendingReconciles.has(binding.id)) return; if (running) this.pendingReconciles.set(binding.id, { binding, settled: false }); else if (!entry.settled) this.pendingReconciles.set(binding.id, { binding, settled: true }); } async reconcileBinding(binding: FactoryRunBindingRecord): Promise { const previous = this.bindingReconciles.get(binding.id); const run = (async () => { if (previous) await previous.catch(() => undefined); await this.reconcileBindingNow(binding); })(); this.bindingReconciles.set(binding.id, run); try { await run; } finally { if (this.bindingReconciles.get(binding.id) === run) this.bindingReconciles.delete(binding.id); } } private async reconcileBindingNow(binding: FactoryRunBindingRecord): Promise { const reader = this.options.messageReader; if (!reader || binding.status !== 'active') return; // One keyed read up front: a binding whose item is gone or no longer in a // single rule stage would ingest nothing, so skip the cursor and message // reads entirely instead of paying them on every walk. const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }); if (!itemInRuleStage(await this.boards.load(binding), item)) { this.cursorBoundaries.delete(binding.id); return; } const cursor = await this.options.storage.getToolResultCursor(binding.orgId, binding.factoryProjectId, binding.id); // The cursor start is inclusive: a message at the cursor time can be rewritten in // place (a suspended tool call that later resumes with its result), and several // messages can share a timestamp. Messages there that were already ingested and // still hold the same results are skipped instead of ingested again every pass. const startAt = cursor ? new Date(cursor.lastMessageCreatedAt).getTime() : undefined; const previous = this.cursorBoundaries.get(binding.id); const ingested = previous && previous.at === startAt ? previous.seen : new Map(); let cursorAt = startAt; let boundary = new Map(); let read = false; let page = 0; while (true) { const result = await reader.listMessages({ threadId: binding.threadId, resourceId: binding.resourceId, page, perPage: TRANSCRIPT_PAGE_SIZE, ...(cursor ? { filter: { dateRange: { start: cursor.lastMessageCreatedAt } } } : {}), orderBy: { field: 'createdAt', direction: 'ASC' }, }); const fresh = result.messages.filter( message => messageTime(message) !== startAt || ingested.get(message.id) !== completedToolCallsKey(message), ); if (fresh.length > 0) await this.ingestMessages(binding, fresh, undefined, item); const last = result.messages.at(-1); if (last) { read = true; const lastAt = messageTime(last); if (lastAt !== cursorAt) { await this.options.storage.advanceToolResultCursor({ bindingId: binding.id, orgId: binding.orgId, factoryProjectId: binding.factoryProjectId, lastMessageCreatedAt: new Date(lastAt), updatedAt: new Date(), }); cursorAt = lastAt; boundary = new Map(); } for (const message of result.messages) { if (messageTime(message) === lastAt) boundary.set(message.id, completedToolCallsKey(message)); } } if (!result.hasMore) break; page += 1; await yieldToEventLoop(); } if (read && cursorAt !== undefined) this.cursorBoundaries.set(binding.id, { at: cursorAt, seen: boundary }); } private async ingestMessages( binding: FactoryRunBindingRecord, messages: MastraDBMessage[], toolCallIds?: ReadonlySet, preloadedItem?: Card, ): Promise { const item = preloadedItem ?? (await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId })); if (!itemInRuleStage(await this.boards.load(binding), item)) return; for (const message of messages) { for (const toolResult of completedToolResults(message)) { if (toolCallIds && !toolCallIds.has(toolResult.toolCallId)) continue; try { await this.options.recordPullRequestProvenance?.({ binding, item, assistantMessageId: toolResult.assistantMessageId, toolCallId: toolResult.toolCallId, toolName: toolResult.toolName, toolInput: toolResult.input, toolResult: toolResult.value, status: toolResult.status, }); } catch { // Provenance is supporting evidence and must not block authoritative rule ingress. } await this.ingestToolResult(binding, item, toolResult); } } } private async ingestToolResult( binding: FactoryRunBindingRecord, loaded: Card, toolResult: CompletedToolResult, ): Promise { let item = loaded; const board = boardForWorkItem(item); const boards = await this.boards.load(binding); const finished = finishedPhase(boards, board, item, binding.role, toolResult); // The exit tool finished the phase: the card may now leave it (the agent moves it). A result // read again later (the step, then the thread) stamps once: the stamp names its tool call. const at = new Date().toISOString(); const stampedCall = (item.metadata?.[PHASE_EXIT_METADATA_KEY] as { toolCallId?: unknown } | undefined)?.toolCallId; if ( finished !== undefined && stampedCall !== toolResult.toolCallId && !exitToolSucceeded(item, finished, toolResult.toolName) ) { const entry = openEntry(item, finished); for (let attempt = 1; ; attempt++) { try { const stamped = await this.options.storage.update({ orgId: binding.orgId, id: item.id, userId: `agent:${binding.id}`, patch: { metadata: { [PHASE_EXIT_METADATA_KEY]: { phase: finished, tool: toolResult.toolName, toolCallId: toolResult.toolCallId, at, }, ...(toolResult.toolName === 'submit_plan' ? { planApprovedAt: at } : {}), }, }, expectedRevision: item.revision, }); if (stamped) item = stamped.item; break; } catch (error) { if (!(error instanceof WorkItemUpdateConflictError)) throw error; // Another write landed first. While the card is still in the same visit to the phase, // the result still finishes it; once the card moved on, it no longer needs finishing. const current = await this.options.storage.get({ orgId: binding.orgId, id: item.id }); if (!current || attempt >= STAMP_ATTEMPTS || openEntry(current, finished) !== entry || entry === undefined) { return; } item = current; } } } const rule = resolveBoardToolRule(boards, board, toolResult.toolName); if (!rule) return; const ingressId = JSON.stringify([ binding.id, binding.threadId, toolResult.assistantMessageId, toolResult.toolCallId, ]); const prior = await this.options.storage.getTransitionResultByIngress( binding.orgId, binding.factoryProjectId, ingressId, ); if (prior) return; const context: FactoryToolResultRuleContext = { tenant: { orgId: binding.orgId, projectId: binding.factoryProjectId }, actor: { type: 'agent', bindingId: binding.id, role: binding.role }, ingress: { type: 'toolResult', id: ingressId }, cause: `Completed ${toolResult.toolName}`, causalChain: [], configVersion: this.options.configVersion, item: { id: item.id, source: workItemSource(item.externalSource), sourceKey: workItemSourceKey(item), parentWorkItemId: item.parentWorkItemId, title: item.title, url: item.externalSource?.url ?? null, stages: item.stages, workItem: item.workItem, acceptedAt: item.acceptedAt, metadata: item.metadata, }, board, itemRevision: item.revision, toolName: toolResult.toolName, threadId: binding.threadId, assistantMessageId: toolResult.assistantMessageId, toolCallId: toolResult.toolCallId, result: { status: toolResult.status, value: toolResult.value }, }; let decision: FactoryRuleDecision | void = undefined; let decisions: FactoryCommitDecision[] = []; let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' }; try { decision = await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))); if (decision?.type === 'reject') { outcome = { status: 'rejected', code: decision.code, reason: decision.reason }; } else if (decision) { const validated = validateFactoryRuleDecisions([decision]); for (const entry of validated) assertFactoryDecisionTarget(entry, boards, board); decisions = validated; } } catch (error) { const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT'; outcome = { status: 'rejected', code: timedOut ? 'timeout' : 'rule_error', reason: timedOut ? 'Factory rule evaluation timed out.' : error instanceof Error ? error.message.slice(0, 2_000) : 'Factory tool-result rule failed.', }; } const committed = await this.options.storage.commitRuleEvaluation({ orgId: binding.orgId, factoryProjectId: binding.factoryProjectId, workItemId: item.id, ingress: { identity: ingressId }, expectedRevision: item.revision, actor: { ...context.actor }, outcome, decisions: decisions.map(entry => ({ ...entry })), causalChain: [], now: new Date(), // The bound agent's own tool call carries the same consent as its governed moves. consentedBy: `agent:${binding.id}`, }); if (committed.status !== 'committed' || !this.options.boardEngine) return; for (const entry of decisions) { if (entry.type !== 'transition') continue; const ingress = { type: 'rule' as const, identity: `decision:${entry.idempotencyKey}` }; const result = await this.options.boardEngine.requestMove({ orgId: binding.orgId, factoryProjectId: binding.factoryProjectId, workItemId: item.id, board: entry.board, stage: entry.stage, ...(entry.reenter ? { reenter: true } : {}), expectedRevision: item.revision, actor: { type: 'system', id: 'factory-tool-result-rule' }, ingress, cause: 'tool_result_rule', causalChain: [{ ingressId, decisionType: entry.type }], ...(isApprovedPlanResult(toolResult) ? { planApproved: true } : {}), ...(toolResult.status === 'success' ? { completedTool: toolResult.toolName } : {}), }); // The dispatcher replays this same decision later. Record the engine's refusal under its // ingress so the replay keeps it instead of asking again without this tool result's context. // A lost revision race is not a refusal and stays unrecorded, like the transition service. if (result.status === 'rejected' && result.code !== 'stale') { await this.options.storage.commitTransition({ orgId: binding.orgId, factoryProjectId: binding.factoryProjectId, workItemId: item.id, expectedRevision: item.revision, destinationStage: entry.stage, actorId: 'factory-tool-result-rule', ingress: { identity: ingress.identity, transitionId: result.transitionId }, causalChain: [{ ingressId, decisionType: entry.type }], evaluation: { outcome: 'rejected', code: result.code, reason: result.reason }, }); } } } }