@mastra/factory 0.29.0-alpha.2 → 0.29.0-alpha.4

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 (211) hide show
  1. package/README.md +44 -5
  2. package/dist/factory.d.ts +8 -0
  3. package/dist/factory.d.ts.map +1 -1
  4. package/dist/factory.js +26 -10
  5. package/dist/factory.js.map +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -2
  9. package/dist/integrations/dependabot/rules.d.ts.map +1 -1
  10. package/dist/integrations/dependabot/rules.js +1 -5
  11. package/dist/integrations/dependabot/rules.js.map +1 -1
  12. package/dist/integrations/github/commits.d.ts +0 -21
  13. package/dist/integrations/github/commits.d.ts.map +1 -1
  14. package/dist/integrations/github/commits.js +1 -24
  15. package/dist/integrations/github/commits.js.map +1 -1
  16. package/dist/integrations/github/integration.d.ts +1 -1
  17. package/dist/integrations/github/integration.d.ts.map +1 -1
  18. package/dist/integrations/github/integration.js +2 -6
  19. package/dist/integrations/github/integration.js.map +1 -1
  20. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  21. package/dist/integrations/github/reconcile-worker.js +30 -1
  22. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  23. package/dist/integrations/github/routes.d.ts +1 -11
  24. package/dist/integrations/github/routes.d.ts.map +1 -1
  25. package/dist/integrations/github/routes.js +6 -515
  26. package/dist/integrations/github/routes.js.map +1 -1
  27. package/dist/integrations/github/rules.d.ts.map +1 -1
  28. package/dist/integrations/github/rules.js +76 -13
  29. package/dist/integrations/github/rules.js.map +1 -1
  30. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  31. package/dist/integrations/github/sandbox.js +11 -2
  32. package/dist/integrations/github/sandbox.js.map +1 -1
  33. package/dist/integrations/gitlab/discovery.d.ts +1 -1
  34. package/dist/integrations/gitlab/discovery.js +1 -1
  35. package/dist/integrations/gitlab/discovery.js.map +1 -1
  36. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/integration.js +0 -1
  38. package/dist/integrations/gitlab/integration.js.map +1 -1
  39. package/dist/integrations/gitlab/routes.d.ts +0 -2
  40. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  41. package/dist/integrations/gitlab/routes.js +49 -165
  42. package/dist/integrations/gitlab/routes.js.map +1 -1
  43. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  44. package/dist/integrations/gitlab/rules.js +20 -7
  45. package/dist/integrations/gitlab/rules.js.map +1 -1
  46. package/dist/integrations/incidentio/routes.d.ts +5 -5
  47. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  48. package/dist/integrations/incidentio/routes.js +3 -59
  49. package/dist/integrations/incidentio/routes.js.map +1 -1
  50. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  51. package/dist/integrations/incidentio/rules.js +1 -5
  52. package/dist/integrations/incidentio/rules.js.map +1 -1
  53. package/dist/integrations/jira/issue-reconciler.d.ts +1 -1
  54. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  55. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  56. package/dist/integrations/jira/routes.d.ts +2 -2
  57. package/dist/integrations/jira/routes.d.ts.map +1 -1
  58. package/dist/integrations/jira/routes.js +0 -68
  59. package/dist/integrations/jira/routes.js.map +1 -1
  60. package/dist/integrations/jira/rules.d.ts.map +1 -1
  61. package/dist/integrations/jira/rules.js +1 -5
  62. package/dist/integrations/jira/rules.js.map +1 -1
  63. package/dist/integrations/linear/routes.d.ts +2 -2
  64. package/dist/integrations/linear/routes.d.ts.map +1 -1
  65. package/dist/integrations/linear/routes.js +0 -83
  66. package/dist/integrations/linear/routes.js.map +1 -1
  67. package/dist/integrations/linear/rules.d.ts.map +1 -1
  68. package/dist/integrations/linear/rules.js +12 -5
  69. package/dist/integrations/linear/rules.js.map +1 -1
  70. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  71. package/dist/integrations/platform/github/integration.js +1 -3
  72. package/dist/integrations/platform/github/integration.js.map +1 -1
  73. package/dist/integrations/platform/jira/routes.d.ts +2 -2
  74. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  75. package/dist/integrations/platform/jira/routes.js +0 -69
  76. package/dist/integrations/platform/jira/routes.js.map +1 -1
  77. package/dist/integrations/vanta/rules.d.ts.map +1 -1
  78. package/dist/integrations/vanta/rules.js +1 -5
  79. package/dist/integrations/vanta/rules.js.map +1 -1
  80. package/dist/metrics/collectors/postgres.d.ts +29 -0
  81. package/dist/metrics/collectors/postgres.d.ts.map +1 -0
  82. package/dist/metrics/collectors/postgres.js +121 -0
  83. package/dist/metrics/collectors/postgres.js.map +1 -0
  84. package/dist/metrics/collectors/probe.d.ts +22 -0
  85. package/dist/metrics/collectors/probe.d.ts.map +1 -0
  86. package/dist/metrics/collectors/probe.js +69 -0
  87. package/dist/metrics/collectors/probe.js.map +1 -0
  88. package/dist/metrics/collectors/process.d.ts +13 -0
  89. package/dist/metrics/collectors/process.d.ts.map +1 -0
  90. package/dist/metrics/collectors/process.js +85 -0
  91. package/dist/metrics/collectors/process.js.map +1 -0
  92. package/dist/metrics/collectors/redis.d.ts +29 -0
  93. package/dist/metrics/collectors/redis.d.ts.map +1 -0
  94. package/dist/metrics/collectors/redis.js +97 -0
  95. package/dist/metrics/collectors/redis.js.map +1 -0
  96. package/dist/metrics/config.d.ts +33 -0
  97. package/dist/metrics/config.d.ts.map +1 -0
  98. package/dist/metrics/config.js +65 -0
  99. package/dist/metrics/config.js.map +1 -0
  100. package/dist/metrics/index.d.ts +20 -0
  101. package/dist/metrics/index.d.ts.map +1 -0
  102. package/dist/metrics/index.js +65 -0
  103. package/dist/metrics/index.js.map +1 -0
  104. package/dist/metrics/intake.d.ts +28 -0
  105. package/dist/metrics/intake.d.ts.map +1 -0
  106. package/dist/metrics/intake.js +76 -0
  107. package/dist/metrics/intake.js.map +1 -0
  108. package/dist/metrics/metrics.d.ts +60 -0
  109. package/dist/metrics/metrics.d.ts.map +1 -0
  110. package/dist/metrics/metrics.js +182 -0
  111. package/dist/metrics/metrics.js.map +1 -0
  112. package/dist/metrics/sandbox.d.ts +35 -0
  113. package/dist/metrics/sandbox.d.ts.map +1 -0
  114. package/dist/metrics/sandbox.js +156 -0
  115. package/dist/metrics/sandbox.js.map +1 -0
  116. package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
  117. package/dist/routes/automation-runs.d.ts +0 -2
  118. package/dist/routes/automation-runs.d.ts.map +1 -1
  119. package/dist/routes/automation-runs.js +2 -6
  120. package/dist/routes/automation-runs.js.map +1 -1
  121. package/dist/routes/contracts.d.ts +0 -5
  122. package/dist/routes/contracts.d.ts.map +1 -1
  123. package/dist/routes/contracts.js +2 -4
  124. package/dist/routes/contracts.js.map +1 -1
  125. package/dist/routes/fs.d.ts +10 -0
  126. package/dist/routes/fs.d.ts.map +1 -1
  127. package/dist/routes/fs.js +184 -11
  128. package/dist/routes/fs.js.map +1 -1
  129. package/dist/routes/projects.d.ts.map +1 -1
  130. package/dist/routes/projects.js +4 -17
  131. package/dist/routes/projects.js.map +1 -1
  132. package/dist/routes/source-control-sessions.d.ts +0 -3
  133. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  134. package/dist/routes/source-control-sessions.js +0 -19
  135. package/dist/routes/source-control-sessions.js.map +1 -1
  136. package/dist/routes/surface.d.ts +0 -2
  137. package/dist/routes/surface.d.ts.map +1 -1
  138. package/dist/routes/surface.js +2 -12
  139. package/dist/routes/surface.js.map +1 -1
  140. package/dist/rules/dispatcher.d.ts +1 -0
  141. package/dist/rules/dispatcher.d.ts.map +1 -1
  142. package/dist/rules/dispatcher.js +27 -13
  143. package/dist/rules/dispatcher.js.map +1 -1
  144. package/dist/rules/processor.d.ts.map +1 -1
  145. package/dist/rules/processor.js +1 -6
  146. package/dist/rules/processor.js.map +1 -1
  147. package/dist/rules/start-coordinator.d.ts +1 -0
  148. package/dist/rules/start-coordinator.d.ts.map +1 -1
  149. package/dist/rules/start-coordinator.js +2 -1
  150. package/dist/rules/start-coordinator.js.map +1 -1
  151. package/dist/rules/transition-service.d.ts.map +1 -1
  152. package/dist/rules/transition-service.js +0 -2
  153. package/dist/rules/transition-service.js.map +1 -1
  154. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  155. package/dist/sandbox/session-retirement.js +22 -14
  156. package/dist/sandbox/session-retirement.js.map +1 -1
  157. package/dist/sandbox/session-sandbox.d.ts +2 -0
  158. package/dist/sandbox/session-sandbox.d.ts.map +1 -1
  159. package/dist/sandbox/session-sandbox.js +7 -1
  160. package/dist/sandbox/session-sandbox.js.map +1 -1
  161. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  162. package/dist/storage/domains/boards/schemas.js +0 -4
  163. package/dist/storage/domains/boards/schemas.js.map +1 -1
  164. package/dist/storage/domains/intake/base.d.ts +11 -10
  165. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  166. package/dist/storage/domains/intake/base.js +30 -65
  167. package/dist/storage/domains/intake/base.js.map +1 -1
  168. package/dist/storage/domains/integrations/base.d.ts +0 -2
  169. package/dist/storage/domains/integrations/base.d.ts.map +1 -1
  170. package/dist/storage/domains/integrations/base.js +0 -6
  171. package/dist/storage/domains/integrations/base.js.map +1 -1
  172. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  173. package/dist/storage/domains/projects/base.js +0 -12
  174. package/dist/storage/domains/projects/base.js.map +1 -1
  175. package/dist/storage/domains/source-control/base.d.ts +0 -10
  176. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  177. package/dist/storage/domains/source-control/base.js +1 -19
  178. package/dist/storage/domains/source-control/base.js.map +1 -1
  179. package/dist/storage/domains/source-control/inmemory.d.ts +1 -1
  180. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  181. package/dist/storage/domains/source-control/inmemory.js +1 -6
  182. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  183. package/dist/storage/domains/work-items/base.d.ts +6 -36
  184. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  185. package/dist/storage/domains/work-items/base.js +42 -82
  186. package/dist/storage/domains/work-items/base.js.map +1 -1
  187. package/dist/storage/domains/work-items/work-item-schema.d.ts +12 -3
  188. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  189. package/dist/storage/domains/work-items/work-item-schema.js +12 -3
  190. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  191. package/dist/storage/legacy-collections.d.ts +9 -0
  192. package/dist/storage/legacy-collections.d.ts.map +1 -0
  193. package/dist/storage/legacy-collections.js +17 -0
  194. package/dist/storage/legacy-collections.js.map +1 -0
  195. package/dist/timing.d.ts +4 -1
  196. package/dist/timing.d.ts.map +1 -1
  197. package/dist/timing.js +12 -4
  198. package/dist/timing.js.map +1 -1
  199. package/dist/workspace.d.ts.map +1 -1
  200. package/dist/workspace.js +8 -4
  201. package/dist/workspace.js.map +1 -1
  202. package/factory-skills/configure-factory-rules/SKILL.md +2 -2
  203. package/package.json +10 -10
  204. package/dist/session/filesystem-capture.d.ts +0 -50
  205. package/dist/session/filesystem-capture.d.ts.map +0 -1
  206. package/dist/session/filesystem-capture.js +0 -229
  207. package/dist/session/filesystem-capture.js.map +0 -1
  208. package/dist/storage/domains/filesystem/base.d.ts +0 -30
  209. package/dist/storage/domains/filesystem/base.d.ts.map +0 -1
  210. package/dist/storage/domains/filesystem/base.js +0 -78
  211. package/dist/storage/domains/filesystem/base.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/rules/processor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yCAAyC,CAAC;AAE7E,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAEpF,OAAO,KAAK,EACV,sBAAsB,EACtB,wBAAwB,EACxB,gBAAgB,EAChB,oBAAoB,EACpB,SAAS,EACV,MAAM,yBAAyB,CAAC;AASjC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AAC,EAAE,MAAM,IAAI,CAAC;QAC9B,iBAAiB,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,YAAY,CAAC,CAAC;QACjE,aAAa,CAAC,EAAE,sBAAsB,CAAC;QACvC,2BAA2B,CAAC,EAAE,CAAC,KAAK,EAAE;YACpC,OAAO,EAAE,uBAAuB,CAAC;YACjC,IAAI,EAAE,IAAI,CAAC;YACX,kBAAkB,EAAE,MAAM,CAAC;YAC3B,UAAU,EAAE,MAAM,CAAC;YACnB,QAAQ,EAAE,MAAM,CAAC;YACjB,SAAS,EAAE,oBAAoB,CAAC;YAChC,UAAU,EAAE,oBAAoB,CAAC;YACjC,MAAM,EAAE,SAAS,GAAG,OAAO,CAAC;SAC7B,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACrB,EAGF;IAED;;;;;;;OAOG;IACG,qBAAqB,CAAC,cAAc,EAAE,gBAAgB,CAAC,gBAAgB,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAE7F;IAEK,YAAY,CAAC,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,WAAW,CAAC,CAG/D;IAEK,gBAAgB,CAAC,IAAI,EAAE,oBAAoB,GAAG,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAwBnF;IAED;;;;;;;;;;OAUG;YACW,wBAAwB;IA+BhC,kBAAkB,CAAC,IAAI,EAAE,sBAAsB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAkJxF;IAEK,wBAAwB,IAAI,OAAO,CAAC,IAAI,CAAC,CAI9C;IAEK,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,IAAI,CAAC,CAYtE;YAEa,mBAAmB;YAmCnB,cAAc;YA8Bd,gBAAgB;CAwJ/B"}
