@mastra/factory 0.24.0-alpha.1 → 0.24.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +80 -4
  2. package/dist/auth.d.ts +8 -0
  3. package/dist/auth.d.ts.map +1 -1
  4. package/dist/auth.js +15 -1
  5. package/dist/auth.js.map +1 -1
  6. package/dist/boards/work-transition-policy.d.ts.map +1 -1
  7. package/dist/boards/work-transition-policy.js +10 -0
  8. package/dist/boards/work-transition-policy.js.map +1 -1
  9. package/dist/boards/work.d.ts +14 -0
  10. package/dist/boards/work.d.ts.map +1 -1
  11. package/dist/boards/work.js +70 -7
  12. package/dist/boards/work.js.map +1 -1
  13. package/dist/capabilities/version-control.d.ts +26 -0
  14. package/dist/capabilities/version-control.d.ts.map +1 -1
  15. package/dist/factory.d.ts.map +1 -1
  16. package/dist/factory.js +173 -11
  17. package/dist/factory.js.map +1 -1
  18. package/dist/integrations/github/integration.d.ts.map +1 -1
  19. package/dist/integrations/github/integration.js +37 -1
  20. package/dist/integrations/github/integration.js.map +1 -1
  21. package/dist/integrations/gitlab/api.d.ts +15 -0
  22. package/dist/integrations/gitlab/api.d.ts.map +1 -1
  23. package/dist/integrations/gitlab/api.js +9 -0
  24. package/dist/integrations/gitlab/api.js.map +1 -1
  25. package/dist/integrations/gitlab/version-control.d.ts.map +1 -1
  26. package/dist/integrations/gitlab/version-control.js +37 -3
  27. package/dist/integrations/gitlab/version-control.js.map +1 -1
  28. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  29. package/dist/integrations/platform/github/integration.js +27 -1
  30. package/dist/integrations/platform/github/integration.js.map +1 -1
  31. package/dist/integrations/subscription-session.d.ts +15 -0
  32. package/dist/integrations/subscription-session.d.ts.map +1 -1
  33. package/dist/integrations/subscription-session.js +30 -13
  34. package/dist/integrations/subscription-session.js.map +1 -1
  35. package/dist/provider-display-name.d.ts +2 -0
  36. package/dist/provider-display-name.d.ts.map +1 -0
  37. package/dist/provider-display-name.js +16 -0
  38. package/dist/provider-display-name.js.map +1 -0
  39. package/dist/routes/config.js +2 -2
  40. package/dist/routes/config.js.map +1 -1
  41. package/dist/routes/contracts.d.ts +4 -0
  42. package/dist/routes/contracts.d.ts.map +1 -1
  43. package/dist/routes/contracts.js +3 -1
  44. package/dist/routes/contracts.js.map +1 -1
  45. package/dist/routes/oauth.js +1 -1
  46. package/dist/routes/oauth.js.map +1 -1
  47. package/dist/routes/provider-credentials.d.ts +6 -2
  48. package/dist/routes/provider-credentials.d.ts.map +1 -1
  49. package/dist/routes/provider-credentials.js +20 -7
  50. package/dist/routes/provider-credentials.js.map +1 -1
  51. package/dist/routes/source-control-sessions.d.ts +1 -0
  52. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  53. package/dist/routes/source-control-sessions.js +1 -1
  54. package/dist/routes/source-control-sessions.js.map +1 -1
  55. package/dist/routes/surface.d.ts +1 -0
  56. package/dist/routes/surface.d.ts.map +1 -1
  57. package/dist/routes/surface.js +1 -0
  58. package/dist/routes/surface.js.map +1 -1
  59. package/dist/routes/work-items.d.ts.map +1 -1
  60. package/dist/routes/work-items.js +57 -117
  61. package/dist/routes/work-items.js.map +1 -1
  62. package/dist/rules/dispatcher.d.ts +7 -0
  63. package/dist/rules/dispatcher.d.ts.map +1 -1
  64. package/dist/rules/dispatcher.js +60 -3
  65. package/dist/rules/dispatcher.js.map +1 -1
  66. package/dist/rules/processor.d.ts.map +1 -1
  67. package/dist/rules/processor.js +2 -1
  68. package/dist/rules/processor.js.map +1 -1
  69. package/dist/rules/tools.d.ts.map +1 -1
  70. package/dist/rules/tools.js +82 -3
  71. package/dist/rules/tools.js.map +1 -1
  72. package/dist/rules/transition-service.d.ts +17 -0
  73. package/dist/rules/transition-service.d.ts.map +1 -1
  74. package/dist/rules/transition-service.js +25 -0
  75. package/dist/rules/transition-service.js.map +1 -1
  76. package/dist/rules/types.d.ts +2 -0
  77. package/dist/rules/types.d.ts.map +1 -1
  78. package/dist/rules/types.js.map +1 -1
  79. package/dist/sandbox/local-factory-sandbox.d.ts.map +1 -1
  80. package/dist/sandbox/local-factory-sandbox.js +1 -0
  81. package/dist/sandbox/local-factory-sandbox.js.map +1 -1
  82. package/dist/session/factory-session.d.ts +15 -1
  83. package/dist/session/factory-session.d.ts.map +1 -1
  84. package/dist/session/factory-session.js +4 -2
  85. package/dist/session/factory-session.js.map +1 -1
  86. package/dist/session/reply-credential-processor.d.ts +15 -0
  87. package/dist/session/reply-credential-processor.d.ts.map +1 -0
  88. package/dist/session/reply-credential-processor.js +40 -0
  89. package/dist/session/reply-credential-processor.js.map +1 -0
  90. package/dist/session/source-control-tools.d.ts +19 -1
  91. package/dist/session/source-control-tools.d.ts.map +1 -1
  92. package/dist/session/source-control-tools.js +70 -3
  93. package/dist/session/source-control-tools.js.map +1 -1
  94. package/dist/storage/domains/projects/base.d.ts +6 -0
  95. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  96. package/dist/storage/domains/projects/base.js +12 -0
  97. package/dist/storage/domains/projects/base.js.map +1 -1
  98. package/dist/storage/domains/source-control/base.d.ts +17 -0
  99. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  100. package/dist/storage/domains/source-control/base.js +23 -0
  101. package/dist/storage/domains/source-control/base.js.map +1 -1
  102. package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
  103. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  104. package/dist/storage/domains/source-control/inmemory.js +5 -1
  105. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  106. package/dist/storage/domains/work-items/base.d.ts +56 -0
  107. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  108. package/dist/storage/domains/work-items/base.js +139 -25
  109. package/dist/storage/domains/work-items/base.js.map +1 -1
  110. package/dist/tools/approval-tools.d.ts +15 -0
  111. package/dist/tools/approval-tools.d.ts.map +1 -0
  112. package/dist/tools/approval-tools.js +77 -0
  113. package/dist/tools/approval-tools.js.map +1 -0
  114. package/dist/tools/deliver.d.ts +54 -0
  115. package/dist/tools/deliver.d.ts.map +1 -0
  116. package/dist/tools/deliver.js +105 -0
  117. package/dist/tools/deliver.js.map +1 -0
  118. package/dist/tools/index.d.ts +29 -0
  119. package/dist/tools/index.d.ts.map +1 -0
  120. package/dist/tools/index.js +39 -0
  121. package/dist/tools/index.js.map +1 -0
  122. package/dist/tools/messaging-tools.d.ts +28 -0
  123. package/dist/tools/messaging-tools.d.ts.map +1 -0
  124. package/dist/tools/messaging-tools.js +312 -0
  125. package/dist/tools/messaging-tools.js.map +1 -0
  126. package/dist/tools/permissions.d.ts +31 -0
  127. package/dist/tools/permissions.d.ts.map +1 -0
  128. package/dist/tools/permissions.js +44 -0
  129. package/dist/tools/permissions.js.map +1 -0
  130. package/dist/tools/read-tools.d.ts +27 -0
  131. package/dist/tools/read-tools.d.ts.map +1 -0
  132. package/dist/tools/read-tools.js +285 -0
  133. package/dist/tools/read-tools.js.map +1 -0
  134. package/dist/tools/reports.d.ts +163 -0
  135. package/dist/tools/reports.d.ts.map +1 -0
  136. package/dist/tools/reports.js +352 -0
  137. package/dist/tools/reports.js.map +1 -0
  138. package/dist/tools/run-watch.d.ts +46 -0
  139. package/dist/tools/run-watch.d.ts.map +1 -0
  140. package/dist/tools/run-watch.js +102 -0
  141. package/dist/tools/run-watch.js.map +1 -0
  142. package/dist/tools/scope.d.ts +45 -0
  143. package/dist/tools/scope.d.ts.map +1 -0
  144. package/dist/tools/scope.js +73 -0
  145. package/dist/tools/scope.js.map +1 -0
  146. package/dist/tools/session-tools.d.ts +31 -0
  147. package/dist/tools/session-tools.d.ts.map +1 -0
  148. package/dist/tools/session-tools.js +312 -0
  149. package/dist/tools/session-tools.js.map +1 -0
  150. package/dist/tools/sessions-state-processor.d.ts +37 -0
  151. package/dist/tools/sessions-state-processor.d.ts.map +1 -0
  152. package/dist/tools/sessions-state-processor.js +206 -0
  153. package/dist/tools/sessions-state-processor.js.map +1 -0
  154. package/dist/tools/work-item-tools.d.ts +28 -0
  155. package/dist/tools/work-item-tools.d.ts.map +1 -0
  156. package/dist/tools/work-item-tools.js +322 -0
  157. package/dist/tools/work-item-tools.js.map +1 -0
  158. package/dist/work-items/create-work-item.d.ts +55 -0
  159. package/dist/work-items/create-work-item.d.ts.map +1 -0
  160. package/dist/work-items/create-work-item.js +101 -0
  161. package/dist/work-items/create-work-item.js.map +1 -0
  162. package/dist/work-items/decision-actions.d.ts +42 -0
  163. package/dist/work-items/decision-actions.d.ts.map +1 -0
  164. package/dist/work-items/decision-actions.js +70 -0
  165. package/dist/work-items/decision-actions.js.map +1 -0
  166. package/dist/workspace.d.ts.map +1 -1
  167. package/dist/workspace.js +3 -1
  168. package/dist/workspace.js.map +1 -1
  169. package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
  170. package/factory-skills/factory-gitlab-review/SKILL.md +1 -1
  171. package/factory-skills/factory-plan/SKILL.md +4 -4
  172. package/factory-skills/factory-rereview/SKILL.md +3 -1
  173. package/factory-skills/factory-review/SKILL.md +3 -1
  174. package/factory-skills/factory-self-review/SKILL.md +46 -0
  175. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"processor.js","names":[],"sources":["../../src/rules/processor.ts"],"sourcesContent":["import { resolveRequestThinkingLevel } from '@mastra/code-sdk/agents/model';\nimport type { ThinkingLevel } from '@mastra/code-sdk/providers/openai-codex';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { MastraDBMessage, MessageList } from '@mastra/core/agent/message-list';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type {\n ComputeStateSignalArgs,\n ComputeStateSignalResult,\n ProcessInputArgs,\n ProcessInputStepArgs,\n Processor,\n} from '@mastra/core/processors';\n\nimport { boardForWorkItem, resolveBoardToolRule, workItemPhaseSemantics } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { FactoryRunBindingRecord, WorkItemsStorage, WorkItemRow } from '../storage/domains/work-items/base.js';\nimport { findSessionRunBinding, getFactorySessionCoordinates } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { workItemSource } from './types.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleStage,\n FactoryToolResultRuleContext,\n} from './types.js';\nimport {\n assertFactoryDecisionTarget,\n normalizeFactoryRuleJsonValue,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst STATE_ID = 'factory-phase';\nconst RULE_TIMEOUT_MS = 5_000;\nconst TRANSCRIPT_PAGE_SIZE = 50;\nconst MAX_LINKED_ITEMS = 5;\nfunction ruleStage(boards: BoardRegistry, item: WorkItemRow | null | undefined): string | undefined {\n return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : undefined;\n}\n\nfunction itemInRuleStage(boards: BoardRegistry, item: WorkItemRow | null | undefined): item is WorkItemRow {\n return ruleStage(boards, item) !== undefined;\n}\n\ntype PersistedMessageReader = {\n listMessages(input: {\n threadId: string;\n resourceId?: string;\n page: number;\n perPage: number;\n filter?: { dateRange?: { start?: Date } };\n orderBy: { field: 'createdAt'; direction: 'ASC' };\n }): Promise<{ messages: MastraDBMessage[]; hasMore: boolean }>;\n};\n\ntype CompletedToolResult = {\n assistantMessageId: string;\n messageCreatedAt: Date;\n toolCallId: string;\n toolName: string;\n input: FactoryRuleJsonValue;\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n};\n\nfunction isApprovedPlanResult(result: CompletedToolResult): boolean {\n if (result.toolName !== 'submit_plan' || result.status !== 'success') return false;\n if (typeof result.value === 'string') return result.value.startsWith('Plan approved.');\n if (!result.value || typeof result.value !== 'object' || Array.isArray(result.value)) return false;\n const content = result.value.content;\n return typeof content === 'string' && content.startsWith('Plan approved.');\n}\n\ntype RuntimeSnapshot = {\n modelId: string;\n thinkingLevel: ThinkingLevel;\n};\n\ntype ActivePhaseSnapshotBase = {\n bindingId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n role: string;\n configVersion: string;\n status: 'active';\n};\n\ntype ActivePhaseSnapshotValue = ActivePhaseSnapshotBase & {\n board: string;\n modelId?: string;\n thinkingLevel?: ThinkingLevel;\n};\n\ntype PhaseSnapshotValue = ActivePhaseSnapshotValue | { bindingId?: string; status: 'none' };\n\nfunction reviewRuntimeFromRequestContext(\n requestContext: ComputeStateSignalArgs['requestContext'],\n factoryThinkingLevel: ThinkingLevel | undefined,\n): RuntimeSnapshot {\n if (!requestContext || typeof requestContext.get !== 'function') {\n throw new Error('Factory review phase requires a controller request context.');\n }\n const context = requestContext.get<'controller', AgentControllerRequestContext<MastraCodeState>>('controller');\n const modelId = context?.session?.modelId.trim();\n if (!modelId) {\n throw new Error('Factory review phase requires a selected session model.');\n }\n return {\n modelId,\n thinkingLevel: resolveRequestThinkingLevel({ state: context?.state }, undefined, factoryThinkingLevel),\n };\n}\n\nfunction workItemSourceKey(item: WorkItemRow): string | null {\n const source = item.externalSource;\n return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;\n}\n\nfunction boundedError(value: unknown): FactoryRuleJsonValue {\n const message = value instanceof Error ? value.message : typeof value === 'string' ? value : 'Tool execution failed.';\n return { message: message.slice(0, 2_000) };\n}\n\nfunction boundedResult(value: unknown): FactoryRuleJsonValue {\n try {\n return normalizeFactoryRuleJsonValue(value);\n } catch {\n return { message: 'Tool result was not serializable.' };\n }\n}\n\nfunction messageParts(message: MastraDBMessage): unknown[] {\n const content = message.content as { parts?: unknown[]; toolInvocations?: unknown[] } | unknown[] | undefined;\n if (Array.isArray(content)) return content;\n if (Array.isArray(content?.parts)) return content.parts;\n return Array.isArray(content?.toolInvocations) ? content.toolInvocations : [];\n}\n\nfunction completedStepToolCallIds(steps: unknown[]): Set<string> {\n const ids = new Set<string>();\n for (const rawStep of steps) {\n if (!rawStep || typeof rawStep !== 'object') continue;\n const toolResults = (rawStep as { toolResults?: unknown[] }).toolResults;\n if (!Array.isArray(toolResults)) continue;\n for (const rawResult of toolResults) {\n if (!rawResult || typeof rawResult !== 'object') continue;\n const toolCallId = (rawResult as { toolCallId?: unknown }).toolCallId;\n if (typeof toolCallId === 'string') ids.add(toolCallId);\n }\n }\n return ids;\n}\n\nfunction completedToolResults(message: MastraDBMessage): CompletedToolResult[] {\n if (message.role !== 'assistant') return [];\n const createdAt = message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt);\n const completed: CompletedToolResult[] = [];\n for (const rawPart of messageParts(message)) {\n if (!rawPart || typeof rawPart !== 'object') continue;\n const part = rawPart as Record<string, unknown>;\n const invocation =\n part.type === 'tool-invocation' && part.toolInvocation && typeof part.toolInvocation === 'object'\n ? (part.toolInvocation as Record<string, unknown>)\n : part;\n const state = invocation.state;\n if (state !== 'result' && state !== 'error') continue;\n const toolCallId = invocation.toolCallId;\n const toolName = invocation.toolName ?? invocation.name;\n if (typeof toolCallId !== 'string' || typeof toolName !== 'string') continue;\n completed.push({\n assistantMessageId: message.id,\n messageCreatedAt: createdAt,\n toolCallId,\n toolName: toolName.slice(0, 256),\n input: boundedResult(invocation.args ?? {}),\n status: state === 'error' ? 'error' : 'success',\n value: state === 'error' ? boundedError(invocation.result ?? invocation.error) : boundedResult(invocation.result),\n });\n }\n return completed;\n}\n\nfunction currentCompletedToolMessage(\n messages: MastraDBMessage[],\n toolCallIds: ReadonlySet<string>,\n): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if (completedToolResults(message).some(result => toolCallIds.has(result.toolCallId))) return message;\n }\n return undefined;\n}\n\nasync function phaseCacheKey(value: ActivePhaseSnapshotValue, linked: WorkItemRow[]): Promise<string> {\n const serialized = JSON.stringify({\n ...value,\n linked: linked.map(item => [item.id, item.revision, item.stages[0]]),\n });\n return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized))).toString(\n 'hex',\n );\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');\n}\n\nfunction phaseFromSignal(signal: { metadata?: Record<string, unknown> } | undefined): PhaseSnapshotValue | undefined {\n return (signal?.metadata?.value as { phase?: PhaseSnapshotValue } | undefined)?.phase;\n}\n\nfunction latestPhase(args: ComputeStateSignalArgs): PhaseSnapshotValue | undefined {\n for (const signal of [...args.activeStateSignals].reverse()) {\n const phase = phaseFromSignal(signal);\n if (phase) return phase;\n }\n return phaseFromSignal(args.lastSnapshot);\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nconst reportedUnavailableMemorySettings = new WeakSet<object>();\n\n/**\n * Marks this run's Factory memory settings as unavailable so memory falls back\n * to auto, and tells the thread once per request that saved choices were not\n * applied. The reserved request-context key keeps clients from spoofing it.\n */\nexport function reportMemorySettingsUnavailable(\n requestContext: NonNullable<ProcessInputArgs['requestContext']>,\n reason: string,\n): void {\n requestContext.set('mastra__factoryMemorySettings', { status: 'unavailable', reason });\n console.warn('[Factory Memory Settings] Failed to load settings for run', { error: reason });\n if (reportedUnavailableMemorySettings.has(requestContext)) return;\n reportedUnavailableMemorySettings.add(requestContext);\n const controller = requestContext.get('controller') as\n | Pick<AgentControllerRequestContext<MastraCodeState>, 'emitEvent'>\n | undefined;\n controller?.emitEvent?.({\n type: 'error',\n error: new Error(\n 'Memory settings could not be loaded for this run, so observational memory is using Auto models and default thresholds.',\n ),\n errorType: 'factory_memory_settings_unavailable',\n retryable: false,\n });\n}\n\nexport class FactoryPhaseStateProcessor implements Processor<'factory-phase'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n /** Request contexts whose caller row is already resolved for this request. */\n private readonly loadedMemorySettings = new WeakSet<object>();\n\n constructor(\n private readonly options: {\n configVersion: string;\n storage: WorkItemsStorage;\n boards: BoardRegistry;\n loadMemorySettings?: (args: {\n requestContext: ProcessInputStepArgs['requestContext'];\n binding: FactoryRunBindingRecord | null;\n }) => Promise<void>;\n /** The Factory's stored thinking default, used when the session has not picked a level. */\n factoryThinkingLevel?: (factoryProjectId: string) => Promise<ThinkingLevel>;\n transitionService?: Pick<FactoryTransitionService, 'transition'>;\n messageReader?: PersistedMessageReader;\n recordPullRequestProvenance?: (input: {\n binding: FactoryRunBindingRecord;\n item: WorkItemRow;\n assistantMessageId: string;\n toolCallId: string;\n toolName: string;\n toolInput: FactoryRuleJsonValue;\n toolResult: FactoryRuleJsonValue;\n status: 'success' | 'error';\n }) => Promise<void>;\n },\n ) {}\n\n /**\n * Memory settings are caller state, not run state. Factory invokes this while\n * resolving its configured processor list, before Agent resolves dynamic\n * Memory and enumerates Memory's processors. This guarantees both the Memory\n * options and its model callbacks see the authoritative row for this\n * invocation. Doing this in `processInputStep` would be too late: Memory's\n * input-step hook runs before configured processors.\n */\n async prepareMemorySettings(requestContext: ProcessInputArgs['requestContext']): Promise<void> {\n await this.loadCallerMemorySettings(requestContext, undefined, true);\n }\n\n async processInput(args: ProcessInputArgs): Promise<MessageList> {\n await this.loadCallerMemorySettings(args.requestContext);\n return args.messageList;\n }\n\n async processInputStep(args: ProcessInputStepArgs): Promise<MessageList | undefined> {\n const address = getFactorySessionCoordinates(args.requestContext);\n let binding: FactoryRunBindingRecord | null | undefined;\n try {\n binding = address ? await this.options.storage.findRunBindingBySession(address) : undefined;\n } catch {\n await this.loadCallerMemorySettings(args.requestContext, undefined);\n return;\n }\n // Resumed runs skip the input-processor phase, so re-check here: it is a\n // no-op once `processInput` already placed the row for this request. Passing\n // `undefined` (not `null`) keeps the recovery lookup inside the loader, so a\n // recovered session reaches its project row from this hook too.\n await this.loadCallerMemorySettings(args.requestContext, binding);\n if (!binding || binding.status !== 'active') return;\n const completedToolCallIds = completedStepToolCallIds(args.steps);\n const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);\n if (completedMessage) {\n await this.ingestMessages(binding, [completedMessage], completedToolCallIds);\n }\n }\n\n /**\n * Loads the caller's row once per invocation. The input hook always refreshes\n * it in case the controller reused a request context; later step hooks reuse\n * that value (`undefined` means it has not been loaded yet; `null` means an\n * empty row).\n *\n * The WeakSet covers loaders that do not set the context key themselves, so a\n * request is still loaded once. A failed load records an unavailable sentinel\n * (memory then runs both roles on auto with default thresholds) and is not\n * marked loaded so the next step can retry.\n */\n private async loadCallerMemorySettings(\n requestContext: ProcessInputStepArgs['requestContext'] | ProcessInputArgs['requestContext'],\n binding?: FactoryRunBindingRecord | null,\n force = false,\n ): Promise<void> {\n if (!requestContext || !this.options.loadMemorySettings) return;\n const currentSettings = requestContext.get('mastra__factoryMemorySettings') as\n | { status?: unknown }\n | null\n | undefined;\n if (force) this.loadedMemorySettings.delete(requestContext);\n if (!force && currentSettings !== undefined && currentSettings?.status !== 'unavailable') return;\n if (!force && this.loadedMemorySettings.has(requestContext)) return;\n try {\n let runBinding = binding ?? null;\n if (binding === undefined) {\n const address = getFactorySessionCoordinates(requestContext);\n runBinding = address\n ? await this.options.storage.findRunBindingBySession(address)\n : // Crash-recovered sessions come back with empty state, so the binding\n // table is the last source of the project whose row applies. Without\n // this the run would silently read the caller's personal row.\n await findSessionRunBinding(requestContext, this.options.storage);\n }\n await this.options.loadMemorySettings({ requestContext, binding: runBinding });\n this.loadedMemorySettings.add(requestContext);\n } catch (error) {\n reportMemorySettingsUnavailable(requestContext, error instanceof Error ? error.message : String(error));\n }\n }\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const address = getFactorySessionCoordinates(args.requestContext);\n if (!address) return;\n const binding = await this.options.storage.findRunBindingBySession(address);\n const prior = latestPhase(args);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n\n if (!binding) return;\n if (binding.status !== 'active') {\n if (!hasBase || prior?.status !== 'active') return;\n return {\n id: STATE_ID,\n cacheKey: `factory:none:${prior.bindingId ?? 'revoked'}`,\n mode: 'snapshot',\n tagName: 'factory-phase',\n contents: '\\n',\n value: { phase: { status: 'none' } },\n attributes: { status: 'none' },\n metadata: { value: { phase: { status: 'none' } } },\n };\n }\n\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const stage = ruleStage(this.options.boards, item);\n if (!item || !stage) return;\n const allItems = await this.options.storage.list({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n });\n const linked = allItems\n .filter(candidate => candidate.parentWorkItemId === item.id || item.parentWorkItemId === candidate.id)\n .slice(0, MAX_LINKED_ITEMS);\n const board = boardForWorkItem(item);\n const baseValue: ActivePhaseSnapshotBase = {\n status: 'active',\n bindingId: binding.id,\n itemId: item.id,\n revision: item.revision,\n stage,\n role: binding.role,\n configVersion: this.options.configVersion,\n };\n const value: ActivePhaseSnapshotValue =\n board === 'review'\n ? {\n ...baseValue,\n board,\n ...reviewRuntimeFromRequestContext(\n args.requestContext,\n await this.options.factoryThinkingLevel?.(binding.factoryProjectId),\n ),\n }\n : { ...baseValue, board };\n const cacheKey = await phaseCacheKey(value, linked);\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n\n const linkedText = linked.length\n ? `\\nLinked items: ${linked.map(candidate => `${workItemSource(candidate.externalSource)} ${candidate.title}`).join('; ')}`\n : '';\n const phaseLabel = this.options.boards.get(board)?.phases[stage]?.title ?? stage;\n const runtime =\n value.modelId && value.thinkingLevel ? { modelId: value.modelId, thinkingLevel: value.thinkingLevel } : null;\n const snapshotContents =\n `Factory ${board} phase: ${escapeText(phaseLabel)} (${escapeText(stage)})\\n` +\n `Work item: ${escapeText(item.title)} (${item.id})\\n` +\n `Role: ${escapeText(binding.role)}\\nRevision: ${item.revision}\\nConfig: ${escapeText(this.options.configVersion)}\\n` +\n (runtime\n ? `Runtime: model=${escapeText(runtime.modelId)}, reasoning-setting=${escapeText(runtime.thinkingLevel)}\\n`\n : '') +\n ((board === 'work' || board === 'review') && stage === 'intake'\n ? 'This card rests in Intake: its work is paused. Answer questions without moving it; when the user asks to resume, request the transition into the working stage first, then continue the work in this session.\\n'\n : '') +\n `Use factory_transition_work_item with expectedRevision ${item.revision} to request a phase change.${escapeText(linkedText)}`;\n const isDelta = hasBase && prior?.status === 'active';\n return {\n id: STATE_ID,\n cacheKey,\n mode: isDelta ? 'delta' : 'snapshot',\n tagName: 'factory-phase',\n contents: isDelta ? `Factory phase update:\\n${snapshotContents}` : snapshotContents,\n value: { phase: value },\n ...(isDelta ? { delta: { phase: value } } : {}),\n attributes: {\n status: 'active',\n board,\n stage,\n role: binding.role,\n revision: item.revision,\n ...(runtime ?? {}),\n },\n metadata: { value: { phase: value } },\n };\n }\n\n async reconcileAllBoundThreads(): Promise<void> {\n if (!this.options.messageReader) return;\n const bindings = await this.options.storage.listActiveRunBindings();\n for (const binding of bindings) await this.reconcileBinding(binding);\n }\n\n async reconcileBinding(binding: FactoryRunBindingRecord): Promise<void> {\n const reader = this.options.messageReader;\n if (!reader || binding.status !== 'active') return;\n // One keyed read up front: a binding whose item is gone or no longer in a\n // single rule stage would ingest nothing, so skip the cursor and message\n // reads entirely instead of paying them on every walk.\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!itemInRuleStage(this.options.boards, item)) return;\n const cursor = await this.options.storage.getToolResultCursor(binding.orgId, binding.factoryProjectId, binding.id);\n let page = 0;\n while (true) {\n const result = await reader.listMessages({\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n page,\n perPage: TRANSCRIPT_PAGE_SIZE,\n ...(cursor ? { filter: { dateRange: { start: cursor.lastMessageCreatedAt } } } : {}),\n orderBy: { field: 'createdAt', direction: 'ASC' },\n });\n await this.ingestMessages(binding, result.messages, undefined, item);\n const last = result.messages.at(-1);\n if (last) {\n await this.options.storage.advanceToolResultCursor({\n bindingId: binding.id,\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n lastMessageId: last.id,\n lastMessageCreatedAt: last.createdAt instanceof Date ? last.createdAt : new Date(last.createdAt),\n updatedAt: new Date(),\n });\n }\n if (!result.hasMore) break;\n page += 1;\n }\n }\n\n private async ingestMessages(\n binding: FactoryRunBindingRecord,\n messages: MastraDBMessage[],\n toolCallIds?: ReadonlySet<string>,\n preloadedItem?: WorkItemRow,\n ): Promise<void> {\n const item = preloadedItem ?? (await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }));\n if (!itemInRuleStage(this.options.boards, item)) return;\n for (const message of messages) {\n for (const toolResult of completedToolResults(message)) {\n if (toolCallIds && !toolCallIds.has(toolResult.toolCallId)) continue;\n try {\n await this.options.recordPullRequestProvenance?.({\n binding,\n item,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n toolInput: toolResult.input,\n toolResult: toolResult.value,\n status: toolResult.status,\n });\n } catch {\n // Provenance is supporting evidence and must not block authoritative rule ingress.\n }\n await this.ingestToolResult(binding, item, toolResult);\n }\n }\n }\n\n private async ingestToolResult(\n binding: FactoryRunBindingRecord,\n item: WorkItemRow,\n toolResult: CompletedToolResult,\n ): Promise<void> {\n const board = boardForWorkItem(item);\n const rule = resolveBoardToolRule(this.options.boards, board, toolResult.toolName);\n if (!rule) return;\n const ingressId = JSON.stringify([\n binding.id,\n binding.threadId,\n toolResult.assistantMessageId,\n toolResult.toolCallId,\n ]);\n const prior = await this.options.storage.getTransitionResultByIngress(\n binding.orgId,\n binding.factoryProjectId,\n ingressId,\n );\n if (prior) return;\n const context: FactoryToolResultRuleContext = {\n tenant: { orgId: binding.orgId, projectId: binding.factoryProjectId },\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'toolResult', id: ingressId },\n cause: `Completed ${toolResult.toolName}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n item: {\n id: item.id,\n source: workItemSource(item.externalSource),\n sourceKey: workItemSourceKey(item),\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: item.stages,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board,\n itemRevision: item.revision,\n toolName: toolResult.toolName,\n threadId: binding.threadId,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n result: { status: toolResult.status, value: toolResult.value },\n };\n\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: FactoryCommitDecision[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = await withRuleTimeout(Promise.resolve(rule(Object.freeze(context))));\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n const validated = validateFactoryRuleDecisions([decision]);\n for (const entry of validated) assertFactoryDecisionTarget(entry, this.options.boards, board);\n decisions = validated;\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory tool-result rule failed.',\n };\n }\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: ingressId, triggerType: 'tool.result' },\n configVersion: this.options.configVersion,\n expectedRevision: item.revision,\n actor: { ...context.actor },\n outcome,\n decisions: decisions.map(entry => ({ ...entry })),\n causalChain: [],\n now: new Date(),\n });\n if (committed.status !== 'committed' || !this.options.transitionService) return;\n for (const entry of decisions) {\n if (entry.type !== 'transition') continue;\n await this.options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n board: entry.board,\n stage: entry.stage,\n expectedRevision: item.revision,\n actor: { type: 'system', id: 'factory-tool-result-rule' },\n ingress: { type: 'rule', identity: `decision:${entry.idempotencyKey}` },\n cause: 'tool_result_rule',\n causalChain: [{ ingressId, decisionType: entry.type }],\n ...(isApprovedPlanResult(toolResult) ? { planApproved: true } : {}),\n });\n }\n }\n}\n"],"mappings":";;;;;;;AAgCA,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,SAAS,UAAU,QAAuB,MAA0D;CAClG,OAAO,QAAQ,uBAAuB,QAAQ,IAAI,IAAI,KAAK,OAAO,KAAK,KAAA;AACzE;AAEA,SAAS,gBAAgB,QAAuB,MAA2D;CACzG,OAAO,UAAU,QAAQ,IAAI,MAAM,KAAA;AACrC;AAuBA,SAAS,qBAAqB,QAAsC;CAClE,IAAI,OAAO,aAAa,iBAAiB,OAAO,WAAW,WAAW,OAAO;CAC7E,IAAI,OAAO,OAAO,UAAU,UAAU,OAAO,OAAO,MAAM,WAAW,gBAAgB;CACrF,IAAI,CAAC,OAAO,SAAS,OAAO,OAAO,UAAU,YAAY,MAAM,QAAQ,OAAO,KAAK,GAAG,OAAO;CAC7F,MAAM,UAAU,OAAO,MAAM;CAC7B,OAAO,OAAO,YAAY,YAAY,QAAQ,WAAW,gBAAgB;AAC3E;AAyBA,SAAS,gCACP,gBACA,sBACiB;CACjB,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YACnD,MAAM,IAAI,MAAM,6DAA6D;CAE/E,MAAM,UAAU,eAAe,IAAkE,YAAY;CAC7G,MAAM,UAAU,SAAS,SAAS,QAAQ,KAAK;CAC/C,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;EACL;EACA,eAAe,4BAA4B,EAAE,OAAO,SAAS,MAAM,GAAG,KAAA,GAAW,oBAAoB;CACvG;AACF;AAEA,SAAS,kBAAkB,MAAkC;CAC3D,MAAM,SAAS,KAAK;CACpB,OAAO,SAAS,GAAG,OAAO,cAAc,GAAG,OAAO,KAAK,GAAG,O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AChB,CAAC,EAAA,CACa,WAAW,eAAe,CAAC,KAAK,QAAQ,mBAAmB;EACzE,KAAK,MAAM,SAAS,WAAW;GAC7B,IAAI,MAAM,SAAS,cAAc;GACjC,MAAM,KAAK,QAAQ,kBAAkB,WAAW;IAC9C,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B,YAAY,KAAK;IACjB,OAAO,MAAM;IACb,OAAO,MAAM;IACb,kBAAkB,KAAK;IACvB,OAAO;KAAE,MAAM;KAAU,IAAI;IAA2B;IACxD,SAAS;KAAE,MAAM;KAAQ,UAAU,YAAY,MAAM;IAAiB;IACtE,OAAO;IACP,aAAa,CAAC;KAAE;KAAW,cAAc,MAAM;IAAK,CAAC;IACrD,GAAI,qBAAqB,UAAU,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;GACnE,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"processor.js","names":[],"sources":["../../src/rules/processor.ts"],"sourcesContent":["import { resolveRequestThinkingLevel } from '@mastra/code-sdk/agents/model';\nimport type { ThinkingLevel } from '@mastra/code-sdk/providers/openai-codex';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { MastraDBMessage, MessageList } from '@mastra/core/agent/message-list';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type {\n ComputeStateSignalArgs,\n ComputeStateSignalResult,\n ProcessInputArgs,\n ProcessInputStepArgs,\n Processor,\n} from '@mastra/core/processors';\n\nimport { boardForWorkItem, resolveBoardToolRule, workItemPhaseSemantics } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { FactoryRunBindingRecord, WorkItemsStorage, WorkItemRow } from '../storage/domains/work-items/base.js';\nimport { findSessionRunBinding, getFactorySessionCoordinates } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { workItemSource } from './types.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleStage,\n FactoryToolResultRuleContext,\n} from './types.js';\nimport {\n assertFactoryDecisionTarget,\n normalizeFactoryRuleJsonValue,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst STATE_ID = 'factory-phase';\nconst RULE_TIMEOUT_MS = 5_000;\nconst TRANSCRIPT_PAGE_SIZE = 50;\nconst MAX_LINKED_ITEMS = 5;\nfunction ruleStage(boards: BoardRegistry, item: WorkItemRow | null | undefined): string | undefined {\n return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : undefined;\n}\n\nfunction itemInRuleStage(boards: BoardRegistry, item: WorkItemRow | null | undefined): item is WorkItemRow {\n return ruleStage(boards, item) !== undefined;\n}\n\ntype PersistedMessageReader = {\n listMessages(input: {\n threadId: string;\n resourceId?: string;\n page: number;\n perPage: number;\n filter?: { dateRange?: { start?: Date } };\n orderBy: { field: 'createdAt'; direction: 'ASC' };\n }): Promise<{ messages: MastraDBMessage[]; hasMore: boolean }>;\n};\n\ntype CompletedToolResult = {\n assistantMessageId: string;\n messageCreatedAt: Date;\n toolCallId: string;\n toolName: string;\n input: FactoryRuleJsonValue;\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n};\n\nfunction isApprovedPlanResult(result: CompletedToolResult): boolean {\n if (result.toolName !== 'submit_plan' || result.status !== 'success') return false;\n if (typeof result.value === 'string') return result.value.startsWith('Plan approved.');\n if (!result.value || typeof result.value !== 'object' || Array.isArray(result.value)) return false;\n const content = result.value.content;\n return typeof content === 'string' && content.startsWith('Plan approved.');\n}\n\ntype RuntimeSnapshot = {\n modelId: string;\n thinkingLevel: ThinkingLevel;\n};\n\ntype ActivePhaseSnapshotBase = {\n bindingId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n role: string;\n configVersion: string;\n status: 'active';\n};\n\ntype ActivePhaseSnapshotValue = ActivePhaseSnapshotBase & {\n board: string;\n modelId?: string;\n thinkingLevel?: ThinkingLevel;\n};\n\ntype PhaseSnapshotValue = ActivePhaseSnapshotValue | { bindingId?: string; status: 'none' };\n\nfunction reviewRuntimeFromRequestContext(\n requestContext: ComputeStateSignalArgs['requestContext'],\n factoryThinkingLevel: ThinkingLevel | undefined,\n): RuntimeSnapshot {\n if (!requestContext || typeof requestContext.get !== 'function') {\n throw new Error('Factory review phase requires a controller request context.');\n }\n const context = requestContext.get<'controller', AgentControllerRequestContext<MastraCodeState>>('controller');\n const modelId = context?.session?.modelId.trim();\n if (!modelId) {\n throw new Error('Factory review phase requires a selected session model.');\n }\n return {\n modelId,\n thinkingLevel: resolveRequestThinkingLevel({ state: context?.state }, undefined, factoryThinkingLevel),\n };\n}\n\nfunction workItemSourceKey(item: WorkItemRow): string | null {\n const source = item.externalSource;\n return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;\n}\n\nfunction boundedError(value: unknown): FactoryRuleJsonValue {\n const message = value instanceof Error ? value.message : typeof value === 'string' ? value : 'Tool execution failed.';\n return { message: message.slice(0, 2_000) };\n}\n\nfunction boundedResult(value: unknown): FactoryRuleJsonValue {\n try {\n return normalizeFactoryRuleJsonValue(value);\n } catch {\n return { message: 'Tool result was not serializable.' };\n }\n}\n\nfunction messageParts(message: MastraDBMessage): unknown[] {\n const content = message.content as { parts?: unknown[]; toolInvocations?: unknown[] } | unknown[] | undefined;\n if (Array.isArray(content)) return content;\n if (Array.isArray(content?.parts)) return content.parts;\n return Array.isArray(content?.toolInvocations) ? content.toolInvocations : [];\n}\n\nfunction completedStepToolCallIds(steps: unknown[]): Set<string> {\n const ids = new Set<string>();\n for (const rawStep of steps) {\n if (!rawStep || typeof rawStep !== 'object') continue;\n const toolResults = (rawStep as { toolResults?: unknown[] }).toolResults;\n if (!Array.isArray(toolResults)) continue;\n for (const rawResult of toolResults) {\n if (!rawResult || typeof rawResult !== 'object') continue;\n const toolCallId = (rawResult as { toolCallId?: unknown }).toolCallId;\n if (typeof toolCallId === 'string') ids.add(toolCallId);\n }\n }\n return ids;\n}\n\nfunction completedToolResults(message: MastraDBMessage): CompletedToolResult[] {\n if (message.role !== 'assistant') return [];\n const createdAt = message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt);\n const completed: CompletedToolResult[] = [];\n for (const rawPart of messageParts(message)) {\n if (!rawPart || typeof rawPart !== 'object') continue;\n const part = rawPart as Record<string, unknown>;\n const invocation =\n part.type === 'tool-invocation' && part.toolInvocation && typeof part.toolInvocation === 'object'\n ? (part.toolInvocation as Record<string, unknown>)\n : part;\n const state = invocation.state;\n if (state !== 'result' && state !== 'error') continue;\n const toolCallId = invocation.toolCallId;\n const toolName = invocation.toolName ?? invocation.name;\n if (typeof toolCallId !== 'string' || typeof toolName !== 'string') continue;\n completed.push({\n assistantMessageId: message.id,\n messageCreatedAt: createdAt,\n toolCallId,\n toolName: toolName.slice(0, 256),\n input: boundedResult(invocation.args ?? {}),\n status: state === 'error' ? 'error' : 'success',\n value: state === 'error' ? boundedError(invocation.result ?? invocation.error) : boundedResult(invocation.result),\n });\n }\n return completed;\n}\n\nfunction currentCompletedToolMessage(\n messages: MastraDBMessage[],\n toolCallIds: ReadonlySet<string>,\n): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if (completedToolResults(message).some(result => toolCallIds.has(result.toolCallId))) return message;\n }\n return undefined;\n}\n\nasync function phaseCacheKey(value: ActivePhaseSnapshotValue, linked: WorkItemRow[]): Promise<string> {\n const serialized = JSON.stringify({\n ...value,\n linked: linked.map(item => [item.id, item.revision, item.stages[0]]),\n });\n return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized))).toString(\n 'hex',\n );\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');\n}\n\nfunction phaseFromSignal(signal: { metadata?: Record<string, unknown> } | undefined): PhaseSnapshotValue | undefined {\n return (signal?.metadata?.value as { phase?: PhaseSnapshotValue } | undefined)?.phase;\n}\n\nfunction latestPhase(args: ComputeStateSignalArgs): PhaseSnapshotValue | undefined {\n for (const signal of [...args.activeStateSignals].reverse()) {\n const phase = phaseFromSignal(signal);\n if (phase) return phase;\n }\n return phaseFromSignal(args.lastSnapshot);\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nconst reportedUnavailableMemorySettings = new WeakSet<object>();\n\n/**\n * Marks this run's Factory memory settings as unavailable so memory falls back\n * to auto, and tells the thread once per request that saved choices were not\n * applied. The reserved request-context key keeps clients from spoofing it.\n */\nexport function reportMemorySettingsUnavailable(\n requestContext: NonNullable<ProcessInputArgs['requestContext']>,\n reason: string,\n): void {\n requestContext.set('mastra__factoryMemorySettings', { status: 'unavailable', reason });\n console.warn('[Factory Memory Settings] Failed to load settings for run', { error: reason });\n if (reportedUnavailableMemorySettings.has(requestContext)) return;\n reportedUnavailableMemorySettings.add(requestContext);\n const controller = requestContext.get('controller') as\n | Pick<AgentControllerRequestContext<MastraCodeState>, 'emitEvent'>\n | undefined;\n controller?.emitEvent?.({\n type: 'error',\n error: new Error(\n 'Memory settings could not be loaded for this run, so observational memory is using Auto models and default thresholds.',\n ),\n errorType: 'factory_memory_settings_unavailable',\n retryable: false,\n });\n}\n\nexport class FactoryPhaseStateProcessor implements Processor<'factory-phase'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n /** Request contexts whose caller row is already resolved for this request. */\n private readonly loadedMemorySettings = new WeakSet<object>();\n\n constructor(\n private readonly options: {\n configVersion: string;\n storage: WorkItemsStorage;\n boards: BoardRegistry;\n loadMemorySettings?: (args: {\n requestContext: ProcessInputStepArgs['requestContext'];\n binding: FactoryRunBindingRecord | null;\n }) => Promise<void>;\n /** The Factory's stored thinking default, used when the session has not picked a level. */\n factoryThinkingLevel?: (factoryProjectId: string) => Promise<ThinkingLevel>;\n transitionService?: Pick<FactoryTransitionService, 'transition'>;\n messageReader?: PersistedMessageReader;\n recordPullRequestProvenance?: (input: {\n binding: FactoryRunBindingRecord;\n item: WorkItemRow;\n assistantMessageId: string;\n toolCallId: string;\n toolName: string;\n toolInput: FactoryRuleJsonValue;\n toolResult: FactoryRuleJsonValue;\n status: 'success' | 'error';\n }) => Promise<void>;\n },\n ) {}\n\n /**\n * Memory settings are caller state, not run state. Factory invokes this while\n * resolving its configured processor list, before Agent resolves dynamic\n * Memory and enumerates Memory's processors. This guarantees both the Memory\n * options and its model callbacks see the authoritative row for this\n * invocation. Doing this in `processInputStep` would be too late: Memory's\n * input-step hook runs before configured processors.\n */\n async prepareMemorySettings(requestContext: ProcessInputArgs['requestContext']): Promise<void> {\n await this.loadCallerMemorySettings(requestContext, undefined, true);\n }\n\n async processInput(args: ProcessInputArgs): Promise<MessageList> {\n await this.loadCallerMemorySettings(args.requestContext);\n return args.messageList;\n }\n\n async processInputStep(args: ProcessInputStepArgs): Promise<MessageList | undefined> {\n const address = getFactorySessionCoordinates(args.requestContext);\n let binding: FactoryRunBindingRecord | null | undefined;\n try {\n binding = address ? await this.options.storage.findRunBindingBySession(address) : undefined;\n } catch {\n await this.loadCallerMemorySettings(args.requestContext, undefined);\n return;\n }\n // Resumed runs skip the input-processor phase, so re-check here: it is a\n // no-op once `processInput` already placed the row for this request. Passing\n // `undefined` (not `null`) keeps the recovery lookup inside the loader, so a\n // recovered session reaches its project row from this hook too.\n await this.loadCallerMemorySettings(args.requestContext, binding);\n if (!binding || binding.status !== 'active') return;\n const completedToolCallIds = completedStepToolCallIds(args.steps);\n const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);\n if (completedMessage) {\n await this.ingestMessages(binding, [completedMessage], completedToolCallIds);\n }\n }\n\n /**\n * Loads the caller's row once per invocation. The input hook always refreshes\n * it in case the controller reused a request context; later step hooks reuse\n * that value (`undefined` means it has not been loaded yet; `null` means an\n * empty row).\n *\n * The WeakSet covers loaders that do not set the context key themselves, so a\n * request is still loaded once. A failed load records an unavailable sentinel\n * (memory then runs both roles on auto with default thresholds) and is not\n * marked loaded so the next step can retry.\n */\n private async loadCallerMemorySettings(\n requestContext: ProcessInputStepArgs['requestContext'] | ProcessInputArgs['requestContext'],\n binding?: FactoryRunBindingRecord | null,\n force = false,\n ): Promise<void> {\n if (!requestContext || !this.options.loadMemorySettings) return;\n const currentSettings = requestContext.get('mastra__factoryMemorySettings') as\n | { status?: unknown }\n | null\n | undefined;\n if (force) this.loadedMemorySettings.delete(requestContext);\n if (!force && currentSettings !== undefined && currentSettings?.status !== 'unavailable') return;\n if (!force && this.loadedMemorySettings.has(requestContext)) return;\n try {\n let runBinding = binding ?? null;\n if (binding === undefined) {\n const address = getFactorySessionCoordinates(requestContext);\n runBinding = address\n ? await this.options.storage.findRunBindingBySession(address)\n : // Crash-recovered sessions come back with empty state, so the binding\n // table is the last source of the project whose row applies. Without\n // this the run would silently read the caller's personal row.\n await findSessionRunBinding(requestContext, this.options.storage);\n }\n await this.options.loadMemorySettings({ requestContext, binding: runBinding });\n this.loadedMemorySettings.add(requestContext);\n } catch (error) {\n reportMemorySettingsUnavailable(requestContext, error instanceof Error ? error.message : String(error));\n }\n }\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const address = getFactorySessionCoordinates(args.requestContext);\n if (!address) return;\n const binding = await this.options.storage.findRunBindingBySession(address);\n const prior = latestPhase(args);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n\n if (!binding) return;\n if (binding.status !== 'active') {\n if (!hasBase || prior?.status !== 'active') return;\n return {\n id: STATE_ID,\n cacheKey: `factory:none:${prior.bindingId ?? 'revoked'}`,\n mode: 'snapshot',\n tagName: 'factory-phase',\n contents: '\\n',\n value: { phase: { status: 'none' } },\n attributes: { status: 'none' },\n metadata: { value: { phase: { status: 'none' } } },\n };\n }\n\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const stage = ruleStage(this.options.boards, item);\n if (!item || !stage) return;\n const allItems = await this.options.storage.list({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n });\n const linked = allItems\n .filter(candidate => candidate.parentWorkItemId === item.id || item.parentWorkItemId === candidate.id)\n .slice(0, MAX_LINKED_ITEMS);\n const board = boardForWorkItem(item);\n const baseValue: ActivePhaseSnapshotBase = {\n status: 'active',\n bindingId: binding.id,\n itemId: item.id,\n revision: item.revision,\n stage,\n role: binding.role,\n configVersion: this.options.configVersion,\n };\n const value: ActivePhaseSnapshotValue =\n board === 'review'\n ? {\n ...baseValue,\n board,\n ...reviewRuntimeFromRequestContext(\n args.requestContext,\n await this.options.factoryThinkingLevel?.(binding.factoryProjectId),\n ),\n }\n : { ...baseValue, board };\n const cacheKey = await phaseCacheKey(value, linked);\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n\n const linkedText = linked.length\n ? `\\nLinked items: ${linked.map(candidate => `${workItemSource(candidate.externalSource)} ${candidate.title}`).join('; ')}`\n : '';\n const phaseLabel = this.options.boards.get(board)?.phases[stage]?.title ?? stage;\n const runtime =\n value.modelId && value.thinkingLevel ? { modelId: value.modelId, thinkingLevel: value.thinkingLevel } : null;\n const snapshotContents =\n `Factory ${board} phase: ${escapeText(phaseLabel)} (${escapeText(stage)})\\n` +\n `Work item: ${escapeText(item.title)} (${item.id})\\n` +\n `Role: ${escapeText(binding.role)}\\nRevision: ${item.revision}\\nConfig: ${escapeText(this.options.configVersion)}\\n` +\n (runtime\n ? `Runtime: model=${escapeText(runtime.modelId)}, reasoning-setting=${escapeText(runtime.thinkingLevel)}\\n`\n : '') +\n ((board === 'work' || board === 'review') && stage === 'intake'\n ? 'This card rests in Intake: its work is paused. Answer questions without moving it; when the user asks to resume, request the transition into the working stage first, then continue the work in this session.\\n'\n : '') +\n `Use factory_transition_work_item with expectedRevision ${item.revision} to request a phase change.${escapeText(linkedText)}`;\n const isDelta = hasBase && prior?.status === 'active';\n return {\n id: STATE_ID,\n cacheKey,\n mode: isDelta ? 'delta' : 'snapshot',\n tagName: 'factory-phase',\n contents: isDelta ? `Factory phase update:\\n${snapshotContents}` : snapshotContents,\n value: { phase: value },\n ...(isDelta ? { delta: { phase: value } } : {}),\n attributes: {\n status: 'active',\n board,\n stage,\n role: binding.role,\n revision: item.revision,\n ...(runtime ?? {}),\n },\n metadata: { value: { phase: value } },\n };\n }\n\n async reconcileAllBoundThreads(): Promise<void> {\n if (!this.options.messageReader) return;\n const bindings = await this.options.storage.listActiveRunBindings();\n for (const binding of bindings) await this.reconcileBinding(binding);\n }\n\n async reconcileBinding(binding: FactoryRunBindingRecord): Promise<void> {\n const reader = this.options.messageReader;\n if (!reader || binding.status !== 'active') return;\n // One keyed read up front: a binding whose item is gone or no longer in a\n // single rule stage would ingest nothing, so skip the cursor and message\n // reads entirely instead of paying them on every walk.\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!itemInRuleStage(this.options.boards, item)) return;\n const cursor = await this.options.storage.getToolResultCursor(binding.orgId, binding.factoryProjectId, binding.id);\n let page = 0;\n while (true) {\n const result = await reader.listMessages({\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n page,\n perPage: TRANSCRIPT_PAGE_SIZE,\n ...(cursor ? { filter: { dateRange: { start: cursor.lastMessageCreatedAt } } } : {}),\n orderBy: { field: 'createdAt', direction: 'ASC' },\n });\n await this.ingestMessages(binding, result.messages, undefined, item);\n const last = result.messages.at(-1);\n if (last) {\n await this.options.storage.advanceToolResultCursor({\n bindingId: binding.id,\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n lastMessageId: last.id,\n lastMessageCreatedAt: last.createdAt instanceof Date ? last.createdAt : new Date(last.createdAt),\n updatedAt: new Date(),\n });\n }\n if (!result.hasMore) break;\n page += 1;\n }\n }\n\n private async ingestMessages(\n binding: FactoryRunBindingRecord,\n messages: MastraDBMessage[],\n toolCallIds?: ReadonlySet<string>,\n preloadedItem?: WorkItemRow,\n ): Promise<void> {\n const item = preloadedItem ?? (await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }));\n if (!itemInRuleStage(this.options.boards, item)) return;\n for (const message of messages) {\n for (const toolResult of completedToolResults(message)) {\n if (toolCallIds && !toolCallIds.has(toolResult.toolCallId)) continue;\n try {\n await this.options.recordPullRequestProvenance?.({\n binding,\n item,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n toolInput: toolResult.input,\n toolResult: toolResult.value,\n status: toolResult.status,\n });\n } catch {\n // Provenance is supporting evidence and must not block authoritative rule ingress.\n }\n await this.ingestToolResult(binding, item, toolResult);\n }\n }\n }\n\n private async ingestToolResult(\n binding: FactoryRunBindingRecord,\n item: WorkItemRow,\n toolResult: CompletedToolResult,\n ): Promise<void> {\n const board = boardForWorkItem(item);\n const rule = resolveBoardToolRule(this.options.boards, board, toolResult.toolName);\n if (!rule) return;\n const ingressId = JSON.stringify([\n binding.id,\n binding.threadId,\n toolResult.assistantMessageId,\n toolResult.toolCallId,\n ]);\n const prior = await this.options.storage.getTransitionResultByIngress(\n binding.orgId,\n binding.factoryProjectId,\n ingressId,\n );\n if (prior) return;\n const context: FactoryToolResultRuleContext = {\n tenant: { orgId: binding.orgId, projectId: binding.factoryProjectId },\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'toolResult', id: ingressId },\n cause: `Completed ${toolResult.toolName}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n item: {\n id: item.id,\n source: workItemSource(item.externalSource),\n sourceKey: workItemSourceKey(item),\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: item.stages,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board,\n itemRevision: item.revision,\n toolName: toolResult.toolName,\n threadId: binding.threadId,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n result: { status: toolResult.status, value: toolResult.value },\n };\n\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: FactoryCommitDecision[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = await withRuleTimeout(Promise.resolve(rule(Object.freeze(context))));\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n const validated = validateFactoryRuleDecisions([decision]);\n for (const entry of validated) assertFactoryDecisionTarget(entry, this.options.boards, board);\n decisions = validated;\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory tool-result rule failed.',\n };\n }\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: ingressId, triggerType: 'tool.result' },\n configVersion: this.options.configVersion,\n expectedRevision: item.revision,\n actor: { ...context.actor },\n outcome,\n decisions: decisions.map(entry => ({ ...entry })),\n causalChain: [],\n now: new Date(),\n // The bound agent's own tool call carries the same consent as its governed moves.\n consentedBy: `agent:${binding.id}`,\n });\n if (committed.status !== 'committed' || !this.options.transitionService) return;\n for (const entry of decisions) {\n if (entry.type !== 'transition') continue;\n await this.options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n board: entry.board,\n stage: entry.stage,\n expectedRevision: item.revision,\n actor: { type: 'system', id: 'factory-tool-result-rule' },\n ingress: { type: 'rule', identity: `decision:${entry.idempotencyKey}` },\n cause: 'tool_result_rule',\n causalChain: [{ ingressId, decisionType: entry.type }],\n ...(isApprovedPlanResult(toolResult) ? { planApproved: true } : {}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.ts","sourceRoot":"","sources":["../../src/rules/tools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAKnE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAEhE,OAAO,KAAK,EAAe,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAC3F,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAEvE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AA8BxE,wBAAsB,4BAA4B,CAAC,OAAO,EAAE;IAC1D,cAAc,EAAE,cAAc,CAAC;IAC/B,OAAO,EAAE,gBAAgB,CAAC;IAC1B,iBAAiB,EAAE,IAAI,CAAC,wBAAwB,EAAE,YAAY,CAAC,CAAC;IAChE,QAAQ,CAAC,EAAE,0BAA0B,CAAC;IACtC,MAAM,CAAC,EAAE,aAAa,CAAC;CACxB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAqF5B;AAED,eAAO,MAAM,eAAe,yCAA0C,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { FACTORY_TRIAGE_TYPES } from "./types.js";
2
2
  import { BOARD_IDENTIFIER_RE } from "./validation.js";
3
3
  import { boardForWorkItem, workItemPhaseSemantics } from "../boards/semantics.js";
4
+ import "../boards/work.js";
4
5
  import "../boards/index.js";
5
6
  import { WorkItemUpdateConflictError } from "../storage/domains/work-items/base.js";
6
7
  import { resolveFactorySessionAddress } from "./binding-context.js";
@@ -91,9 +92,11 @@ async function createFactoryTransitionTools(options) {
91
92
  };
92
93
  }
93
94
  const REVIEW_VERDICTS = ["approve", "request changes"];
95
+ const MAX_SELF_REVIEW_FINDINGS_LENGTH = 2e4;
94
96
  const reviewVerdictInputSchema = z.object({
95
97
  verdict: z.enum(REVIEW_VERDICTS),
96
- reviewedHeadSha: z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i, "Use the full commit SHA of the reviewed head.")
98
+ reviewedHeadSha: z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i, "Use the full commit SHA of the reviewed head."),
99
+ findings: z.string().trim().min(1).transform((value) => value.length <= MAX_SELF_REVIEW_FINDINGS_LENGTH ? value : `${value.slice(0, MAX_SELF_REVIEW_FINDINGS_LENGTH - 1)}…`).optional().describe("Self-review only: the findings and test report, in Markdown. On request changes the builder receives them; on approve they go in the change request body.")
97
100
  });
