@mastra/factory 0.29.0-alpha.3 → 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 (154) hide show
  1. package/README.md +4 -4
  2. package/dist/factory.d.ts.map +1 -1
  3. package/dist/factory.js +2 -10
  4. package/dist/factory.js.map +1 -1
  5. package/dist/index.d.ts +0 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +1 -2
  8. package/dist/integrations/dependabot/rules.d.ts.map +1 -1
  9. package/dist/integrations/dependabot/rules.js +1 -5
  10. package/dist/integrations/dependabot/rules.js.map +1 -1
  11. package/dist/integrations/github/commits.d.ts +0 -21
  12. package/dist/integrations/github/commits.d.ts.map +1 -1
  13. package/dist/integrations/github/commits.js +1 -24
  14. package/dist/integrations/github/commits.js.map +1 -1
  15. package/dist/integrations/github/integration.d.ts +1 -1
  16. package/dist/integrations/github/integration.d.ts.map +1 -1
  17. package/dist/integrations/github/integration.js +2 -6
  18. package/dist/integrations/github/integration.js.map +1 -1
  19. package/dist/integrations/github/routes.d.ts +1 -11
  20. package/dist/integrations/github/routes.d.ts.map +1 -1
  21. package/dist/integrations/github/routes.js +6 -515
  22. package/dist/integrations/github/routes.js.map +1 -1
  23. package/dist/integrations/github/rules.d.ts.map +1 -1
  24. package/dist/integrations/github/rules.js +59 -10
  25. package/dist/integrations/github/rules.js.map +1 -1
  26. package/dist/integrations/gitlab/discovery.d.ts +1 -1
  27. package/dist/integrations/gitlab/discovery.js +1 -1
  28. package/dist/integrations/gitlab/discovery.js.map +1 -1
  29. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  30. package/dist/integrations/gitlab/integration.js +0 -1
  31. package/dist/integrations/gitlab/integration.js.map +1 -1
  32. package/dist/integrations/gitlab/routes.d.ts +0 -2
  33. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  34. package/dist/integrations/gitlab/routes.js +49 -165
  35. package/dist/integrations/gitlab/routes.js.map +1 -1
  36. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/rules.js +20 -7
  38. package/dist/integrations/gitlab/rules.js.map +1 -1
  39. package/dist/integrations/incidentio/routes.d.ts +5 -5
  40. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  41. package/dist/integrations/incidentio/routes.js +3 -59
  42. package/dist/integrations/incidentio/routes.js.map +1 -1
  43. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  44. package/dist/integrations/incidentio/rules.js +1 -5
  45. package/dist/integrations/incidentio/rules.js.map +1 -1
  46. package/dist/integrations/jira/issue-reconciler.d.ts +1 -1
  47. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  48. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  49. package/dist/integrations/jira/routes.d.ts +2 -2
  50. package/dist/integrations/jira/routes.d.ts.map +1 -1
  51. package/dist/integrations/jira/routes.js +0 -68
  52. package/dist/integrations/jira/routes.js.map +1 -1
  53. package/dist/integrations/jira/rules.d.ts.map +1 -1
  54. package/dist/integrations/jira/rules.js +1 -5
  55. package/dist/integrations/jira/rules.js.map +1 -1
  56. package/dist/integrations/linear/routes.d.ts +2 -2
  57. package/dist/integrations/linear/routes.d.ts.map +1 -1
  58. package/dist/integrations/linear/routes.js +0 -83
  59. package/dist/integrations/linear/routes.js.map +1 -1
  60. package/dist/integrations/linear/rules.d.ts.map +1 -1
  61. package/dist/integrations/linear/rules.js +1 -5
  62. package/dist/integrations/linear/rules.js.map +1 -1
  63. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  64. package/dist/integrations/platform/github/integration.js +1 -3
  65. package/dist/integrations/platform/github/integration.js.map +1 -1
  66. package/dist/integrations/platform/jira/routes.d.ts +2 -2
  67. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  68. package/dist/integrations/platform/jira/routes.js +0 -69
  69. package/dist/integrations/platform/jira/routes.js.map +1 -1
  70. package/dist/integrations/vanta/rules.d.ts.map +1 -1
  71. package/dist/integrations/vanta/rules.js +1 -5
  72. package/dist/integrations/vanta/rules.js.map +1 -1
  73. package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
  74. package/dist/routes/automation-runs.d.ts +0 -2
  75. package/dist/routes/automation-runs.d.ts.map +1 -1
  76. package/dist/routes/automation-runs.js +2 -6
  77. package/dist/routes/automation-runs.js.map +1 -1
  78. package/dist/routes/contracts.d.ts +0 -5
  79. package/dist/routes/contracts.d.ts.map +1 -1
  80. package/dist/routes/contracts.js +2 -4
  81. package/dist/routes/contracts.js.map +1 -1
  82. package/dist/routes/fs.d.ts +10 -0
  83. package/dist/routes/fs.d.ts.map +1 -1
  84. package/dist/routes/fs.js +184 -11
  85. package/dist/routes/fs.js.map +1 -1
  86. package/dist/routes/projects.d.ts.map +1 -1
  87. package/dist/routes/projects.js +4 -17
  88. package/dist/routes/projects.js.map +1 -1
  89. package/dist/routes/source-control-sessions.d.ts +0 -3
  90. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  91. package/dist/routes/source-control-sessions.js +0 -19
  92. package/dist/routes/source-control-sessions.js.map +1 -1
  93. package/dist/routes/surface.d.ts +0 -2
  94. package/dist/routes/surface.d.ts.map +1 -1
  95. package/dist/routes/surface.js +1 -12
  96. package/dist/routes/surface.js.map +1 -1
  97. package/dist/rules/dispatcher.d.ts.map +1 -1
  98. package/dist/rules/dispatcher.js +1 -5
  99. package/dist/rules/dispatcher.js.map +1 -1
  100. package/dist/rules/processor.d.ts.map +1 -1
  101. package/dist/rules/processor.js +1 -6
  102. package/dist/rules/processor.js.map +1 -1
  103. package/dist/rules/start-coordinator.js +1 -1
  104. package/dist/rules/start-coordinator.js.map +1 -1
  105. package/dist/rules/transition-service.d.ts.map +1 -1
  106. package/dist/rules/transition-service.js +0 -2
  107. package/dist/rules/transition-service.js.map +1 -1
  108. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  109. package/dist/storage/domains/boards/schemas.js +0 -4
  110. package/dist/storage/domains/boards/schemas.js.map +1 -1
  111. package/dist/storage/domains/intake/base.d.ts +11 -10
  112. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  113. package/dist/storage/domains/intake/base.js +30 -65
  114. package/dist/storage/domains/intake/base.js.map +1 -1
  115. package/dist/storage/domains/integrations/base.d.ts +0 -2
  116. package/dist/storage/domains/integrations/base.d.ts.map +1 -1
  117. package/dist/storage/domains/integrations/base.js +0 -6
  118. package/dist/storage/domains/integrations/base.js.map +1 -1
  119. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  120. package/dist/storage/domains/projects/base.js +0 -12
  121. package/dist/storage/domains/projects/base.js.map +1 -1
  122. package/dist/storage/domains/source-control/base.d.ts +0 -10
  123. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  124. package/dist/storage/domains/source-control/base.js +1 -19
  125. package/dist/storage/domains/source-control/base.js.map +1 -1
  126. package/dist/storage/domains/source-control/inmemory.d.ts +1 -1
  127. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  128. package/dist/storage/domains/source-control/inmemory.js +1 -6
  129. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  130. package/dist/storage/domains/work-items/base.d.ts +1 -36
  131. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  132. package/dist/storage/domains/work-items/base.js +24 -81
  133. package/dist/storage/domains/work-items/base.js.map +1 -1
  134. package/dist/storage/domains/work-items/work-item-schema.d.ts +12 -3
  135. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  136. package/dist/storage/domains/work-items/work-item-schema.js +12 -3
  137. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  138. package/dist/storage/legacy-collections.d.ts +9 -0
  139. package/dist/storage/legacy-collections.d.ts.map +1 -0
  140. package/dist/storage/legacy-collections.js +17 -0
  141. package/dist/storage/legacy-collections.js.map +1 -0
  142. package/dist/workspace.d.ts.map +1 -1
  143. package/dist/workspace.js +1 -3
  144. package/dist/workspace.js.map +1 -1
  145. package/factory-skills/configure-factory-rules/SKILL.md +2 -2
  146. package/package.json +9 -9
  147. package/dist/session/filesystem-capture.d.ts +0 -50
  148. package/dist/session/filesystem-capture.d.ts.map +0 -1
  149. package/dist/session/filesystem-capture.js +0 -229
  150. package/dist/session/filesystem-capture.js.map +0 -1
  151. package/dist/storage/domains/filesystem/base.d.ts +0 -30
  152. package/dist/storage/domains/filesystem/base.d.ts.map +0 -1
  153. package/dist/storage/domains/filesystem/base.js +0 -78
  154. 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,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,SAAS,eAAe,QAAyC,SAAwC;CACvG,MAAM,QAAQ,aAAa,QAAQ,MAAM,KAAK,QAAQ,OAAO,KAAK,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S;IACd,QAAQ,KAAK,kDAAkD,QAAQ,WAAW,IAAI,KAAK;GAC7F,CAAC;EACL;EAEA,MAAM,QAAQ,OAAO,WAAW,aAAa,QAAQ,IAAI,QAAQ,KAAK,IAAI,KAAA;EAC1E,IAAI,SAAS,OAAO,WAAW,YAAY;GACzC,MAAM,QAAQ;IACZ,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B,YAAY,QAAQ;IACpB,UAAU,OAAO;IACjB,OAAO,QAAQ;GACjB;GACA,IAAI,MAAM,WAAW,OAAO,KAAK,GAAG;IAClC,MAAM,kBAAkB,KAAK;IAC7B,IAAI,iBAAiB,MAAM,KAAK,eAAe,gBAAgB;KAAE,GAAG;KAAO,OAAO,OAAO;IAAM,CAAC,CAAC;GACnG,OAAO,IAAI,cAAc,KAAA,KAAa,KAAK,gBAAgB;IACzD,MAAM,UAAU,MAAM,aAAa,SAAS;IAC5C,MAAM,YAAY,MAAM,aAAa,OAAO,KAAK;IACjD,MAAM,gBAAgB,KAAK;IAC3B,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,MA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a,SAAS;IAC5C,MAAM,YAAY,MAAM,aAAa,OAAO,KAAK;IACjD,MAAM,gBAAgB,KAAK;IAC3B,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 +1 @@
