@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":"transition-service.js","names":[],"sources":["../../src/rules/transition-service.ts"],"sourcesContent":["import { DEFAULT_BOARD_ID, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { autoApprovedExitTool, exitToolSucceeded } from '../boards/phase-automation.js';\nimport { phaseRunDecision } from '../boards/phase-runner.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { boardFlow, boardForWorkItem, hasPullRequest, pullRequestCardRejection } from '../boards/semantics.js';\nimport { boardTransitionPolicyResultSchema, immutablePolicySnapshot } from '../boards/transition-policy.js';\nimport type { AuditActorProfileInput, AuditActorType, AuditContext } from '../storage/domains/audit/base.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport { isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport { isAgentActor } from '../storage/domains/work-items/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleActor,\n FactoryRuleBoard,\n FactoryRuleCausalEntry,\n FactoryRuleRejectionCode,\n FactoryRuleStage,\n FactoryStageRuleContext,\n FactoryTransitionResult,\n FactoryTransitionResultRejected,\n} from './types.js';\nimport { factoryRuleSourceForWorkItem, workItemSource } from './types.js';\nimport {\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n assertFactoryDecisionTarget,\n validateFactoryRuleDecision,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\nconst MAX_REJECTION_REASON = 512;\n/** Longest a committed transition waits for terminal resource cleanup. Cleanup\n * reattaches remote sandboxes, so a hung provider call must not leave the\n * already-committed transition request pending; past this bound the cleanup\n * keeps running in the background as pure best-effort. */\nconst TERMINAL_CLEANUP_TIMEOUT_MS = 30_000;\n\nexport interface FactoryTransitionRequest {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** Installed board id; the service rejects boards that are not installed. */\n board: string;\n stage: FactoryRuleStage;\n expectedRevision: number;\n actor: FactoryRuleActor;\n actorProfile?: AuditActorProfileInput;\n /** Where a browser request came from; rules and agents carry none. */\n context?: AuditContext;\n ingress: { type: 'human' | 'agent' | 'toolResult' | 'github' | 'rule'; identity: string; transitionId?: string };\n cause: string;\n causalChain?: readonly FactoryRuleCausalEntry[];\n /** Internal materialization path: start the destination phase's runner even when already at that stage. */\n initialEntry?: boolean;\n /** Starts the stage's runner again when the item already holds that stage, to restart work the entry invalidated. */\n reenter?: boolean;\n /** Internal proof that this move consumes an approved `submit_plan` result. */\n planApproved?: true;\n /** Internal: the tool whose successful result this move consumes (a tool-result rule's move). */\n completedTool?: string;\n /**\n * Internal: an intake route moves the card on a status event. A route is admin-authored, so it\n * may name any phase on the card's board regardless of the board's next phases, working ones\n * included. The phase's `autoStart` and the dispatcher's approval check decide whether its run starts.\n */\n eventRoute?: { routeId: string };\n}\n\nexport interface FactoryTransitionServiceOptions {\n configVersion: string;\n storage: WorkItemsStorage;\n /** A fixed registry, or the per-project boards; each transition loads its project's boards. */\n boards?: BoardRegistry | ProjectBoardSource;\n /** Every commit, accepted or rejected, lands here as `stage_moved` / `transition_rejected` under the request's actor. */\n audit?: AuditRecorder;\n timeoutMs?: number;\n /**\n * Called after a transition commits into a phase the board declares\n * terminal — the point where the item's sessions stop receiving runs, so\n * resources they hold (e.g. sandboxes) can be released for reuse. Awaited,\n * but failures are swallowed: releasing resources must never break or roll\n * back the committed transition.\n */\n onTerminalStage?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n stage: FactoryRuleStage;\n revision: number;\n /** The actor that committed this terminal transition. Lets cleanup leave\n * the seat that drove its own transition (an agent tool call) untouched. */\n actor: FactoryRuleActor;\n }) => Promise<void> | void;\n /**\n * Called after a transition commits a stage change, e.g. to tell the item's\n * followers. Not awaited, and failures are logged: a notification must never\n * fail or delay the committed transition.\n */\n onTransitionCommitted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n fromStage: string | undefined;\n toStage: string;\n }) => Promise<void> | void;\n /**\n * Called after a transition commits out of the last phase that runs in a\n * context: the new phase runs in another context (or none) and is not\n * terminal, e.g. Triage → Planning. The context's session gets no more\n * runs until the card comes back, so its sandbox can stop. Awaited under\n * the same bound as `onTerminalStage`, and failures are swallowed.\n */\n onContextLeft?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** The context the card left. */\n context: string;\n /** The context the new phase runs in, if it runs one. */\n toContext: string | undefined;\n revision: number;\n actor: FactoryRuleActor;\n }) => Promise<void> | void;\n /** Upper bound on how long a committed transition waits for\n * `onTerminalStage` or `onContextLeft` before returning (default 30s). The\n * cleanup continues in the background past the bound. */\n terminalCleanupTimeoutMs?: number;\n /**\n * Called after a person moves a Work card from Intake or Triage into Planning or\n * Building, which approves the work. Fire-and-forget: failures are swallowed, the committed transition never\n * depends on it.\n */\n onAccepted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n item: Card;\n }) => Promise<void> | void;\n}\n\nfunction rejection(\n transitionId: string,\n itemId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n): FactoryTransitionResult {\n return { status: 'rejected', transitionId, itemId, code, reason: reason.slice(0, MAX_REJECTION_REASON) };\n}\n\nfunction actorId(actor: FactoryRuleActor): string {\n switch (actor.type) {\n case 'human':\n case 'system':\n return actor.id;\n case 'agent':\n return `agent:${actor.bindingId}`;\n case 'github':\n return `github:${actor.login}`;\n case 'gitlab':\n return `gitlab:${actor.username}`;\n }\n}\n\n// The dispatcher executes an agent-approved decision as a human actor so its consent carries; the trail still names the agent.\nexport function auditActorOf(actor: FactoryRuleActor): { actorId: string; actorType: AuditActorType } {\n const id = actorId(actor);\n switch (actor.type) {\n case 'github':\n case 'gitlab':\n return { actorId: id, actorType: 'human' };\n case 'human':\n return { actorId: id, actorType: isAgentActor(id) ? 'agent' : isFactoryPrincipalId(id) ? 'system' : 'human' };\n default:\n return { actorId: id, actorType: actor.type };\n }\n}\n\nfunction isStale(result: FactoryTransitionResult): result is FactoryTransitionResultRejected {\n return result.status === 'rejected' && result.code === 'stale';\n}\n\n/** Tell the caller where the card is now, so a model doesn't read \"stale\" as \"already moved\". */\nfunction staleRejection(result: FactoryTransitionResultRejected, current: Card): FactoryTransitionResult {\n const stage = currentStage(current.stages) ?? current.stages.join(', ');\n return rejection(\n result.transitionId,\n result.itemId,\n 'stale',\n `The card changed (now revision ${current.revision}, in ${stage}). Retry with expectedRevision ${current.revision} if the move still applies.`,\n );\n}\n\nexport function currentStage(stages: readonly string[]): FactoryRuleStage | undefined {\n return stages.length === 1 ? stages[0] : undefined;\n}\n\ninterface TransitionConsentOptions {\n autonomy?: 'arm' | 'disarm';\n consentedBy?: string;\n /** A person moved a card into its board's build seat from before it (see {@link acceptsWork}): that move approves the work. */\n accepted?: boolean;\n}\n\n/**\n * Whether moving a card from `from` to `to` hands it to the board's builder for the first time: `to`\n * runs in the seat of the board's build phase ({@link boardFlow}), and `from` is a resting phase or a\n * working phase of another seat that is no review (Work: Intake or Triage into Planning or Building).\n */\nfunction acceptsWork(board: InstalledBoard, from: string, to: string): boolean {\n const buildRole = boardFlow(board).buildRole;\n if (!buildRole || board.roleForPhase(to) !== buildRole) return false;\n const fromPhase = board.phases[from];\n if (!fromPhase || fromPhase.kind === 'terminal') return false;\n if (fromPhase.kind === 'resting') return true;\n const fromRole = fromPhase.runner.context;\n return fromRole !== buildRole && fromRole !== REVIEW_CONTEXT;\n}\n\n// Entering a resting lane disarms whoever rests it; only a person's move into a working lane arms.\nfunction transitionConsent(working: boolean, humanMove: boolean): 'arm' | 'disarm' | undefined {\n if (!working) return 'disarm';\n return humanMove ? 'arm' : undefined;\n}\n\n// An event arriving as data (GitHub, sweeps) never pre-approves the runs its transition queues.\nfunction bearsConsent(actor: FactoryRuleActor): boolean {\n return actor.type === 'human' || actor.type === 'agent';\n}\n\n// Rides the transition's own revision-checked commit, so a stale or rejected commit flips nothing.\nfunction consentEffect(\n request: FactoryTransitionRequest,\n working: boolean,\n humanMove: boolean,\n): TransitionConsentOptions {\n // A provider event (a reopen, a close) is not a person's say-so: whatever a person armed before\n // no longer stands once a route moves the card.\n if (request.eventRoute) return { autonomy: 'disarm' };\n const autonomy = transitionConsent(working, humanMove);\n return bearsConsent(request.actor) ? { autonomy, consentedBy: actorId(request.actor) } : { autonomy };\n}\n\ntype RunStartDecision = Extract<FactoryCommitDecision, { type: 'invokeSkill' | 'sendMessage' }>;\n\nfunction startsRun(decision: FactoryCommitDecision): decision is RunStartDecision {\n return decision.type === 'invokeSkill' || (decision.type === 'sendMessage' && decision.prepareBinding === true);\n}\n\n// Answering a recorded run start, or the role's own mid-run agent, with a run would start a second one.\n// A run that starts after its own agent's move is queued onto that agent's run instead.\nfunction runAlreadyUnderway(request: FactoryTransitionRequest, decision: RunStartDecision): boolean {\n if (request.cause === 'run_start') return true;\n if (decision.type === 'invokeSkill' && decision.startsAfterOwnMove === true) return false;\n return request.actor.type === 'agent' && request.actor.role === decision.role;\n}\n\nfunction stageTransitionMessage(fromStage: FactoryRuleStage, toStage: FactoryRuleStage): string {\n return `This work was moved from the ${fromStage} stage to the ${toStage} stage.`;\n}\n\nfunction isHumanTransition(request: FactoryTransitionRequest): boolean {\n return request.actor.type === 'human' && request.ingress.type === 'human';\n}\n\nfunction ruleFailure(error: unknown): { code: FactoryRuleRejectionCode; reason: string } {\n return {\n code: 'rule_error',\n reason: error instanceof Error ? `Factory rule failed: ${error.message}` : 'Factory rule failed.',\n };\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), timeoutMs);\n });\n try {\n return await Promise.race([operation, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport class FactoryTransitionService {\n readonly #configVersion: string;\n readonly #boards: ProjectBoardSource;\n readonly #storage: WorkItemsStorage;\n readonly #timeoutMs: number;\n readonly #onTerminalStage: FactoryTransitionServiceOptions['onTerminalStage'];\n readonly #onContextLeft: FactoryTransitionServiceOptions['onContextLeft'];\n readonly #terminalCleanupTimeoutMs: number;\n readonly #onAccepted: FactoryTransitionServiceOptions['onAccepted'];\n readonly #onTransitionCommitted: FactoryTransitionServiceOptions['onTransitionCommitted'];\n readonly #audit: AuditRecorder | undefined;\n\n constructor(options: FactoryTransitionServiceOptions) {\n this.#configVersion = options.configVersion;\n this.#boards = toBoardSource(options.boards);\n this.#storage = options.storage;\n this.#audit = options.audit;\n this.#timeoutMs = options.timeoutMs ?? RULE_TIMEOUT_MS;\n this.#onTerminalStage = options.onTerminalStage;\n this.#onContextLeft = options.onContextLeft;\n this.#onAccepted = options.onAccepted;\n this.#onTransitionCommitted = options.onTransitionCommitted;\n this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;\n }\n\n get configVersion(): string {\n return this.#configVersion;\n }\n\n async transition(request: FactoryTransitionRequest): Promise<FactoryTransitionResult> {\n const replay = await this.#storage.getTransitionResultByIngress(\n request.orgId,\n request.factoryProjectId,\n request.ingress.identity,\n );\n if (replay) return replay as unknown as FactoryTransitionResult;\n\n const transitionId = request.ingress.transitionId ?? globalThis.crypto.randomUUID();\n const item = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (!item) {\n const rejection = await this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'Work item not found.',\n );\n await this.#recordTransition(request, undefined, rejection);\n return rejection;\n }\n let result = await this.#evaluateAndCommit(request, transitionId, item);\n if (isStale(result)) {\n const current = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (current) result = staleRejection(result, current);\n }\n await this.#recordTransition(request, item, result);\n this.#notifyCommitted(request, item, result);\n return result;\n }\n\n #notifyCommitted(request: FactoryTransitionRequest, item: Card, result: FactoryTransitionResult): void {\n const onTransitionCommitted = this.#onTransitionCommitted;\n if (!onTransitionCommitted || result.status !== 'accepted') return;\n // Board-neutral: `currentStage` only knows the built-in rule stages.\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (result.stage === fromStage) return;\n // Inside the chain so a synchronous throw is isolated the same way an async rejection is.\n void Promise.resolve()\n .then(() =>\n onTransitionCommitted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: item.id,\n fromStage,\n toStage: result.stage,\n }),\n )\n .catch(error => {\n console.warn(`[factory] stage notification failed for work item ${item.id}:`, error);\n });\n }\n\n /** A rejection can outlive its work item: the row still names the id the caller asked for. */\n async #recordTransition(\n request: FactoryTransitionRequest,\n item: Card | undefined,\n result: FactoryTransitionResult,\n ): Promise<void> {\n if (!this.#audit) return;\n // Board-neutral, like the stage notification: `currentStage` only knows the\n // built-in rule stages and would drop custom-board phases.\n const from = item && item.stages.length === 1 ? item.stages[0] : undefined;\n if (result.status === 'accepted' && result.stage === from && !request.reenter) return;\n const outcome =\n result.status === 'accepted'\n ? { action: 'factory.work_item.stage_moved' as const, to: result.stage, revision: result.revision }\n : {\n action: 'factory.work_item.transition_rejected' as const,\n to: request.stage,\n code: result.code,\n reason: result.reason,\n };\n const { action, ...detail } = outcome;\n await this.#audit\n .record({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n ...auditActorOf(request.actor),\n actorProfile: request.actorProfile,\n ...(request.context ? { context: request.context } : {}),\n action,\n idempotencyKey: result.transitionId,\n targets: [{ type: 'work_item', id: item?.id ?? request.workItemId, ...(item ? { name: item.title } : {}) }],\n metadata: {\n transitionId: result.transitionId,\n ingressType: request.ingress.type,\n cause: request.cause,\n configVersion: this.#configVersion,\n ...(from ? { from } : {}),\n ...(request.reenter ? { reenter: true } : {}),\n ...detail,\n },\n })\n .catch(error => {\n console.warn(`[factory] audit failed for transition ${result.transitionId}:`, error);\n });\n }\n\n async #evaluateAndCommit(\n request: FactoryTransitionRequest,\n transitionId: string,\n item: Card,\n ): Promise<FactoryTransitionResult> {\n const boards = await this.#boards.load(request);\n if (request.causalChain && request.causalChain.length > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n return this.#commitRejection(\n request,\n transitionId,\n 'causal_depth_exceeded',\n 'Factory rule causal depth exceeded.',\n );\n }\n const itemSource = workItemSource(item.externalSource);\n const source = factoryRuleSourceForWorkItem(itemSource);\n const isPullRequest = source === 'pullRequest' || source === 'gitlabPullRequest';\n // Rows filed before boards were persisted belong to the default board.\n if (item.board === null && !boards.has(DEFAULT_BOARD_ID)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'This legacy work item has no assigned board. Assign an installed board and phase through the work-item PATCH endpoint before transitioning it.',\n );\n }\n const itemBoard = boardForWorkItem(item);\n if (request.board !== itemBoard) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The work item belongs to board \"${itemBoard}\", not \"${request.board}\".`,\n );\n }\n const board = boards.get(request.board);\n if (!board) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `Board \"${request.board}\" is not installed.`,\n );\n }\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!fromStage || !Object.prototype.hasOwnProperty.call(board.phases, fromStage)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not have one canonical phase on the requested board.',\n );\n }\n // The board's own reason comes first: its phase graph alone only says the move is not\n // declared, which leaves an agent moving an issue card to PR review guessing why.\n const cardShapeRejection = pullRequestCardRejection(\n board,\n {\n standalonePullRequest: isPullRequest,\n hasPullRequest: hasPullRequest({ workItem: item.workItem, source: itemSource }),\n },\n request.stage,\n );\n if (cardShapeRejection) {\n return this.#commitRejection(request, transitionId, 'invalid_transition', cardShapeRejection);\n }\n if (\n !Object.prototype.hasOwnProperty.call(board.phases, request.stage) ||\n (!request.eventRoute && !board.allowsTransition(fromStage, request.stage))\n ) {\n const nextStages = [...new Set((board.transitions[fromStage] ?? []).map(transition => transition.to))];\n const nextStagesReason =\n nextStages.length > 0\n ? `Next stages declared from ${fromStage}: ${nextStages.join(', ')}.`\n : `No next stage is declared from ${fromStage}.`;\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The ${board.name} board does not allow moving from ${fromStage} to ${request.stage}. ${nextStagesReason}`,\n );\n }\n\n // The coordinator's own self-move at run start would otherwise inject a second run's kickoff.\n const humanMove = request.actor.type === 'human' && fromStage !== request.stage && request.cause !== 'run_start';\n // The board, not the phase name, says whether a seat is engaged on either side of this move.\n const entersWorking = board.isWorking(request.stage);\n const seatRole = board.roleForPhase(request.stage);\n\n const contextBase = {\n tenant: { orgId: request.orgId, projectId: request.factoryProjectId },\n actor: request.actor,\n ingress: { type: request.ingress.type, id: request.ingress.identity },\n cause: request.cause,\n causalChain: request.causalChain ?? [],\n configVersion: this.#configVersion,\n item: {\n id: item.id,\n source: itemSource,\n sourceKey: item.externalSource\n ? `${item.externalSource.integrationId}:${item.externalSource.type}:${item.externalSource.externalId}`\n : null,\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: request.board,\n itemRevision: item.revision,\n source,\n fromStage,\n toStage: request.stage,\n } satisfies Omit<FactoryStageRuleContext, 'stage'>;\n\n let evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[]; intents: TransitionConsentOptions }\n | { outcome: 'rejected'; code: string; reason: string };\n try {\n evaluation = await withRuleTimeout(\n (async () => {\n // Plans are approved without a person only where the card's phase auto-approves submit_plan.\n const plansAutoApproved = autoApprovedExitTool(boards, item) === 'submit_plan';\n // A phase with an exit tool holds the card until the tool succeeds (for submit_plan, with\n // an approved plan; autoApprove only decides whether it approves itself). Then the agent,\n // or the board's own rule for the tool, moves the card. A person can move it any time.\n const fromPhase = board.phases[fromStage];\n const exitTool = fromPhase?.kind === 'working' ? fromPhase.exitTool : undefined;\n if (\n request.actor.type !== 'human' &&\n // A start lands the card where its run already is; it is not the agent leaving a phase.\n request.cause !== 'run_start' &&\n !request.eventRoute &&\n exitTool &&\n fromStage !== request.stage &&\n entersWorking &&\n !(exitTool.id === 'submit_plan' ? request.planApproved === true : request.completedTool === exitTool.id) &&\n !exitToolSucceeded(item, fromStage, exitTool.id)\n ) {\n return {\n outcome: 'rejected' as const,\n code: 'approval_required',\n reason:\n exitTool.id === 'submit_plan'\n ? `${fromPhase!.name} ends when submit_plan comes back with an approved plan; until then the card stays here. Call submit_plan and wait for a person to approve the plan (or for it to be approved automatically), then move the card into ${board.phases[request.stage]?.name ?? request.stage} with factory_transition_work_item.`\n : `${fromPhase!.name} ends when ${exitTool.id} succeeds; until then the card stays here. A person can also move it from the Factory board or a chat they are signed in to.`,\n };\n }\n const policy = boardTransitionPolicyResultSchema.parse(\n await board.transitionPolicy?.(\n immutablePolicySnapshot({\n ...contextBase,\n item: { ...contextBase.item, triageType: item.triageType },\n initialEntry: request.initialEntry ?? false,\n reenter: request.reenter ?? false,\n isHumanTransition: isHumanTransition(request),\n plansAutoApproved,\n planApproved: request.planApproved === true,\n requestedTriageType: undefined,\n }),\n ),\n );\n if (policy?.type === 'reject') {\n return { outcome: 'rejected' as const, code: policy.code, reason: policy.reason };\n }\n const run = phaseRunDecision(board, request.stage, contextBase, {\n initialEntry: request.initialEntry,\n reenter: request.reenter,\n });\n const validated = validateFactoryRuleDecisions(run ? [run] : [], contextBase.causalChain.length).filter(\n decision => {\n assertFactoryDecisionTarget(decision, boards, itemBoard);\n return !(startsRun(decision) && runAlreadyUnderway(request, decision));\n },\n );\n if (humanMove) {\n const message = stageTransitionMessage(fromStage, request.stage);\n const skill = validated.find(decision => decision.type === 'invokeSkill');\n if (skill) {\n skill.precedingMessage = message;\n } else {\n validated.unshift({\n type: 'sendMessage',\n idempotencyKey: `factory-stage:${transitionId}`,\n message,\n priority: 'urgent',\n idleBehavior: 'wake',\n // Parking a card says stop: no seat is right by construction, so\n // the notice goes to whichever session is live — or nobody.\n ...(entersWorking && seatRole !== undefined ? { role: seatRole, prepareBinding: true } : {}),\n });\n }\n }\n return {\n outcome: 'accepted' as const,\n intents: {\n accepted: isHumanTransition(request) && acceptsWork(board, fromStage, request.stage),\n },\n decisions: validateFactoryRuleDecisions(validated) as unknown as Record<string, unknown>[],\n };\n })(),\n this.#timeoutMs,\n );\n } catch (error) {\n const failed =\n error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT'\n ? { code: 'timeout' as const, reason: 'Factory rule evaluation timed out.' }\n : ruleFailure(error);\n evaluation = { outcome: 'rejected', ...failed };\n }\n return this.#commit(\n request,\n transitionId,\n evaluation,\n evaluation.outcome === 'accepted'\n ? { ...consentEffect(request, entersWorking, humanMove), ...evaluation.intents }\n : {},\n boards,\n fromStage,\n );\n }\n\n async #commitRejection(\n request: FactoryTransitionRequest,\n transitionId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n ): Promise<FactoryTransitionResult> {\n return this.#commit(\n request,\n transitionId,\n { outcome: 'rejected', code, reason: reason.slice(0, MAX_REJECTION_REASON) },\n {},\n undefined,\n );\n }\n\n async #commit(\n request: FactoryTransitionRequest,\n transitionId: string,\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string },\n options: TransitionConsentOptions,\n // The registry the move was evaluated against; rejected moves never release resources.\n boards: BoardRegistry | undefined,\n fromStage?: string,\n ): Promise<FactoryTransitionResult> {\n const committed = await this.#storage.commitTransition({\n autonomy: options.autonomy,\n consentedBy: options.consentedBy,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n expectedRevision: request.expectedRevision,\n destinationStage: request.stage,\n actorId: actorId(request.actor),\n ingress: { identity: request.ingress.identity, triggerType: request.ingress.type, transitionId },\n configVersion: this.#configVersion,\n causalChain: [...(request.causalChain ?? [])],\n evaluation,\n });\n if (committed.status === 'missing') {\n return rejection(transitionId, request.workItemId, 'invalid_transition', 'Work item not found.');\n }\n const result = committed.result as unknown as FactoryTransitionResult;\n if (\n this.#onAccepted &&\n options.accepted &&\n committed.status === 'committed' &&\n result.status === 'accepted' &&\n committed.item\n ) {\n const item = committed.item;\n const onAccepted = this.#onAccepted;\n // Invoke inside the chain so a synchronous throw is isolated the same way an async rejection is.\n void Promise.resolve()\n .then(() =>\n onAccepted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n item,\n }),\n )\n .catch(error => {\n console.warn(`[factory] acceptance hook failed for work item ${request.workItemId}:`, error);\n });\n }\n // Only an installed board's declaration releases resources; an unknown board or phase never does.\n const board = result.status === 'accepted' ? boards?.get(request.board) : undefined;\n if (board && result.status === 'accepted') {\n const hooks = {\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n revision: result.revision,\n actor: request.actor,\n };\n if (board.isTerminal(result.stage)) {\n const onTerminalStage = this.#onTerminalStage;\n if (onTerminalStage) await this.#bounded(() => onTerminalStage({ ...hooks, stage: result.stage }));\n } else if (fromStage !== undefined && this.#onContextLeft) {\n const context = board.roleForPhase(fromStage);\n const toContext = board.roleForPhase(result.stage);\n const onContextLeft = this.#onContextLeft;\n if (context !== undefined && context !== toContext) {\n await this.#bounded(() => onContextLeft({ ...hooks, context, toContext }));\n }\n }\n }\n return result;\n }\n\n /** Run a resource-release hook, waiting at most the cleanup bound; it never fails the committed transition. */\n async #bounded(release: () => Promise<void> | void): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const cleanup = Promise.resolve().then(release);\n // A late rejection after the timeout wins the race must not surface\n // as an unhandled rejection.\n cleanup.catch(() => {});\n await Promise.race([\n cleanup,\n new Promise<void>(resolve => {\n timer = setTimeout(resolve, this.#terminalCleanupTimeoutMs);\n }),\n ]);\n } catch {\n // Resource release is best-effort — never fail a committed transition.\n } finally {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;;;;;AAK7B,MAAM,8BAA8B;AAyGpC,SAAS,UACP,cACA,QACA,MACA,QACyB;CACzB,OAAO;EAAE,QAAQ;EAAY;EAAc;EAAQ;EAAM,QAAQ,OAAO,MAAM,GAAG,oBAAoB;CAAE;AACzG;AAEA,SAAS,QAAQ,OAAiC;CAChD,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,UACH,OAAO,MAAM;EACf,KAAK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IAAI,YAAY,KAAA,KAAa,YAAY,WACvC,MAAM,KAAK,eAAe,cAAc;KAAE,GAAG;KAAO;KAAS;IAAU,CAAC,CAAC;GAE7E;EACF;EACA,OAAO;CACT;;CAGA,MAAM,SAAS,SAAoD;EACjE,IAAI;EACJ,IAAI;GACF,MAAM,UAAU,QAAQ,QAAQ,CAAC,CAAC,KAAK,OAAO;GAG9C,QAAQ,YAAY,CAAC,CAAC;GACtB,MAAM,QAAQ,KAAK,CACjB,SACA,IAAI,SAAc,YAAW;IAC3B,QAAQ,WAAW,SAAS,KAAK,yBAAyB;GAC5D,CAAC,CACH,CAAC;EACH,QAAQ,CAER,UAAU;GACR,aAAa,KAAK;EACpB;CACF;AACF"}
1
+ {"version":3,"file":"transition-service.js","names":[],"sources":["../../src/rules/transition-service.ts"],"sourcesContent":["import { DEFAULT_BOARD_ID, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { autoApprovedExitTool, exitToolSucceeded } from '../boards/phase-automation.js';\nimport { phaseRunDecision } from '../boards/phase-runner.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { boardFlow, boardForWorkItem, hasPullRequest, pullRequestCardRejection } from '../boards/semantics.js';\nimport { boardTransitionPolicyResultSchema, immutablePolicySnapshot } from '../boards/transition-policy.js';\nimport type { AuditActorProfileInput, AuditActorType, AuditContext } from '../storage/domains/audit/base.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport { isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport { isAgentActor } from '../storage/domains/work-items/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleActor,\n FactoryRuleBoard,\n FactoryRuleCausalEntry,\n FactoryRuleRejectionCode,\n FactoryRuleStage,\n FactoryStageRuleContext,\n FactoryTransitionResult,\n FactoryTransitionResultRejected,\n} from './types.js';\nimport { factoryRuleSourceForWorkItem, workItemSource } from './types.js';\nimport {\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n assertFactoryDecisionTarget,\n validateFactoryRuleDecision,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\nconst MAX_REJECTION_REASON = 512;\n/** Longest a committed transition waits for terminal resource cleanup. Cleanup\n * reattaches remote sandboxes, so a hung provider call must not leave the\n * already-committed transition request pending; past this bound the cleanup\n * keeps running in the background as pure best-effort. */\nconst TERMINAL_CLEANUP_TIMEOUT_MS = 30_000;\n\nexport interface FactoryTransitionRequest {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** Installed board id; the service rejects boards that are not installed. */\n board: string;\n stage: FactoryRuleStage;\n expectedRevision: number;\n actor: FactoryRuleActor;\n actorProfile?: AuditActorProfileInput;\n /** Where a browser request came from; rules and agents carry none. */\n context?: AuditContext;\n ingress: { type: 'human' | 'agent' | 'toolResult' | 'github' | 'rule'; identity: string; transitionId?: string };\n cause: string;\n causalChain?: readonly FactoryRuleCausalEntry[];\n /** Internal materialization path: start the destination phase's runner even when already at that stage. */\n initialEntry?: boolean;\n /** Starts the stage's runner again when the item already holds that stage, to restart work the entry invalidated. */\n reenter?: boolean;\n /** Internal proof that this move consumes an approved `submit_plan` result. */\n planApproved?: true;\n /** Internal: the tool whose successful result this move consumes (a tool-result rule's move). */\n completedTool?: string;\n /**\n * Internal: an intake route moves the card on a status event. A route is admin-authored, so it\n * may name any phase on the card's board regardless of the board's next phases, working ones\n * included. The phase's `autoStart` and the dispatcher's approval check decide whether its run starts.\n */\n eventRoute?: { routeId: string };\n}\n\nexport interface FactoryTransitionServiceOptions {\n configVersion: string;\n storage: WorkItemsStorage;\n /** A fixed registry, or the per-project boards; each transition loads its project's boards. */\n boards?: BoardRegistry | ProjectBoardSource;\n /** Every commit, accepted or rejected, lands here as `stage_moved` / `transition_rejected` under the request's actor. */\n audit?: AuditRecorder;\n timeoutMs?: number;\n /**\n * Called after a transition commits into a phase the board declares\n * terminal — the point where the item's sessions stop receiving runs, so\n * resources they hold (e.g. sandboxes) can be released for reuse. Awaited,\n * but failures are swallowed: releasing resources must never break or roll\n * back the committed transition.\n */\n onTerminalStage?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n stage: FactoryRuleStage;\n revision: number;\n /** The actor that committed this terminal transition. Lets cleanup leave\n * the seat that drove its own transition (an agent tool call) untouched. */\n actor: FactoryRuleActor;\n }) => Promise<void> | void;\n /**\n * Called after a transition commits a stage change, e.g. to tell the item's\n * followers. Not awaited, and failures are logged: a notification must never\n * fail or delay the committed transition.\n */\n onTransitionCommitted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n fromStage: string | undefined;\n toStage: string;\n }) => Promise<void> | void;\n /**\n * Called after a transition commits out of the last phase that runs in a\n * context: the new phase runs in another context (or none) and is not\n * terminal, e.g. Triage → Planning. The context's session gets no more\n * runs until the card comes back, so its sandbox can stop. Awaited under\n * the same bound as `onTerminalStage`, and failures are swallowed.\n */\n onContextLeft?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** The context the card left. */\n context: string;\n /** The context the new phase runs in, if it runs one. */\n toContext: string | undefined;\n revision: number;\n actor: FactoryRuleActor;\n }) => Promise<void> | void;\n /** Upper bound on how long a committed transition waits for\n * `onTerminalStage` or `onContextLeft` before returning (default 30s). The\n * cleanup continues in the background past the bound. */\n terminalCleanupTimeoutMs?: number;\n /**\n * Called after a person moves a Work card from Intake or Triage into Planning or\n * Building, which approves the work. Fire-and-forget: failures are swallowed, the committed transition never\n * depends on it.\n */\n onAccepted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n item: Card;\n }) => Promise<void> | void;\n}\n\nfunction rejection(\n transitionId: string,\n itemId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n): FactoryTransitionResult {\n return { status: 'rejected', transitionId, itemId, code, reason: reason.slice(0, MAX_REJECTION_REASON) };\n}\n\nfunction actorId(actor: FactoryRuleActor): string {\n switch (actor.type) {\n case 'human':\n case 'system':\n return actor.id;\n case 'agent':\n return `agent:${actor.bindingId}`;\n case 'github':\n return `github:${actor.login}`;\n case 'gitlab':\n return `gitlab:${actor.username}`;\n }\n}\n\n// The dispatcher executes an agent-approved decision as a human actor so its consent carries; the trail still names the agent.\nexport function auditActorOf(actor: FactoryRuleActor): { actorId: string; actorType: AuditActorType } {\n const id = actorId(actor);\n switch (actor.type) {\n case 'github':\n case 'gitlab':\n return { actorId: id, actorType: 'human' };\n case 'human':\n return { actorId: id, actorType: isAgentActor(id) ? 'agent' : isFactoryPrincipalId(id) ? 'system' : 'human' };\n default:\n return { actorId: id, actorType: actor.type };\n }\n}\n\nfunction isStale(result: FactoryTransitionResult): result is FactoryTransitionResultRejected {\n return result.status === 'rejected' && result.code === 'stale';\n}\n\n/** Tell the caller where the card is now, so a model doesn't read \"stale\" as \"already moved\". */\nfunction staleRejection(result: FactoryTransitionResultRejected, current: Card): FactoryTransitionResult {\n const stage = currentStage(current.stages) ?? current.stages.join(', ');\n return rejection(\n result.transitionId,\n result.itemId,\n 'stale',\n `The card changed (now revision ${current.revision}, in ${stage}). Retry with expectedRevision ${current.revision} if the move still applies.`,\n );\n}\n\nexport function currentStage(stages: readonly string[]): FactoryRuleStage | undefined {\n return stages.length === 1 ? stages[0] : undefined;\n}\n\ninterface TransitionConsentOptions {\n autonomy?: 'arm' | 'disarm';\n consentedBy?: string;\n /** A person moved a card into its board's build seat from before it (see {@link acceptsWork}): that move approves the work. */\n accepted?: boolean;\n}\n\n/**\n * Whether moving a card from `from` to `to` hands it to the board's builder for the first time: `to`\n * runs in the seat of the board's build phase ({@link boardFlow}), and `from` is a resting phase or a\n * working phase of another seat that is no review (Work: Intake or Triage into Planning or Building).\n */\nfunction acceptsWork(board: InstalledBoard, from: string, to: string): boolean {\n const buildRole = boardFlow(board).buildRole;\n if (!buildRole || board.roleForPhase(to) !== buildRole) return false;\n const fromPhase = board.phases[from];\n if (!fromPhase || fromPhase.kind === 'terminal') return false;\n if (fromPhase.kind === 'resting') return true;\n const fromRole = fromPhase.runner.context;\n return fromRole !== buildRole && fromRole !== REVIEW_CONTEXT;\n}\n\n// Entering a resting lane disarms whoever rests it; only a person's move into a working lane arms.\nfunction transitionConsent(working: boolean, humanMove: boolean): 'arm' | 'disarm' | undefined {\n if (!working) return 'disarm';\n return humanMove ? 'arm' : undefined;\n}\n\n// An event arriving as data (GitHub, sweeps) never pre-approves the runs its transition queues.\nfunction bearsConsent(actor: FactoryRuleActor): boolean {\n return actor.type === 'human' || actor.type === 'agent';\n}\n\n// Rides the transition's own revision-checked commit, so a stale or rejected commit flips nothing.\nfunction consentEffect(\n request: FactoryTransitionRequest,\n working: boolean,\n humanMove: boolean,\n): TransitionConsentOptions {\n // A provider event (a reopen, a close) is not a person's say-so: whatever a person armed before\n // no longer stands once a route moves the card.\n if (request.eventRoute) return { autonomy: 'disarm' };\n const autonomy = transitionConsent(working, humanMove);\n return bearsConsent(request.actor) ? { autonomy, consentedBy: actorId(request.actor) } : { autonomy };\n}\n\ntype RunStartDecision = Extract<FactoryCommitDecision, { type: 'invokeSkill' | 'sendMessage' }>;\n\nfunction startsRun(decision: FactoryCommitDecision): decision is RunStartDecision {\n return decision.type === 'invokeSkill' || (decision.type === 'sendMessage' && decision.prepareBinding === true);\n}\n\n// Answering a recorded run start, or the role's own mid-run agent, with a run would start a second one.\n// A run that starts after its own agent's move is queued onto that agent's run instead.\nfunction runAlreadyUnderway(request: FactoryTransitionRequest, decision: RunStartDecision): boolean {\n if (request.cause === 'run_start') return true;\n if (decision.type === 'invokeSkill' && decision.startsAfterOwnMove === true) return false;\n return request.actor.type === 'agent' && request.actor.role === decision.role;\n}\n\nfunction stageTransitionMessage(fromStage: FactoryRuleStage, toStage: FactoryRuleStage): string {\n return `This work was moved from the ${fromStage} stage to the ${toStage} stage.`;\n}\n\nfunction isHumanTransition(request: FactoryTransitionRequest): boolean {\n return request.actor.type === 'human' && request.ingress.type === 'human';\n}\n\nfunction ruleFailure(error: unknown): { code: FactoryRuleRejectionCode; reason: string } {\n return {\n code: 'rule_error',\n reason: error instanceof Error ? `Factory rule failed: ${error.message}` : 'Factory rule failed.',\n };\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), timeoutMs);\n });\n try {\n return await Promise.race([operation, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport class FactoryTransitionService {\n readonly #configVersion: string;\n readonly #boards: ProjectBoardSource;\n readonly #storage: WorkItemsStorage;\n readonly #timeoutMs: number;\n readonly #onTerminalStage: FactoryTransitionServiceOptions['onTerminalStage'];\n readonly #onContextLeft: FactoryTransitionServiceOptions['onContextLeft'];\n readonly #terminalCleanupTimeoutMs: number;\n readonly #onAccepted: FactoryTransitionServiceOptions['onAccepted'];\n readonly #onTransitionCommitted: FactoryTransitionServiceOptions['onTransitionCommitted'];\n readonly #audit: AuditRecorder | undefined;\n\n constructor(options: FactoryTransitionServiceOptions) {\n this.#configVersion = options.configVersion;\n this.#boards = toBoardSource(options.boards);\n this.#storage = options.storage;\n this.#audit = options.audit;\n this.#timeoutMs = options.timeoutMs ?? RULE_TIMEOUT_MS;\n this.#onTerminalStage = options.onTerminalStage;\n this.#onContextLeft = options.onContextLeft;\n this.#onAccepted = options.onAccepted;\n this.#onTransitionCommitted = options.onTransitionCommitted;\n this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;\n }\n\n get configVersion(): string {\n return this.#configVersion;\n }\n\n async transition(request: FactoryTransitionRequest): Promise<FactoryTransitionResult> {\n const replay = await this.#storage.getTransitionResultByIngress(\n request.orgId,\n request.factoryProjectId,\n request.ingress.identity,\n );\n if (replay) return replay as unknown as FactoryTransitionResult;\n\n const transitionId = request.ingress.transitionId ?? globalThis.crypto.randomUUID();\n const item = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (!item) {\n const rejection = await this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'Work item not found.',\n );\n await this.#recordTransition(request, undefined, rejection);\n return rejection;\n }\n let result = await this.#evaluateAndCommit(request, transitionId, item);\n if (isStale(result)) {\n const current = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (current) result = staleRejection(result, current);\n }\n await this.#recordTransition(request, item, result);\n this.#notifyCommitted(request, item, result);\n return result;\n }\n\n #notifyCommitted(request: FactoryTransitionRequest, item: Card, result: FactoryTransitionResult): void {\n const onTransitionCommitted = this.#onTransitionCommitted;\n if (!onTransitionCommitted || result.status !== 'accepted') return;\n // Board-neutral: `currentStage` only knows the built-in rule stages.\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (result.stage === fromStage) return;\n // Inside the chain so a synchronous throw is isolated the same way an async rejection is.\n void Promise.resolve()\n .then(() =>\n onTransitionCommitted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: item.id,\n fromStage,\n toStage: result.stage,\n }),\n )\n .catch(error => {\n console.warn(`[factory] stage notification failed for work item ${item.id}:`, error);\n });\n }\n\n /** A rejection can outlive its work item: the row still names the id the caller asked for. */\n async #recordTransition(\n request: FactoryTransitionRequest,\n item: Card | undefined,\n result: FactoryTransitionResult,\n ): Promise<void> {\n if (!this.#audit) return;\n // Board-neutral, like the stage notification: `currentStage` only knows the\n // built-in rule stages and would drop custom-board phases.\n const from = item && item.stages.length === 1 ? item.stages[0] : undefined;\n if (result.status === 'accepted' && result.stage === from && !request.reenter) return;\n const outcome =\n result.status === 'accepted'\n ? { action: 'factory.work_item.stage_moved' as const, to: result.stage, revision: result.revision }\n : {\n action: 'factory.work_item.transition_rejected' as const,\n to: request.stage,\n code: result.code,\n reason: result.reason,\n };\n const { action, ...detail } = outcome;\n await this.#audit\n .record({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n ...auditActorOf(request.actor),\n actorProfile: request.actorProfile,\n ...(request.context ? { context: request.context } : {}),\n action,\n idempotencyKey: result.transitionId,\n targets: [{ type: 'work_item', id: item?.id ?? request.workItemId, ...(item ? { name: item.title } : {}) }],\n metadata: {\n transitionId: result.transitionId,\n ingressType: request.ingress.type,\n cause: request.cause,\n configVersion: this.#configVersion,\n ...(from ? { from } : {}),\n ...(request.reenter ? { reenter: true } : {}),\n ...detail,\n },\n })\n .catch(error => {\n console.warn(`[factory] audit failed for transition ${result.transitionId}:`, error);\n });\n }\n\n async #evaluateAndCommit(\n request: FactoryTransitionRequest,\n transitionId: string,\n item: Card,\n ): Promise<FactoryTransitionResult> {\n const boards = await this.#boards.load(request);\n if (request.causalChain && request.causalChain.length > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n return this.#commitRejection(\n request,\n transitionId,\n 'causal_depth_exceeded',\n 'Factory rule causal depth exceeded.',\n );\n }\n const itemSource = workItemSource(item.externalSource);\n const source = factoryRuleSourceForWorkItem(itemSource);\n const isPullRequest = source === 'pullRequest' || source === 'gitlabPullRequest';\n // Rows filed before boards were persisted belong to the default board.\n if (item.board === null && !boards.has(DEFAULT_BOARD_ID)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'This legacy work item has no assigned board. Assign an installed board and phase through the work-item PATCH endpoint before transitioning it.',\n );\n }\n const itemBoard = boardForWorkItem(item);\n if (request.board !== itemBoard) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The work item belongs to board \"${itemBoard}\", not \"${request.board}\".`,\n );\n }\n const board = boards.get(request.board);\n if (!board) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `Board \"${request.board}\" is not installed.`,\n );\n }\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!fromStage || !Object.prototype.hasOwnProperty.call(board.phases, fromStage)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not have one canonical phase on the requested board.',\n );\n }\n // The board's own reason comes first: its phase graph alone only says the move is not\n // declared, which leaves an agent moving an issue card to PR review guessing why.\n const cardShapeRejection = pullRequestCardRejection(\n board,\n {\n standalonePullRequest: isPullRequest,\n hasPullRequest: hasPullRequest({ workItem: item.workItem, source: itemSource }),\n },\n request.stage,\n );\n if (cardShapeRejection) {\n return this.#commitRejection(request, transitionId, 'invalid_transition', cardShapeRejection);\n }\n if (\n !Object.prototype.hasOwnProperty.call(board.phases, request.stage) ||\n (!request.eventRoute && !board.allowsTransition(fromStage, request.stage))\n ) {\n const nextStages = [...new Set((board.transitions[fromStage] ?? []).map(transition => transition.to))];\n const nextStagesReason =\n nextStages.length > 0\n ? `Next stages declared from ${fromStage}: ${nextStages.join(', ')}.`\n : `No next stage is declared from ${fromStage}.`;\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The ${board.name} board does not allow moving from ${fromStage} to ${request.stage}. ${nextStagesReason}`,\n );\n }\n\n // The coordinator's own self-move at run start would otherwise inject a second run's kickoff.\n const humanMove = request.actor.type === 'human' && fromStage !== request.stage && request.cause !== 'run_start';\n // The board, not the phase name, says whether a seat is engaged on either side of this move.\n const entersWorking = board.isWorking(request.stage);\n const seatRole = board.roleForPhase(request.stage);\n\n const contextBase = {\n tenant: { orgId: request.orgId, projectId: request.factoryProjectId },\n actor: request.actor,\n ingress: { type: request.ingress.type, id: request.ingress.identity },\n cause: request.cause,\n causalChain: request.causalChain ?? [],\n configVersion: this.#configVersion,\n item: {\n id: item.id,\n source: itemSource,\n sourceKey: item.externalSource\n ? `${item.externalSource.integrationId}:${item.externalSource.type}:${item.externalSource.externalId}`\n : null,\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: request.board,\n itemRevision: item.revision,\n source,\n fromStage,\n toStage: request.stage,\n } satisfies Omit<FactoryStageRuleContext, 'stage'>;\n\n let evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[]; intents: TransitionConsentOptions }\n | { outcome: 'rejected'; code: string; reason: string };\n try {\n evaluation = await withRuleTimeout(\n (async () => {\n // Plans are approved without a person only where the card's phase auto-approves submit_plan.\n const plansAutoApproved = autoApprovedExitTool(boards, item) === 'submit_plan';\n // A phase with an exit tool holds the card until the tool succeeds (for submit_plan, with\n // an approved plan; autoApprove only decides whether it approves itself). Then the agent,\n // or the board's own rule for the tool, moves the card. A person can move it any time.\n const fromPhase = board.phases[fromStage];\n const exitTool = fromPhase?.kind === 'working' ? fromPhase.exitTool : undefined;\n if (\n request.actor.type !== 'human' &&\n // A start lands the card where its run already is; it is not the agent leaving a phase.\n request.cause !== 'run_start' &&\n !request.eventRoute &&\n exitTool &&\n fromStage !== request.stage &&\n entersWorking &&\n !(exitTool.id === 'submit_plan' ? request.planApproved === true : request.completedTool === exitTool.id) &&\n !exitToolSucceeded(item, fromStage, exitTool.id)\n ) {\n return {\n outcome: 'rejected' as const,\n code: 'approval_required',\n reason:\n exitTool.id === 'submit_plan'\n ? `${fromPhase!.name} ends when submit_plan comes back with an approved plan; until then the card stays here. Call submit_plan and wait for a person to approve the plan (or for it to be approved automatically), then move the card into ${board.phases[request.stage]?.name ?? request.stage} with factory_transition_work_item.`\n : `${fromPhase!.name} ends when ${exitTool.id} succeeds; until then the card stays here. A person can also move it from the Factory board or a chat they are signed in to.`,\n };\n }\n const policy = boardTransitionPolicyResultSchema.parse(\n await board.transitionPolicy?.(\n immutablePolicySnapshot({\n ...contextBase,\n item: { ...contextBase.item, triageType: item.triageType },\n initialEntry: request.initialEntry ?? false,\n reenter: request.reenter ?? false,\n isHumanTransition: isHumanTransition(request),\n plansAutoApproved,\n planApproved: request.planApproved === true,\n requestedTriageType: undefined,\n }),\n ),\n );\n if (policy?.type === 'reject') {\n return { outcome: 'rejected' as const, code: policy.code, reason: policy.reason };\n }\n const run = phaseRunDecision(board, request.stage, contextBase, {\n initialEntry: request.initialEntry,\n reenter: request.reenter,\n });\n const validated = validateFactoryRuleDecisions(run ? [run] : [], contextBase.causalChain.length).filter(\n decision => {\n assertFactoryDecisionTarget(decision, boards, itemBoard);\n return !(startsRun(decision) && runAlreadyUnderway(request, decision));\n },\n );\n if (humanMove) {\n const message = stageTransitionMessage(fromStage, request.stage);\n const skill = validated.find(decision => decision.type === 'invokeSkill');\n if (skill) {\n skill.precedingMessage = message;\n } else {\n validated.unshift({\n type: 'sendMessage',\n idempotencyKey: `factory-stage:${transitionId}`,\n message,\n priority: 'urgent',\n idleBehavior: 'wake',\n // Parking a card says stop: no seat is right by construction, so\n // the notice goes to whichever session is live — or nobody.\n ...(entersWorking && seatRole !== undefined ? { role: seatRole, prepareBinding: true } : {}),\n });\n }\n }\n return {\n outcome: 'accepted' as const,\n intents: {\n accepted: isHumanTransition(request) && acceptsWork(board, fromStage, request.stage),\n },\n decisions: validateFactoryRuleDecisions(validated) as unknown as Record<string, unknown>[],\n };\n })(),\n this.#timeoutMs,\n );\n } catch (error) {\n const failed =\n error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT'\n ? { code: 'timeout' as const, reason: 'Factory rule evaluation timed out.' }\n : ruleFailure(error);\n evaluation = { outcome: 'rejected', ...failed };\n }\n return this.#commit(\n request,\n transitionId,\n evaluation,\n evaluation.outcome === 'accepted'\n ? { ...consentEffect(request, entersWorking, humanMove), ...evaluation.intents }\n : {},\n boards,\n fromStage,\n );\n }\n\n async #commitRejection(\n request: FactoryTransitionRequest,\n transitionId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n ): Promise<FactoryTransitionResult> {\n return this.#commit(\n request,\n transitionId,\n { outcome: 'rejected', code, reason: reason.slice(0, MAX_REJECTION_REASON) },\n {},\n undefined,\n );\n }\n\n async #commit(\n request: FactoryTransitionRequest,\n transitionId: string,\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string },\n options: TransitionConsentOptions,\n // The registry the move was evaluated against; rejected moves never release resources.\n boards: BoardRegistry | undefined,\n fromStage?: string,\n ): Promise<FactoryTransitionResult> {\n const committed = await this.#storage.commitTransition({\n autonomy: options.autonomy,\n consentedBy: options.consentedBy,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n expectedRevision: request.expectedRevision,\n destinationStage: request.stage,\n actorId: actorId(request.actor),\n ingress: { identity: request.ingress.identity, transitionId },\n causalChain: [...(request.causalChain ?? [])],\n evaluation,\n });\n if (committed.status === 'missing') {\n return rejection(transitionId, request.workItemId, 'invalid_transition', 'Work item not found.');\n }\n const result = committed.result as unknown as FactoryTransitionResult;\n if (\n this.#onAccepted &&\n options.accepted &&\n committed.status === 'committed' &&\n result.status === 'accepted' &&\n committed.item\n ) {\n const item = committed.item;\n const onAccepted = this.#onAccepted;\n // Invoke inside the chain so a synchronous throw is isolated the same way an async rejection is.\n void Promise.resolve()\n .then(() =>\n onAccepted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n item,\n }),\n )\n .catch(error => {\n console.warn(`[factory] acceptance hook failed for work item ${request.workItemId}:`, error);\n });\n }\n // Only an installed board's declaration releases resources; an unknown board or phase never does.\n const board = result.status === 'accepted' ? boards?.get(request.board) : undefined;\n if (board && result.status === 'accepted') {\n const hooks = {\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n revision: result.revision,\n actor: request.actor,\n };\n if (board.isTerminal(result.stage)) {\n const onTerminalStage = this.#onTerminalStage;\n if (onTerminalStage) await this.#bounded(() => onTerminalStage({ ...hooks, stage: result.stage }));\n } else if (fromStage !== undefined && this.#onContextLeft) {\n const context = board.roleForPhase(fromStage);\n const toContext = board.roleForPhase(result.stage);\n const onContextLeft = this.#onContextLeft;\n if (context !== undefined && context !== toContext) {\n await this.#bounded(() => onContextLeft({ ...hooks, context, toContext }));\n }\n }\n }\n return result;\n }\n\n /** Run a resource-release hook, waiting at most the cleanup bound; it never fails the committed transition. */\n async #bounded(release: () => Promise<void> | void): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const cleanup = Promise.resolve().then(release);\n // A late rejection after the timeout wins the race must not surface\n // as an unhandled rejection.\n cleanup.catch(() => {});\n await Promise.race([\n cleanup,\n new Promise<void>(resolve => {\n timer = setTimeout(resolve, this.#terminalCleanupTimeoutMs);\n }),\n ]);\n } catch {\n // Resource release is best-effort — never fail a committed transition.\n } finally {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;;;;;AAK7B,MAAM,8BAA8B;AAyGpC,SAAS,UACP,cACA,QACA,MACA,QACyB;CACzB,OAAO;EAAE,QAAQ;EAAY;EAAc;EAAQ;EAAM,QAAQ,OAAO,MAAM,GAAG,oBAAoB;CAAE;AACzG;AAEA,SAAS,QAAQ,OAAiC;CAChD,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,UACH,OAAO,MAAM;EACf,KAAK,SACH,OAAO,SAAS,MAAM;EACxB,KAAK,UACH,OAAO,UAAU,MAAM;EACzB,KAAK,UACH,OAAO,UAAU,MAAM;CAC3B;AACF;AAGA,SAAgB,aAAa,OAAyE;CACpG,MAAM,KAAK,QAAQ,KAAK;CACxB,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,UACH,OAAO;GAAE,SAAS;GAAI,WAAW;EAAQ;EAC3C,KAAK,SACH,OAAO;GAAE,SAAS;GAAI,WAAW,aAAa,EAAE,IAAI,UAAU,qBAAqB,EAAE,IAAI,WAAW;EAAQ;EAC9G,SACE,OAAO;GAAE,SAAS;GAAI,WAAW,MAAM;EAAK;CAChD;AACF;AAEA,SAAS,QAAQ,QAA4E;CAC3F,OAAO,OAAO,WAAW,cAAc,OAAO,SAAS;AACzD;;AAGA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,CAAC,IAAI,CAAC,CAchB;IAEK,+BAA+B,CAAC,OAAO,EAAE;QAC7C,aAAa,EAAE,0BAA0B,CAAC;QAC1C,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,wBAAwB,CAAC,CAAC;QAC7D,KAAK,EAAE,MAAM,CAAC;QACd,mBAAmB,EAAE,MAAM,CAAC;KAC7B,GAAG,OAAO,CAAC,IAAI,CAAC,CAehB;CAmRF"}
@@ -1,5 +1,6 @@
1
1
  import { destroyDetachedSessionSandbox, releaseSessionSandbox, stopDetachedSessionSandbox } from "../integrations/github/sandbox-release.js";
2
2
  import { DEFAULT_COMMAND_TIMEOUT_MS, runTeardownCommand } from "../integrations/github/sandbox.js";
3
+ import { factoryMetrics } from "../metrics/metrics.js";
3
4
  import { peekSessionEnvironmentTeardown } from "../session/environment-state-processor.js";
4
5
  import { requireExec } from "./materialization.js";
5
6
  import { clearFailedSetupCommands, evictSessionSandbox, peekSessionSandbox } from "./session-sandbox.js";
@@ -46,7 +47,7 @@ var SessionRetirementCoordinator = class {
46
47
  this.#destroyTimeoutMs = options.destroyTimeoutMs ?? DEFAULT_DESTROY_TIMEOUT_MS;
47
48
  }
48
49
  async retireSession(input) {
49
- await this.#withSessionLock(input.sessionId, () => this.#retireSession(input));
50
+ if (await this.#withSessionLock(input.sessionId, () => this.#retireSession(input))) factoryMetrics().count("sandbox", "mastra_factory_sandbox_retired_total");
50
51
  }
51
52
  /**
52
53
  * Destroy a session's sandbox so its next message boots a fresh VM from the
@@ -56,7 +57,9 @@ var SessionRetirementCoordinator = class {
56
57
  * A destroy failure keeps the persisted id so a retry can reach the VM.
57
58
  */
58
59
  async recreateSessionSandbox(input) {
59
- return this.#withSessionLock(input.sessionId, () => this.#recreateSessionSandbox(input));
60
+ const result = await this.#withSessionLock(input.sessionId, () => this.#recreateSessionSandbox(input));
61
+ if (result === "recreated") factoryMetrics().count("sandbox", "mastra_factory_sandbox_recreated_total", { kind: "recreate" });
62
+ return result;
60
63
  }
61
64
  /**
62
65
  * Replace the session's VM while keeping its sandbox instance, for the
@@ -69,7 +72,9 @@ var SessionRetirementCoordinator = class {
69
72
  * `not-here` means this process holds no instance for the session.
70
73
  */
71
74
  async resetSessionSandbox(input) {
72
- return this.#withSessionLock(input.sessionId, () => this.#resetSessionSandbox(input));
75
+ const result = await this.#withSessionLock(input.sessionId, () => this.#resetSessionSandbox(input));
76
+ if (result === "reset") factoryMetrics().count("sandbox", "mastra_factory_sandbox_recreated_total", { kind: "reset" });
77
+ return result;
73
78
  }
74
79
  /**
75
80
  * Stop a session's sandbox and keep everything else: the row, its files and
@@ -126,11 +131,13 @@ var SessionRetirementCoordinator = class {
126
131
  deleteSession: true
127
132
  })));
128
133
  }
134
+ /** Resolves `true` when the session had a sandbox and releasing it succeeded. */
129
135
  async #retireSession(input) {
130
136
  const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);
131
- if (!session || session.orgId !== input.orgId) return;
137
+ if (!session || session.orgId !== input.orgId) return false;
138
+ let released = false;
132
139
  try {
133
- await this.#teardownSessionSandbox(input, session);
140
+ released = await this.#teardownSessionSandbox(input, session);
134
141
  } finally {
135
142
  await this.#invalidate(session);
136
143
  if (input.deleteSession) {
@@ -141,13 +148,11 @@ var SessionRetirementCoordinator = class {
141
148
  await input.sourceControl.sessions.delete(session.id);
142
149
  }
143
150
  }
151
+ return released;
144
152
  }
145
153
  async #teardownSessionSandbox(input, session) {
146
154
  const entry = peekSessionSandbox(session.id);
147
- if (!entry) {
148
- await this.#releaseDetachedSandbox(input, session);
149
- return;
150
- }
155
+ if (!entry) return this.#releaseDetachedSandbox(input, session);
151
156
  const environmentTeardown = peekSessionEnvironmentTeardown(session.sessionId);
152
157
  if (environmentTeardown.length > 0) {
153
158
  for (const repo of environmentTeardown) try {
@@ -161,8 +166,7 @@ var SessionRetirementCoordinator = class {
161
166
  error: boundedError(error)
162
167
  });
163
168
  }
164
- await this.#releaseSandbox(input, session);
165
- return;
169
+ return this.#releaseSandbox(input, session);
166
170
  }