@@ -424,7 +424,6 @@ var FactoryPhaseStateProcessor = class {
424
424
  bindingId: binding.id,
425
425
  orgId: binding.orgId,
426
426
  factoryProjectId: binding.factoryProjectId,
427
- lastMessageId: last.id,
428
427
  lastMessageCreatedAt: last.createdAt instanceof Date ? last.createdAt : new Date(last.createdAt),
429
428
  updatedAt: /* @__PURE__ */ new Date()
430
429
  });
@@ -568,11 +567,7 @@ var FactoryPhaseStateProcessor = class {
568
567
  orgId: binding.orgId,
569
568
  factoryProjectId: binding.factoryProjectId,
570
569
  workItemId: item.id,
571
- ingress: {
572
- identity: ingressId,
573
- triggerType: "tool.result"
574
- },
575
- configVersion: this.options.configVersion,
570
+ ingress: { identity: ingressId },
576
571
  expectedRevision: item.revision,
577
572
  actor: { ...context.actor },
578
573
  outcome,
@@ -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 {\n boardFlow,\n boardForWorkItem,\n resolveBoardToolRule,\n reviewsPullRequest,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { workStageCarries } from '../boards/legacy-plan-role.js';\nimport { exitToolSucceeded, PHASE_EXIT_METADATA_KEY } from '../boards/phase-automation.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { FactoryRunBindingRecord, WorkItemsStorage, Card } 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: Card | null | undefined): string | undefined {\n return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : undefined;\n}\n\nfunction itemInRuleStage(boards: BoardRegistry, item: Card | null | undefined): item is Card {\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\nconst STAMP_ATTEMPTS = 3;\n\n/** When the card's current visit to `stage` began, if it is in `stage` alone. */\nfunction openEntry(item: Card, stage: string): string | undefined {\n if (item.stages.length !== 1 || item.stages[0] !== stage) return undefined;\n return item.stageHistory?.findLast(entry => entry.stage === stage && entry.exitedAt === undefined)?.enteredAt;\n}\n\n/**\n * The phase this result finishes: the card's phase whose exit tool succeeded (for `submit_plan`,\n * with an approved plan) in the session that works the card there. Undefined otherwise.\n */\nfunction finishedPhase(\n boards: BoardRegistry,\n board: string,\n item: Card,\n role: string,\n toolResult: CompletedToolResult,\n): string | undefined {\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n const definition = boards.get(board);\n const phase = stage === undefined ? undefined : definition?.phases[stage];\n if (phase?.kind !== 'working' || phase.exitTool?.id !== toolResult.toolName) return undefined;\n if (toolResult.status !== 'success') return undefined;\n if (toolResult.toolName === 'submit_plan' && !isApprovedPlanResult(toolResult)) return undefined;\n // Only the session that works the card in this phase finishes it: one in another context that\n // still holds the card (a triage session, say) calling the same tool leaves the phase unfinished.\n // A Work card planned before Planning ran in the `work` context still holds its `plan` session.\n if (role !== phase.runner.context && workStageCarries(definition, stage!, role, undefined) !== true) {\n return undefined;\n }\n return stage;\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 defaultThinkingLevel: 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, defaultThinkingLevel),\n };\n}\n\nfunction workItemSourceKey(item: Card): 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 // A result read during the run is the tool's in-memory value (submit_plan's holds undefined\n // fields); read it as the JSON the thread stores, so it means the same now as after the run.\n return normalizeFactoryRuleJsonValue(value === undefined ? null : JSON.parse(JSON.stringify(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\n/**\n * The tool results the step about to run follows: the latest assistant message, past any signals\n * after it. A run continued after a tool call (such as submit_plan's approval) carries steps\n * without their tool results, so the step ids alone can miss the result the agent acts on next.\n */\nfunction latestToolResultMessage(messages: MastraDBMessage[]): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if ((message.role as string) === 'signal') continue;\n return message.role === 'assistant' && completedToolResults(message).length > 0 ? message : undefined;\n }\n return undefined;\n}\n\nasync function phaseCacheKey(value: ActivePhaseSnapshotValue, linked: Card[]): 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 private readonly bindingReconciles = new Map<string, Promise<void>>();\n private readonly boards: ProjectBoardSource;\n\n constructor(\n private readonly options: {\n configVersion: string;\n storage: WorkItemsStorage;\n boards: BoardRegistry | ProjectBoardSource;\n loadMemorySettings?: (args: {\n requestContext: ProcessInputStepArgs['requestContext'];\n binding: FactoryRunBindingRecord | null;\n }) => Promise<void>;\n /** The session's routed thinking default, used when the session has not picked a level. */\n defaultThinkingLevel?: (requestContext: ComputeStateSignalArgs['requestContext']) => Promise<ThinkingLevel>;\n /** Called on every step of a run on an active bound thread, so an idle dispatcher reconciles its tool results. */\n onBoundThreadRun?: () => void;\n transitionService?: Pick<FactoryTransitionService, 'transition'>;\n messageReader?: PersistedMessageReader;\n recordPullRequestProvenance?: (input: {\n binding: FactoryRunBindingRecord;\n item: Card;\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 this.boards = toBoardSource(options.boards);\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 this.options.onBoundThreadRun?.();\n const completedToolCallIds = completedStepToolCallIds(args.steps);\n const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);\n if (completedMessage) {\n await this.ingestMessages(binding, [completedMessage], completedToolCallIds);\n return;\n }\n const latest = latestToolResultMessage(args.messages);\n if (latest) await this.ingestMessages(binding, [latest]);\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 // Say where the card went, so the session stops its work instead of guessing why its phase vanished.\n const moved = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const movedBoards = moved ? await this.boards.load(binding) : undefined;\n const movedTo = moved && movedBoards ? ruleStage(movedBoards, moved) : undefined;\n const movedName = movedTo\n ? (movedBoards?.get(boardForWorkItem(moved!))?.phases[movedTo]?.name ?? movedTo)\n : undefined;\n return {\n id: STATE_ID,\n cacheKey: `factory:none:${prior.bindingId ?? 'revoked'}${movedTo ? `:${movedTo}` : ''}`,\n mode: 'snapshot',\n tagName: 'factory-phase',\n contents: movedName\n ? `This session no longer works its Factory card; the card is now in ${escapeText(movedName)}. Your part is done: do not continue its work here. Answer questions only.\\n`\n : '\\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 boards = await this.boards.load(binding);\n const stage = ruleStage(boards, item);\n if (!item || !stage) return;\n const linked = await this.options.storage.listLinked({ item, limit: 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 flow = boardFlow(boards.get(board));\n const value: ActivePhaseSnapshotValue = reviewsPullRequest({\n flow,\n item: { source: workItemSource(item.externalSource), workItem: item.workItem },\n })\n ? {\n ...baseValue,\n board,\n ...reviewRuntimeFromRequestContext(\n args.requestContext,\n await this.options.defaultThinkingLevel?.(args.requestContext),\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 definition = boards.get(board);\n const phase = definition?.phases[stage];\n const phaseLabel = phase?.name ?? stage;\n const nextText = phase\n ? `Next phases: ${\n phase.nextPhases.length\n ? phase.nextPhases\n .map(key => `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})`)\n .join('; ')\n : 'none'\n }\\n`\n : '';\n const exitText =\n phase?.kind === 'working' && phase.exitTool\n ? `This phase ends when ${escapeText(phase.exitTool.id)} succeeds${phase.exitTool.id === 'submit_plan' ? ' with an approved plan' : ''}; until then the card stays here. ${\n definition?.tools[phase.exitTool.id]\n ? 'Its result moves the card on.'\n : `Then move the card with factory_transition_work_item to one of: ${phase.nextPhases.map(escapeText).join(', ')}.`\n }\\n`\n : '';\n // Skills name phases by role in the pull request loop, never by key: this line maps them.\n const flowPhase = (key: string | undefined) =>\n key ? `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})` : undefined;\n const completed = flow.completed?.phase;\n const canceled = flow.canceled?.phase === completed ? undefined : flow.canceled?.phase;\n const flowParts = [\n definition ? `rest: ${flowPhase(definition.initialPhase)}` : undefined,\n flow.triage ? `triage: ${flowPhase(flow.triage)}` : undefined,\n flow.build ? `build: ${flowPhase(flow.build)}` : undefined,\n flow.selfReview ? `self-review: ${flowPhase(flow.selfReview)}` : undefined,\n flow.pullRequestReview ? `pull request review: ${flowPhase(flow.pullRequestReview)}` : undefined,\n completed ? `completed: ${flowPhase(completed)}` : undefined,\n canceled ? `canceled: ${flowPhase(canceled)}` : undefined,\n ].filter(part => part !== undefined);\n const flowText = flowParts.length ? `Board phases by part: ${flowParts.join('; ')}\\n` : '';\n // The card moved to a phase another context works; this session's tools for it are gone.\n const handedOnText =\n phase?.kind === 'working' &&\n phase.runner.context !== binding.role &&\n // A Work card planned before Planning ran in `work` keeps its `plan` session there.\n workStageCarries(definition, stage, binding.role, undefined) !== true\n ? `This card is now in ${escapeText(phaseLabel)}, which runs in the ${escapeText(phase.runner.context)} context in another session. Your part is done: do not continue its work here. Answer questions, and move the card only if it must come back to you.\\n`\n : '';\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 (phase?.kind === 'resting'\n ? `This card rests in ${escapeText(phaseLabel)}: 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 nextText +\n flowText +\n exitText +\n handedOnText +\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 previous = this.bindingReconciles.get(binding.id);\n const run = (async () => {\n if (previous) await previous.catch(() => undefined);\n await this.reconcileBindingNow(binding);\n })();\n this.bindingReconciles.set(binding.id, run);\n try {\n await run;\n } finally {\n if (this.bindingReconciles.get(binding.id) === run) this.bindingReconciles.delete(binding.id);\n }\n }\n\n private async reconcileBindingNow(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(await this.boards.load(binding), 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?: Card,\n ): Promise<void> {\n const item = preloadedItem ?? (await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }));\n if (!itemInRuleStage(await this.boards.load(binding), 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 loaded: Card,\n toolResult: CompletedToolResult,\n ): Promise<void> {\n let item = loaded;\n const board = boardForWorkItem(item);\n const boards = await this.boards.load(binding);\n const finished = finishedPhase(boards, board, item, binding.role, toolResult);\n // The exit tool finished the phase: the card may now leave it (the agent moves it). A result\n // read again later (the step, then the thread) stamps once: the stamp names its tool call.\n const at = new Date().toISOString();\n const stampedCall = (item.metadata?.[PHASE_EXIT_METADATA_KEY] as { toolCallId?: unknown } | undefined)?.toolCallId;\n if (\n finished !== undefined &&\n stampedCall !== toolResult.toolCallId &&\n !exitToolSucceeded(item, finished, toolResult.toolName)\n ) {\n const entry = openEntry(item, finished);\n for (let attempt = 1; ; attempt++) {\n try {\n const stamped = await this.options.storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n patch: {\n metadata: {\n [PHASE_EXIT_METADATA_KEY]: {\n phase: finished,\n tool: toolResult.toolName,\n toolCallId: toolResult.toolCallId,\n at,\n },\n ...(toolResult.toolName === 'submit_plan' ? { planApprovedAt: at } : {}),\n },\n },\n expectedRevision: item.revision,\n });\n if (stamped) item = stamped.item;\n break;\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n // Another write landed first. While the card is still in the same visit to the phase,\n // the result still finishes it; once the card moved on, it no longer needs finishing.\n const current = await this.options.storage.get({ orgId: binding.orgId, id: item.id });\n if (!current || attempt >= STAMP_ATTEMPTS || openEntry(current, finished) !== entry || entry === undefined) {\n return;\n }\n item = current;\n }\n }\n }\n const rule = resolveBoardToolRule(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 workItem: item.workItem,\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, 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 ...(entry.reenter ? { reenter: true } : {}),\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 ...(toolResult.status === 'success' ? { completedTool: toolResult.toolName } : {}),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,SAAS,UAAU,QAAuB,MAAmD;CAC3F,OAAO,QAAQ,uBAAuB,QAAQ,IAAI,IAAI,KAAK,OAAO,KAAK,KAAA;AACzE;AAEA,SAAS,gBAAgB,QAAuB,MAA6C;CAC3F,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;AAEA,MAAM,iBAAiB;;AAGvB,SAAS,UAAU,MAAY,OAAmC;CAChE,IAAI,KAAK,OAAO,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;EAChC,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,GAAI,MAAM,UAAU,EAAE,SAAS,KAAK,IAAI,CAAC;IACzC,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;IACjE,GAAI,WAAW,WAAW,YAAY,EAAE,eAAe,WAAW,SAAS,IAAI,CAAC;GAClF,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 {\n boardFlow,\n boardForWorkItem,\n resolveBoardToolRule,\n reviewsPullRequest,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { workStageCarries } from '../boards/legacy-plan-role.js';\nimport { exitToolSucceeded, PHASE_EXIT_METADATA_KEY } from '../boards/phase-automation.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { FactoryRunBindingRecord, WorkItemsStorage, Card } 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: Card | null | undefined): string | undefined {\n return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : undefined;\n}\n\nfunction itemInRuleStage(boards: BoardRegistry, item: Card | null | undefined): item is Card {\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\nconst STAMP_ATTEMPTS = 3;\n\n/** When the card's current visit to `stage` began, if it is in `stage` alone. */\nfunction openEntry(item: Card, stage: string): string | undefined {\n if (item.stages.length !== 1 || item.stages[0] !== stage) return undefined;\n return item.stageHistory?.findLast(entry => entry.stage === stage && entry.exitedAt === undefined)?.enteredAt;\n}\n\n/**\n * The phase this result finishes: the card's phase whose exit tool succeeded (for `submit_plan`,\n * with an approved plan) in the session that works the card there. Undefined otherwise.\n */\nfunction finishedPhase(\n boards: BoardRegistry,\n board: string,\n item: Card,\n role: string,\n toolResult: CompletedToolResult,\n): string | undefined {\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n const definition = boards.get(board);\n const phase = stage === undefined ? undefined : definition?.phases[stage];\n if (phase?.kind !== 'working' || phase.exitTool?.id !== toolResult.toolName) return undefined;\n if (toolResult.status !== 'success') return undefined;\n if (toolResult.toolName === 'submit_plan' && !isApprovedPlanResult(toolResult)) return undefined;\n // Only the session that works the card in this phase finishes it: one in another context that\n // still holds the card (a triage session, say) calling the same tool leaves the phase unfinished.\n // A Work card planned before Planning ran in the `work` context still holds its `plan` session.\n if (role !== phase.runner.context && workStageCarries(definition, stage!, role, undefined) !== true) {\n return undefined;\n }\n return stage;\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 defaultThinkingLevel: 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, defaultThinkingLevel),\n };\n}\n\nfunction workItemSourceKey(item: Card): 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 // A result read during the run is the tool's in-memory value (submit_plan's holds undefined\n // fields); read it as the JSON the thread stores, so it means the same now as after the run.\n return normalizeFactoryRuleJsonValue(value === undefined ? null : JSON.parse(JSON.stringify(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\n/**\n * The tool results the step about to run follows: the latest assistant message, past any signals\n * after it. A run continued after a tool call (such as submit_plan's approval) carries steps\n * without their tool results, so the step ids alone can miss the result the agent acts on next.\n */\nfunction latestToolResultMessage(messages: MastraDBMessage[]): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if ((message.role as string) === 'signal') continue;\n return message.role === 'assistant' && completedToolResults(message).length > 0 ? message : undefined;\n }\n return undefined;\n}\n\nasync function phaseCacheKey(value: ActivePhaseSnapshotValue, linked: Card[]): 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 private readonly bindingReconciles = new Map<string, Promise<void>>();\n private readonly boards: ProjectBoardSource;\n\n constructor(\n private readonly options: {\n configVersion: string;\n storage: WorkItemsStorage;\n boards: BoardRegistry | ProjectBoardSource;\n loadMemorySettings?: (args: {\n requestContext: ProcessInputStepArgs['requestContext'];\n binding: FactoryRunBindingRecord | null;\n }) => Promise<void>;\n /** The session's routed thinking default, used when the session has not picked a level. */\n defaultThinkingLevel?: (requestContext: ComputeStateSignalArgs['requestContext']) => Promise<ThinkingLevel>;\n /** Called on every step of a run on an active bound thread, so an idle dispatcher reconciles its tool results. */\n onBoundThreadRun?: () => void;\n transitionService?: Pick<FactoryTransitionService, 'transition'>;\n messageReader?: PersistedMessageReader;\n recordPullRequestProvenance?: (input: {\n binding: FactoryRunBindingRecord;\n item: Card;\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 this.boards = toBoardSource(options.boards);\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 this.options.onBoundThreadRun?.();\n const completedToolCallIds = completedStepToolCallIds(args.steps);\n const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);\n if (completedMessage) {\n await this.ingestMessages(binding, [completedMessage], completedToolCallIds);\n return;\n }\n const latest = latestToolResultMessage(args.messages);\n if (latest) await this.ingestMessages(binding, [latest]);\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 // Say where the card went, so the session stops its work instead of guessing why its phase vanished.\n const moved = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const movedBoards = moved ? await this.boards.load(binding) : undefined;\n const movedTo = moved && movedBoards ? ruleStage(movedBoards, moved) : undefined;\n const movedName = movedTo\n ? (movedBoards?.get(boardForWorkItem(moved!))?.phases[movedTo]?.name ?? movedTo)\n : undefined;\n return {\n id: STATE_ID,\n cacheKey: `factory:none:${prior.bindingId ?? 'revoked'}${movedTo ? `:${movedTo}` : ''}`,\n mode: 'snapshot',\n tagName: 'factory-phase',\n contents: movedName\n ? `This session no longer works its Factory card; the card is now in ${escapeText(movedName)}. Your part is done: do not continue its work here. Answer questions only.\\n`\n : '\\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 boards = await this.boards.load(binding);\n const stage = ruleStage(boards, item);\n if (!item || !stage) return;\n const linked = await this.options.storage.listLinked({ item, limit: 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 flow = boardFlow(boards.get(board));\n const value: ActivePhaseSnapshotValue = reviewsPullRequest({\n flow,\n item: { source: workItemSource(item.externalSource), workItem: item.workItem },\n })\n ? {\n ...baseValue,\n board,\n ...reviewRuntimeFromRequestContext(\n args.requestContext,\n await this.options.defaultThinkingLevel?.(args.requestContext),\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 definition = boards.get(board);\n const phase = definition?.phases[stage];\n const phaseLabel = phase?.name ?? stage;\n const nextText = phase\n ? `Next phases: ${\n phase.nextPhases.length\n ? phase.nextPhases\n .map(key => `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})`)\n .join('; ')\n : 'none'\n }\\n`\n : '';\n const exitText =\n phase?.kind === 'working' && phase.exitTool\n ? `This phase ends when ${escapeText(phase.exitTool.id)} succeeds${phase.exitTool.id === 'submit_plan' ? ' with an approved plan' : ''}; until then the card stays here. ${\n definition?.tools[phase.exitTool.id]\n ? 'Its result moves the card on.'\n : `Then move the card with factory_transition_work_item to one of: ${phase.nextPhases.map(escapeText).join(', ')}.`\n }\\n`\n : '';\n // Skills name phases by role in the pull request loop, never by key: this line maps them.\n const flowPhase = (key: string | undefined) =>\n key ? `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})` : undefined;\n const completed = flow.completed?.phase;\n const canceled = flow.canceled?.phase === completed ? undefined : flow.canceled?.phase;\n const flowParts = [\n definition ? `rest: ${flowPhase(definition.initialPhase)}` : undefined,\n flow.triage ? `triage: ${flowPhase(flow.triage)}` : undefined,\n flow.build ? `build: ${flowPhase(flow.build)}` : undefined,\n flow.selfReview ? `self-review: ${flowPhase(flow.selfReview)}` : undefined,\n flow.pullRequestReview ? `pull request review: ${flowPhase(flow.pullRequestReview)}` : undefined,\n completed ? `completed: ${flowPhase(completed)}` : undefined,\n canceled ? `canceled: ${flowPhase(canceled)}` : undefined,\n ].filter(part => part !== undefined);\n const flowText = flowParts.length ? `Board phases by part: ${flowParts.join('; ')}\\n` : '';\n // The card moved to a phase another context works; this session's tools for it are gone.\n const handedOnText =\n phase?.kind === 'working' &&\n phase.runner.context !== binding.role &&\n // A Work card planned before Planning ran in `work` keeps its `plan` session there.\n workStageCarries(definition, stage, binding.role, undefined) !== true\n ? `This card is now in ${escapeText(phaseLabel)}, which runs in the ${escapeText(phase.runner.context)} context in another session. Your part is done: do not continue its work here. Answer questions, and move the card only if it must come back to you.\\n`\n : '';\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 (phase?.kind === 'resting'\n ? `This card rests in ${escapeText(phaseLabel)}: 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 nextText +\n flowText +\n exitText +\n handedOnText +\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 previous = this.bindingReconciles.get(binding.id);\n const run = (async () => {\n if (previous) await previous.catch(() => undefined);\n await this.reconcileBindingNow(binding);\n })();\n this.bindingReconciles.set(binding.id, run);\n try {\n await run;\n } finally {\n if (this.bindingReconciles.get(binding.id) === run) this.bindingReconciles.delete(binding.id);\n }\n }\n\n private async reconcileBindingNow(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(await this.boards.load(binding), 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 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?: Card,\n ): Promise<void> {\n const item = preloadedItem ?? (await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }));\n if (!itemInRuleStage(await this.boards.load(binding), 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 loaded: Card,\n toolResult: CompletedToolResult,\n ): Promise<void> {\n let item = loaded;\n const board = boardForWorkItem(item);\n const boards = await this.boards.load(binding);\n const finished = finishedPhase(boards, board, item, binding.role, toolResult);\n // The exit tool finished the phase: the card may now leave it (the agent moves it). A result\n // read again later (the step, then the thread) stamps once: the stamp names its tool call.\n const at = new Date().toISOString();\n const stampedCall = (item.metadata?.[PHASE_EXIT_METADATA_KEY] as { toolCallId?: unknown } | undefined)?.toolCallId;\n if (\n finished !== undefined &&\n stampedCall !== toolResult.toolCallId &&\n !exitToolSucceeded(item, finished, toolResult.toolName)\n ) {\n const entry = openEntry(item, finished);\n for (let attempt = 1; ; attempt++) {\n try {\n const stamped = await this.options.storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n patch: {\n metadata: {\n [PHASE_EXIT_METADATA_KEY]: {\n phase: finished,\n tool: toolResult.toolName,\n toolCallId: toolResult.toolCallId,\n at,\n },\n ...(toolResult.toolName === 'submit_plan' ? { planApprovedAt: at } : {}),\n },\n },\n expectedRevision: item.revision,\n });\n if (stamped) item = stamped.item;\n break;\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n // Another write landed first. While the card is still in the same visit to the phase,\n // the result still finishes it; once the card moved on, it no longer needs finishing.\n const current = await this.options.storage.get({ orgId: binding.orgId, id: item.id });\n if (!current || attempt >= STAMP_ATTEMPTS || openEntry(current, finished) !== entry || entry === undefined) {\n return;\n }\n item = current;\n }\n }\n }\n const rule = resolveBoardToolRule(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 workItem: item.workItem,\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, 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 },\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 ...(entry.reenter ? { reenter: true } : {}),\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 ...(toolResult.status === 'success' ? { completedTool: toolResult.toolName } : {}),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,SAAS,UAAU,QAAuB,MAAmD;CAC3F,OAAO,QAAQ,uBAAuB,QAAQ,IAAI,IAAI,KAAK,OAAO,KAAK,KAAA;AACzE;AAEA,SAAS,gBAAgB,QAAuB,MAA6C;CAC3F,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,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GAC/B,kBAAkB,KAAK;GACvB,OAAO,EAAE,GAAG,QAAQ,MAAM;GAC1B;GACA,WAAW,UAAU,KAAI,WAAU,EAAE,GAAG,MAAM,EAAE;GAChD,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;GAEd,aAAa,SAAS,QAAQ;EAChC,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,GAAI,MAAM,UAAU,EAAE,SAAS,KAAK,IAAI,CAAC;IACzC,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;IACjE,GAAI,WAAW,WAAW,YAAY,EAAE,eAAe,WAAW,SAAS,IAAI,CAAC;GAClF,CAAC;EACH;CACF;AACF"}
@@ -20,6 +20,7 @@ export interface FactoryStartRequest {
20
20
  */
21
21
  startedBy?: FactoryRuleActor;
22
22
  sessionId: string;
23
+ expectedBindingId?: string;
23
24
  threadTitle: string;
24
25
  kickoffKey: string;
25
26
  /** Where the arrival path lands the card; a session opened on an existing card names none. */
@@ -1 +1 @@
1
- {"version":3,"file":"start-coordinator.d.ts","sourceRoot":"","sources":["../../src/rules/start-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;A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ACzC,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,SAAS,GAAG,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,CAAC;IAClE,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,KAAK,iBAAiB,GAAG,eAAe,CAAC,eAAe,CAAC,CAAC;AA+B1D,qBAAa,uBAAuB;;IAclC,YACE,UAAU,EAAE,iBAAiB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,iBAAiB,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,YAAY,CAAC,EAChE,aAAa,CAAC,EACV,0BAA0B,GAC1B,CAAC,CACC,OAAO,EAAE,mBAAmB,KACzB,0BAA0B,GAAG,SAAS,GAAG,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAAC,EAClG,MAAM,CAAC,EAAE,aAAa,EACtB,YAAY,CAAC,EAAE;QAAE,QAAQ,EAAE,sBAAsB,CAAC;QAAC,aAAa,EAAE,oBAAoB,CAAA;KAAE;IACxF,uIAAuI;IACvI,MAAM,CAAC,EAAE,aAAa,GAAG,kBAAkB,EAU5C;IAEK,OAAO,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAmO/E;CACF"}
@@ -227,6 +227,7 @@ var FactoryStartCoordinator = class {
227
227
  input: request.workItem.input
228
228
  },
229
229
  role: request.workItem.role,
230
+ expectedBindingId: request.expectedBindingId,
230
231
  session: {
231
232
  sessionId: sourceSession.sessionId,
232
233
  branch: sourceSession.branch,
@@ -265,7 +266,7 @@ var FactoryStartCoordinator = class {
265
266
  cause: "run_start"
266
267
  });
267
268
  if (transition.status === "rejected") {
268
- await storage.markPendingStart(prepared.binding.id, "failed", transition.reason);
269
+ await storage.markPendingStart(prepared.binding.id, "failed");
269
270
  throw new FactoryStartTransitionError(transition);
270
271
  }
271
272
  revision = transition.revision;
@@ -1 +1 @@
1
- {"version":3,"file":"start-coordinator.js","names":[],"sources":["../../src/rules/start-coordinator.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\n\nimport { boardForWorkItem, hasPullRequest, isPullRequestReviewPhase, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { primeTenantCredentialsForTenant } from '../routes/tenant-credentials.js';\nimport { hydrateFactorySession, resolveFactorySessionModel } from '../session/factory-session.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlSession, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { CreateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { externallyAuthoredWorkItem } from './types.js';\nimport type { FactoryRuleActor, FactoryRuleStage, FactoryTransitionResult } from './types.js';\n\nexport interface FactoryStartRequest {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /**\n * Who started the work, where that is not the session's owner: the Factory owns the\n * sessions it runs, and the move a start makes is still the mover's.\n */\n startedBy?: FactoryRuleActor;\n sessionId: string;\n threadTitle: string;\n kickoffKey: string;\n /** Where the arrival path lands the card; a session opened on an existing card names none. */\n destinationStage?: FactoryRuleStage;\n /** The run's effective scope; a hybrid Factory's runs use the Factory's model and credentials. */\n modelScope: EffectiveModelScope;\n defaultModelId?: string;\n workItem: {\n id?: string;\n role: string;\n input: CreateWorkItemInput;\n };\n requestContext?: RequestContext;\n}\n\nexport class UntrustedSharedSessionError extends Error {\n constructor(readonly sessionId: string) {\n super(\n `Session ${sessionId} already shares memory with this Factory, so it cannot run untrusted content. Start the run in a new session.`,\n );\n this.name = 'UntrustedSharedSessionError';\n }\n}\n\n/**\n * The memory resource a run works on. Trusted runs share the Factory's resource.\n * A run that reads attacker-controllable content (a pull request checkout, or a\n * card written outside the write-access circle) keeps its own resource, so it can\n * neither plant observations that trusted runs read nor read what they observed.\n * A session that was isolated stays isolated; one already sharing memory refuses\n * untrusted work instead of carrying that memory into it.\n */\nasync function runMemoryResource(\n controller: Pick<FactoryController, 'queryThreadById'>,\n input: { sessionId: string; factoryProjectId: string; untrusted: boolean },\n): Promise<string> {\n const existing = await controller.queryThreadById({ threadId: input.sessionId });\n if (existing?.resourceId === input.sessionId) return input.sessionId;\n if (!input.untrusted) return existing?.resourceId ?? input.factoryProjectId;\n if (existing) throw new UntrustedSharedSessionError(input.sessionId);\n return input.sessionId;\n}\n\nexport class WorkItemRepositoryError extends Error {\n constructor(\n readonly code: 'repository_mismatch' | 'repository_ambiguous' | 'repository_unlinked',\n message: string,\n readonly candidates: string[] = [],\n ) {\n super(message);\n this.name = 'WorkItemRepositoryError';\n }\n}\n\nexport class FactoryStartTransitionError extends Error {\n readonly result: Extract<FactoryTransitionResult, { status: 'rejected' }>;\n\n constructor(result: Extract<FactoryTransitionResult, { status: 'rejected' }>) {\n super(result.reason);\n this.name = 'FactoryStartTransitionError';\n this.result = result;\n }\n}\n\nexport interface FactoryStartPreparedResult {\n workItemId: string;\n bindingId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n revision: number;\n kickoffStatus: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n replayed: boolean;\n}\n\ntype FactoryController = AgentController<MastraCodeState>;\ntype FactorySession = Awaited<ReturnType<FactoryController['createSession']>>;\n\nasync function resolveSourceSession(\n storage: SourceControlStorageHandle,\n request: FactoryStartRequest,\n): Promise<SourceControlSession & { projectRepositoryId: string }> {\n const session = await storage.sessions.getBySessionId(request.sessionId);\n if (!session || session.orgId !== request.orgId || session.userId !== request.userId) {\n throw new Error('Factory session not found');\n }\n const projectRepositoryId = session.projectRepositoryId;\n if (!projectRepositoryId) throw new Error('Factory session repository not found');\n const projectRepository = await storage.projectRepositories.get({ orgId: request.orgId, id: projectRepositoryId });\n if (!projectRepository) throw new Error('Factory session repository not found');\n const connection = await storage.connections.get({ orgId: request.orgId, id: projectRepository.connectionId });\n if (!connection || connection.factoryProjectId !== request.factoryProjectId) {\n throw new Error('Factory session does not belong to this project');\n }\n return { ...session, projectRepositoryId };\n}\n\nasync function configureThread(session: FactorySession, request: FactoryStartRequest): Promise<string> {\n const threadId = session.thread.requireId();\n // Derived from the work item, not a user rename, so leave the title\n // unpinned and let auto-naming keep refining it.\n await session.thread.rename({ title: request.threadTitle, pin: false });\n await session.thread.setSetting({ key: 'factorySessionId', value: request.sessionId });\n return threadId;\n}\n\nexport class FactoryStartCoordinator {\n readonly #controller: FactoryController;\n readonly #storage: WorkItemsStorage;\n readonly #transitionService?: Pick<FactoryTransitionService, 'transition'>;\n readonly #sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>);\n readonly #intake?: IntakeStorage;\n readonly #projects?: FactoryProjectsStorage;\n readonly #modelDefaults?: ModelDefaultsStorage;\n readonly #boards?: ProjectBoardSource;\n\n constructor(\n controller: FactoryController,\n storage: WorkItemsStorage,\n transitionService?: Pick<FactoryTransitionService, 'transition'>,\n sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>),\n intake?: IntakeStorage,\n sessionModel?: { projects: FactoryProjectsStorage; modelDefaults: ModelDefaultsStorage },\n /** Tells a pull request review run from the card's other review runs; without it every review run with a pull request is untrusted. */\n boards?: BoardRegistry | ProjectBoardSource,\n ) {\n this.#controller = controller;\n this.#storage = storage;\n this.#transitionService = transitionService;\n this.#sourceControl = sourceControl;\n this.#intake = intake;\n this.#projects = sessionModel?.projects;\n this.#modelDefaults = sessionModel?.modelDefaults;\n this.#boards = boards ? toBoardSource(boards) : undefined;\n }\n\n async prepare(request: FactoryStartRequest): Promise<FactoryStartPreparedResult> {\n const storage = this.#storage;\n const sourceControl =\n typeof this.#sourceControl === 'function' ? await this.#sourceControl(request) : this.#sourceControl;\n if (!sourceControl) throw new Error('Factory source control storage is unavailable');\n const sourceSession = await resolveSourceSession(sourceControl, request);\n const sessionModel =\n this.#projects && this.#modelDefaults\n ? await resolveFactorySessionModel({\n projects: this.#projects,\n modelDefaults: this.#modelDefaults,\n factoryProjectId: request.factoryProjectId,\n orgId: request.orgId,\n ownerUserId: sourceSession.userId,\n context: 'run',\n })\n : { modelScope: request.modelScope, modelId: request.defaultModelId };\n const storedItem = request.workItem.id\n ? await storage.get({ orgId: request.orgId, id: request.workItem.id })\n : null;\n const intakeConfig = await this.#intake?.getConfig({ orgId: request.orgId, integrationIds: ['linear'] });\n let repository = await resolveWorkItemRepository({\n sourceControl,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n item: storedItem ?? {\n metadata: request.workItem.input.metadata ?? null,\n workItem: { metadata: request.workItem.input.metadata ?? null },\n },\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n });\n if (repository.status === 'ambiguous') {\n // A retry of this role's existing session keeps its already-chosen\n // repository; a newly minted session must not choose for the card.\n if (storedItem?.sessions[request.workItem.role]?.sessionId !== sourceSession.sessionId) {\n throw new WorkItemRepositoryError(\n 'repository_ambiguous',\n `Choose a repository for this work item: ${repository.candidates.join(', ')}.`,\n repository.candidates,\n );\n }\n const link = await sourceControl.projectRepositories.get({\n orgId: request.orgId,\n id: sourceSession.projectRepositoryId,\n });\n const linked = link && (await sourceControl.repositories.get({ orgId: request.orgId, id: link.repositoryId }));\n const currentLinks = link\n ? await sourceControl.projectRepositories.list({ orgId: request.orgId, connectionId: link.connectionId })\n : [];\n if (\n !linked ||\n !repository.candidates.includes(linked.slug) ||\n !currentLinks.some(candidate => candidate.id === sourceSession.projectRepositoryId)\n ) {\n throw new WorkItemRepositoryError(\n 'repository_unlinked',\n 'The existing session repository is not linked to this Factory.',\n );\n }\n repository = { status: 'resolved', slug: linked.slug, projectRepositoryId: sourceSession.projectRepositoryId };\n }\n if (repository.status === 'unlinked') {\n throw new WorkItemRepositoryError('repository_unlinked', repository.hint);\n }\n if (repository.projectRepositoryId !== sourceSession.projectRepositoryId) {\n throw new WorkItemRepositoryError(\n 'repository_mismatch',\n `This run session is bound to a different repository than ${repository.slug}.`,\n );\n }\n const requestContext = request.requestContext ?? new RequestContext();\n // Preserve an authenticated caller when present. Autonomous starts still\n // need a principal so deployed credential resolution can authenticate the\n // request before selecting the stamped session owner's exclusive scope.\n const existingUser = requestContext.get('user');\n if (!existingUser || typeof existingUser !== 'object') {\n requestContext.set('user', {\n workosId: request.userId,\n organizationId: request.orgId,\n });\n }\n // Sessions kicked off against third-party content (a PR under review, or\n // any pull-request-sourced work item) get `untrustedCheckout` so the SDK\n // never ingests the checkout's AGENTS.md/CLAUDE.md into the system prompt\n // or reminders — those files are attacker-writable in a PR branch.\n // An issue card's PR review checks out the attached pull request's head, so it counts too.\n // The run's stage is where the card is going: a card started from its resting phase into\n // its board's pull request review is moved only after the session is ready.\n const runStage = request.destinationStage ?? storedItem?.stages[0];\n const reviewsAttachedPullRequest =\n request.workItem.role === REVIEW_CONTEXT &&\n storedItem != null &&\n hasPullRequest({ workItem: storedItem.workItem }) &&\n (!this.#boards ||\n isPullRequestReviewPhase((await this.#boards.load(request)).get(boardForWorkItem(storedItem)), runStage));\n const untrustedCheckout =\n request.workItem.input.externalSource?.type === 'pull-request' || reviewsAttachedPullRequest;\n // The trusted ref the SDK may serve project instruction files from on an\n // untrusted checkout (the PR's base branch). Prefer the session record's\n // base branch; fall back to the intake metadata captured from the PR.\n const metadataBaseBranch = storedItem\n ? storedItem.workItem.metadata?.baseBranch\n : request.workItem.input.metadata?.baseBranch;\n const baseRef =\n (sourceSession.baseBranch || undefined) ??\n (typeof metadataBaseBranch === 'string' && metadataBaseBranch ? metadataBaseBranch : undefined);\n const memoryResourceId = await runMemoryResource(this.#controller, {\n sessionId: sourceSession.sessionId,\n factoryProjectId: request.factoryProjectId,\n untrusted:\n untrustedCheckout ||\n externallyAuthoredWorkItem(\n storedItem ?? {\n externalSource: request.workItem.input.externalSource ?? null,\n metadata: request.workItem.input.metadata ?? null,\n },\n ),\n });\n const sessionTags = {\n factoryProjectId: request.factoryProjectId,\n projectRepositoryId: sourceSession.projectRepositoryId,\n };\n // The run is addressed by its session id; its threads and memory belong to\n // the Factory, so concurrent runs share one memory resource.\n const session = await this.#controller.createSession({\n id: sourceSession.sessionId,\n ownerId: request.userId,\n resourceId: memoryResourceId,\n threadId: sourceSession.sessionId,\n requestContext,\n tags: sessionTags,\n });\n // Bound-agent authority gates (the transition tool, the factory-phase\n // processor, workspace token selection) resolve the session address from\n // controller state. Seed it server-side — `tags` covers fresh creation,\n // the explicit setState covers get-or-create returning a session another\n // caller created without them — so autonomous runs never depend on a\n // browser connecting to populate the state. `untrustedCheckout` is a\n // boolean so it rides only on state (tags are string-valued).\n const targetRepositoryInstruction = `Target repository: ${repository.slug}. Before editing files or creating a pull request, verify this session's checkout matches the target repository.`;\n const existingPluginInstructions = session.state.get()?.pluginInstructions ?? [];\n await session.state.set({\n ...sessionTags,\n // The authoritative org id for every downstream identity read (the\n // memory seam's organizationId): the session owner is a USER id, not an\n // org, so it must never be improvised from ownerId.\n factoryOrgId: request.orgId,\n factoryModelScope: sessionModel.modelScope,\n factoryOwnerUserId: sourceSession.userId,\n pluginInstructions: [\n ...existingPluginInstructions.filter(instruction => instruction !== targetRepositoryInstruction),\n targetRepositoryInstruction,\n ],\n ...(untrustedCheckout ? { untrustedCheckout: true, ...(baseRef ? { baseRef } : {}) } : {}),\n });\n await primeTenantCredentialsForTenant({\n orgId: request.orgId,\n userId: sourceSession.userId,\n credentialScope: sessionModel.modelScope,\n });\n // Apply the factory's main model before any model-dependent run work.\n // Observational-memory settings are loaded per invocation by the input processor.\n await hydrateFactorySession(session, {\n orgId: request.orgId,\n modelScope: sessionModel.modelScope,\n ownerUserId: sourceSession.userId,\n defaultModelId: sessionModel.modelId,\n });\n // The tool is `requireApproval`, and that prompt parks the run whether or not\n // someone pressed Start — a person is reading the plan, not an approval queue.\n // Starting the run was already the say-so; the rules engine still governs.\n await session.permissions.setForTool({ toolName: 'factory_transition_work_item', policy: 'allow' });\n const threadId = await configureThread(session, request);\n const prepared = await storage.prepareRunStart({\n orgId: request.orgId,\n userId: request.userId,\n factoryProjectId: request.factoryProjectId,\n workItem: { id: request.workItem.id, input: request.workItem.input },\n role: request.workItem.role,\n session: { sessionId: sourceSession.sessionId, branch: sourceSession.branch, threadId },\n resourceId: memoryResourceId,\n kickoffKey: request.kickoffKey,\n kickoffMessage: null,\n });\n await session.thread.setSetting({ key: 'factoryWorkItemId', value: prepared.item.id });\n\n let revision = prepared.item.revision;\n const destinationStage = request.destinationStage;\n if (destinationStage && (prepared.item.stages.length !== 1 || prepared.item.stages[0] !== destinationStage)) {\n if (!this.#transitionService) throw new Error('Factory transition service is unavailable.');\n const transition = await this.#transitionService.transition({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: prepared.item.id,\n board: boardForWorkItem(prepared.item),\n stage: destinationStage,\n expectedRevision: prepared.item.revision,\n actor:\n request.startedBy ??\n (isFactoryPrincipalId(request.userId)\n ? { type: 'system', id: request.userId }\n : { type: 'human', id: request.userId }),\n ingress: { type: 'human', identity: `start:${request.kickoffKey}:transition` },\n cause: 'run_start',\n });\n if (transition.status === 'rejected') {\n await storage.markPendingStart(prepared.binding.id, 'failed', transition.reason);\n throw new FactoryStartTransitionError(transition);\n }\n revision = transition.revision;\n }\n\n await storage.markPendingStart(prepared.binding.id, 'sent');\n prepared.pendingStart.status = 'sent';\n\n return {\n workItemId: prepared.item.id,\n bindingId: prepared.binding.id,\n threadId,\n resourceId: memoryResourceId,\n sessionId: sourceSession.sessionId,\n branch: sourceSession.branch,\n revision,\n kickoffStatus: prepared.pendingStart.status,\n replayed: prepared.replayed,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,IAAa,8BAAb,cAAiD,MAAM;CAChC;CAArB,YAAY,WAA4B;EACtC,MACE,WAAW,UAAU,8GACvB;EAHmB,KAAA,YAAA;EAInB,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,eAAe,kBACb,YACA,OACiB;CACjB,MAAM,WAAW,MAAM,WAAW,gBAAgB,EAAE,UAAU,MAAM,UAAU,CAAC;CAC/E,IAAI,UAAU,eAAe,MAAM,WAAW,OAAO,MAAM;CAC3D,IAAI,CAAC,MAAM,WAAW,OAAO,UAAU,cAAc,MAAM;CAC3D,IAAI,UAAU,MAAM,IAAI,4BAA4B,MAAM,SAAS;CACnE,OAAO,MAAM;AACf;AAEA,IAAa,0BAAb,cAA6C,MAAM;CAEtC;CAEA;CAHX,YACE,MACA,SACA,aAAgC,CAAC,GACjC;EACA,MAAM,OAAO;EAJJ,KAAA,OAAA;EAEA,KAAA,aAAA;EAGT,KAAK,OAAO;CACd;AACF;AAEA,IAAa,8BAAb,cAAiD,MAAM;CACrD;CAEA,YAAY,QAAkE;EAC5E,MAAM,OAAO,MAAM;EACnB,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAiBA,eAAe,qBACb,SACA,SACiE;CACjE,MAAM,UAAU,MAAM,QAAQ,SAAS,eAAe,QAAQ,SAAS;CACvE,IAAI,CAAC,WAAW,QAAQ,UAAU,QAAQ,SAAS,QAAQ,WAAW,QAAQ,QAC5E,MAAM,IAAI,MAAM,2BAA2B;CAE7C,MAAM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,MAAM,QAAQ,OAAO,WAAW;GAAE,KAAK;GAAqB,OAAO,SAAS,KAAK;EAAG,CAAC;EAErF,IAAI,WAAW,SAAS,KAAK;EAC7B,MAAM,mBAAmB,QAAQ;EACjC,IAAI,qBAAqB,SAAS,KAAK,OAAO,WAAW,KAAK,SAAS,KAAK,OAAO,OAAO,mBAAmB;GAC3G,IAAI,CAAC,KAAK,oBAAoB,MAAM,IAAI,MAAM,4CAA4C;GAC1F,MAAM,aAAa,MAAM,KAAK,mBAAmB,WAAW;IAC1D,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B,YAAY,SAAS,KAAK;IAC1B,OAAO,iBAAiB,SAAS,IAAI;IACrC,OAAO;IACP,kBAAkB,SAAS,KAAK;IAChC,OACE,QAAQ,cACP,qBAAqB,QAAQ,MAAM,IAChC;KAAE,MAAM;KAAU,IAAI,QAAQ;IAAO,IACrC;KAAE,MAAM;KAAS,IAAI,QAAQ;IAAO;IAC1C,SAAS;KAAE,MAAM;KAAS,UAAU,SAAS,QAAQ,WAAW;IAAa;IAC7E,OAAO;GACT,CAAC;GACD,IAAI,WAAW,WAAW,YAAY;IACpC,MAAM,QAAQ,iBAAiB,SAAS,QAAQ,IAAI,UAAU,WAAW,MAAM;IAC/E,MAAM,IAAI,4BAA4B,UAAU;GAClD;GACA,WAAW,WAAW;EACxB;EAEA,MAAM,QAAQ,iBAAiB,SAAS,QAAQ,IAAI,MAAM;EAC1D,SAAS,aAAa,SAAS;EAE/B,OAAO;GACL,YAAY,SAAS,KAAK;GAC1B,WAAW,SAAS,QAAQ;GAC5B;GACA,YAAY;GACZ,WAAW,cAAc;GACzB,QAAQ,cAAc;GACtB;GACA,eAAe,SAAS,aAAa;GACrC,UAAU,SAAS;EACrB;CACF;AACF"}
1
+ {"version":3,"file":"start-coordinator.js","names":[],"sources":["../../src/rules/start-coordinator.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\n\nimport { boardForWorkItem, hasPullRequest, isPullRequestReviewPhase, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { primeTenantCredentialsForTenant } from '../routes/tenant-credentials.js';\nimport { hydrateFactorySession, resolveFactorySessionModel } from '../session/factory-session.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlSession, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { CreateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { externallyAuthoredWorkItem } from './types.js';\nimport type { FactoryRuleActor, FactoryRuleStage, FactoryTransitionResult } from './types.js';\n\nexport interface FactoryStartRequest {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /**\n * Who started the work, where that is not the session's owner: the Factory owns the\n * sessions it runs, and the move a start makes is still the mover's.\n */\n startedBy?: FactoryRuleActor;\n sessionId: string;\n expectedBindingId?: string;\n threadTitle: string;\n kickoffKey: string;\n /** Where the arrival path lands the card; a session opened on an existing card names none. */\n destinationStage?: FactoryRuleStage;\n /** The run's effective scope; a hybrid Factory's runs use the Factory's model and credentials. */\n modelScope: EffectiveModelScope;\n defaultModelId?: string;\n workItem: {\n id?: string;\n role: string;\n input: CreateWorkItemInput;\n };\n requestContext?: RequestContext;\n}\n\nexport class UntrustedSharedSessionError extends Error {\n constructor(readonly sessionId: string) {\n super(\n `Session ${sessionId} already shares memory with this Factory, so it cannot run untrusted content. Start the run in a new session.`,\n );\n this.name = 'UntrustedSharedSessionError';\n }\n}\n\n/**\n * The memory resource a run works on. Trusted runs share the Factory's resource.\n * A run that reads attacker-controllable content (a pull request checkout, or a\n * card written outside the write-access circle) keeps its own resource, so it can\n * neither plant observations that trusted runs read nor read what they observed.\n * A session that was isolated stays isolated; one already sharing memory refuses\n * untrusted work instead of carrying that memory into it.\n */\nasync function runMemoryResource(\n controller: Pick<FactoryController, 'queryThreadById'>,\n input: { sessionId: string; factoryProjectId: string; untrusted: boolean },\n): Promise<string> {\n const existing = await controller.queryThreadById({ threadId: input.sessionId });\n if (existing?.resourceId === input.sessionId) return input.sessionId;\n if (!input.untrusted) return existing?.resourceId ?? input.factoryProjectId;\n if (existing) throw new UntrustedSharedSessionError(input.sessionId);\n return input.sessionId;\n}\n\nexport class WorkItemRepositoryError extends Error {\n constructor(\n readonly code: 'repository_mismatch' | 'repository_ambiguous' | 'repository_unlinked',\n message: string,\n readonly candidates: string[] = [],\n ) {\n super(message);\n this.name = 'WorkItemRepositoryError';\n }\n}\n\nexport class FactoryStartTransitionError extends Error {\n readonly result: Extract<FactoryTransitionResult, { status: 'rejected' }>;\n\n constructor(result: Extract<FactoryTransitionResult, { status: 'rejected' }>) {\n super(result.reason);\n this.name = 'FactoryStartTransitionError';\n this.result = result;\n }\n}\n\nexport interface FactoryStartPreparedResult {\n workItemId: string;\n bindingId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n revision: number;\n kickoffStatus: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n replayed: boolean;\n}\n\ntype FactoryController = AgentController<MastraCodeState>;\ntype FactorySession = Awaited<ReturnType<FactoryController['createSession']>>;\n\nasync function resolveSourceSession(\n storage: SourceControlStorageHandle,\n request: FactoryStartRequest,\n): Promise<SourceControlSession & { projectRepositoryId: string }> {\n const session = await storage.sessions.getBySessionId(request.sessionId);\n if (!session || session.orgId !== request.orgId || session.userId !== request.userId) {\n throw new Error('Factory session not found');\n }\n const projectRepositoryId = session.projectRepositoryId;\n if (!projectRepositoryId) throw new Error('Factory session repository not found');\n const projectRepository = await storage.projectRepositories.get({ orgId: request.orgId, id: projectRepositoryId });\n if (!projectRepository) throw new Error('Factory session repository not found');\n const connection = await storage.connections.get({ orgId: request.orgId, id: projectRepository.connectionId });\n if (!connection || connection.factoryProjectId !== request.factoryProjectId) {\n throw new Error('Factory session does not belong to this project');\n }\n return { ...session, projectRepositoryId };\n}\n\nasync function configureThread(session: FactorySession, request: FactoryStartRequest): Promise<string> {\n const threadId = session.thread.requireId();\n // Derived from the work item, not a user rename, so leave the title\n // unpinned and let auto-naming keep refining it.\n await session.thread.rename({ title: request.threadTitle, pin: false });\n await session.thread.setSetting({ key: 'factorySessionId', value: request.sessionId });\n return threadId;\n}\n\nexport class FactoryStartCoordinator {\n readonly #controller: FactoryController;\n readonly #storage: WorkItemsStorage;\n readonly #transitionService?: Pick<FactoryTransitionService, 'transition'>;\n readonly #sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>);\n readonly #intake?: IntakeStorage;\n readonly #projects?: FactoryProjectsStorage;\n readonly #modelDefaults?: ModelDefaultsStorage;\n readonly #boards?: ProjectBoardSource;\n\n constructor(\n controller: FactoryController,\n storage: WorkItemsStorage,\n transitionService?: Pick<FactoryTransitionService, 'transition'>,\n sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>),\n intake?: IntakeStorage,\n sessionModel?: { projects: FactoryProjectsStorage; modelDefaults: ModelDefaultsStorage },\n /** Tells a pull request review run from the card's other review runs; without it every review run with a pull request is untrusted. */\n boards?: BoardRegistry | ProjectBoardSource,\n ) {\n this.#controller = controller;\n this.#storage = storage;\n this.#transitionService = transitionService;\n this.#sourceControl = sourceControl;\n this.#intake = intake;\n this.#projects = sessionModel?.projects;\n this.#modelDefaults = sessionModel?.modelDefaults;\n this.#boards = boards ? toBoardSource(boards) : undefined;\n }\n\n async prepare(request: FactoryStartRequest): Promise<FactoryStartPreparedResult> {\n const storage = this.#storage;\n const sourceControl =\n typeof this.#sourceControl === 'function' ? await this.#sourceControl(request) : this.#sourceControl;\n if (!sourceControl) throw new Error('Factory source control storage is unavailable');\n const sourceSession = await resolveSourceSession(sourceControl, request);\n const sessionModel =\n this.#projects && this.#modelDefaults\n ? await resolveFactorySessionModel({\n projects: this.#projects,\n modelDefaults: this.#modelDefaults,\n factoryProjectId: request.factoryProjectId,\n orgId: request.orgId,\n ownerUserId: sourceSession.userId,\n context: 'run',\n })\n : { modelScope: request.modelScope, modelId: request.defaultModelId };\n const storedItem = request.workItem.id\n ? await storage.get({ orgId: request.orgId, id: request.workItem.id })\n : null;\n const intakeConfig = await this.#intake?.getConfig({ orgId: request.orgId, integrationIds: ['linear'] });\n let repository = await resolveWorkItemRepository({\n sourceControl,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n item: storedItem ?? {\n metadata: request.workItem.input.metadata ?? null,\n workItem: { metadata: request.workItem.input.metadata ?? null },\n },\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n });\n if (repository.status === 'ambiguous') {\n // A retry of this role's existing session keeps its already-chosen\n // repository; a newly minted session must not choose for the card.\n if (storedItem?.sessions[request.workItem.role]?.sessionId !== sourceSession.sessionId) {\n throw new WorkItemRepositoryError(\n 'repository_ambiguous',\n `Choose a repository for this work item: ${repository.candidates.join(', ')}.`,\n repository.candidates,\n );\n }\n const link = await sourceControl.projectRepositories.get({\n orgId: request.orgId,\n id: sourceSession.projectRepositoryId,\n });\n const linked = link && (await sourceControl.repositories.get({ orgId: request.orgId, id: link.repositoryId }));\n const currentLinks = link\n ? await sourceControl.projectRepositories.list({ orgId: request.orgId, connectionId: link.connectionId })\n : [];\n if (\n !linked ||\n !repository.candidates.includes(linked.slug) ||\n !currentLinks.some(candidate => candidate.id === sourceSession.projectRepositoryId)\n ) {\n throw new WorkItemRepositoryError(\n 'repository_unlinked',\n 'The existing session repository is not linked to this Factory.',\n );\n }\n repository = { status: 'resolved', slug: linked.slug, projectRepositoryId: sourceSession.projectRepositoryId };\n }\n if (repository.status === 'unlinked') {\n throw new WorkItemRepositoryError('repository_unlinked', repository.hint);\n }\n if (repository.projectRepositoryId !== sourceSession.projectRepositoryId) {\n throw new WorkItemRepositoryError(\n 'repository_mismatch',\n `This run session is bound to a different repository than ${repository.slug}.`,\n );\n }\n const requestContext = request.requestContext ?? new RequestContext();\n // Preserve an authenticated caller when present. Autonomous starts still\n // need a principal so deployed credential resolution can authenticate the\n // request before selecting the stamped session owner's exclusive scope.\n const existingUser = requestContext.get('user');\n if (!existingUser || typeof existingUser !== 'object') {\n requestContext.set('user', {\n workosId: request.userId,\n organizationId: request.orgId,\n });\n }\n // Sessions kicked off against third-party content (a PR under review, or\n // any pull-request-sourced work item) get `untrustedCheckout` so the SDK\n // never ingests the checkout's AGENTS.md/CLAUDE.md into the system prompt\n // or reminders — those files are attacker-writable in a PR branch.\n // An issue card's PR review checks out the attached pull request's head, so it counts too.\n // The run's stage is where the card is going: a card started from its resting phase into\n // its board's pull request review is moved only after the session is ready.\n const runStage = request.destinationStage ?? storedItem?.stages[0];\n const reviewsAttachedPullRequest =\n request.workItem.role === REVIEW_CONTEXT &&\n storedItem != null &&\n hasPullRequest({ workItem: storedItem.workItem }) &&\n (!this.#boards ||\n isPullRequestReviewPhase((await this.#boards.load(request)).get(boardForWorkItem(storedItem)), runStage));\n const untrustedCheckout =\n request.workItem.input.externalSource?.type === 'pull-request' || reviewsAttachedPullRequest;\n // The trusted ref the SDK may serve project instruction files from on an\n // untrusted checkout (the PR's base branch). Prefer the session record's\n // base branch; fall back to the intake metadata captured from the PR.\n const metadataBaseBranch = storedItem\n ? storedItem.workItem.metadata?.baseBranch\n : request.workItem.input.metadata?.baseBranch;\n const baseRef =\n (sourceSession.baseBranch || undefined) ??\n (typeof metadataBaseBranch === 'string' && metadataBaseBranch ? metadataBaseBranch : undefined);\n const memoryResourceId = await runMemoryResource(this.#controller, {\n sessionId: sourceSession.sessionId,\n factoryProjectId: request.factoryProjectId,\n untrusted:\n untrustedCheckout ||\n externallyAuthoredWorkItem(\n storedItem ?? {\n externalSource: request.workItem.input.externalSource ?? null,\n metadata: request.workItem.input.metadata ?? null,\n },\n ),\n });\n const sessionTags = {\n factoryProjectId: request.factoryProjectId,\n projectRepositoryId: sourceSession.projectRepositoryId,\n };\n // The run is addressed by its session id; its threads and memory belong to\n // the Factory, so concurrent runs share one memory resource.\n const session = await this.#controller.createSession({\n id: sourceSession.sessionId,\n ownerId: request.userId,\n resourceId: memoryResourceId,\n threadId: sourceSession.sessionId,\n requestContext,\n tags: sessionTags,\n });\n // Bound-agent authority gates (the transition tool, the factory-phase\n // processor, workspace token selection) resolve the session address from\n // controller state. Seed it server-side — `tags` covers fresh creation,\n // the explicit setState covers get-or-create returning a session another\n // caller created without them — so autonomous runs never depend on a\n // browser connecting to populate the state. `untrustedCheckout` is a\n // boolean so it rides only on state (tags are string-valued).\n const targetRepositoryInstruction = `Target repository: ${repository.slug}. Before editing files or creating a pull request, verify this session's checkout matches the target repository.`;\n const existingPluginInstructions = session.state.get()?.pluginInstructions ?? [];\n await session.state.set({\n ...sessionTags,\n // The authoritative org id for every downstream identity read (the\n // memory seam's organizationId): the session owner is a USER id, not an\n // org, so it must never be improvised from ownerId.\n factoryOrgId: request.orgId,\n factoryModelScope: sessionModel.modelScope,\n factoryOwnerUserId: sourceSession.userId,\n pluginInstructions: [\n ...existingPluginInstructions.filter(instruction => instruction !== targetRepositoryInstruction),\n targetRepositoryInstruction,\n ],\n ...(untrustedCheckout ? { untrustedCheckout: true, ...(baseRef ? { baseRef } : {}) } : {}),\n });\n await primeTenantCredentialsForTenant({\n orgId: request.orgId,\n userId: sourceSession.userId,\n credentialScope: sessionModel.modelScope,\n });\n // Apply the factory's main model before any model-dependent run work.\n // Observational-memory settings are loaded per invocation by the input processor.\n await hydrateFactorySession(session, {\n orgId: request.orgId,\n modelScope: sessionModel.modelScope,\n ownerUserId: sourceSession.userId,\n defaultModelId: sessionModel.modelId,\n });\n // The tool is `requireApproval`, and that prompt parks the run whether or not\n // someone pressed Start — a person is reading the plan, not an approval queue.\n // Starting the run was already the say-so; the rules engine still governs.\n await session.permissions.setForTool({ toolName: 'factory_transition_work_item', policy: 'allow' });\n const threadId = await configureThread(session, request);\n const prepared = await storage.prepareRunStart({\n orgId: request.orgId,\n userId: request.userId,\n factoryProjectId: request.factoryProjectId,\n workItem: { id: request.workItem.id, input: request.workItem.input },\n role: request.workItem.role,\n expectedBindingId: request.expectedBindingId,\n session: { sessionId: sourceSession.sessionId, branch: sourceSession.branch, threadId },\n resourceId: memoryResourceId,\n kickoffKey: request.kickoffKey,\n kickoffMessage: null,\n });\n await session.thread.setSetting({ key: 'factoryWorkItemId', value: prepared.item.id });\n\n let revision = prepared.item.revision;\n const destinationStage = request.destinationStage;\n if (destinationStage && (prepared.item.stages.length !== 1 || prepared.item.stages[0] !== destinationStage)) {\n if (!this.#transitionService) throw new Error('Factory transition service is unavailable.');\n const transition = await this.#transitionService.transition({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: prepared.item.id,\n board: boardForWorkItem(prepared.item),\n stage: destinationStage,\n expectedRevision: prepared.item.revision,\n actor:\n request.startedBy ??\n (isFactoryPrincipalId(request.userId)\n ? { type: 'system', id: request.userId }\n : { type: 'human', id: request.userId }),\n ingress: { type: 'human', identity: `start:${request.kickoffKey}:transition` },\n cause: 'run_start',\n });\n if (transition.status === 'rejected') {\n await storage.markPendingStart(prepared.binding.id, 'failed');\n throw new FactoryStartTransitionError(transition);\n }\n revision = transition.revision;\n }\n\n await storage.markPendingStart(prepared.binding.id, 'sent');\n prepared.pendingStart.status = 'sent';\n\n return {\n workItemId: prepared.item.id,\n bindingId: prepared.binding.id,\n threadId,\n resourceId: memoryResourceId,\n sessionId: sourceSession.sessionId,\n branch: sourceSession.branch,\n revision,\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AO,EAAE,+BAA+B,EAWnD;IAED,IAAI,aAAa,IAAI,MAAM,CAE1B;IAEK,UAAU,CAAC,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,uBAAuB,CAAC,CA4BpF;CAqZF"}
@@ -384,10 +384,8 @@ var FactoryTransitionService = class {
384
384
  actorId: actorId(request.actor),
385
385
  ingress: {
386
386
  identity: request.ingress.identity,
387
- triggerType: request.ingress.type,
388
387
  transitionId
389
388
  },
390
- configVersion: this.#configVersion,
391
389
  causalChain: [...request.causalChain ?? []],
392
390
  evaluation
393
391
  });