98
101
  /**
99
102
  * A review pass ends by recording its verdict on the card, which stays in
@@ -103,10 +106,10 @@ const reviewVerdictInputSchema = z.object({
103
106
  function createReviewVerdictTool(options, boundWorkItemId) {
104
107
  return { factory_record_review_verdict: createTool({
105
108
  id: "factory_record_review_verdict",
106
- description: "Record the published review verdict and the PR head SHA it covers on the Review card bound to this thread. The card stays in Reviewing; this ends the review pass.",
109
+ description: "Record the review verdict and the head SHA it covers on the card bound to this thread, ending the review pass. On a Review card it records the published PR verdict and the card stays in Reviewing. On a Work card in Review with no change request open yet (self-review), approve keeps the card in Review and wakes the builder to open the change request; request changes sends it back to Building with your findings.",
107
110
  inputSchema: reviewVerdictInputSchema,
108
111
  requireApproval: false,
109
- execute: async ({ verdict, reviewedHeadSha }, execution) => {
112
+ execute: async ({ verdict, reviewedHeadSha, findings }, execution) => {
110
113
  const resolution = await resolveFactorySessionAddress({
111
114
  requestContext: execution.requestContext,
112
115
  storage: options.storage,
@@ -119,6 +122,16 @@ function createReviewVerdictTool(options, boundWorkItemId) {
119
122
  id: binding.workItemId
120
123
  });
121
124
  if (!item) throw new Error("Bound Factory work item not found.");
125
+ if (boardForWorkItem(item) === "work" && item.stages[0] === "review" && typeof item.metadata?.openPullRequestNumber !== "number") return recordSelfReviewVerdict({
126
+ storage: options.storage,
127
+ transitionService: options.transitionService,
128
+ binding,
129
+ item,
130
+ verdict,
131
+ reviewedHeadSha: reviewedHeadSha.toLowerCase(),
132
+ findings,
133
+ toolCallId: execution.agent?.toolCallId
134
+ });
122
135
  if (boardForWorkItem(item) !== "review" || item.stages[0] !== "review") throw new Error(`Only a card in Reviewing records a verdict; this one is in ${item.stages.join(", ")}.`);
123
136
  const reviewedAt = (/* @__PURE__ */ new Date()).toISOString();