167
171
  let projectRepository;
168
172
  try {
@@ -188,16 +192,16 @@ var SessionRetirementCoordinator = class {
188
192
  error: boundedError(error)
189
193
  });
190
194
  }
191
- await this.#releaseSandbox(input, session);
195
+ return this.#releaseSandbox(input, session);
192
196
  }
193
197
  /**
194
198
  * Stop (or, for a deleted session, destroy) a session's VM that this
195
199
  * process never attached to. Only for sessions that materialized (a
196
200
  * persisted `sandboxId`): nothing is started, no teardown command runs —
197
- * the provider pauses or kills by identity.
201
+ * the provider pauses or kills by identity. Resolves whether a sandbox was released.
198
202
  */
199
203
  async #releaseDetachedSandbox(input, session) {
200
- if (!session.sandboxId || !this.#sandbox) return;
204
+ if (!session.sandboxId || !this.#sandbox) return false;
201
205
  try {
202
206
  if (input.deleteSession) await destroyDetachedSessionSandbox({
203
207
  sandbox: this.#sandbox,
@@ -207,6 +211,7 @@ var SessionRetirementCoordinator = class {
207
211
  sandbox: this.#sandbox,
208
212
  session
209
213
  });
214
+ return true;
210
215
  } catch (error) {
211
216
  this.#warn(`Factory detached session sandbox ${input.deleteSession ? "destroy" : "stop"} failed`, {
212
217
  orgId: session.orgId,
@@ -214,6 +219,7 @@ var SessionRetirementCoordinator = class {
214
219
  projectRepositoryId: session.projectRepositoryId,
215
220
  error: boundedError(error)
216
221
  });
222
+ return false;
217
223
  }
218
224
  }
219
225
  /** Bump the session's workspace generation; a failing unregister is logged, never fatal. */
@@ -338,6 +344,7 @@ var SessionRetirementCoordinator = class {
338
344
  sessionId: session.id,
339
345
  destroy: input.deleteSession
340
346
  });