1
- {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/boards/schemas.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,sFAAsF;AACtF,eAAO,MAAM,qBAAqB,EAAE,gBAmBnC,CAAC;AAEF,0EAA0E;AAC1E,eAAO,MAAM,2BAA2B,EAAE,gBA4BzC,CAAC;AAEF,yFAAyF;AACzF,eAAO,MAAM,4BAA4B,EAAE,gBAgC1C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,EAAE,gBAY/C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,wCAAwC,EAAE,gBAgBtD,CAAC"}
1
+ {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/boards/schemas.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,sFAAsF;AACtF,eAAO,MAAM,qBAAqB,EAAE,gBAmBnC,CAAC;AAEF,0EAA0E;AAC1E,eAAO,MAAM,2BAA2B,EAAE,gBA4BzC,CAAC;AAEF,yFAAyF;AACzF,eAAO,MAAM,4BAA4B,EAAE,gBA8B1C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,EAAE,gBAY/C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,wCAAwC,EAAE,gBAgBtD,CAAC"}
@@ -113,10 +113,6 @@ const FACTORY_INTAKE_ROUTES_SCHEMA = {
113
113
  type: "json",
114
114
  nullable: true
115
115
  },
116
- allow_working_phase: {
117
- type: "boolean",
118
- nullable: true
119
- },
120
116
  join_closed_issue: {
121
117
  type: "boolean",
122
118
  nullable: true
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.js","names":[],"sources":["../../../../src/storage/domains/boards/schemas.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\n/** A project's boards. `board_key` is the id cards reference (`work_items.board`). */\nexport const FACTORY_BOARDS_SCHEMA: CollectionSchema = {\n name: 'factory_boards',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n position: { type: 'integer' },\n // Rises on every write to the board or its phases; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'factory_boards_project_key', columns: ['org_id', 'factory_project_id', 'board_key'] }],\n indexes: [{ name: 'factory_boards_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A board's ordered phases. `phase_key` is the stage id cards sit in. */\nexport const FACTORY_BOARD_PHASES_SCHEMA: CollectionSchema = {\n name: 'factory_board_phases',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n phase_key: { type: 'text' },\n position: { type: 'integer' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n kind: { type: 'text' },\n // { skill?, context?, instructions? }; room for other runner types later.\n runner: { type: 'json', nullable: true },\n next_phases: { type: 'json', nullable: true },\n auto_start: { type: 'boolean', default: false },\n auto_start_when: { type: 'json', nullable: true },\n exit_tool: { type: 'json', nullable: true },\n // Factory tools the phase grants the session working the card there, e.g. [\"factory_record_review_verdict\"].\n tools: { type: 'json', nullable: true },\n },\n uniqueIndexes: [\n {\n name: 'factory_board_phases_project_board_phase',\n columns: ['org_id', 'factory_project_id', 'board_key', 'phase_key'],\n },\n ],\n indexes: [{ name: 'factory_board_phases_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A project's ordered intake routes: where new cards matching `when_condition` land. */\nexport const FACTORY_INTAKE_ROUTES_SCHEMA: CollectionSchema = {\n name: 'factory_intake_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n name: { type: 'text' },\n enabled: { type: 'boolean', default: true },\n position: { type: 'integer' },\n // A card RuleGroup; null matches every card. Not named `when`, which is an SQL keyword.\n when_condition: { type: 'json', nullable: true },\n board_key: { type: 'text' },\n // Null lands the card in the board's first phase.\n phase_key: { type: 'text', nullable: true },\n // The status events the route handles (`StatusEvent`s). Null on rows written before routes named\n // events: those place new cards, as `['work_item.created']`.\n on_events: { type: 'json', nullable: true },\n // No longer read or written: a route moves a card into any phase. Kept so existing tables match.\n allow_working_phase: { type: 'boolean', nullable: true },\n // True files a pull request on the card of the issue it closes instead of a new card. Null on rows written before it.\n join_closed_issue: { type: 'boolean', nullable: true },\n // Rises on every write to the route, including a move; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_intake_routes_project_position', columns: ['org_id', 'factory_project_id', 'position'] },\n ],\n indexes: [{ name: 'factory_intake_routes_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project that every write adding, deleting or moving intake routes upserts first,\n * inside its transaction. The upsert holds the row until commit, so those writes on one project\n * run one after another and positions stay 0..n-1 with no gaps.\n */\nexport const FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_intake_route_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n locked_at: { type: 'timestamp' },\n // Keys of the default routes Factory added to the project (`DEFAULT_INTAKE_ROUTES`), so each is\n // added once. Null on rows written before the list: those projects got `outside-authors`.\n seeded_defaults: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_intake_route_locks_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project whose `version` is replaced inside every board write, so other replicas\n * can tell their cached boards are stale with one indexed read.\n */\nexport const FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA: CollectionSchema = {\n name: 'factory_board_definition_versions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n version: { type: 'text' },\n updated_at: { type: 'timestamp' },\n // Keys of the boards Factory stored in the project (Work, app and seed boards); each is stored\n // once, so one the project deleted stays deleted. Null on projects stored before the list.\n seeded_boards: { type: 'json', nullable: true },\n // Keys of the board migrations applied to the project, so each runs once: a field a user\n // later sets back to an old default is never rewritten again. Null before the first one.\n applied_migrations: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_board_definition_versions_project', columns: ['org_id', 'factory_project_id'] }],\n};\n"],"mappings":";;AAGA,MAAa,wBAA0C;CACrD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,WAAW,EAAE,MAAM,OAAO;EAC1B,MAAM,EAAE,MAAM,OAAO;EACrB,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK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Ae;GAAE,MAAM;GAAQ,UAAU;EAAK;EAG9C,oBAAoB;GAAE,MAAM;GAAQ,UAAU;EAAK;CACrD;CACA,eAAe,CAAC;EAAE,MAAM;EAA6C,SAAS,CAAC,UAAU,oBAAoB;CAAE,CAAC;AAClH"}
1
+ {"version":3,"file":"schemas.js","names":[],"sources":["../../../../src/storage/domains/boards/schemas.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\n/** A project's boards. `board_key` is the id cards reference (`work_items.board`). */\nexport const FACTORY_BOARDS_SCHEMA: CollectionSchema = {\n name: 'factory_boards',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n position: { type: 'integer' },\n // Rises on every write to the board or its phases; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'factory_boards_project_key', columns: ['org_id', 'factory_project_id', 'board_key'] }],\n indexes: [{ name: 'factory_boards_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A board's ordered phases. `phase_key` is the stage id cards sit in. */\nexport const FACTORY_BOARD_PHASES_SCHEMA: CollectionSchema = {\n name: 'factory_board_phases',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n phase_key: { type: 'text' },\n position: { type: 'integer' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n kind: { type: 'text' },\n // { skill?, context?, instructions? }; room for other runner types later.\n runner: { type: 'json', nullable: true },\n next_phases: { type: 'json', nullable: true },\n auto_start: { type: 'boolean', default: false },\n auto_start_when: { type: 'json', nullable: true },\n exit_tool: { type: 'json', nullable: true },\n // Factory tools the phase grants the session working the card there, e.g. [\"factory_record_review_verdict\"].\n tools: { type: 'json', nullable: true },\n },\n uniqueIndexes: [\n {\n name: 'factory_board_phases_project_board_phase',\n columns: ['org_id', 'factory_project_id', 'board_key', 'phase_key'],\n },\n ],\n indexes: [{ name: 'factory_board_phases_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A project's ordered intake routes: where new cards matching `when_condition` land. */\nexport const FACTORY_INTAKE_ROUTES_SCHEMA: CollectionSchema = {\n name: 'factory_intake_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n name: { type: 'text' },\n enabled: { type: 'boolean', default: true },\n position: { type: 'integer' },\n // A card RuleGroup; null matches every card. Not named `when`, which is an SQL keyword.\n when_condition: { type: 'json', nullable: true },\n board_key: { type: 'text' },\n // Null lands the card in the board's first phase.\n phase_key: { type: 'text', nullable: true },\n // The status events the route handles (`StatusEvent`s). Null on rows written before routes named\n // events: those place new cards, as `['work_item.created']`.\n on_events: { type: 'json', nullable: true },\n // True files a pull request on the card of the issue it closes instead of a new card. Null on rows written before it.\n join_closed_issue: { type: 'boolean', nullable: true },\n // Rises on every write to the route, including a move; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_intake_routes_project_position', columns: ['org_id', 'factory_project_id', 'position'] },\n ],\n indexes: [{ name: 'factory_intake_routes_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project that every write adding, deleting or moving intake routes upserts first,\n * inside its transaction. The upsert holds the row until commit, so those writes on one project\n * run one after another and positions stay 0..n-1 with no gaps.\n */\nexport const FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_intake_route_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n locked_at: { type: 'timestamp' },\n // Keys of the default routes Factory added to the project (`DEFAULT_INTAKE_ROUTES`), so each is\n // added once. Null on rows written before the list: those projects got `outside-authors`.\n seeded_defaults: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_intake_route_locks_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project whose `version` is replaced inside every board write, so other replicas\n * can tell their cached boards are stale with one indexed read.\n */\nexport const FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA: CollectionSchema = {\n name: 'factory_board_definition_versions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n version: { type: 'text' },\n updated_at: { type: 'timestamp' },\n // Keys of the boards Factory stored in the project (Work, app and seed boards); each is stored\n // once, so one the project deleted stays deleted. Null on projects stored before the list.\n seeded_boards: { type: 'json', nullable: true },\n // Keys of the board migrations applied to the project, so each runs once: a field a user\n // later sets back to an old default is never rewritten again. Null before the first one.\n applied_migrations: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_board_definition_versions_project', columns: ['org_id', 'factory_project_id'] }],\n};\n"],"mappings":";;AAGA,MAAa,wBAA0C;CACrD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,WAAW,EAAE,MAAM,OAAO;EAC1B,MAAM,EAAE,MAAM,OAAO;EACrB,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,UAAU,EAAE,MAAM,UAAU;EAE5B,UAAU,EAAE,MAAM,UAAU;EAC5B,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAA8B,SAAS;GAAC;GAAU;GAAsB;EAAW;CAAE,CAAC;CAC9G,SAAS,CAAC;EAAE,MAAM;EAA0B,SAAS,C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GAAE,MAAM;GAAW,UAAU;EAAK;EAErD,UAAU,EAAE,MAAM,UAAU;EAC5B,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CACb;EAAE,MAAM;EAA0C,SAAS;GAAC;GAAU;GAAsB;EAAU;CAAE,CAC1G;CACA,SAAS,CAAC;EAAE,MAAM;EAAiC,SAAS,CAAC,UAAU,oBAAoB;CAAE,CAAC;AAChG;;;;;;AAOA,MAAa,oCAAsD;CACjE,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,WAAW,EAAE,MAAM,YAAY;EAG/B,iBAAiB;GAAE,MAAM;GAAQ,UAAU;EAAK;CAClD;CACA,eAAe,CAAC;EAAE,MAAM;EAAsC,SAAS,CAAC,UAAU,oBAAoB;CAAE,CAAC;AAC3G;;;;;AAMA,MAAa,2CAA6D;CACxE,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,SAAS,EAAE,MAAM,OAAO;EACxB,YAAY,EAAE,MAAM,YAAY;EAGhC,eAAe;GAAE,MAAM;GAAQ,UAAU;EAAK;EAG9C,oBAAoB;GAAE,MAAM;GAAQ,UAAU;EAAK;CACrD;CACA,eAAe,CAAC;EAAE,MAAM;EAA6C,SAAS,CAAC,UAAU,oBAAoB;CAAE,CAAC;AAClH"}
@@ -20,7 +20,10 @@ export interface IntakeSelection {
20
20
  export type IntakeConfig = Record<string, IntakeSelection>;
21
21
  export declare const DEFAULT_INTAKE_CONFIG: IntakeConfig;
22
22
  export declare const INTAKE_ORG_SETTINGS_SCHEMA: CollectionSchema;
23
- /** Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and are folded at boot. */
23
+ /**
24
+ * Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and
25
+ * are folded at boot. Registered only on a database an earlier release already created it in.
26
+ */
24
27
  export declare const LEGACY_INTAKE_USER_SETTINGS_SCHEMA: CollectionSchema;
25
28
  /** What the org effectively saw while selections were personal: a member's sources fed the shared board only while their switch was on. */
26
29
  export declare function mergeIntakeSelections(configs: readonly IntakeConfig[]): IntakeConfig;
@@ -34,8 +37,9 @@ export declare function mergeIntakeSelections(configs: readonly IntakeConfig[]):
34
37
  *
35
38
  * Frozen: its unique index allows one binding per source, and indexes cannot be
36
39
  * narrowed, so bindings moved to {@link INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA}. Rows
37
- * are copied once at boot and never written again; the collection stays
38
- * registered so an earlier build that is rolled back to still finds them.
40
+ * are copied once at boot and never written again. Registered, with
41
+ * {@link INTAKE_DATA_MIGRATIONS_SCHEMA}, only on a database an earlier release
42
+ * already created it in, so a build rolled back to still finds the rows there.
39
43
  */
40
44
  export declare const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema;
41
45
  /**
@@ -45,7 +49,10 @@ export declare const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema;
45
49
  * projects share a source, each taking the issues carrying its own labels.
46
50
  */
47
51
  export declare const INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA: CollectionSchema;
48
- /** One-time data migrations that have run, so none re-runs over rows users have changed since. */
52
+ /**
53
+ * One-time data migrations that have run, so none re-runs over rows users have changed since. Its one
54
+ * migration copies {@link INTAKE_SOURCE_BINDINGS_SCHEMA}, so it exists only alongside that collection.
55
+ */
49
56
  export declare const INTAKE_DATA_MIGRATIONS_SCHEMA: CollectionSchema;
50
57
  export interface IntakeSourceBinding {
51
58
  integrationId: string;
@@ -75,12 +82,6 @@ export declare function bindingLabelSlice(binding: Pick<IntakeSourceBinding, 'fa
75
82
  export declare function bindingTakesIssue(binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>, siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[], labels: readonly string[]): boolean;
76
83
  /** Trim and de-duplicate case-insensitively, keeping the first spelling the user typed. */
77
84
  export declare function normalizeBindingLabels(labels: readonly string[]): string[];
78
- /**
79
- * Retired: label routes sent labelled items to a board. Intake routes replaced them; the collection
80
- * stays registered so an earlier build that is rolled back to still finds it, but nothing reads or
81
- * writes it.
82
- */
83
- export declare const INTAKE_LABEL_ROUTES_SCHEMA: CollectionSchema;
84
85
  /** Labels are matched the way GitHub treats them: case-insensitively. */
85
86
  export declare function normalizeIntakeLabel(label: string): string;
86
87
  export declare class IntakeStorage extends FactoryStorageDomain {
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/intake/base.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,oBAAoB,EAAwB,MAAM,sBAAsB,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEhF,qBAAa,2BAA4B,SAAQ,KAAK;IACpD,cAGC;CACF;AAQD,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,OAAO,CAAC;IACjB,mEAAmE;IACnE,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC3B,yBAAyB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACpD;AAED,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;AAE3D,eAAO,MAAM,qBAAqB,EAAE,YAAiB,CAAC;AAEtD,eAAO,MAAM,0BAA0B,EAAE,gBAUxC,CAAC;AAEF,6HAA6H;AAC7H,eAAO,MAAM,kCAAkC,EAAE,gBAWhD,CAAC;AAEF,2IAA2I;AAC3I,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,SA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,EAAE,MAAM,CAAC;QACzB,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,GAAG,OAAO,CAAC,IAAI,CAAC,CAiBhB;IAED;;;;;;OAMG;IACG,gBAAgB,CAAC,EACrB,KAAK,EACL,aAAa,EACb,QAAQ,EACR,gBAAgB,EAChB,MAAM,EACN,MAAM,GACP,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,aAAa,EAAE,MAAM,CAAC;QACtB,QAAQ,EAAE,MAAM,CAAC;QACjB,gBAAgB,EAAE,MAAM,CAAC;QACzB,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QACxB,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,GAAG,OAAO,CAAC;QAAE,SAAS,EAAE,qBAAqB,EAAE,CAAA;KAAE,CAAC,CAclD;IAED,yFAAyF;IACnF,gBAAgB,CAAC,EACrB,KAAK,EACL,aAAa,EACb,UAAU,GACX,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,aAAa,EAAE,MAAM,CAAC;QACtB,UAAU,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KACjD,GAAG,OAAO,CAAC;QAAE,UAAU,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QAAC,SAAS,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,CAAC,CAAA;KAAE,CAAC,CAyE/G;CACF"}
@@ -1,3 +1,4 @@
1
+ import { ensureLegacyCollections } from "../../legacy-collections.js";
1
2
  import { FactoryStorageDomain, UniqueViolationError } from "@mastra/core/storage";
2
3
  // src/storage/domains/intake/base.ts
3
4
  /**
@@ -35,7 +36,10 @@ const INTAKE_ORG_SETTINGS_SCHEMA = {
35
36
  columns: ["org_id"]
36
37
  }]
37
38
  };
38
- /** Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and are folded at boot. */
39
+ /**
40
+ * Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and
41
+ * are folded at boot. Registered only on a database an earlier release already created it in.
42
+ */
39
43
  const LEGACY_INTAKE_USER_SETTINGS_SCHEMA = {
40
44
  name: "intake_settings",
41
45
  columns: {
@@ -78,8 +82,9 @@ function mergeIntakeSelections(configs) {
78
82
  *
79
83
  * Frozen: its unique index allows one binding per source, and indexes cannot be
80
84
  * narrowed, so bindings moved to {@link INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA}. Rows
81
- * are copied once at boot and never written again; the collection stays
82
- * registered so an earlier build that is rolled back to still finds them.
85
+ * are copied once at boot and never written again. Registered, with
86
+ * {@link INTAKE_DATA_MIGRATIONS_SCHEMA}, only on a database an earlier release
87
+ * already created it in, so a build rolled back to still finds the rows there.
83
88
  */
84
89
  const INTAKE_SOURCE_BINDINGS_SCHEMA = {
85
90
  name: "intake_source_bindings",
@@ -89,11 +94,6 @@ const INTAKE_SOURCE_BINDINGS_SCHEMA = {
89
94
  integration_id: { type: "text" },
90
95
  source_id: { type: "text" },
91
96
  factory_project_id: { type: "text" },
92
- /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */
93
- board: {
94
- type: "text",
95
- nullable: true
96
- },
97
97
  created_by_user_id: {
98
98
  type: "text",
99
99
  nullable: true
@@ -128,11 +128,6 @@ const INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA = {
128
128
  integration_id: { type: "text" },
129
129
  source_id: { type: "text" },
130
130
  factory_project_id: { type: "text" },
131
- /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */
132
- board: {
133
- type: "text",
134
- nullable: true
135
- },
136
131
  /** Labels whose issues this binding takes, as the user typed them; `null` takes every unclaimed issue. */
137
132
  labels: {
138
133
  type: "json",
@@ -159,7 +154,10 @@ const INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA = {
159
154
  ]
160
155
  }]
161
156
  };
162
- /** One-time data migrations that have run, so none re-runs over rows users have changed since. */
157
+ /**
158
+ * One-time data migrations that have run, so none re-runs over rows users have changed since. Its one
159
+ * migration copies {@link INTAKE_SOURCE_BINDINGS_SCHEMA}, so it exists only alongside that collection.
160
+ */
163
161
  const INTAKE_DATA_MIGRATIONS_SCHEMA = {
164
162
  name: "intake_data_migrations",
165
163
  columns: {
@@ -213,42 +211,6 @@ function normalizeBindingLabels(labels) {
213
211
  }
214
212
  return kept;
215
213
  }
216
- /**
217
- * Retired: label routes sent labelled items to a board. Intake routes replaced them; the collection
218
- * stays registered so an earlier build that is rolled back to still finds it, but nothing reads or
219
- * writes it.
220
- */
221
- const INTAKE_LABEL_ROUTES_SCHEMA = {
222
- name: "intake_label_routes",
223
- columns: {
224
- id: { type: "uuid-pk" },
225
- org_id: { type: "text" },
226
- factory_project_id: { type: "text" },
227
- integration_id: { type: "text" },
228
- /** Label as the provider reports it; matched case-insensitively. */
229
- label: { type: "text" },
230
- board: { type: "text" },
231
- created_by_user_id: {
232
- type: "text",
233
- nullable: true
234
- },
235
- created_at: { type: "timestamp" },
236
- updated_at: { type: "timestamp" }
237
- },
238
- indexes: [{
239
- name: "intake_label_routes_project_idx",
240
- columns: ["org_id", "factory_project_id"]
241
- }],
242
- uniqueIndexes: [{
243
- name: "intake_label_routes_org_project_integration_label_unique",
244
- columns: [
245
- "org_id",
246
- "factory_project_id",
247
- "integration_id",
248
- "label"
249
- ]
250
- }]
251
- };
252
214
  /** Labels are matched the way GitHub treats them: case-insensitively. */
253
215
  function normalizeIntakeLabel(label) {
254
216
  return label.trim().toLowerCase();
@@ -295,20 +257,22 @@ async function upsertBinding(ops, key, patch, userId) {
295
257
  });
296
258
  }
297
259
  var IntakeStorage = class extends FactoryStorageDomain {
260
+ /** The legacy collections this database has, so only those are read, migrated, or cleared. */
261
+ #legacy = {
262
+ userSettings: false,
263
+ bindings: false
264
+ };
298
265
  constructor() {
299
266
  super("intake");
300
267
  }
301
268
  async init() {
302
- await this.ensureCollections([
303
- INTAKE_ORG_SETTINGS_SCHEMA,
304
- LEGACY_INTAKE_USER_SETTINGS_SCHEMA,
305
- INTAKE_SOURCE_BINDINGS_SCHEMA,
306
- INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA,
307
- INTAKE_DATA_MIGRATIONS_SCHEMA,
308
- INTAKE_LABEL_ROUTES_SCHEMA
309
- ]);
310
- await this.#foldLegacyUserSelections();
311
- await this.#copyLegacyBindings();
269
+ await this.ensureCollections([INTAKE_ORG_SETTINGS_SCHEMA, INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA]);
270
+ this.#legacy = {
271
+ userSettings: await ensureLegacyCollections(this.storage, [LEGACY_INTAKE_USER_SETTINGS_SCHEMA]),
272
+ bindings: await ensureLegacyCollections(this.storage, [INTAKE_SOURCE_BINDINGS_SCHEMA, INTAKE_DATA_MIGRATIONS_SCHEMA])
273
+ };
274
+ if (this.#legacy.userSettings) await this.#foldLegacyUserSelections();
275
+ if (this.#legacy.bindings) await this.#copyLegacyBindings();
312
276
  }
313
277
  /**
314
278
  * Copy `intake_source_bindings` into `intake_source_subscriptions` as
@@ -357,11 +321,12 @@ var IntakeStorage = class extends FactoryStorageDomain {
357
321
  }
358
322
  async dangerouslyClearAll() {
359
323
  await this.ops.deleteMany("intake_org_settings", {});
360
- await this.ops.deleteMany("intake_settings", {});
361
- await this.ops.deleteMany("intake_source_bindings", {});
324
+ if (this.#legacy.userSettings) await this.ops.deleteMany("intake_settings", {});
325
+ if (this.#legacy.bindings) {
326
+ await this.ops.deleteMany("intake_source_bindings", {});
327
+ await this.ops.deleteMany("intake_data_migrations", {});
328
+ }
362
329
  await this.ops.deleteMany("intake_source_subscriptions", {});
363
- await this.ops.deleteMany("intake_data_migrations", {});
364
- await this.ops.deleteMany("intake_label_routes", {});
365
330
  }
366
331
  get #db() {
367
332
  return this.ops;
@@ -595,6 +560,6 @@ var IntakeStorage = class extends FactoryStorageDomain {
595
560
  }, { isolationLevel: "serializable" });
596
561
  }
597
562
  };
598
- export { DEFAULT_INTAKE_CONFIG, FactoryProjectNotFoundError, INTAKE_DATA_MIGRATIONS_SCHEMA, INTAKE_LABEL_ROUTES_SCHEMA, INTAKE_ORG_SETTINGS_SCHEMA, INTAKE_SOURCE_BINDINGS_SCHEMA, INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA, IntakeStorage, LEGACY_INTAKE_USER_SETTINGS_SCHEMA, bindingLabelSlice, bindingTakesIssue, mergeIntakeSelections, normalizeBindingLabels, normalizeIntakeLabel };
563
+ export { DEFAULT_INTAKE_CONFIG, FactoryProjectNotFoundError, INTAKE_DATA_MIGRATIONS_SCHEMA, INTAKE_ORG_SETTINGS_SCHEMA, INTAKE_SOURCE_BINDINGS_SCHEMA, INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA, IntakeStorage, LEGACY_INTAKE_USER_SETTINGS_SCHEMA, bindingLabelSlice, bindingTakesIssue, mergeIntakeSelections, normalizeBindingLabels, normalizeIntakeLabel };
599
564
 
600
565
  //# sourceMappingURL=base.js.map