124
137
  try {
@@ -162,6 +175,72 @@ function createReviewVerdictTool(options, boundWorkItemId) {
162
175
  }) };
163
176
  }
164
177
  /**
178
+ * Self-review ends the same way a PR review does, but on the Work card before
179
+ * any change request exists, and it moves the card itself: the verdict is the
180
+ * only thing that decides where the work goes next.
181
+ */
182
+ async function recordSelfReviewVerdict(input) {
183
+ const { storage, binding, item, verdict, reviewedHeadSha, findings } = input;
184
+ if (!input.toolCallId) throw new Error("Self-review verdicts require an authenticated bound agent tool call.");
185
+ const reviewedAt = (/* @__PURE__ */ new Date()).toISOString();
186
+ const previousRounds = typeof item.metadata?.selfReviewRounds === "number" ? item.metadata.selfReviewRounds : 0;
187
+ const rounds = verdict === "request changes" ? previousRounds + 1 : previousRounds;
188
+ const parked = verdict === "request changes" && rounds % 3 === 0;
189
+ let updated;
190
+ try {
191
+ updated = await storage.update({
192
+ orgId: binding.orgId,
193
+ id: item.id,
194
+ userId: `agent:${binding.id}`,
195
+ expectedRevision: item.revision,
196
+ patch: { metadata: {
197
+ selfReviewVerdict: verdict,
198
+ selfReviewedHeadSha: reviewedHeadSha,
199
+ selfReviewedAt: reviewedAt,
200
+ selfReviewFindings: findings ?? null,
201
+ selfReviewRounds: rounds,
202
+ selfReviewNeedsHuman: parked
203
+ } }
204
+ });
205
+ } catch (error) {
206
+ if (!(error instanceof WorkItemUpdateConflictError)) throw error;
207
+ throw new Error("The Work card changed while recording the verdict; call again to record it on the current card.");
208
+ }
209
+ if (!updated) throw new Error("Bound Factory work item not found.");
210
+ if (verdict === "approve") return {
211
+ status: "recorded",
212
+ verdict,
213
+ reviewedHeadSha,
214
+ reviewedAt,
215
+ selfReviewRounds: rounds
216
+ };
217
+ return {
218
+ status: "recorded",
219
+ verdict,
220
+ reviewedHeadSha,
221
+ reviewedAt,
222
+ selfReviewRounds: rounds,
223
+ transition: await input.transitionService.transition({
224
+ orgId: binding.orgId,
225
+ factoryProjectId: binding.factoryProjectId,
226
+ workItemId: binding.workItemId,
227
+ board: "work",
228
+ stage: parked ? "intake" : "execute",
229
+ expectedRevision: updated.item.revision,
230
+ actor: {
231
+ type: "agent",
232
+ bindingId: binding.id,
233
+ role: binding.role
234
+ },
235
+ ingress: {
236
+ type: "agent",
237
+ identity: `${binding.id}:${input.toolCallId}`
238
+ },
239
+ cause: parked ? `Self-review requested changes ${rounds} times; parked for a person to decide how to proceed.` : `Self-review requested changes on ${reviewedHeadSha} (round ${rounds}).`
240
+ })
241
+ };
242
+ }
243
+ /**
165
244
  * A retired session's transition tool: it exists only to fail loudly. The run's
166
245
  * binding was revoked when its work item settled at a terminal stage, so there
167
246
  * is nothing to transition. Registering it (instead of dropping the tool) stops
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../../src/rules/tools.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { boardForWorkItem, workItemPhaseSemantics } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactorySessionSourceLookup } from './binding-context.js';\nimport { resolveFactorySessionAddress } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { FACTORY_TRIAGE_TYPES } from './types.js';\nimport { BOARD_IDENTIFIER_RE, MAX_BOARD_IDENTIFIER_LENGTH } from './validation.js';\n\nconst MAX_RATIONALE_LENGTH = 1_000;\n\nconst transitionInputSchema = z\n .object({\n stage: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n expectedRevision: z.number().int().positive(),\n // Providers strip maxLength from the JSON schema and models can't count characters, so a\n // hard cap invites overshoot-retry loops at the end of every run. Accept and clamp instead.\n rationale: z\n .string()\n .trim()\n .min(1)\n .transform(value =>\n value.length <= MAX_RATIONALE_LENGTH ? value : `${value.slice(0, MAX_RATIONALE_LENGTH - 1)}…`,\n ),\n // Sessions are shared across role rotations, so a non-triage agent sees the triage\n // agent's earlier call (with triageType) in its history and copies the shape. Accept\n // the key here and drop it in execute rather than fail the whole call on it.\n triageType: z.enum(FACTORY_TRIAGE_TYPES).optional(),\n })\n .strict();\n\nconst triageTransitionInputSchema = transitionInputSchema.extend({\n triageType: z.enum(FACTORY_TRIAGE_TYPES),\n});\n\nexport async function createFactoryTransitionTools(options: {\n requestContext: RequestContext;\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n sessions?: FactorySessionSourceLookup;\n boards?: BoardRegistry;\n}): Promise<IntegrationTools> {\n const resolution = await resolveFactorySessionAddress({\n requestContext: options.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n if (!resolution) return {};\n const availableBinding = resolution.binding ?? (await options.storage.findActiveRunBinding(resolution.address));\n if (!availableBinding) {\n // No live binding for this session. A resumed session whose binding was\n // revoked when its work item reached a terminal stage was retired out from\n // under the model: rather than silently drop the tool — which leaves the\n // resumed run to rationalize a false blocked state — surface a tool that\n // fails with the concrete reason. Threads that were never bound (or whose\n // binding was rotated to a peer role, leaving the item still in flight) get\n // no tool as before.\n const retired = await options.storage.findRunBindingBySession(resolution.address);\n if (retired && retired.status === 'revoked' && options.boards) {\n const item = await options.storage.get({ orgId: retired.orgId, id: retired.workItemId });\n if (item && workItemPhaseSemantics(options.boards, item)?.kind === 'terminal') {\n return { factory_transition_work_item: createRetiredSessionTool(retired.workItemId, item.stages[0]) };\n }\n }\n return {};\n }\n let isTriage = false;\n if (availableBinding.role === 'triage') {\n const item = await options.storage.get({ orgId: availableBinding.orgId, id: availableBinding.workItemId });\n if (!item) return {};\n isTriage = boardForWorkItem(item) === 'work';\n }\n\n return {\n ...(availableBinding.role === 'review' ? createReviewVerdictTool(options, availableBinding.workItemId) : {}),\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description: isTriage\n ? 'Report the triage classification and request a governed stage transition for the Factory work item exactly bound to this thread. Only bugs may request Planning autonomously; closure outcomes may request a terminal stage. Feature requests and other non-bug classifications that remain open must stay in their current Intake or Triage stage for maintainer approval.'\n : 'Request a governed stage transition for the Factory work item exactly bound to this thread. Use the current revision from the factory-phase signal and explain why the transition is appropriate.',\n inputSchema: isTriage ? triageTransitionInputSchema : transitionInputSchema,\n requireApproval: true,\n execute: async ({ stage, expectedRevision, rationale, triageType: requestedTriageType }, execution) => {\n const currentResolution = await resolveFactorySessionAddress({\n requestContext: execution.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n const currentAddress = currentResolution?.address ?? null;\n const toolCallId = execution.agent?.toolCallId;\n if (!currentAddress || !toolCallId) {\n throw new Error('Factory transitions require an authenticated bound agent tool call.');\n }\n const binding = await options.storage.findActiveRunBinding(currentAddress);\n // Authority is the work item this session is bound to, not the individual\n // binding row. Handing the next role its turn in an existing session\n // rotates the binding, and tools built for the previous role stay live\n // across that rotation; keying on row identity would strand the run that\n // the rotation exists to start. Re-pointing a session at a different item\n // is the hijack this guards against.\n if (!binding || binding.workItemId !== availableBinding.workItemId) {\n throw new Error('Factory agent binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n const board = boardForWorkItem(item);\n // Only a Work triage binding may classify; other roles can echo the key from history.\n const triageType = board === 'work' && binding.role === 'triage' ? requestedTriageType : undefined;\n\n const result = await options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n board,\n stage,\n expectedRevision,\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'agent', identity: `${binding.id}:${toolCallId}` },\n cause: rationale,\n ...(triageType ? { triageType } : {}),\n });\n\n return result;\n },\n }),\n };\n}\n\nexport const REVIEW_VERDICTS = ['approve', 'request changes'] as const;\n\nconst reviewVerdictInputSchema = z.object({\n verdict: z.enum(REVIEW_VERDICTS),\n reviewedHeadSha: z\n .string()\n .regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i, 'Use the full commit SHA of the reviewed head.'),\n});\n\n/**\n * A review pass ends by recording its verdict on the card, which stays in\n * Reviewing: Done is reserved for the merge, and a verdict is not a lane. The\n * next push re-reviews from the recorded verdict.\n */\nfunction createReviewVerdictTool(\n options: { requestContext: RequestContext; storage: WorkItemsStorage; sessions?: FactorySessionSourceLookup },\n boundWorkItemId: string,\n): IntegrationTools {\n return {\n factory_record_review_verdict: createTool({\n id: 'factory_record_review_verdict',\n description:\n 'Record the published review verdict and the PR head SHA it covers on the Review card bound to this thread. The card stays in Reviewing; this ends the review pass.',\n inputSchema: reviewVerdictInputSchema,\n requireApproval: false,\n execute: async ({ verdict, reviewedHeadSha }, execution) => {\n const resolution = await resolveFactorySessionAddress({\n requestContext: execution.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n const binding = resolution ? await options.storage.findActiveRunBinding(resolution.address) : null;\n if (!binding || binding.workItemId !== boundWorkItemId || binding.role !== 'review') {\n throw new Error('Factory review binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n if (boardForWorkItem(item) !== 'review' || item.stages[0] !== 'review') {\n throw new Error(`Only a card in Reviewing records a verdict; this one is in ${item.stages.join(', ')}.`);\n }\n const reviewedAt = new Date().toISOString();\n // Revision-checked, so a merge that moves the card between the stage\n // check and this write fails the call instead of stamping a Done card.\n try {\n await options.storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n expectedRevision: item.revision,\n patch: {\n metadata: {\n ...(item.metadata ?? {}),\n reviewVerdict: verdict,\n reviewedHeadSha: reviewedHeadSha.toLowerCase(),\n reviewedAt,\n },\n },\n });\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n throw new Error(\n 'The Review card changed while recording the verdict; call again to record it on the current card.',\n );\n }\n // Mirror the verdict onto the Work item that authored the PR, so its\n // builder cannot close the work while changes are still requested.\n const parent = item.parentWorkItemId\n ? await options.storage.get({ orgId: binding.orgId, id: item.parentWorkItemId })\n : null;\n if (parent && boardForWorkItem(parent) === 'work') {\n await options.storage.update({\n orgId: binding.orgId,\n id: parent.id,\n userId: `agent:${binding.id}`,\n patch: {\n metadata: { reviewVerdict: verdict, reviewedHeadSha: reviewedHeadSha.toLowerCase(), reviewedAt },\n },\n });\n }\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt };\n },\n }),\n };\n}\n\n/**\n * A retired session's transition tool: it exists only to fail loudly. The run's\n * binding was revoked when its work item settled at a terminal stage, so there\n * is nothing to transition. Registering it (instead of dropping the tool) stops\n * a resumed model from inventing a false \"blocked\" state when the affordance it\n * expects has silently vanished.\n */\nfunction createRetiredSessionTool(workItemId: string, stage: string | undefined): IntegrationTools[string] {\n return createTool({\n id: 'factory_transition_work_item',\n description:\n 'This Factory session has been retired: its work item already reached a terminal stage and the run binding was revoked. No further transitions can be requested from this session.',\n inputSchema: transitionInputSchema,\n requireApproval: false,\n execute: async () => {\n throw new Error(\n `This Factory session has been retired: work item ${workItemId} reached a terminal stage${\n stage ? ` (${stage})` : ''\n } and its run binding was revoked. No transition can be requested from this session.`,\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;AAeA,MAAM,uBAAuB;AAE7B,MAAM,wBAAwB,EAC3B,OAAO;CACN,OAAO,EAAE,OAAO,CAAC,CAAC,IAAA,GAA+B,CAAC,CAAC,MAAM,mBAAmB;CAC5E,kBAAkB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,S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AAQ,IAAI;IAAE,OAAO,QAAQ;IAAO,IAAI,KAAK;GAAiB,CAAC,IAC7E;GACJ,IAAI,UAAU,iBAAiB,MAAM,MAAM,QACzC,MAAM,QAAQ,QAAQ,OAAO;IAC3B,OAAO,QAAQ;IACf,IAAI,OAAO;IACX,QAAQ,SAAS,QAAQ;IACzB,OAAO,EACL,UAAU;KAAE,eAAe;KAAS,iBAAiB,gBAAgB,YAAY;KAAG;IAAW,EACjG;GACF,CAAC;GAEH,OAAO;IAAE,QAAQ;IAAY;IAAS;IAAiB;GAAW;EACpE;CACF,CAAC,EACH;AACF;;;;;;;;AASA,SAAS,yBAAyB,YAAoB,OAAqD;CACzG,OAAO,WAAW;EAChB,IAAI;EACJ,aACE;EACF,aAAa;EACb,iBAAiB;EACjB,SAAS,YAAY;GACnB,MAAM,IAAI,MACR,oDAAoD,WAAW,2BAC7D,QAAQ,KAAK,MAAM,KAAK,GACzB,oFACH;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"tools.js","names":[],"sources":["../../src/rules/tools.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { boardForWorkItem, workItemPhaseSemantics } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { SELF_REVIEW_ROUND_LIMIT } from '../boards/work.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactorySessionSourceLookup } from './binding-context.js';\nimport { resolveFactorySessionAddress } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { FACTORY_TRIAGE_TYPES } from './types.js';\nimport { BOARD_IDENTIFIER_RE, MAX_BOARD_IDENTIFIER_LENGTH } from './validation.js';\n\nconst MAX_RATIONALE_LENGTH = 1_000;\n\nconst transitionInputSchema = z\n .object({\n stage: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n expectedRevision: z.number().int().positive(),\n // Providers strip maxLength from the JSON schema and models can't count characters, so a\n // hard cap invites overshoot-retry loops at the end of every run. Accept and clamp instead.\n rationale: z\n .string()\n .trim()\n .min(1)\n .transform(value =>\n value.length <= MAX_RATIONALE_LENGTH ? value : `${value.slice(0, MAX_RATIONALE_LENGTH - 1)}…`,\n ),\n // Sessions are shared across role rotations, so a non-triage agent sees the triage\n // agent's earlier call (with triageType) in its history and copies the shape. Accept\n // the key here and drop it in execute rather than fail the whole call on it.\n triageType: z.enum(FACTORY_TRIAGE_TYPES).optional(),\n })\n .strict();\n\nconst triageTransitionInputSchema = transitionInputSchema.extend({\n triageType: z.enum(FACTORY_TRIAGE_TYPES),\n});\n\nexport async function createFactoryTransitionTools(options: {\n requestContext: RequestContext;\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n sessions?: FactorySessionSourceLookup;\n boards?: BoardRegistry;\n}): Promise<IntegrationTools> {\n const resolution = await resolveFactorySessionAddress({\n requestContext: options.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n if (!resolution) return {};\n const availableBinding = resolution.binding ?? (await options.storage.findActiveRunBinding(resolution.address));\n if (!availableBinding) {\n // No live binding for this session. A resumed session whose binding was\n // revoked when its work item reached a terminal stage was retired out from\n // under the model: rather than silently drop the tool — which leaves the\n // resumed run to rationalize a false blocked state — surface a tool that\n // fails with the concrete reason. Threads that were never bound (or whose\n // binding was rotated to a peer role, leaving the item still in flight) get\n // no tool as before.\n const retired = await options.storage.findRunBindingBySession(resolution.address);\n if (retired && retired.status === 'revoked' && options.boards) {\n const item = await options.storage.get({ orgId: retired.orgId, id: retired.workItemId });\n if (item && workItemPhaseSemantics(options.boards, item)?.kind === 'terminal') {\n return { factory_transition_work_item: createRetiredSessionTool(retired.workItemId, item.stages[0]) };\n }\n }\n return {};\n }\n let isTriage = false;\n if (availableBinding.role === 'triage') {\n const item = await options.storage.get({ orgId: availableBinding.orgId, id: availableBinding.workItemId });\n if (!item) return {};\n isTriage = boardForWorkItem(item) === 'work';\n }\n\n return {\n ...(availableBinding.role === 'review' ? createReviewVerdictTool(options, availableBinding.workItemId) : {}),\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description: isTriage\n ? 'Report the triage classification and request a governed stage transition for the Factory work item exactly bound to this thread. Only bugs may request Planning autonomously; closure outcomes may request a terminal stage. Feature requests and other non-bug classifications that remain open must stay in their current Intake or Triage stage for maintainer approval.'\n : 'Request a governed stage transition for the Factory work item exactly bound to this thread. Use the current revision from the factory-phase signal and explain why the transition is appropriate.',\n inputSchema: isTriage ? triageTransitionInputSchema : transitionInputSchema,\n requireApproval: true,\n execute: async ({ stage, expectedRevision, rationale, triageType: requestedTriageType }, execution) => {\n const currentResolution = await resolveFactorySessionAddress({\n requestContext: execution.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n const currentAddress = currentResolution?.address ?? null;\n const toolCallId = execution.agent?.toolCallId;\n if (!currentAddress || !toolCallId) {\n throw new Error('Factory transitions require an authenticated bound agent tool call.');\n }\n const binding = await options.storage.findActiveRunBinding(currentAddress);\n // Authority is the work item this session is bound to, not the individual\n // binding row. Handing the next role its turn in an existing session\n // rotates the binding, and tools built for the previous role stay live\n // across that rotation; keying on row identity would strand the run that\n // the rotation exists to start. Re-pointing a session at a different item\n // is the hijack this guards against.\n if (!binding || binding.workItemId !== availableBinding.workItemId) {\n throw new Error('Factory agent binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n const board = boardForWorkItem(item);\n // Only a Work triage binding may classify; other roles can echo the key from history.\n const triageType = board === 'work' && binding.role === 'triage' ? requestedTriageType : undefined;\n\n const result = await options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n board,\n stage,\n expectedRevision,\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'agent', identity: `${binding.id}:${toolCallId}` },\n cause: rationale,\n ...(triageType ? { triageType } : {}),\n });\n\n return result;\n },\n }),\n };\n}\n\nexport const REVIEW_VERDICTS = ['approve', 'request changes'] as const;\n\nconst MAX_SELF_REVIEW_FINDINGS_LENGTH = 20_000;\n\nconst reviewVerdictInputSchema = z.object({\n verdict: z.enum(REVIEW_VERDICTS),\n reviewedHeadSha: z\n .string()\n .regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i, 'Use the full commit SHA of the reviewed head.'),\n findings: z\n .string()\n .trim()\n .min(1)\n .transform(value =>\n value.length <= MAX_SELF_REVIEW_FINDINGS_LENGTH\n ? value\n : `${value.slice(0, MAX_SELF_REVIEW_FINDINGS_LENGTH - 1)}…`,\n )\n .optional()\n .describe(\n 'Self-review only: the findings and test report, in Markdown. On request changes the builder receives them; on approve they go in the change request body.',\n ),\n});\n\n/**\n * A review pass ends by recording its verdict on the card, which stays in\n * Reviewing: Done is reserved for the merge, and a verdict is not a lane. The\n * next push re-reviews from the recorded verdict.\n */\nfunction createReviewVerdictTool(\n options: {\n requestContext: RequestContext;\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n sessions?: FactorySessionSourceLookup;\n },\n boundWorkItemId: string,\n): IntegrationTools {\n return {\n factory_record_review_verdict: createTool({\n id: 'factory_record_review_verdict',\n description:\n 'Record the review verdict and the head SHA it covers on the card bound to this thread, ending the review pass. On a Review card it records the published PR verdict and the card stays in Reviewing. On a Work card in Review with no change request open yet (self-review), approve keeps the card in Review and wakes the builder to open the change request; request changes sends it back to Building with your findings.',\n inputSchema: reviewVerdictInputSchema,\n requireApproval: false,\n execute: async ({ verdict, reviewedHeadSha, findings }, execution) => {\n const resolution = await resolveFactorySessionAddress({\n requestContext: execution.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n const binding = resolution ? await options.storage.findActiveRunBinding(resolution.address) : null;\n if (!binding || binding.workItemId !== boundWorkItemId || binding.role !== 'review') {\n throw new Error('Factory review binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n if (\n boardForWorkItem(item) === 'work' &&\n item.stages[0] === 'review' &&\n typeof item.metadata?.openPullRequestNumber !== 'number'\n ) {\n return recordSelfReviewVerdict({\n storage: options.storage,\n transitionService: options.transitionService,\n binding,\n item,\n verdict,\n reviewedHeadSha: reviewedHeadSha.toLowerCase(),\n findings,\n toolCallId: execution.agent?.toolCallId,\n });\n }\n if (boardForWorkItem(item) !== 'review' || item.stages[0] !== 'review') {\n throw new Error(`Only a card in Reviewing records a verdict; this one is in ${item.stages.join(', ')}.`);\n }\n const reviewedAt = new Date().toISOString();\n // Revision-checked, so a merge that moves the card between the stage\n // check and this write fails the call instead of stamping a Done card.\n try {\n await options.storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n expectedRevision: item.revision,\n patch: {\n metadata: {\n ...(item.metadata ?? {}),\n reviewVerdict: verdict,\n reviewedHeadSha: reviewedHeadSha.toLowerCase(),\n reviewedAt,\n },\n },\n });\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n throw new Error(\n 'The Review card changed while recording the verdict; call again to record it on the current card.',\n );\n }\n // Mirror the verdict onto the Work item that authored the PR, so its\n // builder cannot close the work while changes are still requested.\n const parent = item.parentWorkItemId\n ? await options.storage.get({ orgId: binding.orgId, id: item.parentWorkItemId })\n : null;\n if (parent && boardForWorkItem(parent) === 'work') {\n await options.storage.update({\n orgId: binding.orgId,\n id: parent.id,\n userId: `agent:${binding.id}`,\n patch: {\n metadata: { reviewVerdict: verdict, reviewedHeadSha: reviewedHeadSha.toLowerCase(), reviewedAt },\n },\n });\n }\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt };\n },\n }),\n };\n}\n\n/**\n * Self-review ends the same way a PR review does, but on the Work card before\n * any change request exists, and it moves the card itself: the verdict is the\n * only thing that decides where the work goes next.\n */\nasync function recordSelfReviewVerdict(input: {\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n binding: { id: string; orgId: string; factoryProjectId: string; workItemId: string; role: string };\n item: WorkItemRow;\n verdict: (typeof REVIEW_VERDICTS)[number];\n reviewedHeadSha: string;\n findings: string | undefined;\n toolCallId: string | undefined;\n}) {\n const { storage, binding, item, verdict, reviewedHeadSha, findings } = input;\n if (!input.toolCallId) throw new Error('Self-review verdicts require an authenticated bound agent tool call.');\n const reviewedAt = new Date().toISOString();\n const previousRounds = typeof item.metadata?.selfReviewRounds === 'number' ? item.metadata.selfReviewRounds : 0;\n const rounds = verdict === 'request changes' ? previousRounds + 1 : previousRounds;\n // Every SELF_REVIEW_ROUND_LIMIT rounds the card rests in Intake for a person instead of looping;\n // moving it back to Building grants another full set of rounds.\n const parked = verdict === 'request changes' && rounds % SELF_REVIEW_ROUND_LIMIT === 0;\n let updated: Awaited<ReturnType<WorkItemsStorage['update']>>;\n try {\n updated = await storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n expectedRevision: item.revision,\n patch: {\n metadata: {\n selfReviewVerdict: verdict,\n selfReviewedHeadSha: reviewedHeadSha,\n selfReviewedAt: reviewedAt,\n selfReviewFindings: findings ?? null,\n selfReviewRounds: rounds,\n selfReviewNeedsHuman: parked,\n },\n },\n });\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n throw new Error('The Work card changed while recording the verdict; call again to record it on the current card.');\n }\n if (!updated) throw new Error('Bound Factory work item not found.');\n if (verdict === 'approve')\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt, selfReviewRounds: rounds };\n const transition = await input.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n board: 'work',\n stage: parked ? 'intake' : 'execute',\n expectedRevision: updated.item.revision,\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'agent', identity: `${binding.id}:${input.toolCallId}` },\n cause: parked\n ? `Self-review requested changes ${rounds} times; parked for a person to decide how to proceed.`\n : `Self-review requested changes on ${reviewedHeadSha} (round ${rounds}).`,\n });\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt, selfReviewRounds: rounds, transition };\n}\n\n/**\n * A retired session's transition tool: it exists only to fail loudly. The run's\n * binding was revoked when its work item settled at a terminal stage, so there\n * is nothing to transition. Registering it (instead of dropping the tool) stops\n * a resumed model from inventing a false \"blocked\" state when the affordance it\n * expects has silently vanished.\n */\nfunction createRetiredSessionTool(workItemId: string, stage: string | undefined): IntegrationTools[string] {\n return createTool({\n id: 'factory_transition_work_item',\n description:\n 'This Factory session has been retired: its work item already reached a terminal stage and the run binding was revoked. No further transitions can be requested from this session.',\n inputSchema: transitionInputSchema,\n requireApproval: false,\n execute: async () => {\n throw new Error(\n `This Factory session has been retired: work item ${workItemId} reached a terminal stage${\n stage ? ` (${stage})` : ''\n } and its run binding was revoked. No transition can be requested from this session.`,\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;;AAgBA,MAAM,uBAAuB;AAE7B,MAAM,wBAAwB,EAC3B,OAAO;CACN,OAAO,EAAE,OAAO,CAAC,CAAC,IAAA,GAA+B,CAAC,CAAC,MAAM,mBAAmB;CAC5E,kBAAkB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;CAG5C,WAAW,EACR,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,CAAC,CAAC,CACN,WAAU,UACT,MAAM,UAAU,uBAAuB,QAAQ,GAAG,MAAM,MAAM,GAAG,uBAAuB,CAAC,EAAE,EAC7F;CAIF,YAAY,EAAE,KAAK,oBAAoB,CAAC,CAAC,SAAS;AACpD,CAAC,CAAC,CACD,OAAO;AAEV,MAAM,8BAA8B,sBAAsB,OAAO,EAC/D,YAAY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AAM;EAC3D,MAAM,IAAI,MAAM,iGAAiG;CACnH;CACA,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,oCAAoC;CAClE,IAAI,YAAY,WACd,OAAO;EAAE,QAAQ;EAAY;EAAS;EAAiB;EAAY,kBAAkB;CAAO;CAc9F,OAAO;EAAE,QAAQ;EAAY;EAAS;EAAiB;EAAY,kBAAkB;EAAQ,YAAA,MAbpE,MAAM,kBAAkB,WAAW;GAC1D,OAAO,QAAQ;GACf,kBAAkB,QAAQ;GAC1B,YAAY,QAAQ;GACpB,OAAO;GACP,OAAO,SAAS,WAAW;GAC3B,kBAAkB,QAAQ,KAAK;GAC/B,OAAO;IAAE,MAAM;IAAS,WAAW,QAAQ;IAAI,MAAM,QAAQ;GAAK;GAClE,SAAS;IAAE,MAAM;IAAS,UAAU,GAAG,QAAQ,GAAG,GAAG,MAAM;GAAa;GACxE,OAAO,SACH,iCAAiC,OAAO,yDACxC,oCAAoC,gBAAgB,UAAU,OAAO;EAC3E,CAAC;CACuG;AAC1G;;;;;;;;AASA,SAAS,yBAAyB,YAAoB,OAAqD;CACzG,OAAO,WAAW;EAChB,IAAI;EACJ,aACE;EACF,aAAa;EACb,iBAAiB;EACjB,SAAS,YAAY;GACnB,MAAM,IAAI,MACR,oDAAoD,WAAW,2BAC7D,QAAQ,KAAK,MAAM,KAAK,GACzB,oFACH;EACF;CACF,CAAC;AACH"}
@@ -55,6 +55,18 @@ export interface FactoryTransitionServiceOptions {
55
55
  * the seat that drove its own transition (an agent tool call) untouched. */
56
56
  actor: FactoryRuleActor;
57
57
  }) => Promise<void> | void;
58
+ /**
59
+ * Called after a transition commits a stage change, e.g. to tell the item's
60
+ * followers. Not awaited, and failures are logged: a notification must never
61
+ * fail or delay the committed transition.
62
+ */
63
+ onTransitionCommitted?: (args: {
64
+ orgId: string;
65
+ factoryProjectId: string;
66
+ workItemId: string;
67
+ fromStage: string | undefined;
68
+ toStage: string;
69
+ }) => Promise<void> | void;
58
70
  /** Upper bound on how long a committed transition waits for
59
71
  * `onTerminalStage` before returning (default 30s). The cleanup continues
60
72
  * in the background past the bound. */
@@ -78,6 +90,11 @@ export interface FactoryTransitionServiceOptions {
78
90
  orgId: string;
79
91
  factoryProjectId: string;
80
92
  }) => Promise<boolean>;
93
+ /** Resolves whether a project self-reviews Work items before the change request opens. Unset means off. */
94
+ selfReviewEnabled?: (tenant: {
95
+ orgId: string;
96
+ factoryProjectId: string;
97
+ }) => Promise<boolean>;
81
98
  }
82
99
  export declare function auditActorOf(actor: FactoryRuleActor): {
83
100
  actorId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"transition-service.d.ts","sourceRoot":"","sources":["../../src/rules/transition-service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAC7G,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAExE,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAE3F,OAAO,KAAK,EAEV,gBAAgB,EAEhB,sBAAsB,EAEtB,gBAAgB,EAChB,iBAAiB,EAEjB,uBAAuB,EACxB,MAAM,YAAY,CAAC;AAsBpB,MAAM,WAAW,wBAAwB;IACvC,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,gBAAgB,CAAC;IACxB,gBAAgB,EAAE,MAAM,CAAC;IACzB,KAAK,EAAE,gBAAgB,CAAC;IACxB,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,sEAAsE;IACtE,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,OAAO,EAAE;QAAE,IAAI,EAAE,OAAO,GAAG,OA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ransitionService = class {
109
109
  #onTerminalStage;
110
110
  #terminalCleanupTimeoutMs;
111
111
  #onAccepted;
112
+ #onTransitionCommitted;
112
113
  #autoApprovePlans;
114
+ #selfReviewEnabled;
113
115
  #audit;
114
116
  constructor(options) {
115
117
  this.#configVersion = options.configVersion;
@@ -119,7 +121,9 @@ var FactoryTransitionService = class {
119
121
  this.#timeoutMs = options.timeoutMs ?? RULE_TIMEOUT_MS;
120
122
  this.#onTerminalStage = options.onTerminalStage;
121
123
  this.#onAccepted = options.onAccepted;
124
+ this.#onTransitionCommitted = options.onTransitionCommitted;
122
125
  this.#autoApprovePlans = options.autoApprovePlans;
126
+ this.#selfReviewEnabled = options.selfReviewEnabled;
123
127
  this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;
124
128
  }
125
129
  get configVersion() {
@@ -140,8 +144,24 @@ var FactoryTransitionService = class {
140
144
  }
141
145
  const result = await this.#evaluateAndCommit(request, transitionId, item);
142
146
  await this.#recordTransition(request, item, result);
147
+ this.#notifyCommitted(request, item, result);
143
148
  return result;
144
149
  }
150
+ #notifyCommitted(request, item, result) {
151
+ const onTransitionCommitted = this.#onTransitionCommitted;
152
+ if (!onTransitionCommitted || result.status !== "accepted") return;
153
+ const fromStage = item.stages.length === 1 ? item.stages[0] : void 0;
154
+ if (result.stage === fromStage) return;
155
+ Promise.resolve().then(() => onTransitionCommitted({
156
+ orgId: request.orgId,
157
+ factoryProjectId: request.factoryProjectId,
158
+ workItemId: item.id,
159
+ fromStage,
160
+ toStage: result.stage
161
+ })).catch((error) => {
162
+ console.warn(`[factory] stage notification failed for work item ${item.id}:`, error);
163
+ });
164
+ }
145
165
  /** A rejection can outlive its work item: the row still names the id the caller asked for. */
146
166
  async #recordTransition(request, item, result) {
147
167
  if (!this.#audit) return;
@@ -267,6 +287,10 @@ var FactoryTransitionService = class {
267
287
  code: "approval_required",
268
288
  reason: "This card comes from outside the write-access circle; a person must resume it from the Factory board."
269
289
  };
290
+ const selfReviewEnabled = request.board === "work" && this.#selfReviewEnabled ? await this.#selfReviewEnabled({
291
+ orgId: request.orgId,
292
+ factoryProjectId: request.factoryProjectId
293
+ }) : false;
270
294
  const decisions = [];
271
295
  for (const rule of resolveFactoryStageRules(this.#boards, {
272
296
  board: request.board,
@@ -278,6 +302,7 @@ var FactoryTransitionService = class {
278
302
  })) {
279
303
  const context = Object.freeze({
280
304
  ...contextBase,
305
+ selfReviewEnabled,
281
306
  stage: rule.phase === "exit" ? fromStage : request.stage
282
307
  });
283
308
  const raw = await rule.handler(context);