347
+ return true;
341
348
  } catch (error) {
342
349
  this.#warn("Factory session sandbox release failed", {
343
350
  orgId: session.orgId,
@@ -345,6 +352,7 @@ var SessionRetirementCoordinator = class {
345
352
  projectRepositoryId: session.projectRepositoryId,
346
353
  error: boundedError(error)
347
354
  });
355
+ return false;
348
356
  }
349
357
  }
350
358
  };
@@ -1 +1 @@
1
- {"version":3,"file":"session-retirement.js","names":[],"sources":["../../src/sandbox/session-retirement.ts"],"sourcesContent":["import type { FactorySandbox, WorkspaceSandbox } from '@mastra/core/workspace';\n\nimport {\n destroyDetachedSessionSandbox,\n releaseSessionSandbox,\n stopDetachedSessionSandbox,\n} from '../integrations/github/sandbox-release.js';\nimport { DEFAULT_COMMAND_TIMEOUT_MS, runTeardownCommand } from '../integrations/github/sandbox.js';\nimport { peekSessionEnvironmentTeardown } from '../session/environment-state-processor.js';\nimport type {\n ProjectRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { requireExec } from './materialization.js';\nimport { clearFailedSetupCommands, evictSessionSandbox, peekSessionSandbox } from './session-sandbox.js';\n\ntype WarningLogger = (message: string, details: Record<string, unknown>) => void;\n\nexport interface SessionRetirementCoordinatorOptions {\n invalidateSession?: (sessionId: string) => Promise<void> | void;\n /**\n * The deploy's sandbox configuration. Used to destroy a deleted session's\n * VM by identity when this process never attached to it (after a restart,\n * or on another replica). Recreate uses it the same way.\n */\n sandbox?: FactorySandbox;\n warn?: WarningLogger;\n /** How long recreate waits on a started sandbox's lifecycle destroy before falling back. */\n destroyTimeoutMs?: number;\n}\n\nexport interface RecreateSessionSandboxInput {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n sessionId: string;\n}\n\nconst DEFAULT_DESTROY_TIMEOUT_MS = 30_000;\n\n/**\n * A provider error meaning the VM is already gone: 410, or a 404 the proxy\n * marks `not_found` (or leaves uncoded). A routing 404 with another code is\n * not proof the VM is gone.\n */\nfunction isSandboxGoneError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const { status, code } = error as { status?: unknown; code?: unknown };\n if (status === 410) return true;\n return status === 404 && (code === undefined || code === null || code === 'not_found');\n}\n\nexport interface RetireSessionInput {\n sourceControl: SourceControlStorageHandle;\n /** When provided, deleting the session row also strips its work-item refs. */\n workItems?: Pick<WorkItemsStorage, 'clearSessionReferences'>;\n orgId: string;\n sessionId: string;\n deleteSession: boolean;\n}\n\nfunction boundedError(error: unknown): string {\n const detail = error instanceof Error ? error.message : String(error);\n if (detail.length <= 2000) return detail;\n return `${detail.slice(0, 200)}...${detail.slice(-1797)}`;\n}\n\n/**\n * Owns terminal and destructive session cleanup. Each session is serialized so\n * duplicate role bindings and competing deletion/transition requests cannot\n * run teardown concurrently.\n *\n * Sandbox identity is the session id: retirement stops (or, for deleted\n * sessions, destroys) the sandbox this process holds in the session memo.\n * Sessions opened on another replica (or before a restart) have no memo entry\n * here: a materialized one is stopped (or, when deleted, destroyed) by\n * identity through the configured sandbox. Providers such as E2B keep paused\n * VMs forever, so the row's deletion must never orphan one.\n */\nexport class SessionRetirementCoordinator {\n readonly #invalidateSession: NonNullable<SessionRetirementCoordinatorOptions['invalidateSession']>;\n readonly #sandbox: FactorySandbox | undefined;\n readonly #warn: WarningLogger;\n readonly #destroyTimeoutMs: number;\n readonly #locks = new Map<string, Promise<unknown>>();\n\n constructor(options: SessionRetirementCoordinatorOptions = {}) {\n this.#invalidateSession = options.invalidateSession ?? (() => {});\n this.#sandbox = options.sandbox;\n this.#warn = options.warn ?? ((message, details) => console.warn(`[Mastra Factory] ${message}`, details));\n this.#destroyTimeoutMs = options.destroyTimeoutMs ?? DEFAULT_DESTROY_TIMEOUT_MS;\n }\n\n async retireSession(input: RetireSessionInput): Promise<void> {\n await this.#withSessionLock(input.sessionId, () => this.#retireSession(input));\n }\n\n /**\n * Destroy a session's sandbox so its next message boots a fresh VM from the\n * template, keeping the session row, its conversation, and work-item refs.\n * Skips teardown commands, and works without a memo entry in this process\n * by destroying a detached instance built from the persisted `sandboxId`.\n * A destroy failure keeps the persisted id so a retry can reach the VM.\n */\n async recreateSessionSandbox(input: RecreateSessionSandboxInput): Promise<'recreated' | 'not-found'> {\n return this.#withSessionLock(input.sessionId, () => this.#recreateSessionSandbox(input));\n }\n\n /**\n * Replace the session's VM while keeping its sandbox instance, for the\n * session's own agent. A run holds the instance it started with until the\n * run ends, so recreate (which destroys the instance) would leave every\n * later command in that run failing. Here the VM is destroyed and the\n * instance is left `stopped` with no VM id, so the run's next command starts\n * a fresh VM and the start hook sets it up again.\n *\n * `not-here` means this process holds no instance for the session.\n */\n async resetSessionSandbox(input: RecreateSessionSandboxInput): Promise<'reset' | 'not-found' | 'not-here'> {\n return this.#withSessionLock(input.sessionId, () => this.#resetSessionSandbox(input));\n }\n\n /**\n * Stop a session's sandbox and keep everything else: the row, its files and\n * its work-item refs, so the session's next start resumes the same sandbox.\n * Unlike retirement no teardown command runs, because a resume does not\n * run setup again. Reaches the VM by identity when this process never\n * attached to it.\n */\n async stopSessionSandbox(input: Omit<RetireSessionInput, 'deleteSession' | 'workItems'>): Promise<void> {\n await this.#withSessionLock(input.sessionId, async () => {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return;\n try {\n if (peekSessionSandbox(session.id)) await releaseSessionSandbox({ sessionId: session.id });\n else await this.#releaseDetachedSandbox({ ...input, deleteSession: false }, session);\n } finally {\n await this.#invalidate(session);\n }\n });\n }\n\n async #withSessionLock<T>(sessionId: string, run: () => Promise<T>): Promise<T> {\n const previous = this.#locks.get(sessionId) ?? Promise.resolve();\n const current = previous.catch(() => {}).then(run);\n this.#locks.set(sessionId, current);\n try {\n return await current;\n } finally {\n if (this.#locks.get(sessionId) === current) this.#locks.delete(sessionId);\n }\n }\n\n async retireWorkItemSessions(options: {\n workItems: Pick<WorkItemsStorage, 'get'>;\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n workItemId: string;\n }): Promise<void> {\n const item = await options.workItems.get({ orgId: options.orgId, id: options.workItemId });\n if (!item) return;\n const sessionIds = [...new Set(Object.values(item.sessions).map(session => session.sessionId))];\n await Promise.all(\n sessionIds.map(sessionId =>\n this.retireSession({\n sourceControl: options.sourceControl,\n orgId: options.orgId,\n sessionId,\n deleteSession: false,\n }),\n ),\n );\n }\n\n async retireProjectRepositorySessions(options: {\n sourceControl: SourceControlStorageHandle;\n workItems?: Pick<WorkItemsStorage, 'clearSessionReferences'>;\n orgId: string;\n projectRepositoryId: string;\n }): Promise<void> {\n const sessions = await options.sourceControl.sessions.listByProjectRepository({\n projectRepositoryId: options.projectRepositoryId,\n });\n await Promise.all(\n sessions.map(session =>\n this.retireSession({\n sourceControl: options.sourceControl,\n ...(options.workItems ? { workItems: options.workItems } : {}),\n orgId: options.orgId,\n sessionId: session.sessionId,\n deleteSession: true,\n }),\n ),\n );\n }\n\n async #retireSession(input: RetireSessionInput): Promise<void> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return;\n\n try {\n await this.#teardownSessionSandbox(input, session);\n } finally {\n await this.#invalidate(session);\n\n if (input.deleteSession) {\n // Refs first: clearing again is a no-op, but refs on a deleted row would dangle forever.\n await input.workItems?.clearSessionReferences({ orgId: input.orgId, sessionId: input.sessionId });\n await input.sourceControl.sessions.delete(session.id);\n }\n }\n }\n\n async #teardownSessionSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<void> {\n const entry = peekSessionSandbox(session.id);\n if (!entry) {\n await this.#releaseDetachedSandbox(input, session);\n return;\n }\n\n // A session booted from its factory environment tears every repository\n // down in position order, each in its own directory; a failure is logged\n // and the next repository still runs.\n const environmentTeardown = peekSessionEnvironmentTeardown(session.sessionId);\n if (environmentTeardown.length > 0) {\n for (const repo of environmentTeardown) {\n try {\n await runTeardownCommand(requireExec(entry.sandbox), repo.dir, repo.command, {\n timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n });\n } catch (error) {\n this.#warn('Factory teardown command failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n repository: repo.slug,\n error: boundedError(error),\n });\n }\n }\n await this.#releaseSandbox(input, session);\n return;\n }\n\n let projectRepository: ProjectRepository | null | undefined;\n try {\n projectRepository = session.projectRepositoryId\n ? await input.sourceControl.projectRepositories.get({ orgId: input.orgId, id: session.projectRepositoryId })\n : null;\n } catch (error) {\n this.#warn('Factory repository settings could not be loaded for session retirement', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n\n // An unresolved workdir means the sandbox never started in this process:\n // nothing was set up, so there is nothing for a teardown command to undo.\n if (projectRepository?.teardownCommand && entry.workdir) {\n try {\n await runTeardownCommand(requireExec(entry.sandbox), entry.workdir, projectRepository.teardownCommand, {\n timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n });\n } catch (error) {\n this.#warn('Factory teardown command failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n await this.#releaseSandbox(input, session);\n }\n\n /**\n * Stop (or, for a deleted session, destroy) a session's VM that this\n * process never attached to. Only for sessions that materialized (a\n * persisted `sandboxId`): nothing is started, no teardown command runs —\n * the provider pauses or kills by identity.\n */\n async #releaseDetachedSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<void> {\n if (!session.sandboxId || !this.#sandbox) return;\n try {\n if (input.deleteSession) await destroyDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n else await stopDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n } catch (error) {\n this.#warn(`Factory detached session sandbox ${input.deleteSession ? 'destroy' : 'stop'} failed`, {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n /** Bump the session's workspace generation; a failing unregister is logged, never fatal. */\n async #invalidate(session: SourceControlSession): Promise<void> {\n try {\n await this.#invalidateSession(session.sessionId);\n } catch (error) {\n this.#warn('Factory session workspace cache invalidation failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n async #recreateSessionSandbox(input: RecreateSessionSandboxInput): Promise<'recreated' | 'not-found'> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return 'not-found';\n\n // Bump the generation first so an in-flight start hook for the old\n // instance throws instead of republishing its sandbox id.\n await this.#invalidate(session);\n const entry = peekSessionSandbox(session.id);\n evictSessionSandbox(session.id);\n\n await this.#destroyForRecreate(session, entry?.sandbox);\n await input.sourceControl.sessions.setSandbox({ id: session.id, sandboxId: null, sandboxWorkdir: '' });\n\n // A resolve that ran between the eviction and clearing the id could have\n // built a fresh instance from the old `sandboxId`; drop it and fence it.\n evictSessionSandbox(session.id);\n await this.#invalidate(session);\n return 'recreated';\n }\n\n async #resetSessionSandbox(input: RecreateSessionSandboxInput): Promise<'reset' | 'not-found' | 'not-here'> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return 'not-found';\n const sandbox = peekSessionSandbox(session.id)?.sandbox;\n if (!sandbox) return 'not-here';\n\n // The provider's own destroy, not the lifecycle wrapper: the wrapper marks\n // the instance destroyed for good. Bounded, so a VM that won't answer\n // can't hold the session lock.\n const destroy = async () => {\n if (!(await this.#settledWithin(this.#destroyDirectly(sandbox)))) {\n throw new Error('Timed out destroying the sandbox. Try again.');\n }\n };\n // Destroyed before waiting on a start in flight, so a start hung on the\n // dead VM can't block recovery; its commands fail fast once the VM is gone.\n await destroy();\n const starting = (sandbox as { _startPromise?: Promise<unknown> })._startPromise;\n if (starting) {\n const settled = await this.#settledWithin(\n starting.then(\n () => {},\n () => {},\n ),\n );\n if (!settled) throw new Error('The old sandbox is still starting. Try again.');\n // That start may have found the old VM gone and provisioned another.\n await destroy();\n }\n\n sandbox.status = 'stopped';\n // The new VM runs setup from scratch, including commands that failed on the old one.\n clearFailedSetupCommands(session.id);\n // Re-read: a start that settled while this reset waited may have stored a newer workdir.\n const latest = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n await input.sourceControl.sessions.setSandbox({\n id: session.id,\n sandboxId: null,\n sandboxWorkdir: latest?.sandboxWorkdir ?? session.sandboxWorkdir ?? '',\n });\n return 'reset';\n }\n\n /**\n * Destroy the session's VM. `_destroy()` silently no-ops on a never-started\n * (`pending`) instance, so pending and detached instances call the\n * provider's `destroy()` directly; a started instance goes through the\n * lifecycle wrapper, bounded so a hung start can't hold the session lock.\n */\n async #destroyForRecreate(session: SourceControlSession, memo: WorkspaceSandbox | undefined): Promise<void> {\n const lifecycle = memo as { _destroy?: () => Promise<void> } | undefined;\n if (memo && memo.status !== 'pending' && lifecycle?._destroy) {\n const destroying = lifecycle._destroy.call(memo);\n if (await this.#settledWithin(destroying)) {\n memo.status = 'destroyed';\n return;\n }\n // Load-bearing: once the hung start settles, this destroy reaps any VM it\n // provisioned. Its rejection must never surface as unhandled.\n destroying.catch(error =>\n this.#warn('Factory sandbox destroy failed after recreate stopped waiting', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n error: boundedError(error),\n }),\n );\n if (!this.#sandbox) {\n throw new Error(\n 'Timed out destroying the session sandbox, and no sandbox provider is configured to retry by identity.',\n );\n }\n await this.#destroyDetachedForRecreate(this.#sandbox, session);\n memo.status = 'destroyed';\n return;\n }\n\n if (memo) {\n await this.#destroyDirectly(memo);\n memo.status = 'destroyed';\n return;\n }\n\n // No instance in this process (restart, or another replica opened it):\n // destroy through a never-started instance carrying the persisted id.\n // Unlike retirement, this runs without a `sandboxId` too: E2B and Docker\n // find the VM by session identity, and Platform's destroy no-ops safely.\n if (this.#sandbox) await this.#destroyDetachedForRecreate(this.#sandbox, session);\n }\n\n async #destroyDetachedForRecreate(sandbox: FactorySandbox, session: SourceControlSession): Promise<void> {\n try {\n await destroyDetachedSessionSandbox({ sandbox, session });\n } catch (error) {\n if (!isSandboxGoneError(error)) throw error;\n }\n }\n\n /** True when the destroy finished in time; false on timeout. Gone-VM errors count as finished. */\n async #settledWithin(destroying: Promise<void>): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<false>(resolve => {\n timer = setTimeout(() => resolve(false), this.#destroyTimeoutMs);\n });\n try {\n return await Promise.race([destroying.then(() => true as const), timedOut]);\n } catch (error) {\n if (isSandboxGoneError(error)) return true;\n throw error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async #destroyDirectly(sandbox: WorkspaceSandbox): Promise<void> {\n try {\n await sandbox.destroy?.();\n } catch (error) {\n if (!isSandboxGoneError(error)) throw error;\n }\n }\n\n async #releaseSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<void> {\n try {\n await releaseSessionSandbox({ sessionId: session.id, destroy: input.deleteSession });\n } catch (error) {\n this.#warn('Factory session sandbox release failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n}\n"],"mappings":";;;;;;AAuCA,MAAM,6BAA6B;;;;;;AAOnC,SAAS,mBAAmB,OAAyB;CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,EAAE,QAAQ,SAAS;CACzB,IAAI,WAAW,KAAK,OAAO;CAC3B,OAAO,WAAW,QAAQ,SAAS,KAAA,KAAa,SAAS,QAAQ,SAAS;AAC5E;AAWA,SAAS,aAAa,OAAwB;CAC5C,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CACpE,IAAI,OAAO,UAAU,KAAM,OAAO;CAClC,OAAO,GAAG,OAAO,MAAM,GAAG,GAAG,EAAE,KAAK,OAAO,MAAM,KAAK;AACxD;;;;;;;;;;;;;AAcA,IAAa,+BAAb,MAA0C;CACxC;CACA;CACA;CACA;CACA,yBAAkB,IAAI,IAA8B;CAEpD,YAAY,UAA+C,CAAC,GAAG;EAC7D,KAAK,qBAAqB,QAAQ,4BAA4B,CAAC;EAC/D,KAAK,WAAW,QAAQ;EACxB,KAAK,QAAQ,QAAQ,UAAU,SAAS,YAAY,QAAQ,KAAK,oBAAoB,WAAW,OAAO;EACvG,KAAK,oBAAoB,QAAQ,oBAAoB;CACvD;CAEA,MAAM,cAAc,OAA0C;EAC5D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E,CAAC;EACD,IAAI;GACF,OAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,WAAW,IAAa,GAAG,QAAQ,CAAC;EAC5E,SAAS,OAAO;GACd,IAAI,mBAAmB,KAAK,GAAG,OAAO;GACtC,MAAM;EACR,UAAU;GACR,aAAa,KAAK;EACpB;CACF;CAEA,MAAM,iBAAiB,SAA0C;EAC/D,IAAI;GACF,MAAM,QAAQ,UAAU;EAC1B,SAAS,OAAO;GACd,IAAI,CAAC,mBAAmB,KAAK,GAAG,MAAM;EACxC;CACF;CAEA,MAAM,gBAAgB,OAA2B,SAA8C;EAC7F,IAAI;GACF,MAAM,sBAAsB;IAAE,WAAW,QAAQ;IAAI,SAAS,MAAM;GAAc,CAAC;EACrF,SAAS,OAAO;GACd,KAAK,MAAM,0CAA0C;IACnD,OAAO,QAAQ;IACf,WAAW,QAAQ;IACnB,qBAAqB,QAAQ;IAC7B,OAAO,aAAa,KAAK;GAC3B,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"session-retirement.js","names":[],"sources":["../../src/sandbox/session-retirement.ts"],"sourcesContent":["import type { FactorySandbox, WorkspaceSandbox } from '@mastra/core/workspace';\n\nimport {\n destroyDetachedSessionSandbox,\n releaseSessionSandbox,\n stopDetachedSessionSandbox,\n} from '../integrations/github/sandbox-release.js';\nimport { DEFAULT_COMMAND_TIMEOUT_MS, runTeardownCommand } from '../integrations/github/sandbox.js';\nimport { factoryMetrics } from '../metrics/metrics.js';\nimport { peekSessionEnvironmentTeardown } from '../session/environment-state-processor.js';\nimport type {\n ProjectRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { requireExec } from './materialization.js';\nimport { clearFailedSetupCommands, evictSessionSandbox, peekSessionSandbox } from './session-sandbox.js';\n\ntype WarningLogger = (message: string, details: Record<string, unknown>) => void;\n\nexport interface SessionRetirementCoordinatorOptions {\n invalidateSession?: (sessionId: string) => Promise<void> | void;\n /**\n * The deploy's sandbox configuration. Used to destroy a deleted session's\n * VM by identity when this process never attached to it (after a restart,\n * or on another replica). Recreate uses it the same way.\n */\n sandbox?: FactorySandbox;\n warn?: WarningLogger;\n /** How long recreate waits on a started sandbox's lifecycle destroy before falling back. */\n destroyTimeoutMs?: number;\n}\n\nexport interface RecreateSessionSandboxInput {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n sessionId: string;\n}\n\nconst DEFAULT_DESTROY_TIMEOUT_MS = 30_000;\n\n/**\n * A provider error meaning the VM is already gone: 410, or a 404 the proxy\n * marks `not_found` (or leaves uncoded). A routing 404 with another code is\n * not proof the VM is gone.\n */\nfunction isSandboxGoneError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const { status, code } = error as { status?: unknown; code?: unknown };\n if (status === 410) return true;\n return status === 404 && (code === undefined || code === null || code === 'not_found');\n}\n\nexport interface RetireSessionInput {\n sourceControl: SourceControlStorageHandle;\n /** When provided, deleting the session row also strips its work-item refs. */\n workItems?: Pick<WorkItemsStorage, 'clearSessionReferences'>;\n orgId: string;\n sessionId: string;\n deleteSession: boolean;\n}\n\nfunction boundedError(error: unknown): string {\n const detail = error instanceof Error ? error.message : String(error);\n if (detail.length <= 2000) return detail;\n return `${detail.slice(0, 200)}...${detail.slice(-1797)}`;\n}\n\n/**\n * Owns terminal and destructive session cleanup. Each session is serialized so\n * duplicate role bindings and competing deletion/transition requests cannot\n * run teardown concurrently.\n *\n * Sandbox identity is the session id: retirement stops (or, for deleted\n * sessions, destroys) the sandbox this process holds in the session memo.\n * Sessions opened on another replica (or before a restart) have no memo entry\n * here: a materialized one is stopped (or, when deleted, destroyed) by\n * identity through the configured sandbox. Providers such as E2B keep paused\n * VMs forever, so the row's deletion must never orphan one.\n */\nexport class SessionRetirementCoordinator {\n readonly #invalidateSession: NonNullable<SessionRetirementCoordinatorOptions['invalidateSession']>;\n readonly #sandbox: FactorySandbox | undefined;\n readonly #warn: WarningLogger;\n readonly #destroyTimeoutMs: number;\n readonly #locks = new Map<string, Promise<unknown>>();\n\n constructor(options: SessionRetirementCoordinatorOptions = {}) {\n this.#invalidateSession = options.invalidateSession ?? (() => {});\n this.#sandbox = options.sandbox;\n this.#warn = options.warn ?? ((message, details) => console.warn(`[Mastra Factory] ${message}`, details));\n this.#destroyTimeoutMs = options.destroyTimeoutMs ?? DEFAULT_DESTROY_TIMEOUT_MS;\n }\n\n async retireSession(input: RetireSessionInput): Promise<void> {\n const retired = await this.#withSessionLock(input.sessionId, () => this.#retireSession(input));\n if (retired) factoryMetrics().count('sandbox', 'mastra_factory_sandbox_retired_total');\n }\n\n /**\n * Destroy a session's sandbox so its next message boots a fresh VM from the\n * template, keeping the session row, its conversation, and work-item refs.\n * Skips teardown commands, and works without a memo entry in this process\n * by destroying a detached instance built from the persisted `sandboxId`.\n * A destroy failure keeps the persisted id so a retry can reach the VM.\n */\n async recreateSessionSandbox(input: RecreateSessionSandboxInput): Promise<'recreated' | 'not-found'> {\n const result = await this.#withSessionLock(input.sessionId, () => this.#recreateSessionSandbox(input));\n if (result === 'recreated')\n factoryMetrics().count('sandbox', 'mastra_factory_sandbox_recreated_total', { kind: 'recreate' });\n return result;\n }\n\n /**\n * Replace the session's VM while keeping its sandbox instance, for the\n * session's own agent. A run holds the instance it started with until the\n * run ends, so recreate (which destroys the instance) would leave every\n * later command in that run failing. Here the VM is destroyed and the\n * instance is left `stopped` with no VM id, so the run's next command starts\n * a fresh VM and the start hook sets it up again.\n *\n * `not-here` means this process holds no instance for the session.\n */\n async resetSessionSandbox(input: RecreateSessionSandboxInput): Promise<'reset' | 'not-found' | 'not-here'> {\n const result = await this.#withSessionLock(input.sessionId, () => this.#resetSessionSandbox(input));\n if (result === 'reset')\n factoryMetrics().count('sandbox', 'mastra_factory_sandbox_recreated_total', { kind: 'reset' });\n return result;\n }\n\n /**\n * Stop a session's sandbox and keep everything else: the row, its files and\n * its work-item refs, so the session's next start resumes the same sandbox.\n * Unlike retirement no teardown command runs, because a resume does not\n * run setup again. Reaches the VM by identity when this process never\n * attached to it.\n */\n async stopSessionSandbox(input: Omit<RetireSessionInput, 'deleteSession' | 'workItems'>): Promise<void> {\n await this.#withSessionLock(input.sessionId, async () => {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return;\n try {\n if (peekSessionSandbox(session.id)) await releaseSessionSandbox({ sessionId: session.id });\n else await this.#releaseDetachedSandbox({ ...input, deleteSession: false }, session);\n } finally {\n await this.#invalidate(session);\n }\n });\n }\n\n async #withSessionLock<T>(sessionId: string, run: () => Promise<T>): Promise<T> {\n const previous = this.#locks.get(sessionId) ?? Promise.resolve();\n const current = previous.catch(() => {}).then(run);\n this.#locks.set(sessionId, current);\n try {\n return await current;\n } finally {\n if (this.#locks.get(sessionId) === current) this.#locks.delete(sessionId);\n }\n }\n\n async retireWorkItemSessions(options: {\n workItems: Pick<WorkItemsStorage, 'get'>;\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n workItemId: string;\n }): Promise<void> {\n const item = await options.workItems.get({ orgId: options.orgId, id: options.workItemId });\n if (!item) return;\n const sessionIds = [...new Set(Object.values(item.sessions).map(session => session.sessionId))];\n await Promise.all(\n sessionIds.map(sessionId =>\n this.retireSession({\n sourceControl: options.sourceControl,\n orgId: options.orgId,\n sessionId,\n deleteSession: false,\n }),\n ),\n );\n }\n\n async retireProjectRepositorySessions(options: {\n sourceControl: SourceControlStorageHandle;\n workItems?: Pick<WorkItemsStorage, 'clearSessionReferences'>;\n orgId: string;\n projectRepositoryId: string;\n }): Promise<void> {\n const sessions = await options.sourceControl.sessions.listByProjectRepository({\n projectRepositoryId: options.projectRepositoryId,\n });\n await Promise.all(\n sessions.map(session =>\n this.retireSession({\n sourceControl: options.sourceControl,\n ...(options.workItems ? { workItems: options.workItems } : {}),\n orgId: options.orgId,\n sessionId: session.sessionId,\n deleteSession: true,\n }),\n ),\n );\n }\n\n /** Resolves `true` when the session had a sandbox and releasing it succeeded. */\n async #retireSession(input: RetireSessionInput): Promise<boolean> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return false;\n\n let released = false;\n try {\n released = await this.#teardownSessionSandbox(input, session);\n } finally {\n await this.#invalidate(session);\n\n if (input.deleteSession) {\n // Refs first: clearing again is a no-op, but refs on a deleted row would dangle forever.\n await input.workItems?.clearSessionReferences({ orgId: input.orgId, sessionId: input.sessionId });\n await input.sourceControl.sessions.delete(session.id);\n }\n }\n return released;\n }\n\n async #teardownSessionSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<boolean> {\n const entry = peekSessionSandbox(session.id);\n if (!entry) return this.#releaseDetachedSandbox(input, session);\n\n // A session booted from its factory environment tears every repository\n // down in position order, each in its own directory; a failure is logged\n // and the next repository still runs.\n const environmentTeardown = peekSessionEnvironmentTeardown(session.sessionId);\n if (environmentTeardown.length > 0) {\n for (const repo of environmentTeardown) {\n try {\n await runTeardownCommand(requireExec(entry.sandbox), repo.dir, repo.command, {\n timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n });\n } catch (error) {\n this.#warn('Factory teardown command failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n repository: repo.slug,\n error: boundedError(error),\n });\n }\n }\n return this.#releaseSandbox(input, session);\n }\n\n let projectRepository: ProjectRepository | null | undefined;\n try {\n projectRepository = session.projectRepositoryId\n ? await input.sourceControl.projectRepositories.get({ orgId: input.orgId, id: session.projectRepositoryId })\n : null;\n } catch (error) {\n this.#warn('Factory repository settings could not be loaded for session retirement', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n\n // An unresolved workdir means the sandbox never started in this process:\n // nothing was set up, so there is nothing for a teardown command to undo.\n if (projectRepository?.teardownCommand && entry.workdir) {\n try {\n await runTeardownCommand(requireExec(entry.sandbox), entry.workdir, projectRepository.teardownCommand, {\n timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n });\n } catch (error) {\n this.#warn('Factory teardown command failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n return this.#releaseSandbox(input, session);\n }\n\n /**\n * Stop (or, for a deleted session, destroy) a session's VM that this\n * process never attached to. Only for sessions that materialized (a\n * persisted `sandboxId`): nothing is started, no teardown command runs —\n * the provider pauses or kills by identity. Resolves whether a sandbox was released.\n */\n async #releaseDetachedSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<boolean> {\n if (!session.sandboxId || !this.#sandbox) return false;\n try {\n if (input.deleteSession) await destroyDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n else await stopDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n return true;\n } catch (error) {\n this.#warn(`Factory detached session sandbox ${input.deleteSession ? 'destroy' : 'stop'} failed`, {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n return false;\n }\n }\n\n /** Bump the session's workspace generation; a failing unregister is logged, never fatal. */\n async #invalidate(session: SourceControlSession): Promise<void> {\n try {\n await this.#invalidateSession(session.sessionId);\n } catch (error) {\n this.#warn('Factory session workspace cache invalidation failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n async #recreateSessionSandbox(input: RecreateSessionSandboxInput): Promise<'recreated' | 'not-found'> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return 'not-found';\n\n // Bump the generation first so an in-flight start hook for the old\n // instance throws instead of republishing its sandbox id.\n await this.#invalidate(session);\n const entry = peekSessionSandbox(session.id);\n evictSessionSandbox(session.id);\n\n await this.#destroyForRecreate(session, entry?.sandbox);\n await input.sourceControl.sessions.setSandbox({ id: session.id, sandboxId: null, sandboxWorkdir: '' });\n\n // A resolve that ran between the eviction and clearing the id could have\n // built a fresh instance from the old `sandboxId`; drop it and fence it.\n evictSessionSandbox(session.id);\n await this.#invalidate(session);\n return 'recreated';\n }\n\n async #resetSessionSandbox(input: RecreateSessionSandboxInput): Promise<'reset' | 'not-found' | 'not-here'> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return 'not-found';\n const sandbox = peekSessionSandbox(session.id)?.sandbox;\n if (!sandbox) return 'not-here';\n\n // The provider's own destroy, not the lifecycle wrapper: the wrapper marks\n // the instance destroyed for good. Bounded, so a VM that won't answer\n // can't hold the session lock.\n const destroy = async () => {\n if (!(await this.#settledWithin(this.#destroyDirectly(sandbox)))) {\n throw new Error('Timed out destroying the sandbox. Try again.');\n }\n };\n // Destroyed before waiting on a start in flight, so a start hung on the\n // dead VM can't block recovery; its commands fail fast once the VM is gone.\n await destroy();\n const starting = (sandbox as { _startPromise?: Promise<unknown> })._startPromise;\n if (starting) {\n const settled = await this.#settledWithin(\n starting.then(\n () => {},\n () => {},\n ),\n );\n if (!settled) throw new Error('The old sandbox is still starting. Try again.');\n // That start may have found the old VM gone and provisioned another.\n await destroy();\n }\n\n sandbox.status = 'stopped';\n // The new VM runs setup from scratch, including commands that failed on the old one.\n clearFailedSetupCommands(session.id);\n // Re-read: a start that settled while this reset waited may have stored a newer workdir.\n const latest = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n await input.sourceControl.sessions.setSandbox({\n id: session.id,\n sandboxId: null,\n sandboxWorkdir: latest?.sandboxWorkdir ?? session.sandboxWorkdir ?? '',\n });\n return 'reset';\n }\n\n /**\n * Destroy the session's VM. `_destroy()` silently no-ops on a never-started\n * (`pending`) instance, so pending and detached instances call the\n * provider's `destroy()` directly; a started instance goes through the\n * lifecycle wrapper, bounded so a hung start can't hold the session lock.\n */\n async #destroyForRecreate(session: SourceControlSession, memo: WorkspaceSandbox | undefined): Promise<void> {\n const lifecycle = memo as { _destroy?: () => Promise<void> } | undefined;\n if (memo && memo.status !== 'pending' && lifecycle?._destroy) {\n const destroying = lifecycle._destroy.call(memo);\n if (await this.#settledWithin(destroying)) {\n memo.status = 'destroyed';\n return;\n }\n // Load-bearing: once the hung start settles, this destroy reaps any VM it\n // provisioned. Its rejection must never surface as unhandled.\n destroying.catch(error =>\n this.#warn('Factory sandbox destroy failed after recreate stopped waiting', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n error: boundedError(error),\n }),\n );\n if (!this.#sandbox) {\n throw new Error(\n 'Timed out destroying the session sandbox, and no sandbox provider is configured to retry by identity.',\n );\n }\n await this.#destroyDetachedForRecreate(this.#sandbox, session);\n memo.status = 'destroyed';\n return;\n }\n\n if (memo) {\n await this.#destroyDirectly(memo);\n memo.status = 'destroyed';\n return;\n }\n\n // No instance in this process (restart, or another replica opened it):\n // destroy through a never-started instance carrying the persisted id.\n // Unlike retirement, this runs without a `sandboxId` too: E2B and Docker\n // find the VM by session identity, and Platform's destroy no-ops safely.\n if (this.#sandbox) await this.#destroyDetachedForRecreate(this.#sandbox, session);\n }\n\n async #destroyDetachedForRecreate(sandbox: FactorySandbox, session: SourceControlSession): Promise<void> {\n try {\n await destroyDetachedSessionSandbox({ sandbox, session });\n } catch (error) {\n if (!isSandboxGoneError(error)) throw error;\n }\n }\n\n /** True when the destroy finished in time; false on timeout. Gone-VM errors count as finished. */\n async #settledWithin(destroying: Promise<void>): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<false>(resolve => {\n timer = setTimeout(() => resolve(false), this.#destroyTimeoutMs);\n });\n try {\n return await Promise.race([destroying.then(() => true as const), timedOut]);\n } catch (error) {\n if (isSandboxGoneError(error)) return true;\n throw error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async #destroyDirectly(sandbox: WorkspaceSandbox): Promise<void> {\n try {\n await sandbox.destroy?.();\n } catch (error) {\n if (!isSandboxGoneError(error)) throw error;\n }\n }\n\n async #releaseSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<boolean> {\n try {\n await releaseSessionSandbox({ sessionId: session.id, destroy: input.deleteSession });\n return true;\n } catch (error) {\n this.#warn('Factory session sandbox release failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n return false;\n }\n }\n}\n"],"mappings":";;;;;;;AAwCA,MAAM,6BAA6B;;;;;;AAOnC,SAAS,mBAAmB,OAAyB;CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,EAAE,QAAQ,SAAS;CACzB,IAAI,WAAW,KAAK,OAAO;CAC3B,OAAO,WAAW,QAAQ,SAAS,KAAA,KAAa,SAAS,QAAQ,SAAS;AAC5E;AAWA,SAAS,aAAa,OAAwB;CAC5C,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CACpE,IAAI,OAAO,UAAU,KAAM,OAAO;CAClC,OAAO,GAAG,OAAO,MAAM,GAAG,GAAG,EAAE,KAAK,OAAO,MAAM,KAAK;AACxD;;;;;;;;;;;;;AAcA,IAAa,+BAAb,MAA0C;CACxC;CACA;CACA;CACA;CACA,yBAAkB,IAAI,IAA8B;CAEpD,YAAY,UAA+C,CAAC,GAAG;EAC7D,KAAK,qBAAqB,QAAQ,4BAA4B,CAAC;EAC/D,KAAK,WAAW,QAAQ;EACxB,KAAK,QAAQ,QAAQ,UAAU,SAAS,YAAY,QAAQ,KAAK,oBAAoB,WAAW,OAAO;EACvG,KAAK,oBAAoB,QAAQ,oBAAoB;CACvD;CAEA,MAAM,cAAc,OAA0C;EAE5D,IAAI,MADkB,KAAK,iBAAiB,MAAM,iBAAiB,KAAK,eAAe,KAAK,CAAC,GAChF,eAAe,CAAC,CAAC,MAAM,WAAW,sCAAsC;CACvF;;;;;;;;CASA,MAAM,uBAAuB,OAAwE;EACnG,MAAM,SAAS,MAAM,KAAK,iBAAiB,MAAM,iBAAiB,KAAK,wBAAwB,KAAK,CAAC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M,WAAW,IAAI,SAAe,YAAW;GAC7C,QAAQ,iBAAiB,QAAQ,KAAK,GAAG,KAAK,iBAAiB;EACjE,CAAC;EACD,IAAI;GACF,OAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,WAAW,IAAa,GAAG,QAAQ,CAAC;EAC5E,SAAS,OAAO;GACd,IAAI,mBAAmB,KAAK,GAAG,OAAO;GACtC,MAAM;EACR,UAAU;GACR,aAAa,KAAK;EACpB;CACF;CAEA,MAAM,iBAAiB,SAA0C;EAC/D,IAAI;GACF,MAAM,QAAQ,UAAU;EAC1B,SAAS,OAAO;GACd,IAAI,CAAC,mBAAmB,KAAK,GAAG,MAAM;EACxC;CACF;CAEA,MAAM,gBAAgB,OAA2B,SAAiD;EAChG,IAAI;GACF,MAAM,sBAAsB;IAAE,WAAW,QAAQ;IAAI,SAAS,MAAM;GAAc,CAAC;GACnF,OAAO;EACT,SAAS,OAAO;GACd,KAAK,MAAM,0CAA0C;IACnD,OAAO,QAAQ;IACf,WAAW,QAAQ;IACnB,qBAAqB,QAAQ;IAC7B,OAAO,aAAa,KAAK;GAC3B,CAAC;GACD,OAAO;EACT;CACF;AACF"}
@@ -151,6 +151,8 @@ export declare function resolveSessionWorkdir(sessionId: string, sandbox: Worksp
151
151
  export declare function peekSessionSandbox(sessionId: string): SessionSandboxEntry | undefined;
152
152
  /** Drop the memoized instance (on stop/destroy/retirement or construction failure). */
153
153
  export declare function evictSessionSandbox(sessionId: string): void;
154
+ /** How many of this process's session sandboxes are running. */
155
+ export declare function countRunningSessionSandboxes(): number;
154
156
  /** Test-only: reset the process-wide memo between tests. */
155
157
  export declare function __clearSessionSandboxesForTests(): void;
156
158
  export declare function recordFailedSetupCommand(sessionId: string, command: string): void;
@@ -1 +1 @@
1
- {"version":3,"file":"session-sandbox.d.ts","sourceRoot":"","sources":["../../src/sandbox/session-sandbox.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EACV,cAAc,EACd,qBAAqB,IAAI,yBAAyB,EAClD,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0B,EAC/B,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE;IAAE,KAAK,EAAE,4BAA4B,EAAE,CAAC;IAAC,qBAAqB,CAAC,EAAE,MAAM,CAAA;CAAE,GACrF,gBAAgB,CA+ClB"}
@@ -96,6 +96,12 @@ function evictSessionSandbox(sessionId) {
96
96
  sessionSandboxes.delete(sessionId);
97
97
  failedSetupCommands.delete(sessionId);
98
98
  }
99
+ /** How many of this process's session sandboxes are running. */
100
+ function countRunningSessionSandboxes() {
101
+ let running = 0;
102
+ for (const entry of sessionSandboxes.values()) if (entry.sandbox.status === "running") running++;
103
+ return running;
104
+ }
99
105
  /** Test-only: reset the process-wide memo between tests. */
100
106
  function __clearSessionSandboxesForTests() {
101
107
  sessionSandboxes.clear();
@@ -246,6 +252,6 @@ function createEnvironmentSetupHook(run, sessionId, repoFullName, environment) {
246
252
  });
247
253
  };
248
254
  }
249
- export { __clearSessionSandboxesForTests, clearFailedSetupCommands, createEnvironmentSetupHook, createSessionSetupHook, evictSessionSandbox, getSessionSandbox, hasFailedSetupCommand, peekSessionSandbox, recordFailedSetupCommand, resolveSessionWorkdir, sessionLayout };
255
+ export { __clearSessionSandboxesForTests, clearFailedSetupCommands, countRunningSessionSandboxes, createEnvironmentSetupHook, createSessionSetupHook, evictSessionSandbox, getSessionSandbox, hasFailedSetupCommand, peekSessionSandbox, recordFailedSetupCommand, resolveSessionWorkdir, sessionLayout };
250
256
 
251
257
  //# sourceMappingURL=session-sandbox.js.map