@mastra/factory 0.30.0-alpha.4 → 0.31.0-alpha.0
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.
- package/README.md +32 -10
- package/dist/factory.d.ts +12 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +72 -31
- package/dist/factory.js.map +1 -1
- package/dist/integrations/gitlab/api.d.ts +3 -2
- package/dist/integrations/gitlab/api.d.ts.map +1 -1
- package/dist/integrations/gitlab/api.js +12 -9
- package/dist/integrations/gitlab/api.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.d.ts +5 -0
- package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/issue-reconcile-worker.js +17 -1
- package/dist/integrations/issue-reconcile-worker.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts +22 -13
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +63 -64
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/foundation/connect-binding.d.ts +125 -0
- package/dist/integrations/platform/foundation/connect-binding.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-binding.js +252 -0
- package/dist/integrations/platform/foundation/connect-binding.js.map +1 -0
- package/dist/integrations/platform/foundation/connect-event-poller.d.ts +49 -0
- package/dist/integrations/platform/foundation/connect-event-poller.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-event-poller.js +304 -0
- package/dist/integrations/platform/foundation/connect-event-poller.js.map +1 -0
- package/dist/integrations/platform/foundation/connect-events.d.ts +31 -0
- package/dist/integrations/platform/foundation/connect-events.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-events.js +7 -0
- package/dist/integrations/platform/foundation/connect-events.js.map +1 -0
- package/dist/integrations/platform/foundation/index.d.ts +10 -0
- package/dist/integrations/platform/foundation/index.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/index.js +6 -0
- package/dist/integrations/platform/foundation/intake.d.ts +39 -0
- package/dist/integrations/platform/foundation/intake.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/intake.js +45 -0
- package/dist/integrations/platform/foundation/intake.js.map +1 -0
- package/dist/integrations/platform/foundation/integration.d.ts +84 -0
- package/dist/integrations/platform/foundation/integration.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/integration.js +107 -0
- package/dist/integrations/platform/foundation/integration.js.map +1 -0
- package/dist/integrations/platform/github/event-worker.d.ts +2 -2
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +4 -8
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +3 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +131 -70
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/gitlab/connect-events.d.ts +22 -0
- package/dist/integrations/platform/gitlab/connect-events.d.ts.map +1 -0
- package/dist/integrations/platform/gitlab/connect-events.js +49 -0
- package/dist/integrations/platform/gitlab/connect-events.js.map +1 -0
- package/dist/integrations/platform/gitlab/integration.d.ts +24 -15
- package/dist/integrations/platform/gitlab/integration.d.ts.map +1 -1
- package/dist/integrations/platform/gitlab/integration.js +61 -26
- package/dist/integrations/platform/gitlab/integration.js.map +1 -1
- package/dist/integrations/platform/incidentio/intake.d.ts +33 -0
- package/dist/integrations/platform/incidentio/intake.d.ts.map +1 -0
- package/dist/integrations/platform/incidentio/intake.js +271 -0
- package/dist/integrations/platform/incidentio/intake.js.map +1 -0
- package/dist/integrations/platform/incidentio/integration.d.ts +11 -23
- package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/platform/incidentio/integration.js +27 -297
- package/dist/integrations/platform/incidentio/integration.js.map +1 -1
- package/dist/integrations/platform/jira/intake.d.ts +60 -0
- package/dist/integrations/platform/jira/intake.d.ts.map +1 -0
- package/dist/integrations/platform/jira/intake.js +445 -0
- package/dist/integrations/platform/jira/intake.js.map +1 -0
- package/dist/integrations/platform/jira/integration.d.ts +13 -37
- package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
- package/dist/integrations/platform/jira/integration.js +29 -468
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +5 -9
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts +3 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +9 -9
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/platform/logging.d.ts +6 -0
- package/dist/integrations/platform/logging.d.ts.map +1 -0
- package/dist/integrations/platform/logging.js +25 -0
- package/dist/integrations/platform/logging.js.map +1 -0
- package/dist/integrations/platform/platform-connect.d.ts +38 -0
- package/dist/integrations/platform/platform-connect.d.ts.map +1 -0
- package/dist/integrations/platform/platform-connect.js +109 -0
- package/dist/integrations/platform/platform-connect.js.map +1 -0
- package/dist/integrations/platform/vanta/integration.d.ts +12 -18
- package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
- package/dist/integrations/platform/vanta/integration.js +38 -38
- package/dist/integrations/platform/vanta/integration.js.map +1 -1
- package/dist/memory-embedder.d.ts +11 -0
- package/dist/memory-embedder.d.ts.map +1 -0
- package/dist/memory-embedder.js +19 -0
- package/dist/memory-embedder.js.map +1 -0
- package/dist/metrics/config.d.ts +1 -1
- package/dist/metrics/config.d.ts.map +1 -1
- package/dist/metrics/config.js +1 -0
- package/dist/metrics/config.js.map +1 -1
- package/dist/metrics/index.js +2 -2
- package/dist/metrics/index.js.map +1 -1
- package/dist/metrics/sandbox.d.ts +3 -3
- package/dist/metrics/sandbox.js +13 -13
- package/dist/metrics/sandbox.js.map +1 -1
- package/dist/metrics/session.d.ts +28 -0
- package/dist/metrics/session.d.ts.map +1 -0
- package/dist/metrics/session.js +76 -0
- package/dist/metrics/session.js.map +1 -0
- package/dist/routes/source-control-sessions.d.ts +5 -0
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +65 -7
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +5 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +1 -0
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts +29 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +156 -23
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/public-failure-reason.js +1 -1
- package/dist/rules/public-failure-reason.js.map +1 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +33 -9
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +2 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +4 -2
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/work-item-branch.d.ts +7 -1
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +9 -1
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/card-facts.d.ts.map +1 -1
- package/dist/work-items/card-facts.js +2 -2
- package/dist/work-items/card-facts.js.map +1 -1
- package/package.json +13 -13
- package/dist/integrations/platform/api-client.d.ts +0 -34
- package/dist/integrations/platform/api-client.d.ts.map +0 -1
- package/dist/integrations/platform/api-client.js +0 -186
- package/dist/integrations/platform/api-client.js.map +0 -1
- package/dist/integrations/platform/gitlab/event-worker.d.ts +0 -64
- package/dist/integrations/platform/gitlab/event-worker.d.ts.map +0 -1
- package/dist/integrations/platform/gitlab/event-worker.js +0 -304
- package/dist/integrations/platform/gitlab/event-worker.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispatcher.js","names":[],"sources":["../../src/rules/dispatcher.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController, AgentControllerEventListener, Session } from '@mastra/core/agent-controller';\nimport { classifyProviderError } from '@mastra/core/error';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { GoalObjectiveRecord } from '@mastra/core/storage';\nimport type { SubmitPlanResumeData } from '@mastra/core/tools';\n\nimport { isUpdateEvent } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport { cardRuleFacts } from '../boards/card-facts.js';\nimport {\n boardFlow,\n boardForWorkItem,\n cardBoardFlow,\n hasPullRequest,\n isPullRequestCard,\n isTerminalWorkItem,\n isOpenPullRequestSource,\n pullRequestSources,\n pullRequestTrustKey,\n resolvePhaseSemantics,\n REVIEW_CONTEXT,\n reviewsPullRequest,\n trustedPullRequestSource,\n UNTRUSTED_PULL_REQUESTS_KEY,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport {\n arrivalRuleFacts,\n closedIssueRuleFacts,\n INTAKE_ROUTE_METADATA_KEY,\n placedByIntakeRoute,\n planEventMove,\n resolveIntake,\n resumeLandingPhase,\n projectIntakeEvaluator,\n ROUTE_AGAIN_KEY_PREFIX,\n untrustedPullRequestEvent,\n} from '../boards/intake-routing.js';\nimport type { IntakeRoutesReader, SkippedEventRoute } from '../boards/intake-routing.js';\nimport { autoApprovedExitTool, startsInAutoPhase } from '../boards/phase-automation.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { moveCardToBoard } from '../boards/relocate.js';\nimport {\n FACTORY_OPEN_RUN_STALE_MS,\n heartbeatSessionOpenRun,\n isOpenRunLiveElsewhere,\n listSessionOpenRuns,\n listThreadOpenRuns,\n recordSessionRunStart,\n waitForSessionRunAudit,\n} from '../session/run-audit.js';\nimport { sessionHoldsWork } from '../session/session-unloader.js';\nimport { resolvePromptInvocation, resolveSkillInvocation, resolveSkillResumeInvocation } from '../skills/service.js';\nimport type { SkillSession } from '../skills/service.js';\nimport { isHumanActorId } from '../storage/domains/audit/actors.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { IntakeEvaluator } from '../storage/domains/boards/base.js';\nimport {\n externalSourceKey,\n FACTORY_RULE_MATERIALIZATION_KEY,\n FactoryRunBindingSupersededError,\n WorkItemSourceConflictError,\n WorkItemUpdateConflictError,\n} from '../storage/domains/work-items/base.js';\nimport type {\n FactoryDecisionProvenance,\n FactoryDeferredDecisionRecord,\n FactoryDispatchFailureCode,\n FactoryPendingStartRecord,\n FactoryRunBindingRecord,\n Card,\n WorkItemsStorage,\n UpsertWorkItemResult,\n} from '../storage/domains/work-items/base.js';\nimport type { FactoryRunEndReporter } from '../tools/reports.js';\nimport { withWorkItemDescription } from '../work-items/description-context.js';\nimport { workItemProviderAdapter } from '../work-items/providers/index.js';\nimport { decisionOvertaken } from './decision-applicability.js';\nimport {\n FactoryDispatchError,\n factoryDispatchFailureCode,\n factoryDispatchFailureMetadata,\n FactoryRuleRejectedError,\n} from './dispatch-errors.js';\nimport { isStatusEventDecision } from './event-rules.js';\nimport { endPhaseGoal, PHASE_GOAL_METADATA_KEY, phaseGoalOf, startPhaseGoal } from './phase-goal.js';\nimport { causeOf, isProviderCallError, publicFailureReason } from './public-failure-reason.js';\nimport { isRunBearingDecision } from './run-bearing.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport type { FactoryCommitDecision, FactoryRuleActor, FactoryRuleCausalEntry } from './types.js';\nimport { authorTrusted, externalSourceForWorkItem, workItemSource } from './types.js';\nimport { eventRouteIngress, foldUpdate, updateGroup } from './update-fold.js';\nimport {\n assertFactoryDecisionTarget,\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n validateFactoryRuleDecision,\n} from './validation.js';\n\nconst LEASE_MS = 30_000;\n/** How long the run waits on a status-comment write; well inside one lease so a slow provider never costs the claim. */\nconst REVIEW_STATUS_TIMEOUT_MS = 10_000;\n// Cadence while dispatches are in flight or a cycle filled its batch. An idle\n// dispatcher does not poll: it sleeps until the next row becomes claimable or\n// a write wakes it.\nconst POLL_MS = 1_000;\n// Safety net for an idle dispatcher: a wake lost in transit (a pubsub outage, a\n// write from a process that does not publish) is picked up within this window.\n// Well above Neon's 5-minute autosuspend so an idle database still sleeps.\nconst IDLE_RECHECK_MS = 60 * 60_000;\nconst BATCH_SIZE = 10;\nconst MAX_ATTEMPTS = 5;\n\n// Enough for a run that re-plans after reading its own approval, few enough\n// that an agent looping on submit_plan reaches a person instead of a bill.\nconst MAX_PLAN_APPROVALS = 3;\nconst MAX_ERROR_LENGTH = 512;\nconst MAX_BACKOFF_MS = 60_000;\n// A run the registry no longer shows never started or ended unobserved:\n// checked at this cadence, and failed for retry.\nconst RUN_REGISTRY_HEARTBEAT_MS = 10 * 60_000;\n// A run the registry still shows past this is a hang, not a slow run: failed\n// terminally so the lease and the in-flight slot come back.\nconst SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS = 6 * 60 * 60_000;\n// Dispatches can legitimately run for minutes. Woken skill invocations hold\n// capacity until their agent run reaches a terminal state; binding preparation\n// also runs detached from the poll loop under this concurrency cap.\nconst MAX_IN_FLIGHT = 10;\nconst isBookkeepingDecision = (decision: Record<string, unknown>): boolean => !isRunBearingDecision(decision);\n/**\n * A wake a person is waiting on: a reply a person sent on the card's pull\n * request or issue, which GitHub typed as a `User` (not an app or bot) with\n * write access, that Factory did not write itself, and that came straight from\n * the webhook rather than from a move or decision it caused. Everything else,\n * including actors with no record of being a person, stays automated.\n */\nexport const isInteractiveDecision = (\n decision: Record<string, unknown>,\n { actor, causalChain }: FactoryDecisionProvenance,\n): boolean =>\n (decision.type === 'sendMessage' || decision.type === 'signalActivity') &&\n decision.idleBehavior !== 'persist' &&\n causalChain.length === 0 &&\n actor?.type === 'github' &&\n actor.human === true &&\n actor.trusted === true &&\n actor.factoryAuthored === false;\nconst isAutomatedRunDecision = (decision: Record<string, unknown>, provenance: FactoryDecisionProvenance): boolean =>\n isRunBearingDecision(decision) && !isInteractiveDecision(decision, provenance);\nconst MAX_INTERACTIVE_IN_FLIGHT = 2;\nconst BOOKKEEPING_MAX_IN_FLIGHT = 4;\n// Staleness sweep: legacy/leaked active bindings (item deleted, transition\n// path bypassed, or pre-dating terminal-stage revocation) are revoked on a\n// slow cadence so the per-tick reconcile walk stays bounded.\nconst STALE_BINDING_SWEEP_INTERVAL_MS = 10 * 60_000;\nconst STALE_BINDING_TTL_MS = 24 * 60 * 60_000;\n// The bound-thread reconcile walk reads a cursor + messages per binding; it\n// exists to catch results missed at run end, so it runs on a slow cadence off\n// the claim path rather than on every 1s tick.\nconst RECONCILE_INTERVAL_MS = 30_000;\n\n/** The card moved on before this run could act; it settles as superseded, not succeeded. */\nclass FactoryDecisionSuperseded extends Error {}\n\n/**\n * A client stopped the run on purpose (Stop, Esc, /stop). Like a card that moved on, nothing is\n * left for the decision to do: it settles as superseded, neither failed nor retried.\n */\nclass FactoryRunStopped extends FactoryDecisionSuperseded {}\n\n/** The decision cannot act yet and did nothing: it goes back to the queue and is claimed again later. */\nclass FactoryDecisionPostponed extends Error {\n constructor(readonly availableAt?: Date) {\n super();\n }\n}\n\n/**\n * How long an update waits for more updates to the same card before its routes run: a burst of\n * label or assignee changes within this window becomes one event.\n */\nexport const UPDATE_BURST_MS = 5_000;\n\n// How often a decision that cannot act yet (a route move waiting on the card's run) is tried again.\nconst POSTPONE_MS = 10_000;\n\n/** A run that ran and ended in error; the session's own listener reports it to followers. */\nclass RunEndedInError extends FactoryDispatchError {}\n\n// The Mastra Code credential resolver's own failure; free text that merely mentions credentials does not count.\nconst CREDENTIAL_RESOLUTION_FAILURE = 'tenant model credential policy could not be resolved';\n// The resolver's reason when the request context has no user; it recurs on every retry of the same start.\nconst NO_AUTHENTICATED_USER = 'the request has no authenticated user';\n\nfunction httpStatus(error: unknown): number | undefined {\n if (!error || typeof error !== 'object') return undefined;\n if ('statusCode' in error && typeof error.statusCode === 'number') return error.statusCode;\n return 'status' in error && typeof error.status === 'number' ? error.status : undefined;\n}\n\nfunction runErrorCode(error: unknown, message: string): FactoryDispatchFailureCode {\n const lower = message.toLowerCase();\n if (lower.includes(CREDENTIAL_RESOLUTION_FAILURE)) {\n return lower.includes(NO_AUTHENTICATED_USER) ? 'run_user_unauthenticated' : 'run_credentials_unavailable';\n }\n const status = httpStatus(error) ?? httpStatus(causeOf(error));\n if (status === 401 || status === 403) return 'run_credentials_unavailable';\n const providerCall = isProviderCallError(error) || isProviderCallError(causeOf(error));\n return providerCall && classifyProviderError(error) === 'auth' ? 'run_credentials_unavailable' : 'run_failed';\n}\n\nfunction runErrorFailure(label: string, error: unknown): RunEndedInError {\n const cause = (error instanceof Error ? error.message : String(error ?? '')).trim();\n if (!cause) return new RunEndedInError('run_failed', `${label} ended in error.`, { cause: error });\n return new RunEndedInError(runErrorCode(error, cause), `${label} ended in error: ${cause}`, { cause: error });\n}\n\n/** A run in the review seat: a pull request review, unless it is the card's board's self-review. */\nfunction reviewSeatSkill(decision: unknown): { skillName?: unknown } | undefined {\n if (!decision || typeof decision !== 'object') return undefined;\n const value = decision as { type?: unknown; role?: unknown; skillName?: unknown };\n return value.type === 'invokeSkill' && value.role === REVIEW_CONTEXT ? value : undefined;\n}\n\n// Rescheduling a failure that can never succeed only delays the moment a person sees why.\nfunction isTerminalFailure(attempts: number, failureCode: FactoryDispatchFailureCode): boolean {\n const failure = factoryDispatchFailureMetadata(failureCode);\n return (\n attempts >= (failureCode === 'run_incomplete' ? 2 : MAX_ATTEMPTS) ||\n !failure.canRetry ||\n failure.autoRetry === false\n );\n}\n\n/**\n * Conservative check for observational-memory failures that a retry cannot fix:\n * a provider rejecting the request outright (HTTP 400 / model unsupported /\n * authentication). Anything ambiguous (timeouts, 5xx, rate limits, network\n * blips) is intentionally left retryable to avoid dead-ending a card that would\n * have recovered on its own.\n */\nfunction isPermanentProviderRejection(error: string): boolean {\n const normalized = error.toLowerCase();\n return (\n /\\bhttp(?:\\/\\d(?:\\.\\d)?)?\\s*400\\b/.test(normalized) ||\n /\\bstatus(?:\\s*code)?\\s*[:=]?\\s*400\\b/.test(normalized) ||\n /\\b400\\s*(?:bad request|status)\\b/.test(normalized) ||\n normalized.includes('model not supported') ||\n normalized.includes('model is not supported') ||\n normalized.includes('unsupported model') ||\n normalized.includes('not supported with') ||\n normalized.includes('unauthorized') ||\n normalized.includes('authentication') ||\n (normalized.includes('invalid') && normalized.includes('model'))\n );\n}\n\nfunction watchRun(\n session: Pick<DispatcherSession, 'subscribe' | 'respondToToolSuspension'>,\n {\n timeoutMs,\n autoApprovedTool,\n autoApproving,\n requestContext,\n onAgentEnd,\n label,\n runStillActive,\n stopRequested,\n }: {\n timeoutMs: number;\n /** The tool this run answers itself when it pauses on it; any other pause waits for a person. */\n autoApprovedTool?: string;\n /** Where the run says which paused calls it is about to answer. */\n autoApproving?: Set<string>;\n /** The run's own request context; resuming an approved plan resolves the session's workspace with it. */\n requestContext?: RequestContext;\n onAgentEnd?: () => Promise<boolean>;\n label: string;\n /** Level-triggered check against the run registry, consulted at every heartbeat the edge-triggered wait misses. */\n runStillActive: () => boolean;\n stopRequested?: () => Promise<boolean>;\n },\n) {\n let resolveAgentEnd!: () => void;\n let agentEnd!: Promise<void>;\n let endReason: 'complete' | 'aborted' | 'error' | 'suspended' | undefined;\n let supersededAtEnd: Promise<boolean> | undefined;\n let parked: { toolName: string; toolCallId: string } | undefined;\n let approvals = 0;\n const announced = new Set<string>();\n // Latest observational-memory failure seen on this run. The stream aborts the\n // run when observation/reflection fails, but the abort itself carries no\n // reason — so without this the true cause (e.g. a provider rejecting the OM\n // model) is lost and the abort is retried blindly.\n let omFailure: string | undefined;\n // The run's own error event precedes its `agent_end: 'error'` and is the only place the cause appears.\n let runError: unknown;\n // Re-armed before a redelivery so the second send waits on its own run's\n // ending rather than seeing the one that already resolved.\n const arm = () => {\n endReason = undefined;\n supersededAtEnd = undefined;\n omFailure = undefined;\n runError = undefined;\n agentEnd = new Promise<void>(resolve => {\n resolveAgentEnd = resolve;\n });\n };\n arm();\n const unsubscribe = session.subscribe(event => {\n if (event.type === 'agent_end') {\n endReason = event.reason;\n supersededAtEnd = onAgentEnd?.();\n resolveAgentEnd();\n return;\n }\n if (event.type === 'error') {\n runError = event.error;\n return;\n }\n if (event.type === 'om_observation_failed' || event.type === 'om_buffering_failed') {\n if (event.error) omFailure = event.error;\n return;\n }\n if (event.type === 'tool_suspended') {\n parked = { toolName: event.toolName, toolCallId: event.toolCallId };\n // Said before the run ends on it, so nobody is asked to answer what this run answers itself.\n if (event.toolName === autoApprovedTool && approvals < MAX_PLAN_APPROVALS) {\n announced.add(event.toolCallId);\n autoApproving?.add(event.toolCallId);\n }\n return;\n }\n if (event.type === 'tool_suspension_cancelled' && parked?.toolCallId === event.toolCallId) {\n parked = undefined;\n }\n });\n // Failing a run the registry still shows would kick off a duplicate into a busy session.\n const wait = async () => {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const heartbeatMs = Math.min(RUN_REGISTRY_HEARTBEAT_MS, deadline - Date.now());\n if (await waitForAgentEndOrTimeout(agentEnd, heartbeatMs)) return true;\n if (!runStillActive()) return false;\n }\n throw new FactoryDispatchError(\n 'run_overdue',\n `${label} is still in flight after ${Math.round(timeoutMs / 3_600_000)} hours and needs a person.`,\n );\n };\n\n return {\n arm,\n wait,\n supersededAtEnd: () => supersededAtEnd,\n endReason: () => endReason,\n /** The tool the run is parked on, when it ended suspended. */\n parked: () => parked,\n close: () => {\n // A watch that gives up answers nothing more, so its pauses wait for a person again.\n for (const toolCallId of announced) autoApproving?.delete(toolCallId);\n unsubscribe();\n },\n /** The run's own verdict, thrown as what the dispatcher should record. */\n async settle(): Promise<void> {\n let observed = await wait();\n // Past the cap the plan stays parked: the person it waits for sees it in the inbox.\n while (autoApprovedTool && parked?.toolName === autoApprovedTool && approvals < MAX_PLAN_APPROVALS) {\n const { toolCallId } = parked;\n parked = undefined;\n // Counted before the resumed run can pause again, so its next pause is judged against the cap.\n approvals += 1;\n arm();\n try {\n await session.respondToToolSuspension({ resumeData: { action: 'approved' }, toolCallId, requestContext });\n } finally {\n autoApproving?.delete(toolCallId);\n }\n observed = await wait();\n }\n if (!observed) {\n // A completed decision with no observed run end is exactly the\n // silent-stall failure mode: the card advances while nobody works it.\n // Delivery already began, so retrying with a fresh generation could\n // duplicate work whose terminal event was lost.\n throw new FactoryDispatchError(\n 'run_terminal_event_missing',\n `${label} terminal event was not observed before timeout.`,\n );\n }\n if (endReason === 'error') throw runErrorFailure(label, runError);\n if (endReason === 'aborted') {\n if (await stopRequested?.()) throw new FactoryRunStopped();\n // An abort that follows an observational-memory failure is not the\n // usual \"process went away\" case — the OM stream deliberately aborted\n // the run because observation/reflection failed. Surface that real\n // cause instead of the generic message, and when it is a permanent\n // provider/config rejection (e.g. the OM model is not accepted by the\n // account) fail terminally so retries stop hammering a run that can\n // never succeed until the configuration changes.\n if (omFailure) {\n if (isPermanentProviderRejection(omFailure)) {\n throw new FactoryDispatchError(\n 'run_configuration_invalid',\n `${label} was aborted by an observational-memory failure that will not succeed on retry: ${omFailure}`,\n );\n }\n throw new Error(`${label} was aborted after an observational-memory failure: ${omFailure}`);\n }\n // Nobody marked this run stopped, so the abort is the process going\n // away underneath it — an operator restarting the server. Treating\n // that as terminal dead-ends the card at attempt 1 with nothing on the\n // board to press. A spurious retry is bounded by MAX_ATTEMPTS.\n throw new Error(`${label} was aborted before it finished.`);\n }\n },\n };\n}\n\nfunction waitForAgentEndOrTimeout(agentEnd: Promise<void>, timeoutMs: number): Promise<boolean> {\n return new Promise(resolve => {\n const timeout = setTimeout(() => resolve(false), timeoutMs);\n timeout.unref?.();\n void agentEnd.then(() => {\n clearTimeout(timeout);\n resolve(true);\n });\n });\n}\n\ninterface SessionOwner {\n userId: string;\n orgId: string;\n}\n\ninterface FactoryNotificationResult {\n persisted?: Promise<unknown>;\n accepted?: Promise<{\n action?: string;\n output?: { consumeStream(): Promise<unknown> };\n }>;\n}\n\ninterface DispatcherSession extends SkillSession {\n thread: {\n switch(input: { threadId: string }): Promise<unknown>;\n listActiveMessages(): Promise<Array<{ id: string }>>;\n };\n stream: { isActive(): boolean };\n abort(): void;\n sendSignal(\n input: {\n id: string;\n type: 'user' | 'reactive';\n tagName: string;\n attributes?: { name: string };\n contents: string;\n },\n options: { requestContext: RequestContext; requireDelivery?: boolean },\n ): { accepted: Promise<{ accepted: true; runId?: string; action?: string }> };\n subscribe(listener: AgentControllerEventListener): () => void;\n respondToToolSuspension(input: {\n resumeData: SubmitPlanResumeData;\n toolCallId?: string;\n requestContext?: RequestContext;\n }): Promise<void>;\n}\n\ntype FactoryController = Pick<AgentController<MastraCodeState>, 'getSession' | 'listActiveThreadRuns'>;\ntype BoundDispatcherSession = Session<MastraCodeState>;\n\nfunction factoryRequestContext(input: {\n session: BoundDispatcherSession;\n binding: FactoryRunBindingRecord;\n userId: string;\n orgId: string;\n}): RequestContext {\n const { session, binding, userId, orgId } = input;\n const requestContext = new RequestContext();\n requestContext.set('user', { workosId: userId, organizationId: orgId });\n requestContext.set('controller', {\n state: session.state.get(),\n getState: () => session.state.get(),\n sessionId: binding.sessionId,\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modelId: session.model.get() ?? '',\n },\n workspace: session.getWorkspace(),\n });\n return requestContext;\n}\n\nexport interface FactoryBindingPreparationInput {\n record: FactoryDeferredDecisionRecord;\n item: Card;\n role: string;\n expectedBindingId?: string;\n}\n\nexport type FactoryReviewStatusPhase = 'queued' | 'reviewing' | 'retrying' | 'completed' | 'failed' | 'cancelled';\n\n/** One step of a review run, identified by the decision that started it. */\nexport interface FactoryReviewStatusEvent {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n run: string;\n requestedAt: Date;\n generation: number;\n attempt: number;\n phase: FactoryReviewStatusPhase;\n /** When the agent was handed the review; set on the 'reviewing' step. */\n startedAt?: Date;\n /** When the run ended; set on final steps. */\n endedAt?: Date;\n /** Why the run failed or will retry, already sanitized. */\n reason?: string;\n /** A final step for a run an earlier attempt started: the comment's recorded start still applies. */\n replayed?: true;\n}\n\nexport type FactoryReviewStatusReporter = (event: FactoryReviewStatusEvent) => Promise<void>;\n\nexport interface FactoryDecisionDispatcherOptions {\n audit?: AuditRecorder;\n controller: FactoryController;\n transitionService: Pick<FactoryTransitionService, 'transition' | 'configVersion'>;\n storage: WorkItemsStorage;\n /** Installed boards; defaults to the built-in Work and Review boards. */\n boards?: BoardRegistry | ProjectBoardSource;\n /** The project's intake routes, which place newly filed linked cards. Without it, decisions place cards as they say. */\n intakeRoutes?: IntakeRoutesReader;\n /** Forces an evaluator on every project; without it each project uses its own setting. */\n intakeEvaluator?: IntakeEvaluator;\n ownerId?: string;\n reconcileToolResults?: () => Promise<void>;\n reconcileRunBinding?: (binding: FactoryRunBindingRecord) => Promise<void>;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n /**\n * Told when a run fails terminally at dispatch, so whoever follows the item\n * hears about failures no run end covers. How runs end is reported by the\n * per-session listener (`observeSessionRunReports`). Never throws.\n */\n reportRunEnd?: FactoryRunEndReporter;\n /**\n * Told each step of a pull request review run: accepted, started, retrying,\n * and how it ended. Driven by the dispatcher rather than the agent, so a run\n * that crashes or is cancelled still reports its end. Must not throw.\n */\n reportReviewStatus?: FactoryReviewStatusReporter;\n /** Dismisses superseded Factory change requests on a GitHub pull request. */\n dismissStaleReviews?: (decision: Extract<FactoryCommitDecision, { type: 'dismissStaleReviews' }>) => Promise<void>;\n resolveLinkedWorkItemParentId?: (input: {\n orgId: string;\n factoryProjectId: string;\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>;\n }) => Promise<string | null>;\n /** `false` spends a linked-card decision unfiled: its Factory project was deleted after the decision committed. */\n factoryProjectExists?: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n maxInFlight?: number;\n /**\n * Run slots this process keeps for wakes a person is waiting on (see\n * `isInteractiveDecision`), on top of `maxInFlight`. Defaults to 2.\n */\n maxInteractiveInFlight?: number;\n /** How often the stale-binding sweep runs. Defaults to 10 minutes. */\n staleBindingSweepIntervalMs?: number;\n /** Active bindings older than this are revoked by the sweep. Defaults to 24 hours. */\n staleBindingTtlMs?: number;\n /** How often the bound-thread reconcile walk runs. Defaults to 30 seconds. */\n reconcileIntervalMs?: number;\n /**\n * How long a run the registry still shows in flight is observed before it fails as overdue. Defaults to 6 hours.\n * A run the registry no longer shows fails for retry at the next ten-minute heartbeat instead.\n */\n skillCompletionObservationTimeoutMs?: number;\n}\n\nfunction positiveMs(value: number | undefined, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;\n}\n\n// Provider and source-control key prefixes; run errors carry provider text verbatim.\nconst KEY_SHAPED_TOKEN =\n /\\b(?:sk-[A-Za-z0-9_-]{3,}|gh[pousr]_[A-Za-z0-9]{10,}|github_pat_[A-Za-z0-9_]{10,}|xox[abprs]-[A-Za-z0-9-]{10,})/g;\n\n// Mixed-case alphanumeric runs read as keys; lowercase hex SHAs, UUIDs, path segments and\n// hyphenated names such as branches stay readable.\nfunction looksLikeSecret(token: string): boolean {\n return /[A-Z]/.test(token) && /[a-z]/.test(token) && /\\d/.test(token) && /[A-Za-z0-9]{16,}/.test(token);\n}\n\n// Base64 keys can contain `/`. A `/`-joined token is redacted whole unless one of its pieces is a\n// plain word, which paths and branches nearly always have (`fix`, `cache`, `Users`, `Documents`);\n// those are redacted piece by piece instead.\nfunction redactSecretRun(token: string): string {\n if (looksLikeSecret(token) && !token.split('/').some(piece => /^[A-Za-z][a-z]+$/.test(piece))) return '[redacted]';\n return token.replace(/[A-Za-z0-9_+=-]{24,}/g, piece =>\n looksLikeSecret(piece) || isGroupedKey(piece) ? '[redacted]' : piece,\n );\n}\n\n// Keys printed in `-`/`_` groups (`x7Kp9-Qm2Rt-…`) have no long unbroken run, but every group mixes\n// upper, lower and digits; branch and identifier words such as `Parked-snapshot-lease2-loss` do not.\nfunction isGroupedKey(token: string): boolean {\n const groups = token.split(/[-_]/);\n return groups.length >= 4 && groups.every(group => /[A-Z]/.test(group) && /[a-z]/.test(group) && /\\d/.test(group));\n}\n\nfunction sanitizeDispatchError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return (\n message\n .replace(KEY_SHAPED_TOKEN, '[redacted]')\n .replace(/\\b[A-Za-z0-9_+=/-]{24,}/g, redactSecretRun)\n // `Authorization: Bearer <value>` names the scheme first; consume it so the value goes too.\n .replace(/\\b(?:bearer|token|api[-_ ]?key|authorization)\\s*[:=]?\\s*(?:bearer\\s+)?[^\\s,;]+/gi, '[redacted]')\n .slice(0, MAX_ERROR_LENGTH)\n );\n}\n\nfunction retryAt(now: Date, attempts: number): Date {\n return new Date(now.getTime() + Math.min(1_000 * 2 ** Math.max(0, attempts - 1), MAX_BACKOFF_MS));\n}\n\nfunction externalSourceForDecision(decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>) {\n return externalSourceForWorkItem(decision.source, decision.sourceKey, decision.url ?? undefined);\n}\n\nfunction deferredActor(record: FactoryDeferredDecisionRecord): FactoryRuleActor {\n const actor = record.actor;\n if (\n actor?.type === 'github' &&\n typeof actor.login === 'string' &&\n typeof actor.trusted === 'boolean' &&\n typeof actor.factoryAuthored === 'boolean'\n ) {\n return {\n type: 'github',\n login: actor.login,\n trusted: actor.trusted,\n factoryAuthored: actor.factoryAuthored,\n };\n }\n if (\n actor?.type === 'gitlab' &&\n typeof actor.username === 'string' &&\n typeof actor.trusted === 'boolean' &&\n typeof actor.factoryAuthored === 'boolean'\n ) {\n return {\n type: 'gitlab',\n username: actor.username,\n trusted: actor.trusted,\n factoryAuthored: actor.factoryAuthored,\n };\n }\n return { type: 'system', id: 'factory-rule-dispatcher' };\n}\n\nfunction externalActor(actor: FactoryDeferredDecisionRecord['actor']): boolean {\n return actor !== null && actor.type !== 'human' && actor.type !== 'agent' && actor.type !== 'system';\n}\n\n/** A run start asks for consent; an external event asks before pulling a card back into a working lane. */\nfunction requestsConsent(\n boards: BoardRegistry,\n record: FactoryDeferredDecisionRecord,\n decision: FactoryCommitDecision,\n): boolean {\n if (decision.type === 'invokeSkill') return true;\n if (decision.type !== 'transition' || !externalActor(record.actor)) return false;\n // Fail closed: a phase the installed board does not declare is treated as working, so consent is asked.\n return (resolvePhaseSemantics(boards, decision.board, decision.stage)?.kind ?? 'working') === 'working';\n}\n\n// The Factory reviewing code it wrote is part of the same work, not new work to\n// consent to: a push to a Factory-authored PR re-reviews without a person's click.\nfunction reviewsFactoryAuthoredCode(\n boards: BoardRegistry,\n item: Pick<Card, 'metadata' | 'externalSource' | 'workItem'>,\n decision: FactoryCommitDecision,\n): boolean {\n if (item.metadata?.factoryAuthored !== true) return false;\n if (decision.type === 'transition') {\n const flow = boardFlow(boards.get(decision.board));\n return (\n decision.stage === flow.pullRequestReview &&\n reviewsPullRequest({\n flow,\n item: { source: workItemSource(item.externalSource), workItem: item.workItem },\n })\n );\n }\n return decision.type === 'invokeSkill' && decision.role === REVIEW_CONTEXT;\n}\n\nfunction leaseIdentity(\n record: Pick<FactoryDeferredDecisionRecord | FactoryPendingStartRecord, 'id' | 'orgId' | 'factoryProjectId'>,\n ownerId: string,\n) {\n return { id: record.id, orgId: record.orgId, factoryProjectId: record.factoryProjectId, ownerId };\n}\n\nasync function awaitNotification(\n send: () => Promise<FactoryNotificationResult>,\n requireDelivery = false,\n): Promise<{ action?: string } | undefined> {\n try {\n const notification = await send();\n const [, accepted] = await Promise.all([notification.persisted, notification.accepted]);\n if (!accepted) {\n if (requireDelivery) {\n throw new FactoryDispatchError(\n 'notification_delivery_failed',\n 'Factory notification was persisted without agent delivery.',\n );\n }\n return undefined;\n }\n if (!requireDelivery) return accepted;\n if (accepted.action === 'wake') {\n if (!accepted.output) {\n throw new FactoryDispatchError('notification_delivery_failed', 'Factory notification wake had no output.');\n }\n await accepted.output.consumeStream();\n return accepted;\n }\n if (accepted.action !== 'deliver') {\n throw new FactoryDispatchError(\n 'notification_delivery_failed',\n `Factory notification did not reach the agent (${String(accepted.action)}).`,\n );\n }\n return accepted;\n } catch (error) {\n if (error instanceof FactoryDispatchError) throw error;\n throw new FactoryDispatchError(\n 'notification_delivery_failed',\n `Factory notification delivery failed: ${sanitizeDispatchError(error)}`,\n { cause: error },\n );\n }\n}\n\n/** Card metadata key: the facts each linked pull request joined the card with, by its trust key. */\nconst LINKED_PULL_REQUESTS_KEY = 'linkedPullRequests';\n\ninterface LinkFacts {\n trusted: boolean;\n phase: string | null;\n hasPullRequest: boolean;\n}\n\nfunction linkedPullRequests(metadata: Record<string, unknown> | null | undefined): Record<string, LinkFacts> {\n const links = metadata?.[LINKED_PULL_REQUESTS_KEY];\n return links && typeof links === 'object' && !Array.isArray(links) ? (links as Record<string, LinkFacts>) : {};\n}\n\n/**\n * A pull request's link to `card`, read off the card it joins. Only another trusted, open pull\n * request counts as one the card already has: an outsider's can't keep a maintainer's from Review.\n */\nfunction linkFacts(card: Card, trusted: boolean, trustKey: string): LinkFacts {\n return {\n trusted,\n phase: card.stages.length === 1 ? card.stages[0]! : null,\n hasPullRequest: pullRequestSources(card).some(\n source =>\n pullRequestTrustKey(source) !== trustKey &&\n isOpenPullRequestSource(source) &&\n trustedPullRequestSource(card, source),\n ),\n };\n}\n\nexport class FactoryDecisionDispatcher {\n readonly #audit?: AuditRecorder;\n readonly #controller: FactoryController;\n readonly #transitionService: Pick<FactoryTransitionService, 'transition' | 'configVersion'>;\n readonly #boards: ProjectBoardSource;\n readonly #intakeRoutes?: IntakeRoutesReader;\n /** Forced on every project; undefined: each project's own setting. */\n readonly #intakeEvaluator: IntakeEvaluator | undefined;\n readonly #storage: WorkItemsStorage;\n readonly #ownerId: string;\n readonly #autoApproving = new Set<string>();\n readonly #reconcileToolResults?: () => Promise<void>;\n readonly #reconcileRunBinding?: FactoryDecisionDispatcherOptions['reconcileRunBinding'];\n readonly #prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n readonly #primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n readonly #reportRunEnd?: FactoryRunEndReporter;\n readonly #dismissStaleReviews?: FactoryDecisionDispatcherOptions['dismissStaleReviews'];\n readonly #reportReviewStatus?: FactoryReviewStatusReporter;\n /** Review attempts that already said `queued`, and those that watched their run start. */\n readonly #reviewQueued = new WeakSet<FactoryDeferredDecisionRecord>();\n readonly #reviewWatched = new WeakSet<FactoryDeferredDecisionRecord>();\n /** Re-claims that found an earlier attempt's kickoff landed and its run already over. */\n readonly #reviewReplayed = new WeakSet<FactoryDeferredDecisionRecord>();\n /** Last pending status-comment write per run, so writes stay ordered. */\n /**\n * Per review run: the write chain, the newest step issued, and how many\n * writes were issued and how far the landed ones reach, so a write that\n * outlived its wait and landed after a newer one can be repaired.\n */\n readonly #reviewStatusRuns = new Map<\n string,\n { tail: Promise<void>; issued: number; landed: number; latest: FactoryReviewStatusEvent }\n >();\n readonly #resolveLinkedWorkItemParentId?: FactoryDecisionDispatcherOptions['resolveLinkedWorkItemParentId'];\n readonly #factoryProjectExists?: FactoryDecisionDispatcherOptions['factoryProjectExists'];\n readonly #maxInFlight: number;\n readonly #maxInteractiveInFlight: number;\n readonly #staleBindingSweepIntervalMs: number;\n readonly #staleBindingTtlMs: number;\n #lastStaleBindingSweepAt?: Date;\n readonly #reconcileIntervalMs: number;\n readonly #skillCompletionObservationTimeoutMs: number;\n #lastReconcileAt?: Date;\n #reconcileInFlight?: Promise<void>;\n /** A reconcile is due once activity stops, to drain results of runs that just ended. */\n #reconcileOwed = true;\n /** Last step seen on a bound session thread; counts as activity for one reconcile interval. */\n #lastBoundThreadRunAt?: number;\n #started = false;\n #stopping = false;\n #wakeRequested = false;\n #unsubscribeClaimableWork?: () => void;\n #loop?: Promise<void>;\n #timer?: ReturnType<typeof setTimeout>;\n /** Starts and run-bearing decisions; capped by `maxInFlight`. */\n readonly #runInFlight = new Set<Promise<void>>();\n /** Wakes a person is waiting on; capped by `maxInteractiveInFlight`, borrowing free run slots past it. */\n readonly #interactiveInFlight = new Set<Promise<void>>();\n /** Fast board bookkeeping (transitions, linked-card upserts); its own small cap. */\n readonly #bookkeepingInFlight = new Set<Promise<void>>();\n /** Background work awaited on stop but outside both caps. */\n readonly #backgroundInFlight = new Set<Promise<void>>();\n readonly #bindingSkillRuns = new Map<string, Promise<void>>();\n\n constructor(options: FactoryDecisionDispatcherOptions) {\n this.#audit = options.audit;\n this.#controller = options.controller;\n this.#transitionService = options.transitionService;\n this.#boards = toBoardSource(options.boards);\n this.#intakeRoutes = options.intakeRoutes;\n this.#intakeEvaluator = options.intakeEvaluator;\n this.#storage = options.storage;\n this.#ownerId = options.ownerId ?? `factory-dispatcher:${globalThis.crypto.randomUUID()}`;\n this.#reconcileToolResults = options.reconcileToolResults;\n this.#reconcileRunBinding = options.reconcileRunBinding;\n this.#prepareBinding = options.prepareBinding;\n this.#primeCredentials = options.primeCredentials;\n this.#reportRunEnd = options.reportRunEnd;\n this.#dismissStaleReviews = options.dismissStaleReviews;\n this.#reportReviewStatus = options.reportReviewStatus;\n this.#resolveLinkedWorkItemParentId = options.resolveLinkedWorkItemParentId;\n this.#factoryProjectExists = options.factoryProjectExists;\n const maxInFlight = options.maxInFlight ?? MAX_IN_FLIGHT;\n this.#maxInFlight = Number.isFinite(maxInFlight) && maxInFlight > 0 ? Math.floor(maxInFlight) : MAX_IN_FLIGHT;\n const maxInteractiveInFlight = options.maxInteractiveInFlight ?? MAX_INTERACTIVE_IN_FLIGHT;\n this.#maxInteractiveInFlight =\n Number.isFinite(maxInteractiveInFlight) && maxInteractiveInFlight >= 0\n ? Math.floor(maxInteractiveInFlight)\n : MAX_INTERACTIVE_IN_FLIGHT;\n this.#staleBindingSweepIntervalMs = positiveMs(\n options.staleBindingSweepIntervalMs,\n STALE_BINDING_SWEEP_INTERVAL_MS,\n );\n this.#staleBindingTtlMs = positiveMs(options.staleBindingTtlMs, STALE_BINDING_TTL_MS);\n this.#reconcileIntervalMs = positiveMs(options.reconcileIntervalMs, RECONCILE_INTERVAL_MS);\n this.#skillCompletionObservationTimeoutMs = positiveMs(\n options.skillCompletionObservationTimeoutMs,\n SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS,\n );\n }\n\n start(): void {\n if (this.#started) return;\n this.#started = true;\n this.#stopping = false;\n this.#unsubscribeClaimableWork = this.#storage.onClaimableWork(() => this.wake());\n this.wake();\n }\n\n async stop(): Promise<void> {\n this.#stopping = true;\n this.#unsubscribeClaimableWork?.();\n this.#unsubscribeClaimableWork = undefined;\n this.#clearTimer();\n await this.#loop;\n await Promise.allSettled([\n ...this.#runInFlight,\n ...this.#interactiveInFlight,\n ...this.#bookkeepingInFlight,\n ...this.#backgroundInFlight,\n ]);\n this.#started = false;\n this.#stopping = false;\n }\n\n /**\n * Runs a dispatch cycle now. Called after any write that leaves claimable\n * work, locally or from another replica via pubsub. A wake during a running\n * cycle makes the loop run once more instead of starting a second loop.\n */\n wake(): void {\n if (!this.#started || this.#stopping) return;\n this.#wakeRequested = true;\n if (this.#loop) return;\n this.#clearTimer();\n this.#loop = this.#runLoop();\n }\n\n /**\n * A run is stepping on a bound session thread. Interactive runs queue no\n * work, so without this an idle loop would never see them and the trailing\n * reconcile for results they leave behind would not happen. Each step keeps\n * the loop active for one reconcile interval; only the first step after a\n * settled pass wakes it, since an owed pass already rechecks every interval.\n */\n noteBoundThreadRun(): void {\n if (!this.#reconcileToolResults) return;\n this.#lastBoundThreadRunAt = Date.now();\n if (this.#reconcileOwed) return;\n this.#reconcileOwed = true;\n this.wake();\n }\n\n /**\n * Run slots this process holds now, out of its caps. Per process: other\n * replicas keep their own. `inUse` counts automated slots, including any a\n * person's wake borrowed once the interactive reserve was full.\n */\n runSlots(): { inUse: number; cap: number; interactive: { inUse: number; cap: number } } {\n return {\n inUse: this.#runInFlight.size,\n cap: this.#maxInFlight,\n interactive: { inUse: this.#interactiveInFlight.size, cap: this.#maxInteractiveInFlight },\n };\n }\n\n async runOnce(now = new Date()): Promise<void> {\n void this.#maybeSweepStaleBindings(now);\n this.#maybeReconcileToolResults(now);\n const { dispatches } = await this.#claimAndStart(now);\n await Promise.all(dispatches);\n }\n\n #clearTimer(): void {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n }\n\n async #runLoop(): Promise<void> {\n let delay = POLL_MS;\n do {\n this.#wakeRequested = false;\n try {\n delay = await this.#cycle();\n } catch (error) {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n delay = POLL_MS;\n }\n } while (this.#wakeRequested && !this.#stopping);\n // No await between the loop exit and clearing #loop, so a wake() can\n // never land in between and be lost.\n this.#loop = undefined;\n if (this.#stopping) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n this.wake();\n }, delay);\n this.#timer.unref?.();\n }\n\n /** One loop cycle; returns the delay until the next one. */\n async #cycle(): Promise<number> {\n const now = new Date();\n // Fire-and-forget like the reconcile walk: the sweep reads every active\n // binding, so awaiting it would stretch the cycle as the active set grows.\n void this.#maybeSweepStaleBindings(now);\n // Tool results only come from runs, so the reconcile walk follows local\n // activity, plus one trailing pass after it stops.\n const active =\n this.#runInFlight.size > 0 ||\n this.#interactiveInFlight.size > 0 ||\n this.#bookkeepingInFlight.size > 0 ||\n this.#controller.listActiveThreadRuns().length > 0 ||\n (this.#lastBoundThreadRunAt !== undefined &&\n now.getTime() - this.#lastBoundThreadRunAt < this.#reconcileIntervalMs);\n if (!this.#reconcileToolResults) this.#reconcileOwed = false;\n else if (active) this.#reconcileOwed = true;\n if (this.#reconcileOwed && this.#maybeReconcileToolResults(now) && !active) this.#reconcileOwed = false;\n\n let full: boolean;\n try {\n const claimed = await this.#claimAndStart(now);\n full = claimed.full;\n for (const dispatch of claimed.dispatches) {\n dispatch.catch(error => {\n console.error('Factory decision dispatch failed', sanitizeDispatchError(error));\n });\n }\n } catch (error) {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n return POLL_MS;\n }\n if (\n full ||\n this.#runInFlight.size > 0 ||\n this.#interactiveInFlight.size > 0 ||\n this.#bookkeepingInFlight.size > 0\n ) {\n return POLL_MS;\n }\n\n const dueTimes: number[] = [];\n if (this.#reconcileOwed) {\n dueTimes.push((this.#lastReconcileAt?.getTime() ?? 0) + this.#reconcileIntervalMs);\n }\n try {\n // Covers future retries and leases left behind by a crashed replica.\n const nextClaimableAt = await this.#storage.nextClaimableAt();\n if (nextClaimableAt) dueTimes.push(nextClaimableAt.getTime());\n } catch (error) {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n return POLL_MS;\n }\n return Math.max(POLL_MS, Math.min(Math.min(...dueTimes, Infinity) - Date.now(), IDLE_RECHECK_MS));\n }\n\n /**\n * Claims a batch and starts dispatches without awaiting their completion.\n * Dispatches can legitimately take minutes (skill kickoffs consume the\n * agent's run stream; binding preparation provisions sandboxes), so awaiting\n * them here would freeze the poll loop and starve every other queued\n * decision. In-flight records stay protected from re-claim by lease renewal.\n */\n async #claimAndStart(now: Date): Promise<{ dispatches: Array<Promise<void>>; full: boolean }> {\n let full = false;\n const leaseExpiresAt = new Date(now.getTime() + LEASE_MS);\n const dispatches: Array<Promise<void>> = [];\n // Run slots are held for whole agent runs (minutes), so bookkeeping that\n // only mirrors the board is claimed from its own pool and never waits\n // behind them.\n const startCapacity = this.#maxInFlight - this.#runInFlight.size;\n if (startCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, startCapacity);\n // Starts are claimed before deferred decisions: a pending start is a user\n // waiting on a brand-new session, while a deferred decision is a background\n // continuation of one that is already running. A deep decision queue must\n // never starve new sessions out of the tick.\n const starts = await this.#storage.claimPendingStarts({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit,\n });\n full ||= starts.length >= limit;\n dispatches.push(...starts.map(start => this.#track(this.#runInFlight, this.#dispatchPendingStart(start, now))));\n }\n // A person's wake comes next, into its own reserve and then into any free\n // run slot, so it never waits behind hours of automated runs. Each claimed\n // wake is tracked in the pool whose slot it took.\n const reserveCapacity = Math.max(0, this.#maxInteractiveInFlight - this.#interactiveInFlight.size);\n const interactiveCapacity = reserveCapacity + Math.max(0, this.#maxInFlight - this.#runInFlight.size);\n if (interactiveCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, interactiveCapacity);\n const decisions = await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit,\n decisionFilter: isInteractiveDecision,\n });\n full ||= decisions.length >= limit;\n dispatches.push(\n ...decisions.map((decision, index) =>\n this.#track(\n index < reserveCapacity ? this.#interactiveInFlight : this.#runInFlight,\n this.#dispatchDecision(decision, now),\n ),\n ),\n );\n }\n const runCapacity = this.#maxInFlight - this.#runInFlight.size;\n if (runCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, runCapacity);\n const decisions = await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit,\n decisionFilter: isAutomatedRunDecision,\n });\n full ||= decisions.length >= limit;\n dispatches.push(\n ...decisions.map(decision => this.#track(this.#runInFlight, this.#dispatchDecision(decision, now))),\n );\n }\n const bookkeepingCapacity = BOOKKEEPING_MAX_IN_FLIGHT - this.#bookkeepingInFlight.size;\n if (bookkeepingCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, bookkeepingCapacity);\n const decisions = await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit,\n decisionFilter: isBookkeepingDecision,\n });\n full ||= decisions.length >= limit;\n dispatches.push(\n ...decisions.map(decision => this.#track(this.#bookkeepingInFlight, this.#dispatchDecision(decision, now))),\n );\n }\n return { dispatches, full };\n }\n\n /**\n * Throttled, coalesced, non-blocking bound-thread reconcile: dispatch\n * claiming never waits behind cursor + message reads, and overlapping runs\n * are skipped while one is still in flight.\n */\n #maybeReconcileToolResults(now: Date): boolean {\n if (!this.#reconcileToolResults || this.#reconcileInFlight) return false;\n if (this.#lastReconcileAt && now.getTime() - this.#lastReconcileAt.getTime() < this.#reconcileIntervalMs) {\n return false;\n }\n this.#lastReconcileAt = now;\n const run = this.#reconcileToolResults()\n .catch(error => {\n console.error('Factory tool-result reconcile failed', sanitizeDispatchError(error));\n })\n .finally(() => {\n this.#reconcileInFlight = undefined;\n });\n this.#reconcileInFlight = run;\n this.#track(this.#backgroundInFlight, run);\n return true;\n }\n\n /** Slow-cadence revocation of leaked/legacy bindings; failures never block the claim path. */\n async #maybeSweepStaleBindings(now: Date): Promise<void> {\n // The first tick only anchors the cadence: sweeping at boot would race the\n // startup reconcile that is still draining trailing tool results.\n if (!this.#lastStaleBindingSweepAt) {\n this.#lastStaleBindingSweepAt = now;\n return;\n }\n if (now.getTime() - this.#lastStaleBindingSweepAt.getTime() < this.#staleBindingSweepIntervalMs) return;\n this.#lastStaleBindingSweepAt = now;\n try {\n const revoked = await this.#storage.revokeStaleRunBindings({\n olderThan: new Date(now.getTime() - this.#staleBindingTtlMs),\n now,\n // A run parked on a person, or resumed after one answered, is alive however\n // old its binding is. The session must still be on the binding's thread: its\n // suspension and run state belong to that thread. A failed session lookup revokes.\n keep: async binding => {\n // Age alone says nothing about a card that is still open in the phase this\n // binding works: the session is between turns, not leaked. Revoking it takes\n // the card's tools and updates away, and the card then sits until a person\n // moves it. A run starting for the card elsewhere still replaces the binding.\n try {\n if (await this.#worksOpenCard(binding)) return true;\n } catch (error) {\n // Not knowing is no reason to cut a session off: the next sweep asks again.\n console.warn(\n `Factory stale-binding sweep kept binding card=${binding.workItemId} session=${binding.sessionId}: could not read its card`,\n sanitizeDispatchError(error),\n );\n return true;\n }\n try {\n const session = await this.#controller.getSession(binding.sessionId);\n if (session?.thread.getId() !== binding.threadId) return false;\n return sessionHoldsWork(session);\n } catch {\n return false;\n }\n },\n onRevoked: binding =>\n console.info(\n `Factory stale-binding sweep revoked binding card=${binding.workItemId} session=${binding.sessionId} role=${binding.role}`,\n ),\n });\n if (revoked > 0) console.info(`Factory stale-binding sweep revoked ${revoked} binding(s)`);\n } catch (error) {\n console.error('Factory stale-binding sweep failed', sanitizeDispatchError(error));\n }\n }\n\n /** Whether the binding's card sits in a working phase that the binding's role runs. */\n async #worksOpenCard(binding: FactoryRunBindingRecord): Promise<boolean> {\n const item = await this.#storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item || item.stages.length !== 1) return false;\n const phase = (await this.#boards.load(binding)).get(boardForWorkItem(item))?.phases[item.stages[0]!];\n return phase?.kind === 'working' && phase.runner.context === binding.role;\n }\n\n #track(pool: Set<Promise<void>>, dispatch: Promise<void>): Promise<void> {\n pool.add(dispatch);\n void dispatch\n .catch(() => {})\n .then(() => {\n pool.delete(dispatch);\n // A settled dispatch frees capacity and may have queued a retry.\n if (pool !== this.#backgroundInFlight) this.wake();\n });\n return dispatch;\n }\n\n async #dispatchDecision(record: FactoryDeferredDecisionRecord, now: Date): Promise<void> {\n let executionCompleted = false;\n try {\n const decision = validateFactoryRuleDecision(record.decision, record.causalChain.length);\n if (decision.type === 'reject') throw new Error('Deferred Factory decisions cannot reject.');\n if (await this.#needsApproval(record, decision)) {\n const proposed = await this.#storage.proposeDeferredDecision(leaseIdentity(record, this.#ownerId), new Date());\n if (!proposed) throw new Error('Factory decision lease was lost before approval could be requested.');\n return;\n }\n await this.#supersedeProposals(record, decision);\n // A first claim cannot have delivered its kickoff yet, so it may say `queued` right\n // away. A re-claim may find the run already going; it says `queued` only once the\n // replay guard proves the kickoff never landed.\n if (record.attempts <= 1) await this.#reviewQueuedOnce(record, decision);\n await this.#withLease(\n async leaseExpiresAt =>\n this.#storage.renewDeferredDecisionLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),\n async () => this.#executeDecision(record, decision, now),\n );\n executionCompleted = true;\n const completed = await this.#storage.completeDeferredDecision(leaseIdentity(record, this.#ownerId), new Date());\n if (!completed) throw new Error('Factory decision lease was lost before completion.');\n // Only an attempt that saw the run end may say it finished: the one that watched\n // it, or a re-claim that found the landed run already over (its worker was lost).\n if (this.#reviewWatched.has(record) || this.#reviewReplayed.has(record)) {\n await this.#reviewStatus(record, decision, {\n phase: 'completed',\n endedAt: new Date(),\n ...(this.#reviewReplayed.has(record) ? { replayed: true } : {}),\n });\n }\n } catch (error) {\n if (error instanceof FactoryDecisionSuperseded) {\n await this.#storage.supersedeLeasedDecision(leaseIdentity(record, this.#ownerId), new Date());\n await this.#reviewStatus(record, record.decision, { phase: 'cancelled', endedAt: new Date() });\n return;\n }\n if (error instanceof FactoryDecisionPostponed) {\n await this.#storage.postponeDeferredDecision(\n leaseIdentity(record, this.#ownerId),\n error.availableAt ?? new Date(now.getTime() + POSTPONE_MS),\n new Date(),\n );\n return;\n }\n const failureCode = factoryDispatchFailureCode(error);\n const terminal = isTerminalFailure(record.attempts, failureCode);\n const failed = await this.#storage.failDeferredDecision({\n ...leaseIdentity(record, this.#ownerId),\n now: new Date(),\n availableAt: retryAt(now, record.attempts),\n lastError: sanitizeDispatchError(error),\n failureCode,\n terminal,\n advanceDeliveryGeneration: !executionCompleted,\n });\n if (terminal && failed) await this.#supersedeFailureOnSettledCard(failed);\n // A re-claim that failed before proving its kickoff never landed may be racing\n // an earlier attempt's live run; only a terminal failure may speak over it.\n if (terminal || this.#reviewQueued.has(record)) {\n await this.#reviewStatus(failed ?? record, record.decision, {\n phase: terminal ? 'failed' : 'retrying',\n endedAt: new Date(),\n reason: publicFailureReason(failureCode, error),\n });\n }\n }\n }\n\n /**\n * An earlier attempt's kickoff already landed, so this attempt only has to\n * see that run end before a review's status can be finalized. The open-run\n * wait covers runs in the ledger; a run that landed but died before\n * registering there can still be live in this process, so wait it out too.\n */\n async #replayLanded(\n record: FactoryDeferredDecisionRecord,\n decision: unknown,\n session: Pick<DispatcherSession, 'subscribe' | 'respondToToolSuspension'>,\n runStillActive: () => boolean,\n ): Promise<void> {\n if (!(await this.#isReviewRun(record, decision))) return;\n if (runStillActive()) {\n const run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n label: 'Factory skill run',\n runStillActive,\n });\n try {\n if (runStillActive()) await run.wait();\n } finally {\n run.close();\n }\n }\n this.#reviewReplayed.add(record);\n }\n\n /**\n * Holds the goal a phase's run pursues on the session's thread, and names it on the card so\n * leaving the phase ends it. Keyed on the decision: a retry finds the goal already held.\n */\n async #setPhaseGoal(\n record: FactoryDeferredDecisionRecord,\n goal: { objective: string; maxRuns?: number },\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n ): Promise<GoalObjectiveRecord> {\n // The phase this run is for, read before the goal exists (the kickoff was checked against it):\n // reading it afterwards could stamp the phase the card moved to meanwhile.\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n const phaseKey = item?.stages.length === 1 ? item.stages[0] : undefined;\n const objective = await startPhaseGoal(session.machinery.getAgent(), {\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n goalId: record.id,\n objective: goal.objective,\n maxRuns: goal.maxRuns,\n // Factory has no judge setting of its own: the session's model judges its goal.\n judgeModelId: session.model.get() || undefined,\n });\n if (!objective) {\n throw new FactoryDispatchError('run_configuration_invalid', 'The Factory session has no storage to hold a goal.');\n }\n if (!item || !phaseKey) return objective;\n const stamp = {\n phaseKey,\n boardKey: boardForWorkItem(item),\n goalId: record.id,\n threadId: binding.threadId,\n sessionId: binding.sessionId,\n };\n if (phaseGoalOf(item.metadata)?.goalId !== record.id) {\n await this.#storage.update({\n orgId: record.orgId,\n id: item.id,\n userId: 'factory',\n patch: { metadata: { [PHASE_GOAL_METADATA_KEY]: stamp } },\n });\n }\n // A move that committed before the stamp landed found no goal to end: end it here instead. A\n // same-named phase on another board is a different phase, so the board counts as a move too.\n const after = await this.#storage.get({ orgId: record.orgId, id: item.id });\n if (after?.stages.length !== 1 || after.stages[0] !== phaseKey || boardForWorkItem(after) !== stamp.boardKey) {\n await endPhaseGoal(stamp, { agentFor: async () => session.machinery.getAgent(), store: async () => undefined });\n throw new FactoryDecisionSuperseded();\n }\n return objective;\n }\n\n /**\n * Shows the goal in the thread once its run has the kickoff. A goal whose reminder never landed\n * is paused rather than left judging a run nobody was told about; the retry resumes it.\n */\n async #remindPhaseGoal(\n record: FactoryDeferredDecisionRecord,\n goal: GoalObjectiveRecord,\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n requestContext: RequestContext,\n ): Promise<void> {\n const reminderId = `${record.id}:goal`;\n if ((await session.thread.listActiveMessages()).some(message => message.id === reminderId)) return;\n const agent = session.machinery.getAgent();\n if (goal.status === 'paused') await agent.updateObjectiveOptions({ threadId: binding.threadId, status: 'active' });\n try {\n const settled = await session.sendSignal(\n {\n id: reminderId,\n type: 'system-reminder',\n contents: goal.objective,\n attributes: { type: 'goal' },\n metadata: { goalId: goal.id, goalMaxTurns: goal.maxRuns, judgeModelId: goal.judgeModelId },\n },\n { requestContext, requireDelivery: true },\n ).accepted;\n if (settled.action !== 'wake' && settled.action !== 'deliver') {\n throw new FactoryDispatchError(\n 'notification_delivery_failed',\n `Factory goal reminder did not reach the agent (${String(settled.action)}).`,\n );\n }\n } catch (error) {\n await agent.updateObjectiveOptions({ threadId: binding.threadId, status: 'paused' });\n throw error;\n }\n }\n\n /** A retried decision whose kickoff already landed: make sure its goal is held and shown. */\n async #startPhaseGoal(\n record: FactoryDeferredDecisionRecord,\n goal: { objective: string; maxRuns?: number },\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n requestContext: RequestContext,\n ): Promise<void> {\n const objective = await this.#setPhaseGoal(record, goal, session, binding);\n await this.#remindPhaseGoal(record, objective, session, binding, requestContext);\n }\n\n /**\n * A pull request review run: the only runs that keep a status comment on the pull request. A\n * review-seat run of the skill the card's board self-reviews with checks the builder's own work\n * and reviews no pull request, even on a card that carries one.\n */\n async #isReviewRun(record: FactoryDeferredDecisionRecord, decision: unknown): Promise<boolean> {\n const run = reviewSeatSkill(decision);\n if (!run) return false;\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n if (!item) return true;\n const board = (await this.#boards.load(record)).get(boardForWorkItem(item));\n const selfReview = boardFlow(board).selfReview;\n const phase = selfReview === undefined ? undefined : board?.phases[selfReview];\n return phase?.kind !== 'working' || phase.runner.skill !== run.skillName;\n }\n\n /**\n * When a re-entered review's head was already reviewed while this decision waited for the\n * pass in flight: that pass read the pushed commit, so its verdict is the one this decision\n * was queued to produce. A verdict from before the decision does not count, so a person\n * asking for another pass on the same commit still gets one.\n */\n async #headReviewedSince(record: FactoryDeferredDecisionRecord, decision: unknown): Promise<Date | undefined> {\n if (!record.workItemId || (decision as { resume?: unknown }).resume !== true) return undefined;\n if (!(await this.#isReviewRun(record, decision))) return undefined;\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n const { pullRequestHeadSha: head, reviewedHeadSha: reviewed, reviewedAt } = item?.metadata ?? {};\n if (typeof head !== 'string' || typeof reviewed !== 'string' || typeof reviewedAt !== 'string') return undefined;\n if (head.toLowerCase() !== reviewed.toLowerCase()) return undefined;\n const at = new Date(reviewedAt);\n return at.getTime() >= record.createdAt.getTime() ? at : undefined;\n }\n\n async #reviewQueuedOnce(record: FactoryDeferredDecisionRecord, decision: unknown): Promise<void> {\n if (this.#reviewQueued.has(record)) return;\n this.#reviewQueued.add(record);\n await this.#reviewStatus(record, decision, { phase: 'queued' });\n }\n\n /** Best-effort: a status comment is never worth failing or delaying the review it describes. */\n async #reviewStatus(\n record: FactoryDeferredDecisionRecord,\n decision: unknown,\n step: Pick<FactoryReviewStatusEvent, 'phase' | 'startedAt' | 'endedAt' | 'reason'>,\n ): Promise<void> {\n const report = this.#reportReviewStatus;\n if (!report || !record.workItemId) return;\n try {\n if (!(await this.#isReviewRun(record, decision))) return;\n } catch (error) {\n console.warn('Factory review status update failed', sanitizeDispatchError(error));\n return;\n }\n const event: FactoryReviewStatusEvent = {\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: record.workItemId,\n run: record.id,\n requestedAt: record.createdAt,\n generation: record.deliveryGeneration,\n attempt: record.attempts,\n ...step,\n };\n // Writes for one run go out in order even when the run stops waiting on a\n // slow one, so an earlier step can never land on top of a later one.\n const run = this.#reviewStatusRuns.get(record.id) ?? {\n tail: Promise.resolve(),\n issued: 0,\n landed: 0,\n latest: event,\n };\n this.#reviewStatusRuns.set(record.id, run);\n const previous = run.tail;\n const seq = ++run.issued;\n run.latest = event;\n const send = (next: FactoryReviewStatusEvent) =>\n report(next).catch(error => {\n console.warn('Factory review status update failed', sanitizeDispatchError(error));\n });\n // A write that never settles holds the next one back for one timeout, not forever.\n let waited: ReturnType<typeof setTimeout> | undefined;\n const turn = Promise.race([\n previous,\n new Promise<void>(resolve => {\n waited = setTimeout(resolve, REVIEW_STATUS_TIMEOUT_MS);\n }),\n ]).finally(() => clearTimeout(waited));\n const delivered = turn.then(async () => {\n await send(event);\n // This write outlived its wait and a newer one landed first: it may have\n // put an older step back on the comment, so restate the newest one.\n if (run.landed > seq) await send(run.latest);\n run.landed = Math.max(run.landed, seq);\n });\n run.tail = delivered;\n void delivered.then(() => {\n if (run.tail === delivered && run.landed >= run.issued && this.#reviewStatusRuns.get(record.id) === run) {\n this.#reviewStatusRuns.delete(record.id);\n }\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<'timeout'>(resolve => {\n timer = setTimeout(() => resolve('timeout'), REVIEW_STATUS_TIMEOUT_MS);\n });\n try {\n if ((await Promise.race([delivered, timedOut])) === 'timeout') {\n console.warn(`Factory review status update (${step.phase}) still pending; continuing the run without it`);\n }\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** Terminal cleanup ran before this failure landed, so it never saw this row. */\n async #supersedeFailureOnSettledCard(record: FactoryDeferredDecisionRecord): Promise<void> {\n if (!record.workItemId) return;\n try {\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n if (!item || workItemPhaseSemantics(await this.#boards.load(record), item)?.kind !== 'terminal') return;\n await this.#storage.supersedeDecisionsForWorkItem({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: record.workItemId,\n supersededAt: new Date(),\n });\n } catch (error) {\n // Best-effort: the row stays failed until someone clears it from the card.\n console.error('Factory settled-card supersede failed', sanitizeDispatchError(error));\n }\n }\n\n /**\n * A proposal is a question: \"should this run start?\" Once that run is\n * starting anyway — because a person approved a later copy, or armed the item\n * — the question has been answered and the card must stop asking it. Left\n * alone the badge outlives the work it describes, and the one affordance that\n * means \"the loop is stopped, answer this\" cries wolf.\n */\n async #supersedeProposals(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): Promise<void> {\n if (decision.type !== 'invokeSkill' || !record.workItemId) return;\n try {\n await this.#storage.supersedeDecisionsForWorkItem({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: record.workItemId,\n role: decision.role,\n supersededAt: new Date(),\n });\n } catch (error) {\n // Best-effort: a stale badge is not worth failing the run it describes.\n console.error('Factory proposal supersede failed', sanitizeDispatchError(error));\n }\n }\n\n // Effects a person owns: starting a run (compute + code execution), and an\n // external event pulling a card back into a working lane. The board decides\n // which of them start on their own: a phase with `autoStart` (and a card its\n // `autoStartWhen` matches). Anything else waits for a person.\n async #needsApproval(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): Promise<boolean> {\n if (record.approvedAt !== null) return false;\n // A decision queued by a card move on an outside author's pull request event acts on that\n // author's say-so — a run is compute and code execution, a wake holds a session for one.\n // It waits for a person before the consent check (which lets messages through), past the\n // card's armed autonomy and however its phase starts.\n if (\n (decision.type === 'invokeSkill' || decision.type === 'sendMessage') &&\n decision.untrustedPullRequestEvent === true\n ) {\n return true;\n }\n const boards = await this.#boards.load(record);\n if (!requestsConsent(boards, record, decision)) return false;\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n if (!item) return true;\n // Once someone starts a card, the runs that carry it to review are that same request continuing.\n if (item.autonomyArmedAt != null) return false;\n if (reviewsFactoryAuthoredCode(boards, item, decision)) return false;\n return !startsInAutoPhase(boards, item, decision);\n }\n\n async #executeDecision(\n record: FactoryDeferredDecisionRecord,\n decision: FactoryCommitDecision,\n now: Date,\n ): Promise<void> {\n const nextChain: FactoryRuleCausalEntry[] = [\n ...(record.causalChain as FactoryRuleCausalEntry[]),\n { ingressId: record.idempotencyKey, decisionType: decision.type },\n ];\n if (nextChain.length > MAX_FACTORY_RULE_CAUSAL_DEPTH) throw new Error('Factory rule causal depth exceeded.');\n\n switch (decision.type) {\n case 'transition': {\n if (decision.event) await this.#routeEvent(record, decision.event, nextChain, decision);\n else await this.#applyTransition(record, decision, nextChain);\n return;\n }\n case 'routeEvent': {\n if (isUpdateEvent(decision.event.type)) {\n const combined = await this.#foldUpdates(record, decision, now);\n if (combined) await this.#routeEvent(record, combined, nextChain);\n return;\n }\n await this.#routeEvent(record, decision.event, nextChain);\n return;\n }\n case 'upsertLinkedWorkItem': {\n await this.#upsertLinkedItem(record, decision, nextChain);\n return;\n }\n case 'invokeSkill': {\n // A retry for a role the card has already been handed past cannot win:\n // no seat can be minted for it, and the work it was for is done.\n // Checked before a seat is prepared: a stale run must not mint one for a role the card left.\n if (\n (await this.#roleSuperseded(record, decision.role)) ||\n (await this.#decisionOvertaken(record, decision.role))\n ) {\n throw new FactoryDecisionSuperseded();\n }\n const binding = await this.#requireOrPrepareBinding(record, decision.role);\n await this.#withBindingSkillRun(binding.id, async () => {\n const item = record.workItemId\n ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId })\n : null;\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const requestContext = factoryRequestContext({\n session,\n binding,\n userId: startedBy,\n orgId: record.orgId,\n });\n const resolved =\n decision.skillName === undefined\n ? await resolvePromptInvocation(this.#controller, {\n sessionId: binding.sessionId,\n prompt: decision.prompt,\n })\n : decision.resume === true\n ? await resolveSkillResumeInvocation(this.#controller, {\n sessionId: binding.sessionId,\n name: decision.skillName,\n arguments: decision.arguments,\n })\n : await resolveSkillInvocation(this.#controller, {\n sessionId: binding.sessionId,\n name: decision.skillName,\n arguments: decision.arguments,\n });\n await this.#switchThread(session, binding, { userId: startedBy, orgId: record.orgId });\n const deliveryId =\n record.deliveryGeneration === 0 ? record.id : `${record.id}:retry:${record.deliveryGeneration}`;\n const kickoffLanded = async () =>\n (await session.thread.listActiveMessages()).some(message => message.id === deliveryId);\n const kickoffStale = async () =>\n (await this.#roleSuperseded(record, decision.role)) ||\n (await this.#findBinding(record, decision.role))?.id !== binding.id ||\n (await this.#decisionOvertaken(record, decision.role));\n const runStillActive = () =>\n this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId);\n await this.#waitForOpenRun(session, binding, 'Factory skill run');\n if (await this.#roleSuperseded(record, decision.role)) throw new FactoryDecisionSuperseded();\n const activeBinding = await this.#requireBinding(record, decision.role);\n if (activeBinding.id !== binding.id) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Factory binding ${binding.id} changed while waiting for its open run to end.`,\n );\n }\n if (await kickoffLanded()) {\n if (decision.goal) await this.#startPhaseGoal(record, decision.goal, session, binding, requestContext);\n return this.#replayLanded(record, decision, session, runStillActive);\n }\n if (await kickoffStale()) throw new FactoryDecisionSuperseded();\n const coveredAt = await this.#headReviewedSince(record, decision);\n if (coveredAt) {\n // The verdict this pass was queued for exists; its status reports that verdict, not a cancelled run.\n await this.#reviewStatus(record, decision, {\n phase: 'completed',\n startedAt: record.createdAt,\n endedAt: coveredAt,\n });\n return;\n }\n // Safe under the replay guard above: it matches deliveryId, never prompt content.\n // Re-read: the description may have been edited while the open run drained.\n const current = record.workItemId\n ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId })\n : null;\n const kickoffContents = withWorkItemDescription(resolved.contents, current?.description);\n // A skill kickoff is system-generated, not something the human typed: send it\n // as a typed `skill` signal so the model sees `<skill name=\"…\">` and traces\n // record the skill name. Plain-prompt kickoffs stay user messages.\n const kickoffSignal =\n resolved.skillName !== undefined\n ? {\n type: 'reactive' as const,\n tagName: 'skill',\n attributes: { name: resolved.skillName },\n }\n : { type: 'user' as const, tagName: 'user' };\n // The description read is async storage I/O; the card can move while it runs.\n if (await kickoffLanded()) {\n if (decision.goal) await this.#startPhaseGoal(record, decision.goal, session, binding, requestContext);\n return this.#replayLanded(record, decision, session, runStillActive);\n }\n if (await kickoffStale()) throw new FactoryDecisionSuperseded();\n await this.#reviewQueuedOnce(record, decision);\n if (decision.cancelInFlight && session.stream.isActive()) session.abort();\n const precedingMessage = decision.precedingMessage;\n if (precedingMessage) {\n await awaitNotification(() =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'stage-transition',\n summary: precedingMessage,\n priority: 'medium',\n payload: { message: precedingMessage },\n sourceId: `${record.id}:stage-transition`,\n dedupeKey: `${record.idempotencyKey}:stage-transition`,\n },\n {\n ifActive: { behavior: 'deliver' },\n ifIdle: { behavior: 'persist' },\n requestContext,\n },\n ),\n );\n if (await kickoffStale()) throw new FactoryDecisionSuperseded();\n }\n // Held before the kickoff lands, so the goal judge sees the objective from the run's first turn.\n const goal = decision.goal ? await this.#setPhaseGoal(record, decision.goal, session, binding) : undefined;\n // The run's own verdict, not the delivery's. A signal can reach the\n // agent perfectly and the run still die on a provider error or be\n // cancelled mid-flight; without this the decision reports success and\n // the break is invisible on the card.\n const since = new Date();\n const runItem = record.workItemId\n ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId })\n : null;\n const boards = runItem ? await this.#boards.load(record) : null;\n const stage = runItem?.stages.length === 1 ? runItem.stages[0] : undefined;\n const phase = stage && runItem ? boards?.get(boardForWorkItem(runItem))?.phases[stage] : undefined;\n const workingRevision =\n phase?.kind === 'working' &&\n (phase.runner.goal || phase.exitTool) &&\n phase.runner.context === decision.role &&\n phase.runner.skill === decision.skillName\n ? runItem!.revision\n : null;\n const existingLinkedReviewIds = new Set(\n workingRevision === null || !runItem\n ? []\n : (await this.#storage.listLinked({ item: runItem, limit: 100 })).map(card => card.id),\n );\n const stopRequested = () => this.#runStopRequested(record.orgId, binding.id);\n const run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n autoApprovedTool: await this.#autoApprovedExitTool(record),\n autoApproving: this.#autoApproving,\n requestContext,\n onAgentEnd: () => this.#roleSuperseded(record, decision.role),\n label: 'Factory skill run',\n runStillActive,\n stopRequested,\n });\n\n const sendKickoff = async () => {\n await this.#storage.clearRunBindingStopRequest({ orgId: record.orgId, bindingId: binding.id });\n const result = session.sendSignal(\n {\n id: deliveryId,\n ...kickoffSignal,\n contents: kickoffContents,\n },\n // Without `requireDelivery` the session resolves `accepted` on the\n // next tick and swallows wake failures, so a kickoff that never\n // reached the agent would be marked succeeded and the thread would\n // stay empty forever.\n { requestContext, requireDelivery: true },\n );\n const settled = await result.accepted;\n if (settled.action !== 'wake' && settled.action !== 'deliver') {\n // A named non-delivery action proves no run began and is safe to\n // retry. An absent action did not confirm either outcome, so a new\n // delivery generation could duplicate work.\n throw new FactoryDispatchError(\n settled.action ? 'notification_delivery_failed' : 'skill_delivery_ambiguous',\n `Factory skill invocation signal did not reach the agent (${String(settled.action)}).`,\n );\n }\n return settled;\n };\n\n try {\n let settled = await sendKickoff();\n while (settled.action === 'deliver') {\n // `deliver` means the signal was queued onto a run that was already\n // in flight. If that run ends before draining its queue the prompt\n // is dropped silently: no turn starts, no error surfaces, and the\n // decision reports success while the card sits in its new stage with\n // nobody working. Signals persist under their generation-scoped id\n // (the same identity the replay guard above reads), so confirm the\n // message actually landed in the thread rather than trusting the ack.\n if (await kickoffLanded()) break;\n\n // Another run can start while the previous run is finishing, so one\n // redelivery is not enough to prove the session is idle. Follow each\n // run boundary until the kickoff either lands on an active run or\n // wakes a new one.\n if (!(await run.wait())) {\n throw new FactoryDispatchError(\n 'run_terminal_event_missing',\n 'Factory skill invocation is waiting on a run whose terminal event was not observed.',\n );\n }\n // The queued copy often surfaces only once the run it was queued\n // onto ends. Resend only when it is still missing, and never once\n // the card has moved on or the seat was handed over or revoked —\n // a stale kickoff would restart a phase that already finished.\n if (await kickoffLanded()) break;\n if (await kickoffStale()) throw new FactoryDecisionSuperseded();\n // Stopped while the kickoff was queued: resending would restart what was just stopped.\n if (await stopRequested()) throw new FactoryRunStopped();\n run.arm();\n settled = await sendKickoff();\n }\n if (goal) await this.#remindPhaseGoal(record, goal, session, binding, requestContext);\n await this.#recordRunStart(\n session,\n binding,\n deliveryId,\n record.approvedBy ?? undefined,\n run.endReason,\n item?.title,\n );\n this.#reviewWatched.add(record);\n await this.#reviewStatus(record, decision, { phase: 'reviewing', startedAt: since });\n // A landed `deliver` still runs on the in-flight session, so the run's\n // terminal outcome matters as much as a fresh wake's: a run that ends\n // in error after accepting the prompt has still failed this decision.\n try {\n await this.#reportingRunEnd(\n {\n binding,\n startedBy,\n since,\n attempts: record.attempts,\n // A role that handed the card on mid-turn: the failure is its successor's, not ours.\n superseded: async () =>\n (await run.supersededAtEnd()) ?? (await this.#roleSuperseded(record, decision.role)),\n },\n async () => {\n await this.#withOpenRunHeartbeat(session, deliveryId, () => run.settle());\n if (run.endReason() !== 'complete' || workingRevision === null || (await run.supersededAtEnd()))\n return;\n // A final tool result can persist after agent_end. Read this binding's trailing\n // results before deciding the unchanged card means the run did no work.\n await this.#reconcileRunBinding?.(binding);\n const after = await this.#storage.get({ orgId: record.orgId, id: record.workItemId! });\n if (after?.revision === workingRevision && !(await kickoffStale())) {\n const linked = await this.#storage.listLinked({ item: after, limit: 100 });\n const ownCardHandOff = linked.some(card => {\n if (\n card.parentWorkItemId !== after.id ||\n existingLinkedReviewIds.has(card.id) ||\n card.externalSource?.integrationId !== 'github' ||\n card.externalSource.type !== 'pull-request' ||\n card.stages.length !== 1\n )\n return false;\n const review = boards?.get(boardForWorkItem(card))?.phases[card.stages[0]!];\n return review?.kind === 'working' && review.runner.context === 'review';\n });\n if (ownCardHandOff) return;\n throw new FactoryDispatchError(\n 'run_incomplete',\n 'Factory skill run ended before completing the working phase.',\n );\n }\n },\n );\n // Handed on before the turn ended: the run's clean end is the successor's, not\n // a finished review. A move after the turn ended (a merge) keeps the completion.\n if (await run.supersededAtEnd()) {\n this.#reviewWatched.delete(record);\n await this.#reviewStatus(record, decision, { phase: 'cancelled', endedAt: new Date() });\n }\n } catch (error) {\n // Roles share one session. When this role handed the card on\n // mid-turn, the next role's kickoff was delivered onto the same\n // run and the turn never ended for us — its eventual verdict is\n // the successor's to record, not ours. Capture that state when the\n // terminal event arrives so a later hand-on cannot erase our failure.\n const superseded = (await run.supersededAtEnd()) ?? (await this.#roleSuperseded(record, decision.role));\n if (!superseded) throw error;\n this.#reviewWatched.delete(record);\n await this.#reviewStatus(record, decision, { phase: 'cancelled', endedAt: new Date() });\n }\n } finally {\n run.close();\n }\n });\n return;\n }\n case 'sendMessage': {\n const binding = await this.#messageBinding(record, decision);\n // Nobody live on the card means nobody to tell, not a failure to retry.\n if (!binding) return;\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const requestContext = factoryRequestContext({\n session,\n binding,\n userId: startedBy,\n orgId: record.orgId,\n });\n await awaitNotification(\n () =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'rule-message',\n summary: decision.message,\n priority: decision.priority ?? 'high',\n payload: { message: decision.message },\n sourceId: record.id,\n dedupeKey: record.idempotencyKey,\n },\n {\n ifActive: { behavior: 'deliver' },\n ifIdle: { behavior: decision.idleBehavior ?? 'wake' },\n requestContext,\n },\n ),\n // A persist message succeeds by being stored for the idle session;\n // only a message that must wake or reach a live run fails without it.\n decision.idleBehavior !== 'persist',\n );\n return;\n }\n case 'signalActivity': {\n await this.#signalActivity(record, decision);\n return;\n }\n case 'dismissStaleReviews': {\n if (!this.#dismissStaleReviews) throw new Error('GitHub review dismissal is not configured.');\n await this.#dismissStaleReviews(decision);\n return;\n }\n case 'notify': {\n const selected = await this.#requireBinding(record);\n if (\n (await this.#roleSuperseded(record, selected.role)) ||\n (await this.#decisionOvertaken(record, selected.role))\n ) {\n throw new FactoryDecisionSuperseded();\n }\n const binding = await this.#requireOrPrepareBinding(record, selected.role, selected.id);\n // A notification can wake the idle session, so it runs as the session's\n // owner like any other Factory-started run, never as nobody.\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const requestContext = factoryRequestContext({ session, binding, userId: startedBy, orgId: record.orgId });\n await awaitNotification(() =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'rule-notification',\n summary: decision.title,\n payload: { body: decision.body, level: decision.level },\n sourceId: record.id,\n dedupeKey: record.idempotencyKey,\n },\n { requestContext },\n ),\n );\n }\n }\n }\n\n /**\n * The project's card for a Linear issue by its stable id, wherever its identifier now points.\n * A live card wins over finished ones, as in the Linear rules and issue detail route.\n */\n async #linearCardByIssueId(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n boards: BoardRegistry,\n ) {\n const issueId = decision.metadata?.linearIssueId;\n if (decision.source !== 'linear-issue' || typeof issueId !== 'string') return null;\n const items = await this.#storage.listShared({ orgId: record.orgId, factoryProjectId: record.factoryProjectId });\n const cards = items.filter(\n item => item.externalSource?.integrationId === 'linear' && item.workItem.metadata?.linearIssueId === issueId,\n );\n const card = cards.find(item => !isTerminalWorkItem(boards, item)) ?? cards[0];\n // The shared list is the cache itself: hand on a copy of the card.\n return card ? structuredClone(card) : null;\n }\n\n async #upsertLinkedItem(\n record: FactoryDeferredDecisionRecord,\n requested: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n causalChain: FactoryRuleCausalEntry[],\n ): Promise<void> {\n if (\n this.#factoryProjectExists &&\n !(await this.#factoryProjectExists({ orgId: record.orgId, factoryProjectId: record.factoryProjectId }))\n ) {\n return;\n }\n // A lost completion acknowledgement must not reinterpret a committed\n // materialization against a replacement installation.\n const existing = await this.#storage.getByProjectSource({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n source: externalSourceForDecision(requested),\n });\n // A pull request attached to its issue's card is filed already. Re-filing it (a replayed\n // or swept \"opened\") must not write its facts onto the card's primary issue source. A\n // reopen is the one fact it brings: the attached source is open again.\n if (\n existing &&\n externalSourceKey(existing.externalSource) !== externalSourceKey(externalSourceForDecision(requested))\n ) {\n const source = externalSourceForDecision(requested);\n const facts = workItemProviderAdapter(source).toSource(source, requested.metadata ?? null);\n // The card a pull request linked to may not have had its event yet (the delivery that\n // linked it lost a race); the event's key makes this a no-op once it has.\n if (requested.closesIssue?.workItemId === existing.id && record.workItemId === null) {\n await this.#queueLinkedPullRequestOpened(record, requested, existing, causalChain);\n }\n if (facts?.state === 'open') {\n await this.#storage.syncWorkItemSource({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n provider: facts.provider,\n externalId: facts.externalId,\n patch: current =>\n current.state === 'closed' || current.state === 'merged'\n ? { state: facts.state, metadata: { ...current.metadata, ...facts.metadata } }\n : null,\n });\n }\n return;\n }\n if (!existing && requested.attachTo) {\n // A card takes a pull request when its board reviews pull requests; elsewhere the pull\n // request is filed as its own card.\n const attachBoards = await this.#boards.load(record);\n if (\n await this.#attachLinkedItem(record, requested, requested.attachTo.workItemId, causalChain, card =>\n cardBoardFlow(attachBoards, card).pullRequestReview !== undefined ? { phase: null } : undefined,\n )\n ) {\n return;\n }\n }\n if (!existing && requested.closesIssue && (await this.#linkClosedIssue(record, requested, causalChain))) return;\n const materializedHere = existing?.metadata?.[FACTORY_RULE_MATERIALIZATION_KEY] === record.idempotencyKey;\n // Filing the card *was* the placement, so a retry of the same decision has\n // nothing left to apply — and must not drag a card that has since moved\n // back down to the stage this decision filed it at.\n if (materializedHere && requested.skipRules === true) return;\n const boards = await this.#boards.load(record);\n // A Linear identifier changes when its issue moves teams; the card filed\n // under the old one is still this issue's card.\n const renamed = existing ? null : await this.#linearCardByIssueId(record, requested, boards);\n // Intake routes place only a card this decision files (or is still filing,\n // on a retry); a card already on the board stays where it is.\n const current = existing ?? renamed;\n const decision = !current\n ? await this.#routeArrival(record, requested, boards)\n : materializedHere\n ? await this.#resumeRoutedCard(record, current, requested, boards)\n : this.#keepRoutedCard(current, requested, boards);\n // No board took it: logged Not routed, and filed only once a rule takes it (Route again).\n if (!decision) return;\n if (materializedHere) {\n for (const suffix of ['destination', 'initial-entry']) {\n const replay = await this.#storage.getTransitionResultByIngress(\n record.orgId,\n record.factoryProjectId,\n `decision:${record.idempotencyKey}:${existing.id}:${suffix}`,\n );\n if (replay?.status === 'accepted' && replay.stage === decision.stage) {\n await this.#resolveNotRouted(record, decision.sourceKey);\n return;\n }\n }\n }\n assertFactoryDecisionTarget(decision, boards);\n const definition = boards.get(decision.board);\n if (!definition) throw new Error('Factory decision target board is not installed.');\n const initialPhase = definition.initialPhase;\n // `skipRules` files the card at the stage the decision names, as its first\n // entry, and runs none of the board's phase rules. Without it the card\n // enters through the board's initial phase and transitions from there, so\n // arrival and destination-entry rules both run.\n const skipRules = decision.skipRules === true;\n const entryStage = skipRules ? decision.stage : initialPhase;\n const parentWorkItemId =\n record.workItemId ??\n (await this.#resolveLinkedWorkItemParentId?.({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n decision,\n })) ??\n null;\n let result: UpsertWorkItemResult = renamed\n ? {\n created: false,\n item: renamed,\n previous: { stages: renamed.stages, sessionRoles: Object.keys(renamed.sessions) },\n }\n : await this.#storage.upsert({\n orgId: record.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: record.factoryProjectId,\n input: {\n externalSource: externalSourceForDecision(decision),\n parentWorkItemId,\n title: decision.title,\n ...(decision.description ? { description: decision.description } : {}),\n board: decision.board,\n stages: [entryStage],\n sessions: {},\n metadata: { ...decision.metadata, [FACTORY_RULE_MATERIALIZATION_KEY]: record.idempotencyKey },\n },\n reuseMode: 'preserve',\n });\n // The item is filed once its card stands past initial entry; a retry of this decision resolves it too.\n const filed = () => this.#resolveNotRouted(record, decision.sourceKey);\n const itemBoard = boardForWorkItem(result.item);\n // A pull request's own card already on another board that reviews pull requests (the retired\n // Review board, for a project still using it) stays there: filing its pull request again acts\n // on it where it sits, in that board's own review phase.\n const itemFlow = itemBoard === decision.board ? undefined : boardFlow(boards.get(itemBoard));\n const keptReview = isPullRequestCard({ source: workItemSource(result.item.externalSource) })\n ? itemFlow?.pullRequestReview\n : undefined;\n const board = keptReview === undefined ? decision.board : itemBoard;\n const placeStage =\n keptReview !== undefined && decision.stage === boardFlow(definition).pullRequestReview\n ? keptReview\n : decision.stage;\n if (!skipRules && itemBoard !== board) {\n throw new Error(`The work item belongs to board \"${itemBoard}\", not \"${board}\".`);\n }\n // A re-evaluation for an already-filed card (poll/reconcile re-emitting\n // \"opened\") resolves the card itself as the triggering item; it is not\n // its own parent.\n if (!result.item.parentWorkItemId && parentWorkItemId && parentWorkItemId !== result.item.id) {\n const item = await this.#storage.setParentWorkItemIfMissing({\n orgId: record.orgId,\n id: result.item.id,\n userId: 'factory-rule-dispatcher',\n parentWorkItemId,\n });\n if (item) result = { ...result, item };\n }\n // A `skipRules` decision is a placement and nothing else: the backfill would\n // otherwise walk the arrival decision's facts back onto an existing card,\n // restamping trust the sweep deliberately left unanswered.\n if (!result.created && !skipRules) {\n // Backfill source facts (e.g. sourceCreatedAt) that older cards were filed\n // without. Fill-only: never overwrite, and never adopt the card as\n // materialized by this decision.\n const providerKeys = workItemProviderAdapter(result.item.externalSource).providerMetadataKeys;\n const missing = Object.fromEntries(\n Object.entries(decision.metadata ?? {}).filter(\n ([key]) =>\n key !== FACTORY_RULE_MATERIALIZATION_KEY &&\n (providerKeys.includes(key) ? result.item.workItem.metadata?.[key] : result.item.metadata?.[key]) ===\n undefined,\n ),\n );\n if (Object.keys(missing).length > 0) {\n const filled = await this.#storage.syncCard({\n orgId: record.orgId,\n id: result.item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: missing },\n fillOnly: true,\n });\n if (filled) result = { ...result, item: filled.item };\n }\n }\n if (skipRules) {\n // Creation already filed the card at `stage`. An existing card — one a\n // reconcile pass files again, say — is placed there the same way, through\n // a cross-board relocation, so no phase rule runs for it and no transition\n // is recorded.\n // Another decision of the same delivery (a pull request attaching to this card, say) can\n // change the card in between; a placement skipped for that reason is retried on a fresh read.\n let item: Card | null = result.created ? null : result.item;\n for (let attempt = 0; item && attempt < 3; attempt += 1) {\n const outcome = await moveCardToBoard({\n workItems: this.#storage,\n boardRegistry: boards,\n userId: 'factory-rule-dispatcher',\n item,\n targetBoard: board,\n targetStage: placeStage,\n });\n if (outcome !== 'skipped') break;\n const fresh = await this.#storage.get({ orgId: record.orgId, id: item.id });\n item = fresh && fresh.revision !== item.revision ? fresh : null;\n }\n await filed();\n return;\n }\n const materializedByDecision = result.item.metadata?.[FACTORY_RULE_MATERIALIZATION_KEY] === record.idempotencyKey;\n if (!materializedByDecision && (decision.stage === initialPhase || !result.item.stages.includes(initialPhase))) {\n await filed();\n return;\n }\n\n let expectedRevision = result.item.revision;\n if (materializedByDecision) {\n const initial = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: result.item.id,\n board,\n stage: initialPhase,\n expectedRevision,\n actor: deferredActor(record),\n ingress: { type: 'rule', identity: `decision:${record.idempotencyKey}:${result.item.id}:initial-entry` },\n cause: 'linked_item_materialized',\n causalChain,\n initialEntry: true,\n });\n if (initial.status === 'rejected') {\n if (result.created)\n await this.#storage.delete({ orgId: record.orgId, id: result.item.id, purgeRuleState: false });\n throw new FactoryRuleRejectedError(initial.code, initial.reason);\n }\n expectedRevision = initial.revision;\n }\n await filed();\n if (decision.stage === initialPhase) return;\n\n const moved = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: result.item.id,\n board,\n stage: decision.stage,\n expectedRevision,\n actor: { type: 'system', id: 'factory-rule-dispatcher' },\n ingress: { type: 'rule', identity: `decision:${record.idempotencyKey}:${result.item.id}:destination` },\n cause: materializedByDecision ? 'linked_item_materialized' : 'linked_item_reconciled',\n causalChain,\n // The stage is what intake resolved — a route or the project's default — so, as with a\n // route's status-event move, the first phase's next phases don't restrict it. Only for the\n // card this decision files, though: a reconciled card keeps its board's edges.\n ...(materializedByDecision ? { routeFiling: true } : {}),\n });\n if (moved.status === 'rejected') throw new FactoryRuleRejectedError(moved.code, moved.reason);\n }\n\n /**\n * Files a pull or merge request on the existing card `workItemId`, as one more source, when\n * `admit` takes the card as it is now; the card then moves to the phase `admit` names when its\n * board allows it. Returns false when the card can't take it (gone, finished, a pull request's\n * own card, refused by `admit`, or another card took the record first), so the caller files the\n * record as usual. `admit` runs again on a fresh read whenever the card changed in between.\n */\n async #attachLinkedItem(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n workItemId: string,\n causalChain: FactoryRuleCausalEntry[],\n admit: (card: Card) => { phase: string | null } | undefined,\n cardMetadata?: (metadata: Record<string, unknown>, card: Card) => Record<string, unknown>,\n afterAttach?: (card: Card) => Promise<void>,\n ): Promise<boolean> {\n // A dry run of the work item split has no sources table to attach to: the pull request\n // gets its own card, as before.\n if (this.#storage.legacyMode) return false;\n const boards = await this.#boards.load(record);\n let attached: { card: Card; phase: string | null } | undefined;\n for (let attempt = 0; attempt < 3 && !attached; attempt++) {\n const card = await this.#storage.get({ orgId: record.orgId, id: workItemId });\n if (\n !card ||\n card.factoryProjectId !== record.factoryProjectId ||\n isTerminalWorkItem(boards, card) ||\n isPullRequestCard({ source: workItemSource(card.externalSource) })\n ) {\n return false;\n }\n const admitted = admit(card);\n if (!admitted) return false;\n try {\n // At the revision `admit` read: work starting or another pull request landing in between\n // sends the record round again.\n const result = await this.#storage.attachSource({\n orgId: record.orgId,\n id: card.id,\n source: externalSourceForDecision(decision),\n metadata: decision.metadata ?? null,\n expectedRevision: card.revision,\n // The card as `admit` read it: the attach commits at that revision.\n ...(cardMetadata\n ? { cardMetadata: (metadata: Record<string, unknown>) => cardMetadata(metadata, card) }\n : {}),\n });\n if (!result) return false;\n attached = { card: result.item, phase: admitted.phase };\n } catch (error) {\n if (error instanceof WorkItemSourceConflictError) return false;\n if (error instanceof WorkItemUpdateConflictError) continue;\n throw error;\n }\n }\n if (!attached) return false;\n const { card, phase } = attached;\n await afterAttach?.(card);\n const stage = card.stages.length === 1 ? card.stages[0] : undefined;\n const board = boards.get(boardForWorkItem(card));\n if (!phase || !stage || stage === phase) return true;\n if (!board?.allowsTransition(stage, phase)) {\n console.warn(\n `[factory] attached a pull request to ${card.id}, which stays in ${stage}: its board has no move to ${phase}`,\n );\n return true;\n }\n const moved = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: card.id,\n board: board.id,\n stage: phase,\n expectedRevision: card.revision,\n actor: { type: 'system', id: 'factory-rule-dispatcher' },\n ingress: { type: 'rule', identity: `decision:${record.idempotencyKey}:${card.id}:attach` },\n cause: 'linked_item_attached',\n causalChain,\n });\n // The pull request is on the card either way, and a retry would not move it.\n if (moved.status === 'rejected') {\n console.warn(\n `[factory] attached a pull request to ${card.id} but could not move it to ${phase}: ${moved.code}: ${moved.reason}`,\n );\n }\n return true;\n }\n\n /**\n * Links a pull or merge request to the card of the issue it closes, whoever opened it: Factory\n * does this itself, before intake, wherever the card sits, so long as it is unfinished. Linking\n * runs nothing. An outsider's pull request is recorded as untrusted on the card, so it never\n * becomes the card's working pull request on its own; a person picks it. The card then gets the\n * pull request's `pull_request.opened`, so its board's own card-move rules decide whether it moves.\n */\n async #linkClosedIssue(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n causalChain: FactoryRuleCausalEntry[],\n ): Promise<boolean> {\n if (decision.skipRules === true || record.workItemId !== null) return false;\n const trusted = authorTrusted(decision.metadata);\n const trustKey = this.#pullRequestTrustKey(decision);\n return this.#attachLinkedItem(\n record,\n decision,\n decision.closesIssue!.workItemId,\n causalChain,\n () => ({ phase: null }),\n (metadata, card) => {\n const links = linkedPullRequests(metadata);\n const withLink = {\n ...metadata,\n [LINKED_PULL_REQUESTS_KEY]: { ...links, [trustKey]: links[trustKey] ?? linkFacts(card, trusted, trustKey) },\n };\n if (trusted) return withLink;\n const listed = metadata[UNTRUSTED_PULL_REQUESTS_KEY];\n const untrusted = Array.isArray(listed) ? listed.filter(entry => typeof entry === 'string') : [];\n return untrusted.includes(trustKey)\n ? withLink\n : { ...withLink, [UNTRUSTED_PULL_REQUESTS_KEY]: [...untrusted, trustKey] };\n },\n card => this.#queueLinkedPullRequestOpened(record, decision, card, causalChain),\n );\n }\n\n /** The key a card lists an untrusted attached pull request under (see `UNTRUSTED_PULL_REQUESTS_KEY`). */\n #pullRequestTrustKey(decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>): string {\n const source = externalSourceForDecision(decision);\n return pullRequestTrustKey(workItemProviderAdapter(source).toSource(source, decision.metadata ?? null)!);\n }\n\n /**\n * Hands the card a linked pull request's `pull_request.opened`, with the facts saved when it\n * joined (the card's phase then, and whether a trusted open pull request was already on it), so\n * a retry after the card changed still describes the link as it happened. Keyed by the card and\n * the pull request, so whichever delivery files the pull request, and however often, the card\n * gets the event once.\n */\n async #queueLinkedPullRequestOpened(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n card: Card,\n causalChain: FactoryRuleCausalEntry[],\n ): Promise<void> {\n const sourceKey = externalSourceKey(externalSourceForDecision(decision));\n const key = `linked-pull-request:${card.id}:${sourceKey}`;\n const trustKey = this.#pullRequestTrustKey(decision);\n // A link from before the facts were saved with it reads them off the card as it is now.\n const link =\n linkedPullRequests(card.metadata)[trustKey] ?? linkFacts(card, authorTrusted(decision.metadata), trustKey);\n const queued = await this.#storage.commitRuleEvaluation({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: card.id,\n ingress: { identity: `decision:${key}` },\n expectedRevision: card.revision,\n actor: { type: 'system', id: 'factory-rule-dispatcher' },\n outcome: { status: 'accepted' },\n decisions: [\n {\n type: 'routeEvent',\n idempotencyKey: key,\n event: {\n type: 'pull_request.opened',\n pullRequestTrusted: link.trusted,\n // The author opened it, so the opener's trust is the author's.\n actorTrusted: link.trusted,\n closedIssue: { phase: link.phase, hasPullRequest: link.hasPullRequest },\n },\n },\n ],\n causalChain,\n now: new Date(),\n });\n if (queued.status === 'stale') {\n throw new Error('Factory linked pull request event was not queued: the work item changed concurrently.');\n }\n }\n\n /**\n * Leaves a warning in the decision log for each card-move rule that matched but whose target\n * couldn't take the card; a redelivery of the same event replaces it.\n */\n async #logSkippedRoutes(\n record: FactoryDeferredDecisionRecord,\n item: Card,\n event: BoardEventFacts,\n skipped: readonly SkippedEventRoute[],\n ): Promise<void> {\n if (!this.#intakeRoutes || skipped.length === 0) return;\n const scope = { orgId: record.orgId, factoryProjectId: record.factoryProjectId };\n const evaluator = await projectIntakeEvaluator(this.#intakeEvaluator, this.#intakeRoutes, scope);\n for (const skip of skipped) {\n await this.#intakeRoutes.recordIntakeDecision(scope, {\n idempotencyKey: `rule-skipped:${record.idempotencyKey}:${skip.routeId}`,\n outcome: 'rule_skipped',\n evaluator,\n boardKey: skip.boardKey,\n routeId: skip.routeId,\n reason: `The card-move rule matched ${event.type} but was skipped: ${skip.reason}.`,\n sourceKey: item.externalSource?.externalId ?? null,\n title: item.title,\n url: item.externalSource?.url ?? null,\n });\n }\n }\n\n /** Marks the item's Not routed record, if any, resolved: its card is filed. */\n async #resolveNotRouted(record: FactoryDeferredDecisionRecord, sourceKey: string): Promise<void> {\n await this.#intakeRoutes?.resolveNotRouted(\n { orgId: record.orgId, factoryProjectId: record.factoryProjectId },\n sourceKey,\n 'factory-rule-dispatcher',\n );\n }\n\n /**\n * Places an arrival where intake says (see `resolveIntake`). The board and phase an\n * integration's rule named don't count; only a decision placing the card outright (`skipRules`)\n * keeps its own. Undefined when no board takes it: it is logged Not routed and no card is filed.\n * Every decision is logged, keyed by the arrival's decision so a redelivery replaces its row.\n */\n async #routeArrival(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n boards: BoardRegistry,\n ): Promise<Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }> | undefined> {\n if (decision.skipRules === true) return decision;\n // A card another card's rule files (a board's child card) goes where that\n // board put it; routes place only what arrives from outside.\n if (record.workItemId !== null) return decision;\n if (!this.#intakeRoutes) {\n // Only a forced route list may file without the rules: unread, the project's setting could be\n // intake order, which has no board to fall back on. The arrival waits for the rules.\n if (this.#intakeEvaluator !== 'route-list') throw new Error('Intake rules are unavailable right now.');\n return decision;\n }\n const scope = { orgId: record.orgId, factoryProjectId: record.factoryProjectId };\n const evaluator = decision.idempotencyKey.startsWith(ROUTE_AGAIN_KEY_PREFIX)\n ? 'intake-order'\n : await projectIntakeEvaluator(this.#intakeEvaluator, this.#intakeRoutes, scope);\n const [routes, order] = await Promise.all([\n this.#intakeRoutes.listIntakeRoutes(scope),\n evaluator === 'intake-order'\n ? this.#intakeRoutes.readIntakeOrder(scope, { boards: [...boards.keys()] })\n : undefined,\n ]);\n const facts = await arrivalRuleFacts(decision, {\n factoryProjectId: record.factoryProjectId,\n registry: boards,\n card: id => this.#storage.get({ orgId: record.orgId, id }),\n });\n const resolution = resolveIntake({\n evaluator,\n routes,\n order: order?.boardKeys ?? [],\n facts,\n registry: boards,\n });\n const logged = {\n idempotencyKey: record.idempotencyKey,\n evaluator,\n sourceKey: decision.sourceKey,\n title: decision.title,\n url: decision.url,\n };\n if (resolution.outcome === 'not_routed') {\n await this.#intakeRoutes.recordIntakeDecision(scope, {\n ...logged,\n outcome: 'not_routed',\n reason: resolution.reason,\n arrival: { ...decision },\n });\n return undefined;\n }\n await this.#intakeRoutes.recordIntakeDecision(scope, {\n ...logged,\n outcome: 'placed',\n boardKey: resolution.board,\n routeId: resolution.routeId,\n });\n return {\n ...decision,\n board: resolution.board,\n stage: resolution.phase,\n ...(resolution.routeId !== null && {\n metadata: { ...decision.metadata, [INTAKE_ROUTE_METADATA_KEY]: resolution.routeId },\n }),\n };\n }\n\n /**\n * A retry of the decision that filed `existing` finishes the filing where it started: on the\n * card's board, at the phase its route names now, or the board's first phase when the route was\n * deleted, disabled or re-pointed since. Routes are not re-run, so an edit cannot send the card\n * to a board it isn't on.\n */\n async #resumeRoutedCard(\n record: FactoryDeferredDecisionRecord,\n existing: Card,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n boards: BoardRegistry,\n ): Promise<Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>> {\n const routeId = existing.metadata?.[INTAKE_ROUTE_METADATA_KEY];\n if (typeof routeId !== 'string') return decision;\n const board = boards.get(boardForWorkItem(existing));\n if (!board) return decision;\n const routes = this.#intakeRoutes\n ? await this.#intakeRoutes.listIntakeRoutes({ orgId: record.orgId, factoryProjectId: record.factoryProjectId })\n : [];\n const route = routes.find(entry => entry.id === routeId && entry.enabled && entry.target.boardKey === board.id);\n return {\n ...decision,\n board: board.id,\n stage: resumeLandingPhase(board, route?.target.phaseKey, cardRuleFacts(existing), hasPullRequest(existing)),\n metadata: { ...decision.metadata, [INTAKE_ROUTE_METADATA_KEY]: routeId },\n };\n }\n\n /**\n * A card an intake route placed stays on the route's board when its source is filed again\n * (a reconcile replaying \"opened\"): the decision lands on the card's board at its first phase,\n * so it only backfills facts and moves nothing. An explicit placement (`skipRules`) still wins.\n */\n #keepRoutedCard(\n existing: Card,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n boards: BoardRegistry,\n ): Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }> {\n if (decision.skipRules === true || !placedByIntakeRoute(existing)) return decision;\n const board = boards.get(boardForWorkItem(existing));\n if (!board || board.id === decision.board) return decision;\n return { ...decision, board: board.id, stage: board.initialPhase };\n }\n /** Moves the card as a rule decided, then queues the decision's message for the card's session. */\n async #applyTransition(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'transition' }>,\n nextChain: FactoryRuleCausalEntry[],\n ): Promise<void> {\n const item = await this.#requireItem(record);\n const replay = await this.#storage.getTransitionResultByIngress(\n record.orgId,\n record.factoryProjectId,\n `decision:${record.idempotencyKey}`,\n );\n if (!replay) assertFactoryDecisionTarget(decision, await this.#boards.load(record), item.board ?? undefined);\n const result = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: item.id,\n board: decision.board,\n stage: decision.stage,\n expectedRevision: item.revision,\n actor: record.approvedBy\n ? { type: 'human', id: record.approvedBy }\n : { type: 'system', id: 'factory-rule-dispatcher' },\n ingress: { type: 'rule', identity: `decision:${record.idempotencyKey}` },\n cause: 'rule_decision',\n causalChain: nextChain,\n ...(decision.reenter ? { reenter: true } : {}),\n // A default rule's own move (no stored rule handled the event, or none exists) answers the\n // event too: when it is an outside author's pull request event, the run the destination\n // queues waits for a person just as a rule's move does.\n ...(decision.event && untrustedPullRequestEvent(decision.event) ? { untrustedPullRequestEvent: true } : {}),\n });\n if (result.status === 'rejected') throw new FactoryRuleRejectedError(result.code, result.reason);\n const transitionMessage = decision.message;\n if (!transitionMessage) return;\n // The message may wake an idle session and hold it for a whole agent\n // run, so it is queued as its own sendMessage decision for the run\n // pool; the stage change above never waits on run capacity. Keyed by\n // this decision, so a retry replays rather than queueing it twice.\n const moved = await this.#storage.get({ orgId: record.orgId, id: item.id });\n if (!moved) return;\n const messageKey = `${record.idempotencyKey}:message`;\n // Keyed by revision so a retry after a concurrent write commits under a\n // fresh identity at the item's new revision.\n const queued = await this.#storage.commitRuleEvaluation({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: `decision:${messageKey}@${moved.revision}` },\n expectedRevision: moved.revision,\n actor: record.actor ?? { type: 'system', id: 'factory-rule-dispatcher' },\n outcome: { status: 'accepted' },\n decisions: [\n {\n type: 'sendMessage',\n idempotencyKey: messageKey,\n message: transitionMessage.text,\n priority: 'high',\n // The move's message always reaches the card's session, but an outside author's pull\n // request event never wakes an idle one: the message persists in its notifications\n // instead, read when a person (or an approved run) brings the session back.\n idleBehavior: decision.event && untrustedPullRequestEvent(decision.event) ? 'persist' : 'wake',\n ...(transitionMessage.role !== undefined ? { role: transitionMessage.role } : {}),\n },\n ],\n causalChain: nextChain,\n now: new Date(),\n });\n if (queued.status === 'missing') return;\n if (queued.status === 'stale') {\n throw new Error('Factory transition message was not queued: the work item changed concurrently.');\n }\n const queuedStatus = (queued.result as { status?: string }).status;\n if (queuedStatus !== 'accepted') {\n throw new Error(`Factory transition message was not queued: ${queuedStatus ?? 'unknown'}.`);\n }\n }\n\n /**\n * Moves a card where the project's intake routes send it on a status event. A move into a\n * working or resting phase waits for the run in flight on the card to end, going back to the\n * queue without holding a dispatch slot until it has; a move into a\n * terminal phase does not, so terminal cleanup stops that run at once, as a close always has.\n * A close moves only an unfinished card and a reopen only a finished one. When no route on the\n * card's board handles the event at all, the rule's own move (a board's `sourceClosed` phase)\n * applies instead; when one does but none matches, the card stays. A route's move is a system\n * move by the route: recorded in the card's history and audit, keyed so a replayed delivery\n * moves nothing twice.\n */\n async #routeEvent(\n record: FactoryDeferredDecisionRecord,\n event: BoardEventFacts,\n causalChain: FactoryRuleCausalEntry[],\n fallback?: Extract<FactoryCommitDecision, { type: 'transition' }>,\n ): Promise<void> {\n const identity = eventRouteIngress(record.idempotencyKey);\n if (await this.#storage.getTransitionResultByIngress(record.orgId, record.factoryProjectId, identity)) return;\n if (await this.#statusEventOvertaken(record)) throw new FactoryDecisionSuperseded();\n const resolve = async () => {\n const item = await this.#requireItem(record);\n const boards = await this.#boards.load(record);\n const board = boards.get(boardForWorkItem(item));\n if (!board) return undefined;\n const routes = this.#intakeRoutes\n ? await this.#intakeRoutes.listIntakeRoutes({ orgId: record.orgId, factoryProjectId: record.factoryProjectId })\n : [];\n const skipped: SkippedEventRoute[] = [];\n const plan = planEventMove({\n routes,\n event,\n item,\n registry: boards,\n ...(fallback && { fallback: { stage: fallback.stage } }),\n onSkip: skip => skipped.push(skip),\n });\n await this.#logSkippedRoutes(record, item, event, skipped);\n if (plan.outcome === 'rule_default') return { item, board, fallback: true as const };\n if (plan.outcome !== 'moves') return undefined;\n return { item, board, route: plan.move, target: boards.get(plan.move.board)! };\n };\n const first = await resolve();\n if (!first) return;\n if ('fallback' in first) {\n if (fallback) await this.#applyTransition(record, fallback, causalChain);\n return;\n }\n // Checked again on the next claim: the card may have moved, or the routes changed, by then.\n if (!first.target.isTerminal(first.route.phase) && (await this.#cardRunInFlight(record, first.item))) {\n throw new FactoryDecisionPostponed();\n }\n const { item, board, route } = first;\n const crossesBoards = route.board !== board.id;\n const result = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: item.id,\n board: board.id,\n ...(crossesBoards ? { toBoard: route.board } : {}),\n stage: route.phase,\n expectedRevision: item.revision,\n actor: { type: 'system', id: `intake-route:${route.routeId}` },\n ingress: { type: 'rule', identity },\n cause: 'event_route',\n causalChain,\n eventRoute: { routeId: route.routeId },\n // The rule owns the move; a run the destination queues on an outside author's pull\n // request event still waits for a person, whether the card is the pull request's own\n // or an issue's it links to.\n ...(untrustedPullRequestEvent(event) ? { untrustedPullRequestEvent: true } : {}),\n });\n // A refusal is the card's answer (recorded on it); only a lost revision race is worth a retry.\n if (result.status === 'rejected' && result.code === 'stale')\n throw new FactoryRuleRejectedError(result.code, result.reason);\n // Work the old board proposed for the card is not the new board's to run; what the move queued\n // for the new board stays, even once another worker has parked it as a proposal.\n if (result.status === 'accepted' && crossesBoards) {\n await this.#storage.supersedeDecisionsForWorkItem({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: item.id,\n except: result.decisions.map(decision => String(decision.idempotencyKey)),\n supersededAt: new Date(),\n });\n }\n }\n\n /**\n * Whether the card's session has a run in flight. A binding with no recorded owner never\n * started a run, so it has none.\n */\n async #cardRunInFlight(record: FactoryDeferredDecisionRecord, item: Pick<Card, 'sessions'>): Promise<boolean> {\n const binding = await this.#findBinding(record);\n const startedBy = binding ? item.sessions[binding.role]?.startedBy : undefined;\n if (!binding || !startedBy) return false;\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#findSession(binding, { userId: startedBy, orgId: record.orgId });\n return session !== undefined && (await this.#hasRunInFlight(session, binding));\n }\n\n /**\n * The one update event an update decision stands for, or undefined when it has nothing to do.\n * Updates to the same card of the same kind (work item or pull request, the card's own session\n * or anyone else) and to the same pull request fold into the newest one: an older one gives way to it, and the newest carries\n * the net change of every one since the group last moved the card, so a label added then removed\n * nets out. The newest waits until no update has arrived for {@link UPDATE_BURST_MS}, and one\n * from the card's own session also until the session's run ends.\n */\n async #foldUpdates(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'routeEvent' }>,\n now: Date,\n ): Promise<BoardEventFacts | undefined> {\n if (!record.workItemId) return undefined;\n const group = updateGroup(\n await this.#storage.listDeferredDecisions(record.orgId, record.factoryProjectId, {\n workItemId: record.workItemId,\n }),\n decision,\n );\n const { superseded, since, event } = await foldUpdate(group, record.id, other =>\n this.#moveCommitted(record, other),\n );\n // A newer update not given up on carries this one's change: it folded it, or will.\n if (superseded) throw new FactoryDecisionSuperseded();\n // An older one still leased may be moving the card right now, so wait for it. One claimed in\n // the same batch as this one (same owner, same lease, before any renewal) sees this one and\n // gives way. Lease renewal rewrites `updatedAt`, so it can't tell when the older one was claimed.\n const sameClaim = (other: FactoryDeferredDecisionRecord) =>\n other.leaseOwner === record.leaseOwner && other.leaseExpiresAt?.getTime() === record.leaseExpiresAt?.getTime();\n if (since.some(other => other.status === 'leased' && !sameClaim(other))) {\n throw new FactoryDecisionPostponed();\n }\n const quietAt = record.createdAt.getTime() + UPDATE_BURST_MS;\n if (now.getTime() < quietAt) throw new FactoryDecisionPostponed(new Date(quietAt));\n if (decision.fromCardSession) {\n const item = await this.#requireItem(record);\n if (await this.#cardRunInFlight(record, item)) throw new FactoryDecisionPostponed();\n }\n return event;\n }\n\n /** Whether `other`'s card move committed, even if its decision never finished. */\n async #moveCommitted(record: FactoryDeferredDecisionRecord, other: FactoryDeferredDecisionRecord): Promise<boolean> {\n const identity = eventRouteIngress(other.idempotencyKey);\n return Boolean(await this.#storage.getTransitionResultByIngress(record.orgId, record.factoryProjectId, identity));\n }\n\n /**\n * Whether a later status event was queued for the same card: the source's last word wins, so a\n * close still queued when the issue is reopened moves nothing. Of events queued in the same\n * millisecond, the one with the greatest id is the last; one already settled had its turn.\n */\n async #statusEventOvertaken(record: FactoryDeferredDecisionRecord): Promise<boolean> {\n if (!record.workItemId || !isStatusEventDecision(record.decision)) return false;\n const decisions = await this.#storage.listDeferredDecisions(record.orgId, record.factoryProjectId, {\n workItemId: record.workItemId,\n });\n return decisions.some(\n other =>\n other.id !== record.id &&\n isStatusEventDecision(other.decision) &&\n (other.createdAt.getTime() > record.createdAt.getTime() ||\n (other.createdAt.getTime() === record.createdAt.getTime() &&\n other.completedAt === null &&\n other.id > record.id)),\n );\n }\n\n async #requireItem(record: FactoryDeferredDecisionRecord) {\n if (!record.workItemId) throw new Error('Factory decision is not linked to a work item.');\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n if (!item) throw new Error('Factory work item not found.');\n return item;\n }\n\n async #findBinding(\n record: FactoryDeferredDecisionRecord,\n role?: string,\n ): Promise<FactoryRunBindingRecord | undefined> {\n if (!record.workItemId) throw new Error('Factory decision is not linked to a work item.');\n const bindings = await this.#storage.listRunBindings(record.orgId, record.factoryProjectId, record.workItemId);\n const active = bindings.filter(\n candidate => candidate.status === 'active' && (role === undefined || candidate.role === role),\n );\n // Without a role, the builder's session answers for the card: it owns the work.\n let builder: string | undefined;\n if (role === undefined && active.length > 1) {\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n builder = item ? cardBoardFlow(await this.#boards.load(record), item).buildRole : undefined;\n }\n return active.sort((left, right) => {\n if (builder !== undefined && left.role === builder && right.role !== builder) return -1;\n if (builder !== undefined && right.role === builder && left.role !== builder) return 1;\n return right.createdAt.getTime() - left.createdAt.getTime() || left.id.localeCompare(right.id);\n })[0];\n }\n\n async #requireBinding(record: FactoryDeferredDecisionRecord, role?: string): Promise<FactoryRunBindingRecord> {\n const binding = await this.#findBinding(record, role);\n if (!binding) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n role ? `No active Factory binding for role ${role}.` : 'No active Factory binding.',\n );\n }\n return binding;\n }\n\n /**\n * Points the card's live session at new activity on its source. The message\n * is written here from the decision's pointers, never from provider text.\n * Activity while the session is busy waits as one pending notification per\n * card and kind of activity, counting how many arrived; an idle session is\n * woken unless the decision asks to only persist. A card nobody is working\n * has nobody to tell, so it is dropped.\n */\n async #signalActivity(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'signalActivity' }>,\n ): Promise<void> {\n if (!record.workItemId) return;\n const binding = await this.#findBinding(record);\n if (!binding) return;\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const author = decision.author\n ? `@${decision.author}${decision.authorTrusted ? '' : ' (untrusted author)'}`\n : decision.authorTrusted\n ? undefined\n : 'an untrusted author';\n const message =\n decision.event === 'work_item.commented'\n ? `New comment${author ? ` by ${author}` : ''} on ${decision.reference}: ${decision.url}`\n : `${decision.reference} was edited${author ? ` by ${author}` : ''}: ${decision.url}`;\n // An untrusted author never starts a run, nor does a source that can't tell Factory's own\n // comments apart. Core never wakes a thread for a low-priority notification on any path;\n // a medium one can still wake it through a summary if the busy run ends mid-delivery.\n const wakes = decision.authorTrusted && decision.idleBehavior !== 'persist';\n await awaitNotification(() =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'source-activity',\n summary: message,\n priority: wakes ? 'medium' : 'low',\n sourceId: record.id,\n dedupeKey: record.idempotencyKey,\n coalesceKey: `${record.workItemId}:${decision.event}`,\n },\n {\n ifActive: { behavior: 'persist' },\n ifIdle: { behavior: wakes ? 'wake' : 'persist' },\n requestContext: factoryRequestContext({ session, binding, userId: startedBy, orgId: record.orgId }),\n },\n ),\n );\n }\n\n async #messageBinding(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'sendMessage' }>,\n ): Promise<FactoryRunBindingRecord | undefined> {\n if (decision.prepareBinding && decision.role !== undefined) {\n return this.#requireOrPrepareBinding(record, decision.role);\n }\n return this.#findBinding(record, decision.role);\n }\n\n /**\n * A role is superseded when its binding was revoked by a later role taking\n * the same session (`prepareRunBinding` revokes every other active binding on\n * that session). Only a hand-on — the running agent or a person moving the\n * card — produces that shape, so the role's job is done: its decision is not\n * owed a retry, and whatever ends the shared turn afterwards belongs to the\n * successor's decision. A revoke with no successor (terminal cleanup, an\n * operator pulling the seat) is not supersession and still fails as before.\n * Only a hand-on that happened after this decision was queued counts: a\n * fresh decision for the role (the card came back to it) must still dispatch\n * even though an older revoked binding for that role is on record.\n */\n async #decisionOvertaken(record: FactoryDeferredDecisionRecord, role: string): Promise<boolean> {\n if (!record.workItemId) return false;\n const [item, siblings] = await Promise.all([\n this.#storage.get({ orgId: record.orgId, id: record.workItemId }),\n this.#storage.listDecisionsForEvaluations(record.orgId, record.factoryProjectId, [record.evaluationId]),\n ]);\n return decisionOvertaken({ boards: await this.#boards.load(record), item, record, role, siblings });\n }\n\n async #roleSuperseded(record: FactoryDeferredDecisionRecord, role: string): Promise<boolean> {\n if (!record.workItemId) return false;\n const bindings = await this.#storage.listRunBindings(record.orgId, record.factoryProjectId, record.workItemId);\n const own = bindings.filter(candidate => candidate.role === role);\n // An active seat for this role still runs — a terminal card can legitimately\n // hold one (e.g. a close-out skill dispatched on `done`).\n if (own.some(candidate => candidate.status === 'active')) return false;\n // With no active seat left, a card that has already reached a terminal stage\n // can never mint one for this role again, and its bindings are being revoked\n // out from under the run by terminal-stage cleanup. Treat the decision as\n // superseded so it stops retrying to MAX_ATTEMPTS as `session_unavailable`.\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId }).catch(() => null);\n if (item && workItemPhaseSemantics(await this.#boards.load(record), item)?.kind === 'terminal') return true;\n return own.some(\n revoked =>\n revoked.revokedAt !== null &&\n revoked.revokedAt.getTime() >= record.createdAt.getTime() &&\n bindings.some(\n successor =>\n successor.role !== role &&\n successor.status === 'active' &&\n successor.resourceId === revoked.resourceId &&\n successor.sessionId === revoked.sessionId &&\n successor.threadId === revoked.threadId &&\n successor.createdAt.getTime() >= revoked.revokedAt!.getTime(),\n ),\n );\n }\n\n async #requireOrPrepareBinding(\n record: FactoryDeferredDecisionRecord,\n role: string,\n expectedBindingId?: string,\n ): Promise<FactoryRunBindingRecord> {\n const binding = await this.#findBinding(record, role);\n if (expectedBindingId && binding?.id !== expectedBindingId) {\n return this.#sameRoleReplacement(record, role, expectedBindingId);\n }\n if (binding) {\n const session = await this.#controller.getSession(binding.sessionId);\n if (session) return binding;\n }\n if (!this.#prepareBinding) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n binding ? 'Bound Factory session not found.' : `No active Factory binding for role ${role}.`,\n );\n }\n const item = await this.#requireItem(record);\n try {\n await this.#prepareBinding({ record, item, role, expectedBindingId });\n } catch (error) {\n if (error instanceof FactoryRunBindingSupersededError) {\n if (expectedBindingId) return this.#sameRoleReplacement(record, role, expectedBindingId);\n throw new FactoryDecisionSuperseded();\n }\n throw error;\n }\n return this.#requireBinding(record, role);\n }\n\n async #sameRoleReplacement(\n record: FactoryDeferredDecisionRecord,\n role: string,\n expectedBindingId: string,\n ): Promise<FactoryRunBindingRecord> {\n const replacement = await this.#findBinding(record, role);\n if (\n !replacement ||\n replacement.id === expectedBindingId ||\n (await this.#roleSuperseded(record, role)) ||\n (await this.#decisionOvertaken(record, role))\n ) {\n throw new FactoryDecisionSuperseded();\n }\n if (!(await this.#controller.getSession(replacement.sessionId))) {\n throw new FactoryDispatchError('session_unavailable', 'Bound Factory session not found.');\n }\n return replacement;\n }\n\n async #findSession(\n binding: FactoryRunBindingRecord,\n owner: SessionOwner,\n ): Promise<BoundDispatcherSession | undefined> {\n const session = await this.#controller.getSession(binding.sessionId);\n if (!session) return undefined;\n await this.#switchThread(session, binding, owner);\n return session;\n }\n\n /**\n * The tool whose pauses the run answers itself: the exit tool of the card's phase, where the\n * board approves it without a person for this card. Any other pause waits for a person.\n */\n async #autoApprovedExitTool({\n orgId,\n factoryProjectId,\n workItemId,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string | null;\n }): Promise<string | undefined> {\n const item = workItemId ? await this.#storage.get({ orgId, id: workItemId }) : null;\n return item ? autoApprovedExitTool(await this.#boards.load({ orgId, factoryProjectId }), item) : undefined;\n }\n\n /** Whether a run this dispatcher watches is about to approve `toolCallId` itself, so no person needs asking. */\n autoApproves(toolCallId: string): boolean {\n return this.#autoApproving.has(toolCallId);\n }\n\n /**\n * Whether a run is in flight on any of the card's active seats, as the board shows it: a run the\n * registry here holds on a seat's thread, whoever started it, or one live on another dispatcher.\n * A read-only probe: it never switches a session's thread.\n */\n async hasRunInFlightOnCard({\n orgId,\n factoryProjectId,\n workItemId,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n }): Promise<boolean> {\n const bindings = (await this.#storage.listRunBindings(orgId, factoryProjectId, workItemId)).filter(\n binding => binding.status === 'active',\n );\n const liveThreads = new Set(this.#controller.listActiveThreadRuns().map(active => active.threadId));\n for (const binding of bindings) {\n if (liveThreads.has(binding.threadId)) return true;\n const session = await this.#controller.getSession(binding.sessionId);\n if (session && (await this.#hasRunInFlight(session, binding))) return true;\n }\n return false;\n }\n\n /**\n * Whether a run is in flight on `binding`: live here, or live on another dispatcher. An open-run\n * entry with nothing live behind it is an orphan of a dead process and does not count. Reads the\n * binding's own thread, which the session may have switched away from.\n */\n async #hasRunInFlight(session: BoundDispatcherSession, binding: FactoryRunBindingRecord): Promise<boolean> {\n const open = (await listThreadOpenRuns(session, binding.threadId)).filter(entry => entry.bindingId === binding.id);\n if (open.some(entry => isOpenRunLiveElsewhere(entry, this.#ownerId))) return true;\n // A run with no ledger entry (one the dispatcher didn't record) is still live here.\n return this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId);\n }\n\n /** Waits for the run in flight on `binding` to end, so a kickoff never overlaps it. */\n async #waitForOpenRun(session: BoundDispatcherSession, binding: FactoryRunBindingRecord, label: string) {\n const runStillActive = () =>\n this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId);\n // Only a *live* run on this binding can be duplicated by a second\n // kickoff, so that is the only thing worth waiting on. The open-run\n // ledger is shared by every replica, but the run registry is local, so\n // an entry with nothing live here is one of two things:\n // - live on another replica (fresh heartbeat from another owner):\n // hand the decision back to retry, since that owner will clear the\n // entry and only it can observe the run end;\n // - an orphan (stale or missing heartbeat): the run died with its\n // process and no `agent_end` will ever clear it. Waiting would\n // wedge the binding for good; the next observed run end sweeps it.\n while (true) {\n const openRun = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n label,\n runStillActive,\n });\n try {\n const open = (await listSessionOpenRuns(session)).filter(entry => entry.bindingId === binding.id);\n if (open.length === 0) break;\n if (open.some(entry => isOpenRunLiveElsewhere(entry, this.#ownerId))) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Factory binding ${binding.id} has a run in flight on another dispatcher.`,\n );\n }\n if (!runStillActive()) break;\n if (!(await openRun.wait())) break;\n } finally {\n openRun.close();\n }\n await waitForSessionRunAudit(session);\n }\n }\n\n async #requireSession(binding: FactoryRunBindingRecord, owner: SessionOwner): Promise<BoundDispatcherSession> {\n const session = await this.#findSession(binding, owner);\n if (!session) throw new FactoryDispatchError('session_unavailable', 'Bound Factory session not found.');\n return session;\n }\n\n // Switching subscribes to the thread, which resolves memory and model\n // credentials, so it always runs as the session owner.\n async #switchThread(\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n owner: SessionOwner,\n ): Promise<void> {\n if (session.thread.requireId() === binding.threadId) return;\n const requestContext = factoryRequestContext({ session, binding, userId: owner.userId, orgId: owner.orgId });\n await session.thread.switch({ threadId: binding.threadId, requestContext });\n }\n\n async #withBindingSkillRun(bindingId: string, effect: () => Promise<void>): Promise<void> {\n const previous = this.#bindingSkillRuns.get(bindingId);\n const run = (previous ?? Promise.resolve()).catch(() => {}).then(effect);\n this.#bindingSkillRuns.set(bindingId, run);\n try {\n await run;\n } finally {\n if (this.#bindingSkillRuns.get(bindingId) === run) this.#bindingSkillRuns.delete(bindingId);\n }\n }\n\n async #withLease(\n renew: (leaseExpiresAt: Date) => Promise<unknown | null>,\n effect: () => Promise<void>,\n ): Promise<void> {\n let renewalFailure: unknown;\n let renewal = Promise.resolve();\n const timer = setInterval(\n () => {\n renewal = renewal.then(async () => {\n try {\n const renewed = await renew(new Date(Date.now() + LEASE_MS));\n if (!renewed) renewalFailure = new Error('Factory dispatch lease was lost during execution.');\n } catch (error) {\n renewalFailure = error;\n }\n });\n },\n Math.floor(LEASE_MS / 3),\n );\n timer.unref?.();\n try {\n await effect();\n await renewal;\n if (renewalFailure) throw renewalFailure;\n } finally {\n clearInterval(timer);\n await renewal;\n }\n }\n\n /** Keep this process's claim on an open run fresh for as long as it is watching the run. */\n async #withOpenRunHeartbeat<T>(\n session: BoundDispatcherSession,\n kickoffId: string,\n effect: () => Promise<T>,\n ): Promise<T> {\n if (!this.#audit) return effect();\n const timer = setInterval(\n () => void heartbeatSessionOpenRun(session, kickoffId),\n Math.floor(FACTORY_OPEN_RUN_STALE_MS / 3),\n );\n timer.unref?.();\n try {\n return await effect();\n } finally {\n clearInterval(timer);\n }\n }\n\n /**\n * An unreadable stop counts as a stop: retrying would clear the marker and restart a run a person\n * may have just stopped, while a wrongly settled run only leaves the card idle until started again.\n */\n async #runStopRequested(orgId: string, bindingId: string): Promise<boolean> {\n try {\n return await this.#storage.runBindingStopRequested({ orgId, bindingId });\n } catch (error) {\n console.warn(\n `[factory] could not read the stop request for binding ${bindingId}; treating the run as stopped:`,\n error,\n );\n return true;\n }\n }\n\n /**\n * Settle a watched run; when it fails terminally, tell the item's followers.\n * A retryable failure says nothing, since the retry reports. How a run that\n * ran ends (done, blocked, an error) is reported by the session's own\n * listener; this covers failures no run end shows. The reporter skips\n * recipients that already have a final report from this run, and never\n * throws, so reporting can't change the decision's outcome.\n */\n async #reportingRunEnd(\n {\n binding,\n startedBy,\n since,\n attempts,\n superseded,\n }: {\n binding: FactoryRunBindingRecord;\n startedBy: string;\n since: Date;\n attempts: number;\n superseded?: () => Promise<boolean>;\n },\n settle: () => Promise<void>,\n ): Promise<void> {\n try {\n await settle();\n } catch (error) {\n const reportRunEnd = this.#reportRunEnd;\n if (\n reportRunEnd &&\n !(error instanceof RunEndedInError) &&\n !(error instanceof FactoryDecisionSuperseded) &&\n !(await superseded?.())\n ) {\n const failureCode = factoryDispatchFailureCode(error);\n if (isTerminalFailure(attempts, failureCode)) {\n void reportRunEnd({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n role: binding.role,\n sender: { sessionId: binding.sessionId, threadId: binding.threadId, userId: startedBy },\n since,\n outcome: { status: 'failed', failureCode, reason: sanitizeDispatchError(error) },\n }).catch(reportError => {\n console.warn(`[factory] run-end report failed for binding ${binding.id}:`, reportError);\n });\n }\n }\n throw error;\n }\n }\n\n async #recordRunStart(\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n kickoffId: string,\n approvedBy: string | undefined,\n observedEnd: ReturnType<typeof watchRun>['endReason'],\n workItemName: string | undefined,\n ): Promise<void> {\n if (!this.#audit) return;\n const humanApproved = isHumanActorId(approvedBy);\n await recordSessionRunStart(session, {\n audit: this.#audit,\n actorType: humanApproved ? 'human' : 'system',\n observedEnd,\n run: {\n kickoffId,\n ownerId: this.#ownerId,\n heartbeatAt: Date.now(),\n bindingId: binding.id,\n role: binding.role,\n startedBy: humanApproved ? approvedBy : 'factory-rule-dispatcher',\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n workItemName,\n sessionId: binding.sessionId,\n threadId: binding.threadId,\n branch: binding.branch,\n },\n });\n }\n\n async #dispatchPendingStart(record: FactoryPendingStartRecord, now: Date): Promise<void> {\n try {\n await this.#withLease(\n async leaseExpiresAt =>\n this.#storage.renewPendingStartLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),\n async () => {\n if (record.message === null) return;\n const bindings = await this.#storage.listRunBindings(record.orgId, record.factoryProjectId);\n const binding = bindings.find(\n candidate => candidate.id === record.bindingId && candidate.status === 'active',\n );\n if (!binding) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n 'Prepared Factory binding is unavailable or revoked.',\n );\n }\n // Wake runs build the Factory workspace, which requires the\n // authenticated session owner on the request context.\n const item = await this.#storage.get({ orgId: record.orgId, id: binding.workItemId });\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const requestContext = factoryRequestContext({\n session,\n binding,\n userId: startedBy,\n orgId: record.orgId,\n });\n // The run's own verdict, not the delivery's: a kickoff delivered\n // into a run that is already terminating is consumed without\n // execution, and completing the pending start on the delivery ack\n // alone strands the card with a success ledger entry.\n const since = new Date();\n const stopRequested = () => this.#runStopRequested(record.orgId, binding.id);\n const run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n autoApprovedTool: await this.#autoApprovedExitTool({ ...record, workItemId: binding.workItemId }),\n autoApproving: this.#autoApproving,\n requestContext,\n label: 'Factory kickoff run',\n runStillActive: () =>\n this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId),\n stopRequested,\n });\n const sendKickoff = async (dedupeKey: string) => {\n await this.#storage.clearRunBindingStopRequest({ orgId: record.orgId, bindingId: binding.id });\n return awaitNotification(\n () =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'run-kickoff',\n summary: record.message!,\n priority: 'high',\n payload: { message: record.message },\n sourceId: record.id,\n dedupeKey,\n },\n { ifActive: { behavior: 'deliver' }, ifIdle: { behavior: 'wake' }, requestContext },\n ),\n true,\n );\n };\n try {\n let settled = await sendKickoff(`factory-kickoff:${record.kickoffKey}`);\n let deliveryGeneration = 0;\n while (settled?.action === 'deliver') {\n // `deliver` only proves the signal was queued onto a run already\n // in flight. If that run ends without draining its queue the\n // kickoff is dropped silently. Another run can start while the\n // previous one is finishing, so follow every run boundary until\n // the kickoff wakes an idle session. The generation-scoped\n // dedupeKey defeats inbox dedupe and the kickoff key keeps a\n // duplicate run bounded, while a dropped kickoff strands the card.\n if (!(await run.wait())) {\n throw new Error('Factory kickoff is waiting on a run that has not ended.');\n }\n if (await stopRequested()) throw new FactoryRunStopped();\n run.arm();\n deliveryGeneration += 1;\n settled = await sendKickoff(\n `factory-kickoff:${record.kickoffKey}:retry:${record.attempts}:${deliveryGeneration}`,\n );\n }\n await this.#recordRunStart(\n session,\n binding,\n `factory-kickoff:${record.kickoffKey}:${record.attempts}`,\n startedBy,\n run.endReason,\n item?.title,\n );\n await this.#reportingRunEnd({ binding, startedBy, since, attempts: record.attempts }, () => run.settle());\n } finally {\n run.close();\n }\n },\n );\n const completed = await this.#storage.completePendingStart(leaseIdentity(record, this.#ownerId), new Date());\n if (!completed) throw new Error('Factory kickoff lease was lost before completion.');\n } catch (error) {\n // The kickoff started its run; retrying would undo the stop.\n if (error instanceof FactoryRunStopped) {\n await this.#storage.completePendingStart(leaseIdentity(record, this.#ownerId), new Date());\n return;\n }\n const failureCode = factoryDispatchFailureCode(error);\n await this.#storage.failPendingStart({\n ...leaseIdentity(record, this.#ownerId),\n now: new Date(),\n availableAt: retryAt(now, record.attempts),\n lastError: sanitizeDispatchError(error),\n failureCode,\n terminal: isTerminalFailure(record.attempts, failureCode),\n });\n }\n }\n}\n\nexport const FACTORY_DISPATCH_CONSTANTS = {\n leaseMs: LEASE_MS,\n pollMs: POLL_MS,\n batchSize: BATCH_SIZE,\n maxAttempts: MAX_ATTEMPTS,\n maxErrorLength: MAX_ERROR_LENGTH,\n maxBackoffMs: MAX_BACKOFF_MS,\n skillCompletionObservationTimeoutMs: SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS,\n runRegistryHeartbeatMs: RUN_REGISTRY_HEARTBEAT_MS,\n openRunStaleMs: FACTORY_OPEN_RUN_STALE_MS,\n maxInFlight: MAX_IN_FLIGHT,\n reviewStatusTimeoutMs: REVIEW_STATUS_TIMEOUT_MS,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,MAAM,WAAW;;AAEjB,MAAM,2BAA2B;AAIjC,MAAM,UAAU;AAIhB,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,eAAe;AAIrB,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AAGvB,MAAM,4BAA4B;AAGlC,MAAM,0CA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IAAI,WACJ,MAAM,KACR;KACA,MAAM,KAAK,iBAAiB;MAAE;MAAS;MAAW;MAAO,UAAU,OAAO;KAAS,SAAS,IAAI,OAAO,CAAC;IAC1G,UAAU;KACR,IAAI,MAAM;IACZ;GACF,CACF;GAEA,IAAI,CAAC,MADmB,KAAK,SAAS,qBAAqB,cAAc,QAAQ,KAAK,QAAQ,mBAAG,IAAI,KAAK,CAAC,GAC3F,MAAM,IAAI,MAAM,mDAAmD;EACrF,SAAS,OAAO;GAEd,IAAI,iBAAiB,mBAAmB;IACtC,MAAM,KAAK,SAAS,qBAAqB,cAAc,QAAQ,KAAK,QAAQ,mBAAG,IAAI,KAAK,CAAC;IACzF;GACF;GACA,MAAM,cAAc,2BAA2B,KAAK;GACpD,MAAM,KAAK,SAAS,iBAAiB;IACnC,GAAG,cAAc,QAAQ,KAAK,QAAQ;IACtC,qBAAK,IAAI,KAAK;IACd,aAAa,QAAQ,KAAK,OAAO,QAAQ;IACzC,WAAW,sBAAsB,KAAK;IACtC;IACA,UAAU,kBAAkB,OAAO,UAAU,WAAW;GAC1D,CAAC;EACH;CACF;AACF;AAEA,MAAa,6BAA6B;CACxC,SAAS;CACT,QAAQ;CACR,WAAW;CACX,aAAa;CACb,gBAAgB;CAChB,cAAc;CACd,qCAAqC;CACrC,wBAAwB;CACxB,gBAAgB;CAChB,aAAa;CACb,uBAAuB;AACzB"}
|
|
1
|
+
{"version":3,"file":"dispatcher.js","names":[],"sources":["../../src/rules/dispatcher.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController, AgentControllerEventListener, Session } from '@mastra/core/agent-controller';\nimport { classifyProviderError } from '@mastra/core/error';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { GoalObjectiveRecord } from '@mastra/core/storage';\nimport type { SubmitPlanResumeData } from '@mastra/core/tools';\n\nimport { isUpdateEvent } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport { cardRuleFacts } from '../boards/card-facts.js';\nimport {\n boardFlow,\n boardForWorkItem,\n cardBoardFlow,\n hasPullRequest,\n isPullRequestCard,\n isTerminalWorkItem,\n isOpenPullRequestSource,\n pullRequestSources,\n pullRequestTrustKey,\n resolvePhaseSemantics,\n REVIEW_CONTEXT,\n reviewsPullRequest,\n trustedPullRequestSource,\n UNTRUSTED_PULL_REQUESTS_KEY,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport {\n arrivalRuleFacts,\n closedIssueRuleFacts,\n INTAKE_ROUTE_METADATA_KEY,\n placedByIntakeRoute,\n planEventMove,\n resolveIntake,\n resumeLandingPhase,\n projectIntakeEvaluator,\n ROUTE_AGAIN_KEY_PREFIX,\n untrustedPullRequestEvent,\n} from '../boards/intake-routing.js';\nimport type { IntakeRoutesReader, SkippedEventRoute } from '../boards/intake-routing.js';\nimport { autoApprovedExitTool, startsInAutoPhase } from '../boards/phase-automation.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { moveCardToBoard } from '../boards/relocate.js';\nimport {\n FACTORY_OPEN_RUN_STALE_MS,\n heartbeatSessionOpenRun,\n isOpenRunLiveElsewhere,\n listSessionOpenRuns,\n listThreadOpenRuns,\n recordSessionRunStart,\n waitForSessionRunAudit,\n} from '../session/run-audit.js';\nimport { sessionHoldsWork } from '../session/session-unloader.js';\nimport { resolvePromptInvocation, resolveSkillInvocation, resolveSkillResumeInvocation } from '../skills/service.js';\nimport type { SkillSession } from '../skills/service.js';\nimport { isHumanActorId } from '../storage/domains/audit/actors.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { IntakeEvaluator } from '../storage/domains/boards/base.js';\nimport {\n externalSourceKey,\n FACTORY_RULE_MATERIALIZATION_KEY,\n FactoryRunBindingSupersededError,\n WorkItemSourceConflictError,\n WorkItemUpdateConflictError,\n} from '../storage/domains/work-items/base.js';\nimport type {\n FactoryDecisionProvenance,\n FactoryDeferredDecisionRecord,\n FactoryDispatchFailureCode,\n FactoryPendingStartRecord,\n FactoryRunBindingRecord,\n Card,\n WorkItemsStorage,\n UpsertWorkItemResult,\n} from '../storage/domains/work-items/base.js';\nimport type { FactoryRunEndReporter } from '../tools/reports.js';\nimport { withWorkItemDescription } from '../work-items/description-context.js';\nimport { workItemProviderAdapter } from '../work-items/providers/index.js';\nimport { decisionOvertaken } from './decision-applicability.js';\nimport {\n FactoryDispatchError,\n factoryDispatchFailureCode,\n factoryDispatchFailureMetadata,\n FactoryRuleRejectedError,\n} from './dispatch-errors.js';\nimport { isStatusEventDecision } from './event-rules.js';\nimport { endPhaseGoal, PHASE_GOAL_METADATA_KEY, phaseGoalOf, startPhaseGoal } from './phase-goal.js';\nimport { causeOf, isProviderCallError, publicFailureReason } from './public-failure-reason.js';\nimport { isRunBearingDecision } from './run-bearing.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport type { FactoryCommitDecision, FactoryRuleActor, FactoryRuleCausalEntry } from './types.js';\nimport { authorTrusted, externalSourceForWorkItem, workItemSource } from './types.js';\nimport { eventRouteIngress, foldUpdate, updateGroup } from './update-fold.js';\nimport {\n assertFactoryDecisionTarget,\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n validateFactoryRuleDecision,\n} from './validation.js';\n\nconst LEASE_MS = 30_000;\n/** How long the run waits on a status-comment write; well inside one lease so a slow provider never costs the claim. */\nconst REVIEW_STATUS_TIMEOUT_MS = 10_000;\n// Cadence while dispatches are in flight or a cycle filled its batch. An idle\n// dispatcher does not poll: it sleeps until the next row becomes claimable or\n// a write wakes it.\nconst POLL_MS = 1_000;\n// Safety net for an idle dispatcher: a wake lost in transit (a pubsub outage, a\n// write from a process that does not publish) is picked up within this window.\n// Well above Neon's 5-minute autosuspend so an idle database still sleeps.\nconst IDLE_RECHECK_MS = 60 * 60_000;\nconst BATCH_SIZE = 10;\nconst MAX_ATTEMPTS = 5;\n\n// Enough for a run that re-plans after reading its own approval, few enough\n// that an agent looping on submit_plan reaches a person instead of a bill.\nconst MAX_PLAN_APPROVALS = 3;\nconst MAX_ERROR_LENGTH = 512;\nconst MAX_BACKOFF_MS = 60_000;\n// A run the registry no longer shows never started or ended unobserved:\n// checked at this cadence, and failed for retry.\nconst RUN_REGISTRY_HEARTBEAT_MS = 10 * 60_000;\n// A run the registry still shows past this is a hang, not a slow run: failed\n// terminally so the lease and the in-flight slot come back.\nconst SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS = 6 * 60 * 60_000;\n// Dispatches can legitimately run for minutes. Woken skill invocations hold\n// capacity until their agent run reaches a terminal state; binding preparation\n// also runs detached from the poll loop under this concurrency cap.\nconst MAX_IN_FLIGHT = 10;\nconst isBookkeepingDecision = (decision: Record<string, unknown>): boolean => !isRunBearingDecision(decision);\n/**\n * A wake a person is waiting on: a reply a person sent on the card's pull\n * request or issue, which GitHub typed as a `User` (not an app or bot) with\n * write access, that Factory did not write itself, and that came straight from\n * the webhook rather than from a move or decision it caused. Everything else,\n * including actors with no record of being a person, stays automated.\n */\nexport const isInteractiveDecision = (\n decision: Record<string, unknown>,\n { actor, causalChain }: FactoryDecisionProvenance,\n): boolean =>\n (decision.type === 'sendMessage' || decision.type === 'signalActivity') &&\n decision.idleBehavior !== 'persist' &&\n causalChain.length === 0 &&\n actor?.type === 'github' &&\n actor.human === true &&\n actor.trusted === true &&\n actor.factoryAuthored === false;\nconst isAutomatedRunDecision = (decision: Record<string, unknown>, provenance: FactoryDecisionProvenance): boolean =>\n isRunBearingDecision(decision) && !isInteractiveDecision(decision, provenance);\nconst MAX_INTERACTIVE_IN_FLIGHT = 2;\nconst BOOKKEEPING_MAX_IN_FLIGHT = 4;\n// Staleness sweep: legacy/leaked active bindings (item deleted, transition\n// path bypassed, or pre-dating terminal-stage revocation) are revoked on a\n// slow cadence so the per-tick reconcile walk stays bounded.\nconst STALE_BINDING_SWEEP_INTERVAL_MS = 10 * 60_000;\nconst STALE_BINDING_TTL_MS = 24 * 60 * 60_000;\n// The bound-thread reconcile pass reads a cursor + messages per binding that\n// stepped recently (and every active binding on a much slower cadence); it\n// exists to catch results missed at run end, so it runs off the claim path\n// rather than on every 1s tick.\nconst RECONCILE_INTERVAL_MS = 30_000;\n\n/** The card moved on before this run could act; it settles as superseded, not succeeded. */\nclass FactoryDecisionSuperseded extends Error {}\n\n/**\n * A client stopped the run on purpose (Stop, Esc, /stop). Like a card that moved on, nothing is\n * left for the decision to do: it settles as superseded, neither failed nor retried.\n */\nclass FactoryRunStopped extends FactoryDecisionSuperseded {}\n\n/** The decision cannot act yet and did nothing: it goes back to the queue and is claimed again later. */\nclass FactoryDecisionPostponed extends Error {\n constructor(readonly availableAt?: Date) {\n super();\n }\n}\n\n/**\n * How long an update waits for more updates to the same card before its routes run: a burst of\n * label or assignee changes within this window becomes one event.\n */\nexport const UPDATE_BURST_MS = 5_000;\n\n// How often a decision that cannot act yet (a route move waiting on the card's run) is tried again.\nconst POSTPONE_MS = 10_000;\n\n/** A run that ran and ended in error; the session's own listener reports it to followers. */\nclass RunEndedInError extends FactoryDispatchError {}\n\n// The Mastra Code credential resolver's own failure; free text that merely mentions credentials does not count.\nconst CREDENTIAL_RESOLUTION_FAILURE = 'tenant model credential policy could not be resolved';\n// The resolver's reason when the request context has no user; it recurs on every retry of the same start.\nconst NO_AUTHENTICATED_USER = 'the request has no authenticated user';\n\nfunction httpStatus(error: unknown): number | undefined {\n if (!error || typeof error !== 'object') return undefined;\n if ('statusCode' in error && typeof error.statusCode === 'number') return error.statusCode;\n return 'status' in error && typeof error.status === 'number' ? error.status : undefined;\n}\n\nfunction runErrorCode(error: unknown, message: string): FactoryDispatchFailureCode {\n const lower = message.toLowerCase();\n if (lower.includes(CREDENTIAL_RESOLUTION_FAILURE)) {\n return lower.includes(NO_AUTHENTICATED_USER) ? 'run_user_unauthenticated' : 'run_credentials_unavailable';\n }\n const status = httpStatus(error) ?? httpStatus(causeOf(error));\n if (status === 401 || status === 403) return 'run_credentials_unavailable';\n const providerCall = isProviderCallError(error) || isProviderCallError(causeOf(error));\n return providerCall && classifyProviderError(error) === 'auth' ? 'run_credentials_unavailable' : 'run_failed';\n}\n\nfunction runErrorFailure(label: string, error: unknown): RunEndedInError {\n const cause = (error instanceof Error ? error.message : String(error ?? '')).trim();\n if (!cause) return new RunEndedInError('run_failed', `${label} ended in error.`, { cause: error });\n return new RunEndedInError(runErrorCode(error, cause), `${label} ended in error: ${cause}`, { cause: error });\n}\n\n/** A run in the review seat: a pull request review, unless it is the card's board's self-review. */\nfunction reviewSeatSkill(decision: unknown): { skillName?: unknown } | undefined {\n if (!decision || typeof decision !== 'object') return undefined;\n const value = decision as { type?: unknown; role?: unknown; skillName?: unknown };\n return value.type === 'invokeSkill' && value.role === REVIEW_CONTEXT ? value : undefined;\n}\n\n// Rescheduling a failure that can never succeed only delays the moment a person sees why.\nfunction isTerminalFailure(attempts: number, failureCode: FactoryDispatchFailureCode): boolean {\n const failure = factoryDispatchFailureMetadata(failureCode);\n return (\n attempts >= (failureCode === 'run_incomplete' ? 2 : MAX_ATTEMPTS) ||\n !failure.canRetry ||\n failure.autoRetry === false\n );\n}\n\n/**\n * Conservative check for observational-memory failures that a retry cannot fix:\n * a provider rejecting the request outright (HTTP 400 / model unsupported /\n * authentication). Anything ambiguous (timeouts, 5xx, rate limits, network\n * blips) is intentionally left retryable to avoid dead-ending a card that would\n * have recovered on its own.\n */\nfunction isPermanentProviderRejection(error: string): boolean {\n const normalized = error.toLowerCase();\n return (\n /\\bhttp(?:\\/\\d(?:\\.\\d)?)?\\s*400\\b/.test(normalized) ||\n /\\bstatus(?:\\s*code)?\\s*[:=]?\\s*400\\b/.test(normalized) ||\n /\\b400\\s*(?:bad request|status)\\b/.test(normalized) ||\n normalized.includes('model not supported') ||\n normalized.includes('model is not supported') ||\n normalized.includes('unsupported model') ||\n normalized.includes('not supported with') ||\n normalized.includes('unauthorized') ||\n normalized.includes('authentication') ||\n (normalized.includes('invalid') && normalized.includes('model'))\n );\n}\n\nfunction watchRun(\n session: Pick<DispatcherSession, 'subscribe' | 'respondToToolSuspension'>,\n {\n timeoutMs,\n autoApprovedTool,\n autoApproving,\n requestContext,\n onAgentEnd,\n label,\n runStillActive,\n stopRequested,\n }: {\n timeoutMs: number;\n /** The tool this run answers itself when it pauses on it; any other pause waits for a person. */\n autoApprovedTool?: string;\n /** Where the run says which paused calls it is about to answer. */\n autoApproving?: Set<string>;\n /** The run's own request context; resuming an approved plan resolves the session's workspace with it. */\n requestContext?: RequestContext;\n onAgentEnd?: () => Promise<boolean>;\n label: string;\n /** Level-triggered check against the run registry, consulted at every heartbeat the edge-triggered wait misses. */\n runStillActive: () => boolean;\n stopRequested?: () => Promise<boolean>;\n },\n) {\n let resolveAgentEnd!: () => void;\n let agentEnd!: Promise<void>;\n let endReason: 'complete' | 'aborted' | 'error' | 'suspended' | undefined;\n let supersededAtEnd: Promise<boolean> | undefined;\n let parked: { toolName: string; toolCallId: string } | undefined;\n let approvals = 0;\n const announced = new Set<string>();\n // Latest observational-memory failure seen on this run. The stream aborts the\n // run when observation/reflection fails, but the abort itself carries no\n // reason — so without this the true cause (e.g. a provider rejecting the OM\n // model) is lost and the abort is retried blindly.\n let omFailure: string | undefined;\n // The run's own error event precedes its `agent_end: 'error'` and is the only place the cause appears.\n let runError: unknown;\n // Re-armed before a redelivery so the second send waits on its own run's\n // ending rather than seeing the one that already resolved.\n const arm = () => {\n endReason = undefined;\n supersededAtEnd = undefined;\n omFailure = undefined;\n runError = undefined;\n agentEnd = new Promise<void>(resolve => {\n resolveAgentEnd = resolve;\n });\n };\n arm();\n const unsubscribe = session.subscribe(event => {\n if (event.type === 'agent_end') {\n endReason = event.reason;\n supersededAtEnd = onAgentEnd?.();\n resolveAgentEnd();\n return;\n }\n if (event.type === 'error') {\n runError = event.error;\n return;\n }\n if (event.type === 'om_observation_failed' || event.type === 'om_buffering_failed') {\n if (event.error) omFailure = event.error;\n return;\n }\n if (event.type === 'tool_suspended') {\n parked = { toolName: event.toolName, toolCallId: event.toolCallId };\n // Said before the run ends on it, so nobody is asked to answer what this run answers itself.\n if (event.toolName === autoApprovedTool && approvals < MAX_PLAN_APPROVALS) {\n announced.add(event.toolCallId);\n autoApproving?.add(event.toolCallId);\n }\n return;\n }\n if (event.type === 'tool_suspension_cancelled' && parked?.toolCallId === event.toolCallId) {\n parked = undefined;\n }\n });\n // Failing a run the registry still shows would kick off a duplicate into a busy session.\n const wait = async () => {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const heartbeatMs = Math.min(RUN_REGISTRY_HEARTBEAT_MS, deadline - Date.now());\n if (await waitForAgentEndOrTimeout(agentEnd, heartbeatMs)) return true;\n if (!runStillActive()) return false;\n }\n throw new FactoryDispatchError(\n 'run_overdue',\n `${label} is still in flight after ${Math.round(timeoutMs / 3_600_000)} hours and needs a person.`,\n );\n };\n\n return {\n arm,\n wait,\n supersededAtEnd: () => supersededAtEnd,\n endReason: () => endReason,\n /** The tool the run is parked on, when it ended suspended. */\n parked: () => parked,\n close: () => {\n // A watch that gives up answers nothing more, so its pauses wait for a person again.\n for (const toolCallId of announced) autoApproving?.delete(toolCallId);\n unsubscribe();\n },\n /** The run's own verdict, thrown as what the dispatcher should record. */\n async settle(): Promise<void> {\n let observed = await wait();\n // Past the cap the plan stays parked: the person it waits for sees it in the inbox.\n while (autoApprovedTool && parked?.toolName === autoApprovedTool && approvals < MAX_PLAN_APPROVALS) {\n const { toolCallId } = parked;\n parked = undefined;\n // Counted before the resumed run can pause again, so its next pause is judged against the cap.\n approvals += 1;\n arm();\n try {\n await session.respondToToolSuspension({ resumeData: { action: 'approved' }, toolCallId, requestContext });\n } finally {\n autoApproving?.delete(toolCallId);\n }\n observed = await wait();\n }\n if (!observed) {\n // A completed decision with no observed run end is exactly the\n // silent-stall failure mode: the card advances while nobody works it.\n // Delivery already began, so retrying with a fresh generation could\n // duplicate work whose terminal event was lost.\n throw new FactoryDispatchError(\n 'run_terminal_event_missing',\n `${label} terminal event was not observed before timeout.`,\n );\n }\n if (endReason === 'error') throw runErrorFailure(label, runError);\n if (endReason === 'aborted') {\n if (await stopRequested?.()) throw new FactoryRunStopped();\n // An abort that follows an observational-memory failure is not the\n // usual \"process went away\" case — the OM stream deliberately aborted\n // the run because observation/reflection failed. Surface that real\n // cause instead of the generic message, and when it is a permanent\n // provider/config rejection (e.g. the OM model is not accepted by the\n // account) fail terminally so retries stop hammering a run that can\n // never succeed until the configuration changes.\n if (omFailure) {\n if (isPermanentProviderRejection(omFailure)) {\n throw new FactoryDispatchError(\n 'run_configuration_invalid',\n `${label} was aborted by an observational-memory failure that will not succeed on retry: ${omFailure}`,\n );\n }\n throw new Error(`${label} was aborted after an observational-memory failure: ${omFailure}`);\n }\n // Nobody marked this run stopped, so the abort is the process going\n // away underneath it — an operator restarting the server. Treating\n // that as terminal dead-ends the card at attempt 1 with nothing on the\n // board to press. A spurious retry is bounded by MAX_ATTEMPTS.\n throw new Error(`${label} was aborted before it finished.`);\n }\n },\n };\n}\n\nfunction waitForAgentEndOrTimeout(agentEnd: Promise<void>, timeoutMs: number): Promise<boolean> {\n return new Promise(resolve => {\n const timeout = setTimeout(() => resolve(false), timeoutMs);\n timeout.unref?.();\n void agentEnd.then(() => {\n clearTimeout(timeout);\n resolve(true);\n });\n });\n}\n\ninterface SessionOwner {\n userId: string;\n orgId: string;\n}\n\ninterface FactoryNotificationResult {\n persisted?: Promise<unknown>;\n accepted?: Promise<{\n action?: string;\n output?: { consumeStream(): Promise<unknown> };\n }>;\n}\n\ninterface DispatcherSession extends SkillSession {\n thread: {\n switch(input: { threadId: string }): Promise<unknown>;\n listActiveMessages(): Promise<Array<{ id: string }>>;\n };\n stream: { isActive(): boolean };\n abort(): void;\n sendSignal(\n input: {\n id: string;\n type: 'user' | 'reactive';\n tagName: string;\n attributes?: { name: string };\n contents: string;\n },\n options: { requestContext: RequestContext; requireDelivery?: boolean },\n ): { accepted: Promise<{ accepted: true; runId?: string; action?: string }> };\n subscribe(listener: AgentControllerEventListener): () => void;\n respondToToolSuspension(input: {\n resumeData: SubmitPlanResumeData;\n toolCallId?: string;\n requestContext?: RequestContext;\n }): Promise<void>;\n}\n\ntype FactoryController = Pick<AgentController<MastraCodeState>, 'getSession' | 'listActiveThreadRuns'>;\ntype BoundDispatcherSession = Session<MastraCodeState>;\n\nfunction factoryRequestContext(input: {\n session: BoundDispatcherSession;\n binding: FactoryRunBindingRecord;\n userId: string;\n orgId: string;\n}): RequestContext {\n const { session, binding, userId, orgId } = input;\n const requestContext = new RequestContext();\n requestContext.set('user', { workosId: userId, organizationId: orgId });\n requestContext.set('controller', {\n state: session.state.get(),\n getState: () => session.state.get(),\n sessionId: binding.sessionId,\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modelId: session.model.get() ?? '',\n },\n workspace: session.getWorkspace(),\n });\n return requestContext;\n}\n\nexport interface FactoryBindingPreparationInput {\n record: FactoryDeferredDecisionRecord;\n item: Card;\n role: string;\n expectedBindingId?: string;\n}\n\nexport type FactoryReviewStatusPhase = 'queued' | 'reviewing' | 'retrying' | 'completed' | 'failed' | 'cancelled';\n\n/** One step of a review run, identified by the decision that started it. */\nexport interface FactoryReviewStatusEvent {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n run: string;\n requestedAt: Date;\n generation: number;\n attempt: number;\n phase: FactoryReviewStatusPhase;\n /** When the agent was handed the review; set on the 'reviewing' step. */\n startedAt?: Date;\n /** When the run ended; set on final steps. */\n endedAt?: Date;\n /** Why the run failed or will retry, already sanitized. */\n reason?: string;\n /** A final step for a run an earlier attempt started: the comment's recorded start still applies. */\n replayed?: true;\n}\n\nexport type FactoryReviewStatusReporter = (event: FactoryReviewStatusEvent) => Promise<void>;\n\nexport interface FactoryDecisionDispatcherOptions {\n audit?: AuditRecorder;\n controller: FactoryController;\n transitionService: Pick<FactoryTransitionService, 'transition' | 'configVersion'>;\n storage: WorkItemsStorage;\n /** Installed boards; defaults to the built-in Work and Review boards. */\n boards?: BoardRegistry | ProjectBoardSource;\n /** The project's intake routes, which place newly filed linked cards. Without it, decisions place cards as they say. */\n intakeRoutes?: IntakeRoutesReader;\n /** Forces an evaluator on every project; without it each project uses its own setting. */\n intakeEvaluator?: IntakeEvaluator;\n ownerId?: string;\n reconcileToolResults?: () => Promise<void>;\n reconcileRunBinding?: (binding: FactoryRunBindingRecord) => Promise<void>;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n /**\n * Told when a run fails terminally at dispatch, so whoever follows the item\n * hears about failures no run end covers. How runs end is reported by the\n * per-session listener (`observeSessionRunReports`). Never throws.\n */\n reportRunEnd?: FactoryRunEndReporter;\n /**\n * Told each step of a pull request review run: accepted, started, retrying,\n * and how it ended. Driven by the dispatcher rather than the agent, so a run\n * that crashes or is cancelled still reports its end. Must not throw.\n */\n reportReviewStatus?: FactoryReviewStatusReporter;\n /** Dismisses superseded Factory change requests on a GitHub pull request. */\n dismissStaleReviews?: (decision: Extract<FactoryCommitDecision, { type: 'dismissStaleReviews' }>) => Promise<void>;\n resolveLinkedWorkItemParentId?: (input: {\n orgId: string;\n factoryProjectId: string;\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>;\n }) => Promise<string | null>;\n /** `false` spends a linked-card decision unfiled: its Factory project was deleted after the decision committed. */\n factoryProjectExists?: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n maxInFlight?: number;\n /**\n * Run slots this process keeps for wakes a person is waiting on (see\n * `isInteractiveDecision`), on top of `maxInFlight`. Defaults to 2.\n */\n maxInteractiveInFlight?: number;\n /** How often the stale-binding sweep runs. Defaults to 10 minutes. */\n staleBindingSweepIntervalMs?: number;\n /** Active bindings older than this are revoked by the sweep. Defaults to 24 hours. */\n staleBindingTtlMs?: number;\n /** How often the bound-thread reconcile walk runs. Defaults to 30 seconds. */\n reconcileIntervalMs?: number;\n /**\n * How long a run the registry still shows in flight is observed before it fails as overdue. Defaults to 6 hours.\n * A run the registry no longer shows fails for retry at the next ten-minute heartbeat instead.\n */\n skillCompletionObservationTimeoutMs?: number;\n}\n\nfunction positiveMs(value: number | undefined, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;\n}\n\n// Provider and source-control key prefixes; run errors carry provider text verbatim.\nconst KEY_SHAPED_TOKEN =\n /\\b(?:sk-[A-Za-z0-9_-]{3,}|gh[pousr]_[A-Za-z0-9]{10,}|github_pat_[A-Za-z0-9_]{10,}|xox[abprs]-[A-Za-z0-9-]{10,})/g;\n\n// Mixed-case alphanumeric runs read as keys; lowercase hex SHAs, UUIDs, path segments and\n// hyphenated names such as branches stay readable.\nfunction looksLikeSecret(token: string): boolean {\n return /[A-Z]/.test(token) && /[a-z]/.test(token) && /\\d/.test(token) && /[A-Za-z0-9]{16,}/.test(token);\n}\n\n// Base64 keys can contain `/`. A `/`-joined token is redacted whole unless one of its pieces is a\n// plain word, which paths and branches nearly always have (`fix`, `cache`, `Users`, `Documents`);\n// those are redacted piece by piece instead.\nfunction redactSecretRun(token: string): string {\n if (looksLikeSecret(token) && !token.split('/').some(piece => /^[A-Za-z][a-z]+$/.test(piece))) return '[redacted]';\n return token.replace(/[A-Za-z0-9_+=-]{24,}/g, piece =>\n looksLikeSecret(piece) || isGroupedKey(piece) ? '[redacted]' : piece,\n );\n}\n\n// Keys printed in `-`/`_` groups (`x7Kp9-Qm2Rt-…`) have no long unbroken run, but every group mixes\n// upper, lower and digits; branch and identifier words such as `Parked-snapshot-lease2-loss` do not.\nfunction isGroupedKey(token: string): boolean {\n const groups = token.split(/[-_]/);\n return groups.length >= 4 && groups.every(group => /[A-Z]/.test(group) && /[a-z]/.test(group) && /\\d/.test(group));\n}\n\nfunction sanitizeDispatchError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return (\n message\n .replace(KEY_SHAPED_TOKEN, '[redacted]')\n .replace(/\\b[A-Za-z0-9_+=/-]{24,}/g, redactSecretRun)\n // `Authorization: Bearer <value>` names the scheme first; consume it so the value goes too.\n .replace(/\\b(?:bearer|token|api[-_ ]?key|authorization)\\s*[:=]?\\s*(?:bearer\\s+)?[^\\s,;]+/gi, '[redacted]')\n .slice(0, MAX_ERROR_LENGTH)\n );\n}\n\nfunction retryAt(now: Date, attempts: number): Date {\n return new Date(now.getTime() + Math.min(1_000 * 2 ** Math.max(0, attempts - 1), MAX_BACKOFF_MS));\n}\n\nfunction externalSourceForDecision(decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>) {\n return externalSourceForWorkItem(decision.source, decision.sourceKey, decision.url ?? undefined);\n}\n\nfunction deferredActor(record: FactoryDeferredDecisionRecord): FactoryRuleActor {\n const actor = record.actor;\n if (\n actor?.type === 'github' &&\n typeof actor.login === 'string' &&\n typeof actor.trusted === 'boolean' &&\n typeof actor.factoryAuthored === 'boolean'\n ) {\n return {\n type: 'github',\n login: actor.login,\n trusted: actor.trusted,\n factoryAuthored: actor.factoryAuthored,\n };\n }\n if (\n actor?.type === 'gitlab' &&\n typeof actor.username === 'string' &&\n typeof actor.trusted === 'boolean' &&\n typeof actor.factoryAuthored === 'boolean'\n ) {\n return {\n type: 'gitlab',\n username: actor.username,\n trusted: actor.trusted,\n factoryAuthored: actor.factoryAuthored,\n };\n }\n return { type: 'system', id: 'factory-rule-dispatcher' };\n}\n\nfunction externalActor(actor: FactoryDeferredDecisionRecord['actor']): boolean {\n return actor !== null && actor.type !== 'human' && actor.type !== 'agent' && actor.type !== 'system';\n}\n\n/** A run start asks for consent; an external event asks before pulling a card back into a working lane. */\nfunction requestsConsent(\n boards: BoardRegistry,\n record: FactoryDeferredDecisionRecord,\n decision: FactoryCommitDecision,\n): boolean {\n if (decision.type === 'invokeSkill') return true;\n if (decision.type !== 'transition' || !externalActor(record.actor)) return false;\n // Fail closed: a phase the installed board does not declare is treated as working, so consent is asked.\n return (resolvePhaseSemantics(boards, decision.board, decision.stage)?.kind ?? 'working') === 'working';\n}\n\n// The Factory reviewing code it wrote is part of the same work, not new work to\n// consent to: a push to a Factory-authored PR re-reviews without a person's click.\nfunction reviewsFactoryAuthoredCode(\n boards: BoardRegistry,\n item: Pick<Card, 'metadata' | 'externalSource' | 'workItem'>,\n decision: FactoryCommitDecision,\n): boolean {\n if (item.metadata?.factoryAuthored !== true) return false;\n if (decision.type === 'transition') {\n const flow = boardFlow(boards.get(decision.board));\n return (\n decision.stage === flow.pullRequestReview &&\n reviewsPullRequest({\n flow,\n item: { source: workItemSource(item.externalSource), workItem: item.workItem },\n })\n );\n }\n return decision.type === 'invokeSkill' && decision.role === REVIEW_CONTEXT;\n}\n\nfunction leaseIdentity(\n record: Pick<FactoryDeferredDecisionRecord | FactoryPendingStartRecord, 'id' | 'orgId' | 'factoryProjectId'>,\n ownerId: string,\n) {\n return { id: record.id, orgId: record.orgId, factoryProjectId: record.factoryProjectId, ownerId };\n}\n\nasync function awaitNotification(\n send: () => Promise<FactoryNotificationResult>,\n requireDelivery = false,\n): Promise<{ action?: string } | undefined> {\n try {\n const notification = await send();\n const [, accepted] = await Promise.all([notification.persisted, notification.accepted]);\n if (!accepted) {\n if (requireDelivery) {\n throw new FactoryDispatchError(\n 'notification_delivery_failed',\n 'Factory notification was persisted without agent delivery.',\n );\n }\n return undefined;\n }\n if (!requireDelivery) return accepted;\n if (accepted.action === 'wake') {\n if (!accepted.output) {\n throw new FactoryDispatchError('notification_delivery_failed', 'Factory notification wake had no output.');\n }\n await accepted.output.consumeStream();\n return accepted;\n }\n if (accepted.action !== 'deliver') {\n throw new FactoryDispatchError(\n 'notification_delivery_failed',\n `Factory notification did not reach the agent (${String(accepted.action)}).`,\n );\n }\n return accepted;\n } catch (error) {\n if (error instanceof FactoryDispatchError) throw error;\n throw new FactoryDispatchError(\n 'notification_delivery_failed',\n `Factory notification delivery failed: ${sanitizeDispatchError(error)}`,\n { cause: error },\n );\n }\n}\n\n/** Card metadata key: the facts each linked pull request joined the card with, by its trust key. */\nconst LINKED_PULL_REQUESTS_KEY = 'linkedPullRequests';\n\ninterface LinkFacts {\n trusted: boolean;\n phase: string | null;\n hasPullRequest: boolean;\n}\n\nfunction linkedPullRequests(metadata: Record<string, unknown> | null | undefined): Record<string, LinkFacts> {\n const links = metadata?.[LINKED_PULL_REQUESTS_KEY];\n return links && typeof links === 'object' && !Array.isArray(links) ? (links as Record<string, LinkFacts>) : {};\n}\n\n/**\n * A pull request's link to `card`, read off the card it joins. Only another trusted, open pull\n * request counts as one the card already has: an outsider's can't keep a maintainer's from Review.\n */\nfunction linkFacts(card: Card, trusted: boolean, trustKey: string): LinkFacts {\n return {\n trusted,\n phase: card.stages.length === 1 ? card.stages[0]! : null,\n hasPullRequest: pullRequestSources(card).some(\n source =>\n pullRequestTrustKey(source) !== trustKey &&\n isOpenPullRequestSource(source) &&\n trustedPullRequestSource(card, source),\n ),\n };\n}\n\nexport class FactoryDecisionDispatcher {\n readonly #audit?: AuditRecorder;\n readonly #controller: FactoryController;\n readonly #transitionService: Pick<FactoryTransitionService, 'transition' | 'configVersion'>;\n readonly #boards: ProjectBoardSource;\n readonly #intakeRoutes?: IntakeRoutesReader;\n /** Forced on every project; undefined: each project's own setting. */\n readonly #intakeEvaluator: IntakeEvaluator | undefined;\n readonly #storage: WorkItemsStorage;\n readonly #ownerId: string;\n readonly #autoApproving = new Set<string>();\n readonly #reconcileToolResults?: () => Promise<void>;\n readonly #reconcileRunBinding?: FactoryDecisionDispatcherOptions['reconcileRunBinding'];\n readonly #prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n readonly #primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n readonly #reportRunEnd?: FactoryRunEndReporter;\n readonly #dismissStaleReviews?: FactoryDecisionDispatcherOptions['dismissStaleReviews'];\n readonly #reportReviewStatus?: FactoryReviewStatusReporter;\n /** Review attempts that already said `queued`, and those that watched their run start. */\n readonly #reviewQueued = new WeakSet<FactoryDeferredDecisionRecord>();\n readonly #reviewWatched = new WeakSet<FactoryDeferredDecisionRecord>();\n /** Re-claims that found an earlier attempt's kickoff landed and its run already over. */\n readonly #reviewReplayed = new WeakSet<FactoryDeferredDecisionRecord>();\n /** Last pending status-comment write per run, so writes stay ordered. */\n /**\n * Per review run: the write chain, the newest step issued, and how many\n * writes were issued and how far the landed ones reach, so a write that\n * outlived its wait and landed after a newer one can be repaired.\n */\n readonly #reviewStatusRuns = new Map<\n string,\n { tail: Promise<void>; issued: number; landed: number; latest: FactoryReviewStatusEvent }\n >();\n readonly #resolveLinkedWorkItemParentId?: FactoryDecisionDispatcherOptions['resolveLinkedWorkItemParentId'];\n readonly #factoryProjectExists?: FactoryDecisionDispatcherOptions['factoryProjectExists'];\n readonly #maxInFlight: number;\n readonly #maxInteractiveInFlight: number;\n readonly #staleBindingSweepIntervalMs: number;\n readonly #staleBindingTtlMs: number;\n #lastStaleBindingSweepAt?: Date;\n readonly #reconcileIntervalMs: number;\n readonly #skillCompletionObservationTimeoutMs: number;\n #lastReconcileAt?: Date;\n #reconcileInFlight?: Promise<void>;\n /** A reconcile is due once activity stops, to drain results of runs that just ended. */\n #reconcileOwed = true;\n /** Last step seen on a bound session thread; counts as activity for one reconcile interval. */\n #lastBoundThreadRunAt?: number;\n #started = false;\n #stopping = false;\n #wakeRequested = false;\n #unsubscribeClaimableWork?: () => void;\n #loop?: Promise<void>;\n #timer?: ReturnType<typeof setTimeout>;\n /** Starts and run-bearing decisions; capped by `maxInFlight`. */\n readonly #runInFlight = new Set<Promise<void>>();\n /** Wakes a person is waiting on; capped by `maxInteractiveInFlight`, borrowing free run slots past it. */\n readonly #interactiveInFlight = new Set<Promise<void>>();\n /** Fast board bookkeeping (transitions, linked-card upserts); its own small cap. */\n readonly #bookkeepingInFlight = new Set<Promise<void>>();\n /** Background work awaited on stop but outside both caps. */\n readonly #backgroundInFlight = new Set<Promise<void>>();\n readonly #bindingSkillRuns = new Map<string, Promise<void>>();\n\n constructor(options: FactoryDecisionDispatcherOptions) {\n this.#audit = options.audit;\n this.#controller = options.controller;\n this.#transitionService = options.transitionService;\n this.#boards = toBoardSource(options.boards);\n this.#intakeRoutes = options.intakeRoutes;\n this.#intakeEvaluator = options.intakeEvaluator;\n this.#storage = options.storage;\n this.#ownerId = options.ownerId ?? `factory-dispatcher:${globalThis.crypto.randomUUID()}`;\n this.#reconcileToolResults = options.reconcileToolResults;\n this.#reconcileRunBinding = options.reconcileRunBinding;\n this.#prepareBinding = options.prepareBinding;\n this.#primeCredentials = options.primeCredentials;\n this.#reportRunEnd = options.reportRunEnd;\n this.#dismissStaleReviews = options.dismissStaleReviews;\n this.#reportReviewStatus = options.reportReviewStatus;\n this.#resolveLinkedWorkItemParentId = options.resolveLinkedWorkItemParentId;\n this.#factoryProjectExists = options.factoryProjectExists;\n const maxInFlight = options.maxInFlight ?? MAX_IN_FLIGHT;\n this.#maxInFlight = Number.isFinite(maxInFlight) && maxInFlight > 0 ? Math.floor(maxInFlight) : MAX_IN_FLIGHT;\n const maxInteractiveInFlight = options.maxInteractiveInFlight ?? MAX_INTERACTIVE_IN_FLIGHT;\n this.#maxInteractiveInFlight =\n Number.isFinite(maxInteractiveInFlight) && maxInteractiveInFlight >= 0\n ? Math.floor(maxInteractiveInFlight)\n : MAX_INTERACTIVE_IN_FLIGHT;\n this.#staleBindingSweepIntervalMs = positiveMs(\n options.staleBindingSweepIntervalMs,\n STALE_BINDING_SWEEP_INTERVAL_MS,\n );\n this.#staleBindingTtlMs = positiveMs(options.staleBindingTtlMs, STALE_BINDING_TTL_MS);\n this.#reconcileIntervalMs = positiveMs(options.reconcileIntervalMs, RECONCILE_INTERVAL_MS);\n this.#skillCompletionObservationTimeoutMs = positiveMs(\n options.skillCompletionObservationTimeoutMs,\n SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS,\n );\n }\n\n start(): void {\n if (this.#started) return;\n this.#started = true;\n this.#stopping = false;\n this.#unsubscribeClaimableWork = this.#storage.onClaimableWork(() => this.wake());\n this.wake();\n }\n\n async stop(): Promise<void> {\n this.#stopping = true;\n this.#unsubscribeClaimableWork?.();\n this.#unsubscribeClaimableWork = undefined;\n this.#clearTimer();\n await this.#loop;\n await Promise.allSettled([\n ...this.#runInFlight,\n ...this.#interactiveInFlight,\n ...this.#bookkeepingInFlight,\n ...this.#backgroundInFlight,\n ]);\n this.#started = false;\n this.#stopping = false;\n }\n\n /**\n * Runs a dispatch cycle now. Called after any write that leaves claimable\n * work, locally or from another replica via pubsub. A wake during a running\n * cycle makes the loop run once more instead of starting a second loop.\n */\n wake(): void {\n if (!this.#started || this.#stopping) return;\n this.#wakeRequested = true;\n if (this.#loop) return;\n this.#clearTimer();\n this.#loop = this.#runLoop();\n }\n\n /**\n * A run is stepping on a bound session thread. Interactive runs queue no\n * work, so without this an idle loop would never see them and the trailing\n * reconcile for results they leave behind would not happen. Each step keeps\n * the loop active for one reconcile interval; only the first step after a\n * settled pass wakes it, since an owed pass already rechecks every interval.\n */\n noteBoundThreadRun(): void {\n if (!this.#reconcileToolResults) return;\n this.#lastBoundThreadRunAt = Date.now();\n if (this.#reconcileOwed) return;\n this.#reconcileOwed = true;\n this.wake();\n }\n\n /**\n * Run slots this process holds now, out of its caps. Per process: other\n * replicas keep their own. `inUse` counts automated slots, including any a\n * person's wake borrowed once the interactive reserve was full.\n */\n runSlots(): { inUse: number; cap: number; interactive: { inUse: number; cap: number } } {\n return {\n inUse: this.#runInFlight.size,\n cap: this.#maxInFlight,\n interactive: { inUse: this.#interactiveInFlight.size, cap: this.#maxInteractiveInFlight },\n };\n }\n\n async runOnce(now = new Date()): Promise<void> {\n void this.#maybeSweepStaleBindings(now);\n this.#maybeReconcileToolResults(now);\n const { dispatches } = await this.#claimAndStart(now);\n await Promise.all(dispatches);\n }\n\n #clearTimer(): void {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n }\n\n async #runLoop(): Promise<void> {\n let delay = POLL_MS;\n do {\n this.#wakeRequested = false;\n try {\n delay = await this.#cycle();\n } catch (error) {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n delay = POLL_MS;\n }\n } while (this.#wakeRequested && !this.#stopping);\n // No await between the loop exit and clearing #loop, so a wake() can\n // never land in between and be lost.\n this.#loop = undefined;\n if (this.#stopping) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n this.wake();\n }, delay);\n this.#timer.unref?.();\n }\n\n /** One loop cycle; returns the delay until the next one. */\n async #cycle(): Promise<number> {\n const now = new Date();\n // Fire-and-forget like the reconcile walk: the sweep reads every active\n // binding, so awaiting it would stretch the cycle as the active set grows.\n void this.#maybeSweepStaleBindings(now);\n // Tool results only come from runs, so the reconcile walk follows local\n // activity, plus one trailing pass after it stops.\n const active =\n this.#runInFlight.size > 0 ||\n this.#interactiveInFlight.size > 0 ||\n this.#bookkeepingInFlight.size > 0 ||\n this.#controller.listActiveThreadRuns().length > 0 ||\n (this.#lastBoundThreadRunAt !== undefined &&\n now.getTime() - this.#lastBoundThreadRunAt < this.#reconcileIntervalMs);\n if (!this.#reconcileToolResults) this.#reconcileOwed = false;\n else if (active) this.#reconcileOwed = true;\n if (this.#reconcileOwed && this.#maybeReconcileToolResults(now) && !active) this.#reconcileOwed = false;\n\n let full: boolean;\n try {\n const claimed = await this.#claimAndStart(now);\n full = claimed.full;\n for (const dispatch of claimed.dispatches) {\n dispatch.catch(error => {\n console.error('Factory decision dispatch failed', sanitizeDispatchError(error));\n });\n }\n } catch (error) {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n return POLL_MS;\n }\n if (\n full ||\n this.#runInFlight.size > 0 ||\n this.#interactiveInFlight.size > 0 ||\n this.#bookkeepingInFlight.size > 0\n ) {\n return POLL_MS;\n }\n\n const dueTimes: number[] = [];\n if (this.#reconcileOwed) {\n dueTimes.push((this.#lastReconcileAt?.getTime() ?? 0) + this.#reconcileIntervalMs);\n }\n try {\n // Covers future retries and leases left behind by a crashed replica.\n const nextClaimableAt = await this.#storage.nextClaimableAt();\n if (nextClaimableAt) dueTimes.push(nextClaimableAt.getTime());\n } catch (error) {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n return POLL_MS;\n }\n return Math.max(POLL_MS, Math.min(Math.min(...dueTimes, Infinity) - Date.now(), IDLE_RECHECK_MS));\n }\n\n /**\n * Claims a batch and starts dispatches without awaiting their completion.\n * Dispatches can legitimately take minutes (skill kickoffs consume the\n * agent's run stream; binding preparation provisions sandboxes), so awaiting\n * them here would freeze the poll loop and starve every other queued\n * decision. In-flight records stay protected from re-claim by lease renewal.\n */\n async #claimAndStart(now: Date): Promise<{ dispatches: Array<Promise<void>>; full: boolean }> {\n let full = false;\n const leaseExpiresAt = new Date(now.getTime() + LEASE_MS);\n const dispatches: Array<Promise<void>> = [];\n // Run slots are held for whole agent runs (minutes), so bookkeeping that\n // only mirrors the board is claimed from its own pool and never waits\n // behind them.\n const startCapacity = this.#maxInFlight - this.#runInFlight.size;\n if (startCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, startCapacity);\n // Starts are claimed before deferred decisions: a pending start is a user\n // waiting on a brand-new session, while a deferred decision is a background\n // continuation of one that is already running. A deep decision queue must\n // never starve new sessions out of the tick.\n const starts = await this.#storage.claimPendingStarts({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit,\n });\n full ||= starts.length >= limit;\n dispatches.push(...starts.map(start => this.#track(this.#runInFlight, this.#dispatchPendingStart(start, now))));\n }\n // A person's wake comes next, into its own reserve and then into any free\n // run slot, so it never waits behind hours of automated runs. Each claimed\n // wake is tracked in the pool whose slot it took.\n const reserveCapacity = Math.max(0, this.#maxInteractiveInFlight - this.#interactiveInFlight.size);\n const interactiveCapacity = reserveCapacity + Math.max(0, this.#maxInFlight - this.#runInFlight.size);\n if (interactiveCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, interactiveCapacity);\n const decisions = await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit,\n decisionFilter: isInteractiveDecision,\n });\n full ||= decisions.length >= limit;\n dispatches.push(\n ...decisions.map((decision, index) =>\n this.#track(\n index < reserveCapacity ? this.#interactiveInFlight : this.#runInFlight,\n this.#dispatchDecision(decision, now),\n ),\n ),\n );\n }\n const runCapacity = this.#maxInFlight - this.#runInFlight.size;\n if (runCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, runCapacity);\n const decisions = await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit,\n decisionFilter: isAutomatedRunDecision,\n });\n full ||= decisions.length >= limit;\n dispatches.push(\n ...decisions.map(decision => this.#track(this.#runInFlight, this.#dispatchDecision(decision, now))),\n );\n }\n const bookkeepingCapacity = BOOKKEEPING_MAX_IN_FLIGHT - this.#bookkeepingInFlight.size;\n if (bookkeepingCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, bookkeepingCapacity);\n const decisions = await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit,\n decisionFilter: isBookkeepingDecision,\n });\n full ||= decisions.length >= limit;\n dispatches.push(\n ...decisions.map(decision => this.#track(this.#bookkeepingInFlight, this.#dispatchDecision(decision, now))),\n );\n }\n return { dispatches, full };\n }\n\n /**\n * Throttled, coalesced, non-blocking bound-thread reconcile: dispatch\n * claiming never waits behind cursor + message reads, and overlapping runs\n * are skipped while one is still in flight.\n */\n #maybeReconcileToolResults(now: Date): boolean {\n if (!this.#reconcileToolResults || this.#reconcileInFlight) return false;\n if (this.#lastReconcileAt && now.getTime() - this.#lastReconcileAt.getTime() < this.#reconcileIntervalMs) {\n return false;\n }\n this.#lastReconcileAt = now;\n const run = this.#reconcileToolResults()\n .catch(error => {\n console.error('Factory tool-result reconcile failed', sanitizeDispatchError(error));\n })\n .finally(() => {\n this.#reconcileInFlight = undefined;\n });\n this.#reconcileInFlight = run;\n this.#track(this.#backgroundInFlight, run);\n return true;\n }\n\n /** Slow-cadence revocation of leaked/legacy bindings; failures never block the claim path. */\n async #maybeSweepStaleBindings(now: Date): Promise<void> {\n // The first tick only anchors the cadence: sweeping at boot would race the\n // startup reconcile that is still draining trailing tool results.\n if (!this.#lastStaleBindingSweepAt) {\n this.#lastStaleBindingSweepAt = now;\n return;\n }\n if (now.getTime() - this.#lastStaleBindingSweepAt.getTime() < this.#staleBindingSweepIntervalMs) return;\n this.#lastStaleBindingSweepAt = now;\n try {\n const revoked = await this.#storage.revokeStaleRunBindings({\n olderThan: new Date(now.getTime() - this.#staleBindingTtlMs),\n now,\n // A run parked on a person, or resumed after one answered, is alive however\n // old its binding is. The session must still be on the binding's thread: its\n // suspension and run state belong to that thread. A failed session lookup revokes.\n keep: async binding => {\n // Age alone says nothing about a card that is still open in the phase this\n // binding works: the session is between turns, not leaked. Revoking it takes\n // the card's tools and updates away, and the card then sits until a person\n // moves it. A run starting for the card elsewhere still replaces the binding.\n try {\n if (await this.#worksOpenCard(binding)) return true;\n } catch (error) {\n // Not knowing is no reason to cut a session off: the next sweep asks again.\n console.warn(\n `Factory stale-binding sweep kept binding card=${binding.workItemId} session=${binding.sessionId}: could not read its card`,\n sanitizeDispatchError(error),\n );\n return true;\n }\n try {\n const session = await this.#controller.getSession(binding.sessionId);\n if (session?.thread.getId() !== binding.threadId) return false;\n return sessionHoldsWork(session);\n } catch {\n return false;\n }\n },\n onRevoked: binding =>\n console.info(\n `Factory stale-binding sweep revoked binding card=${binding.workItemId} session=${binding.sessionId} role=${binding.role}`,\n ),\n });\n if (revoked > 0) console.info(`Factory stale-binding sweep revoked ${revoked} binding(s)`);\n } catch (error) {\n console.error('Factory stale-binding sweep failed', sanitizeDispatchError(error));\n }\n }\n\n /** Whether the binding's card sits in a working phase that the binding's role runs. */\n async #worksOpenCard(binding: FactoryRunBindingRecord): Promise<boolean> {\n const item = await this.#storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item || item.stages.length !== 1) return false;\n const phase = (await this.#boards.load(binding)).get(boardForWorkItem(item))?.phases[item.stages[0]!];\n return phase?.kind === 'working' && phase.runner.context === binding.role;\n }\n\n #track(pool: Set<Promise<void>>, dispatch: Promise<void>): Promise<void> {\n pool.add(dispatch);\n void dispatch\n .catch(() => {})\n .then(() => {\n pool.delete(dispatch);\n // A settled dispatch frees capacity and may have queued a retry.\n if (pool !== this.#backgroundInFlight) this.wake();\n });\n return dispatch;\n }\n\n async #dispatchDecision(record: FactoryDeferredDecisionRecord, now: Date): Promise<void> {\n let executionCompleted = false;\n try {\n const decision = validateFactoryRuleDecision(record.decision, record.causalChain.length);\n if (decision.type === 'reject') throw new Error('Deferred Factory decisions cannot reject.');\n if (await this.#needsApproval(record, decision)) {\n const proposed = await this.#storage.proposeDeferredDecision(leaseIdentity(record, this.#ownerId), new Date());\n if (!proposed) throw new Error('Factory decision lease was lost before approval could be requested.');\n return;\n }\n await this.#supersedeProposals(record, decision);\n // A first claim cannot have delivered its kickoff yet, so it may say `queued` right\n // away. A re-claim may find the run already going; it says `queued` only once the\n // replay guard proves the kickoff never landed.\n if (record.attempts <= 1) await this.#reviewQueuedOnce(record, decision);\n await this.#withLease(\n async leaseExpiresAt =>\n this.#storage.renewDeferredDecisionLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),\n async () => this.#executeDecision(record, decision, now),\n );\n executionCompleted = true;\n const completed = await this.#storage.completeDeferredDecision(leaseIdentity(record, this.#ownerId), new Date());\n if (!completed) throw new Error('Factory decision lease was lost before completion.');\n // Only an attempt that saw the run end may say it finished: the one that watched\n // it, or a re-claim that found the landed run already over (its worker was lost).\n if (this.#reviewWatched.has(record) || this.#reviewReplayed.has(record)) {\n await this.#reviewStatus(record, decision, {\n phase: 'completed',\n endedAt: new Date(),\n ...(this.#reviewReplayed.has(record) ? { replayed: true } : {}),\n });\n }\n } catch (error) {\n if (error instanceof FactoryDecisionSuperseded) {\n await this.#storage.supersedeLeasedDecision(leaseIdentity(record, this.#ownerId), new Date());\n await this.#reviewStatus(record, record.decision, { phase: 'cancelled', endedAt: new Date() });\n return;\n }\n if (error instanceof FactoryDecisionPostponed) {\n await this.#storage.postponeDeferredDecision(\n leaseIdentity(record, this.#ownerId),\n error.availableAt ?? new Date(now.getTime() + POSTPONE_MS),\n new Date(),\n );\n return;\n }\n const failureCode = factoryDispatchFailureCode(error);\n const terminal = isTerminalFailure(record.attempts, failureCode);\n const failed = await this.#storage.failDeferredDecision({\n ...leaseIdentity(record, this.#ownerId),\n now: new Date(),\n availableAt: retryAt(now, record.attempts),\n lastError: sanitizeDispatchError(error),\n failureCode,\n terminal,\n advanceDeliveryGeneration: !executionCompleted,\n });\n if (terminal && failed) await this.#supersedeFailureOnSettledCard(failed);\n // A re-claim that failed before proving its kickoff never landed may be racing\n // an earlier attempt's live run; only a terminal failure may speak over it.\n if (terminal || this.#reviewQueued.has(record)) {\n await this.#reviewStatus(failed ?? record, record.decision, {\n phase: terminal ? 'failed' : 'retrying',\n endedAt: new Date(),\n reason: publicFailureReason(failureCode, error),\n });\n }\n }\n }\n\n /**\n * An earlier attempt's kickoff already landed, so this attempt only has to\n * see that run end before a review's status can be finalized. The open-run\n * wait covers runs in the ledger; a run that landed but died before\n * registering there can still be live in this process, so wait it out too.\n */\n async #replayLanded(\n record: FactoryDeferredDecisionRecord,\n decision: unknown,\n session: Pick<DispatcherSession, 'subscribe' | 'respondToToolSuspension'>,\n runStillActive: () => boolean,\n ): Promise<void> {\n if (!(await this.#isReviewRun(record, decision))) return;\n if (runStillActive()) {\n const run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n label: 'Factory skill run',\n runStillActive,\n });\n try {\n if (runStillActive()) await run.wait();\n } finally {\n run.close();\n }\n }\n this.#reviewReplayed.add(record);\n }\n\n /**\n * Holds the goal a phase's run pursues on the session's thread, and names it on the card so\n * leaving the phase ends it. Keyed on the decision: a retry finds the goal already held.\n */\n async #setPhaseGoal(\n record: FactoryDeferredDecisionRecord,\n goal: { objective: string; maxRuns?: number },\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n ): Promise<GoalObjectiveRecord> {\n // The phase this run is for, read before the goal exists (the kickoff was checked against it):\n // reading it afterwards could stamp the phase the card moved to meanwhile.\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n const phaseKey = item?.stages.length === 1 ? item.stages[0] : undefined;\n const objective = await startPhaseGoal(session.machinery.getAgent(), {\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n goalId: record.id,\n objective: goal.objective,\n maxRuns: goal.maxRuns,\n // Factory has no judge setting of its own: the session's model judges its goal.\n judgeModelId: session.model.get() || undefined,\n });\n if (!objective) {\n throw new FactoryDispatchError('run_configuration_invalid', 'The Factory session has no storage to hold a goal.');\n }\n if (!item || !phaseKey) return objective;\n const stamp = {\n phaseKey,\n boardKey: boardForWorkItem(item),\n goalId: record.id,\n threadId: binding.threadId,\n sessionId: binding.sessionId,\n };\n if (phaseGoalOf(item.metadata)?.goalId !== record.id) {\n await this.#storage.update({\n orgId: record.orgId,\n id: item.id,\n userId: 'factory',\n patch: { metadata: { [PHASE_GOAL_METADATA_KEY]: stamp } },\n });\n }\n // A move that committed before the stamp landed found no goal to end: end it here instead. A\n // same-named phase on another board is a different phase, so the board counts as a move too.\n const after = await this.#storage.get({ orgId: record.orgId, id: item.id });\n if (after?.stages.length !== 1 || after.stages[0] !== phaseKey || boardForWorkItem(after) !== stamp.boardKey) {\n await endPhaseGoal(stamp, { agentFor: async () => session.machinery.getAgent(), store: async () => undefined });\n throw new FactoryDecisionSuperseded();\n }\n return objective;\n }\n\n /**\n * Shows the goal in the thread once its run has the kickoff. A goal whose reminder never landed\n * is paused rather than left judging a run nobody was told about; the retry resumes it.\n */\n async #remindPhaseGoal(\n record: FactoryDeferredDecisionRecord,\n goal: GoalObjectiveRecord,\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n requestContext: RequestContext,\n ): Promise<void> {\n const reminderId = `${record.id}:goal`;\n if ((await session.thread.listActiveMessages()).some(message => message.id === reminderId)) return;\n const agent = session.machinery.getAgent();\n if (goal.status === 'paused') await agent.updateObjectiveOptions({ threadId: binding.threadId, status: 'active' });\n try {\n const settled = await session.sendSignal(\n {\n id: reminderId,\n type: 'system-reminder',\n contents: goal.objective,\n attributes: { type: 'goal' },\n metadata: { goalId: goal.id, goalMaxTurns: goal.maxRuns, judgeModelId: goal.judgeModelId },\n },\n { requestContext, requireDelivery: true },\n ).accepted;\n if (settled.action !== 'wake' && settled.action !== 'deliver') {\n throw new FactoryDispatchError(\n 'notification_delivery_failed',\n `Factory goal reminder did not reach the agent (${String(settled.action)}).`,\n );\n }\n } catch (error) {\n await agent.updateObjectiveOptions({ threadId: binding.threadId, status: 'paused' });\n throw error;\n }\n }\n\n /** A retried decision whose kickoff already landed: make sure its goal is held and shown. */\n async #startPhaseGoal(\n record: FactoryDeferredDecisionRecord,\n goal: { objective: string; maxRuns?: number },\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n requestContext: RequestContext,\n ): Promise<void> {\n const objective = await this.#setPhaseGoal(record, goal, session, binding);\n await this.#remindPhaseGoal(record, objective, session, binding, requestContext);\n }\n\n /**\n * A pull request review run: the only runs that keep a status comment on the pull request. A\n * review-seat run of the skill the card's board self-reviews with checks the builder's own work\n * and reviews no pull request, even on a card that carries one.\n */\n async #isReviewRun(record: FactoryDeferredDecisionRecord, decision: unknown): Promise<boolean> {\n const run = reviewSeatSkill(decision);\n if (!run) return false;\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n if (!item) return true;\n const board = (await this.#boards.load(record)).get(boardForWorkItem(item));\n const selfReview = boardFlow(board).selfReview;\n const phase = selfReview === undefined ? undefined : board?.phases[selfReview];\n return phase?.kind !== 'working' || phase.runner.skill !== run.skillName;\n }\n\n /**\n * When a re-entered review's head was already reviewed while this decision waited for the\n * pass in flight: that pass read the pushed commit, so its verdict is the one this decision\n * was queued to produce. A verdict from before the decision does not count, so a person\n * asking for another pass on the same commit still gets one.\n */\n async #headReviewedSince(record: FactoryDeferredDecisionRecord, decision: unknown): Promise<Date | undefined> {\n if (!record.workItemId || (decision as { resume?: unknown }).resume !== true) return undefined;\n if (!(await this.#isReviewRun(record, decision))) return undefined;\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n const { pullRequestHeadSha: head, reviewedHeadSha: reviewed, reviewedAt } = item?.metadata ?? {};\n if (typeof head !== 'string' || typeof reviewed !== 'string' || typeof reviewedAt !== 'string') return undefined;\n if (head.toLowerCase() !== reviewed.toLowerCase()) return undefined;\n const at = new Date(reviewedAt);\n return at.getTime() >= record.createdAt.getTime() ? at : undefined;\n }\n\n async #reviewQueuedOnce(record: FactoryDeferredDecisionRecord, decision: unknown): Promise<void> {\n if (this.#reviewQueued.has(record)) return;\n this.#reviewQueued.add(record);\n await this.#reviewStatus(record, decision, { phase: 'queued' });\n }\n\n /** Best-effort: a status comment is never worth failing or delaying the review it describes. */\n async #reviewStatus(\n record: FactoryDeferredDecisionRecord,\n decision: unknown,\n step: Pick<FactoryReviewStatusEvent, 'phase' | 'startedAt' | 'endedAt' | 'reason'>,\n ): Promise<void> {\n const report = this.#reportReviewStatus;\n if (!report || !record.workItemId) return;\n try {\n if (!(await this.#isReviewRun(record, decision))) return;\n } catch (error) {\n console.warn('Factory review status update failed', sanitizeDispatchError(error));\n return;\n }\n const event: FactoryReviewStatusEvent = {\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: record.workItemId,\n run: record.id,\n requestedAt: record.createdAt,\n generation: record.deliveryGeneration,\n attempt: record.attempts,\n ...step,\n };\n // Writes for one run go out in order even when the run stops waiting on a\n // slow one, so an earlier step can never land on top of a later one.\n const run = this.#reviewStatusRuns.get(record.id) ?? {\n tail: Promise.resolve(),\n issued: 0,\n landed: 0,\n latest: event,\n };\n this.#reviewStatusRuns.set(record.id, run);\n const previous = run.tail;\n const seq = ++run.issued;\n run.latest = event;\n const send = (next: FactoryReviewStatusEvent) =>\n report(next).catch(error => {\n console.warn('Factory review status update failed', sanitizeDispatchError(error));\n });\n // A write that never settles holds the next one back for one timeout, not forever.\n let waited: ReturnType<typeof setTimeout> | undefined;\n const turn = Promise.race([\n previous,\n new Promise<void>(resolve => {\n waited = setTimeout(resolve, REVIEW_STATUS_TIMEOUT_MS);\n }),\n ]).finally(() => clearTimeout(waited));\n const delivered = turn.then(async () => {\n await send(event);\n // This write outlived its wait and a newer one landed first: it may have\n // put an older step back on the comment, so restate the newest one.\n if (run.landed > seq) await send(run.latest);\n run.landed = Math.max(run.landed, seq);\n });\n run.tail = delivered;\n void delivered.then(() => {\n if (run.tail === delivered && run.landed >= run.issued && this.#reviewStatusRuns.get(record.id) === run) {\n this.#reviewStatusRuns.delete(record.id);\n }\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<'timeout'>(resolve => {\n timer = setTimeout(() => resolve('timeout'), REVIEW_STATUS_TIMEOUT_MS);\n });\n try {\n if ((await Promise.race([delivered, timedOut])) === 'timeout') {\n console.warn(`Factory review status update (${step.phase}) still pending; continuing the run without it`);\n }\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** Terminal cleanup ran before this failure landed, so it never saw this row. */\n async #supersedeFailureOnSettledCard(record: FactoryDeferredDecisionRecord): Promise<void> {\n if (!record.workItemId) return;\n try {\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n if (!item || workItemPhaseSemantics(await this.#boards.load(record), item)?.kind !== 'terminal') return;\n await this.#storage.supersedeDecisionsForWorkItem({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: record.workItemId,\n supersededAt: new Date(),\n });\n } catch (error) {\n // Best-effort: the row stays failed until someone clears it from the card.\n console.error('Factory settled-card supersede failed', sanitizeDispatchError(error));\n }\n }\n\n /**\n * A proposal is a question: \"should this run start?\" Once that run is\n * starting anyway — because a person approved a later copy, or armed the item\n * — the question has been answered and the card must stop asking it. Left\n * alone the badge outlives the work it describes, and the one affordance that\n * means \"the loop is stopped, answer this\" cries wolf.\n */\n async #supersedeProposals(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): Promise<void> {\n if (decision.type !== 'invokeSkill' || !record.workItemId) return;\n try {\n await this.#storage.supersedeDecisionsForWorkItem({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: record.workItemId,\n role: decision.role,\n supersededAt: new Date(),\n });\n } catch (error) {\n // Best-effort: a stale badge is not worth failing the run it describes.\n console.error('Factory proposal supersede failed', sanitizeDispatchError(error));\n }\n }\n\n // Effects a person owns: starting a run (compute + code execution), and an\n // external event pulling a card back into a working lane. The board decides\n // which of them start on their own: a phase with `autoStart` (and a card its\n // `autoStartWhen` matches). Anything else waits for a person.\n async #needsApproval(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): Promise<boolean> {\n if (record.approvedAt !== null) return false;\n // A decision queued by a card move on an outside author's pull request event acts on that\n // author's say-so — a run is compute and code execution, a wake holds a session for one.\n // It waits for a person before the consent check (which lets messages through), past the\n // card's armed autonomy and however its phase starts.\n if (\n (decision.type === 'invokeSkill' || decision.type === 'sendMessage') &&\n decision.untrustedPullRequestEvent === true\n ) {\n return true;\n }\n const boards = await this.#boards.load(record);\n if (!requestsConsent(boards, record, decision)) return false;\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n if (!item) return true;\n // Once someone starts a card, the runs that carry it to review are that same request continuing.\n if (item.autonomyArmedAt != null) return false;\n if (reviewsFactoryAuthoredCode(boards, item, decision)) return false;\n return !startsInAutoPhase(boards, item, decision);\n }\n\n async #executeDecision(\n record: FactoryDeferredDecisionRecord,\n decision: FactoryCommitDecision,\n now: Date,\n ): Promise<void> {\n const nextChain: FactoryRuleCausalEntry[] = [\n ...(record.causalChain as FactoryRuleCausalEntry[]),\n { ingressId: record.idempotencyKey, decisionType: decision.type },\n ];\n if (nextChain.length > MAX_FACTORY_RULE_CAUSAL_DEPTH) throw new Error('Factory rule causal depth exceeded.');\n\n switch (decision.type) {\n case 'transition': {\n if (decision.event) await this.#routeEvent(record, decision.event, nextChain, decision);\n else await this.#applyTransition(record, decision, nextChain);\n return;\n }\n case 'routeEvent': {\n if (isUpdateEvent(decision.event.type)) {\n const combined = await this.#foldUpdates(record, decision, now);\n if (combined) await this.#routeEvent(record, combined, nextChain);\n return;\n }\n await this.#routeEvent(record, decision.event, nextChain);\n return;\n }\n case 'upsertLinkedWorkItem': {\n await this.#upsertLinkedItem(record, decision, nextChain);\n return;\n }\n case 'invokeSkill': {\n // A retry for a role the card has already been handed past cannot win:\n // no seat can be minted for it, and the work it was for is done.\n // Checked before a seat is prepared: a stale run must not mint one for a role the card left.\n if (\n (await this.#roleSuperseded(record, decision.role)) ||\n (await this.#decisionOvertaken(record, decision.role))\n ) {\n throw new FactoryDecisionSuperseded();\n }\n const binding = await this.#requireOrPrepareBinding(record, decision.role);\n await this.#withBindingSkillRun(binding.id, async () => {\n const item = record.workItemId\n ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId })\n : null;\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const requestContext = factoryRequestContext({\n session,\n binding,\n userId: startedBy,\n orgId: record.orgId,\n });\n const resolved =\n decision.skillName === undefined\n ? await resolvePromptInvocation(this.#controller, {\n sessionId: binding.sessionId,\n prompt: decision.prompt,\n })\n : decision.resume === true\n ? await resolveSkillResumeInvocation(this.#controller, {\n sessionId: binding.sessionId,\n name: decision.skillName,\n arguments: decision.arguments,\n })\n : await resolveSkillInvocation(this.#controller, {\n sessionId: binding.sessionId,\n name: decision.skillName,\n arguments: decision.arguments,\n });\n await this.#switchThread(session, binding, { userId: startedBy, orgId: record.orgId });\n const deliveryId =\n record.deliveryGeneration === 0 ? record.id : `${record.id}:retry:${record.deliveryGeneration}`;\n const kickoffLanded = async () =>\n (await session.thread.listActiveMessages()).some(message => message.id === deliveryId);\n const kickoffStale = async () =>\n (await this.#roleSuperseded(record, decision.role)) ||\n (await this.#findBinding(record, decision.role))?.id !== binding.id ||\n (await this.#decisionOvertaken(record, decision.role));\n const runStillActive = () =>\n this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId);\n await this.#waitForOpenRun(session, binding, 'Factory skill run');\n if (await this.#roleSuperseded(record, decision.role)) throw new FactoryDecisionSuperseded();\n const activeBinding = await this.#requireBinding(record, decision.role);\n if (activeBinding.id !== binding.id) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Factory binding ${binding.id} changed while waiting for its open run to end.`,\n );\n }\n if (await kickoffLanded()) {\n if (decision.goal) await this.#startPhaseGoal(record, decision.goal, session, binding, requestContext);\n return this.#replayLanded(record, decision, session, runStillActive);\n }\n if (await kickoffStale()) throw new FactoryDecisionSuperseded();\n const coveredAt = await this.#headReviewedSince(record, decision);\n if (coveredAt) {\n // The verdict this pass was queued for exists; its status reports that verdict, not a cancelled run.\n await this.#reviewStatus(record, decision, {\n phase: 'completed',\n startedAt: record.createdAt,\n endedAt: coveredAt,\n });\n return;\n }\n // Safe under the replay guard above: it matches deliveryId, never prompt content.\n // Re-read: the description may have been edited while the open run drained.\n const current = record.workItemId\n ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId })\n : null;\n const kickoffContents = withWorkItemDescription(resolved.contents, current?.description);\n // A skill kickoff is system-generated, not something the human typed: send it\n // as a typed `skill` signal so the model sees `<skill name=\"…\">` and traces\n // record the skill name. Plain-prompt kickoffs stay user messages.\n const kickoffSignal =\n resolved.skillName !== undefined\n ? {\n type: 'reactive' as const,\n tagName: 'skill',\n attributes: { name: resolved.skillName },\n }\n : { type: 'user' as const, tagName: 'user' };\n // The description read is async storage I/O; the card can move while it runs.\n if (await kickoffLanded()) {\n if (decision.goal) await this.#startPhaseGoal(record, decision.goal, session, binding, requestContext);\n return this.#replayLanded(record, decision, session, runStillActive);\n }\n if (await kickoffStale()) throw new FactoryDecisionSuperseded();\n await this.#reviewQueuedOnce(record, decision);\n if (decision.cancelInFlight && session.stream.isActive()) session.abort();\n const precedingMessage = decision.precedingMessage;\n if (precedingMessage) {\n await awaitNotification(() =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'stage-transition',\n summary: precedingMessage,\n priority: 'medium',\n payload: { message: precedingMessage },\n sourceId: `${record.id}:stage-transition`,\n dedupeKey: `${record.idempotencyKey}:stage-transition`,\n },\n {\n ifActive: { behavior: 'deliver' },\n ifIdle: { behavior: 'persist' },\n requestContext,\n },\n ),\n );\n if (await kickoffStale()) throw new FactoryDecisionSuperseded();\n }\n // Held before the kickoff lands, so the goal judge sees the objective from the run's first turn.\n const goal = decision.goal ? await this.#setPhaseGoal(record, decision.goal, session, binding) : undefined;\n // The run's own verdict, not the delivery's. A signal can reach the\n // agent perfectly and the run still die on a provider error or be\n // cancelled mid-flight; without this the decision reports success and\n // the break is invisible on the card.\n const since = new Date();\n const runItem = record.workItemId\n ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId })\n : null;\n const boards = runItem ? await this.#boards.load(record) : null;\n const stage = runItem?.stages.length === 1 ? runItem.stages[0] : undefined;\n const phase = stage && runItem ? boards?.get(boardForWorkItem(runItem))?.phases[stage] : undefined;\n const workingRevision =\n phase?.kind === 'working' &&\n (phase.runner.goal || phase.exitTool) &&\n phase.runner.context === decision.role &&\n phase.runner.skill === decision.skillName\n ? runItem!.revision\n : null;\n const existingLinkedReviewIds = new Set(\n workingRevision === null || !runItem\n ? []\n : (await this.#storage.listLinked({ item: runItem, limit: 100 })).map(card => card.id),\n );\n const stopRequested = () => this.#runStopRequested(record.orgId, binding.id);\n const run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n autoApprovedTool: await this.#autoApprovedExitTool(record),\n autoApproving: this.#autoApproving,\n requestContext,\n onAgentEnd: () => this.#roleSuperseded(record, decision.role),\n label: 'Factory skill run',\n runStillActive,\n stopRequested,\n });\n\n const sendKickoff = async () => {\n await this.#storage.clearRunBindingStopRequest({ orgId: record.orgId, bindingId: binding.id });\n const result = session.sendSignal(\n {\n id: deliveryId,\n ...kickoffSignal,\n contents: kickoffContents,\n },\n // Without `requireDelivery` the session resolves `accepted` on the\n // next tick and swallows wake failures, so a kickoff that never\n // reached the agent would be marked succeeded and the thread would\n // stay empty forever.\n { requestContext, requireDelivery: true },\n );\n const settled = await result.accepted;\n if (settled.action !== 'wake' && settled.action !== 'deliver') {\n // A named non-delivery action proves no run began and is safe to\n // retry. An absent action did not confirm either outcome, so a new\n // delivery generation could duplicate work.\n throw new FactoryDispatchError(\n settled.action ? 'notification_delivery_failed' : 'skill_delivery_ambiguous',\n `Factory skill invocation signal did not reach the agent (${String(settled.action)}).`,\n );\n }\n return settled;\n };\n\n try {\n let settled = await sendKickoff();\n while (settled.action === 'deliver') {\n // `deliver` means the signal was queued onto a run that was already\n // in flight. If that run ends before draining its queue the prompt\n // is dropped silently: no turn starts, no error surfaces, and the\n // decision reports success while the card sits in its new stage with\n // nobody working. Signals persist under their generation-scoped id\n // (the same identity the replay guard above reads), so confirm the\n // message actually landed in the thread rather than trusting the ack.\n if (await kickoffLanded()) break;\n\n // Another run can start while the previous run is finishing, so one\n // redelivery is not enough to prove the session is idle. Follow each\n // run boundary until the kickoff either lands on an active run or\n // wakes a new one.\n if (!(await run.wait())) {\n throw new FactoryDispatchError(\n 'run_terminal_event_missing',\n 'Factory skill invocation is waiting on a run whose terminal event was not observed.',\n );\n }\n // The queued copy often surfaces only once the run it was queued\n // onto ends. Resend only when it is still missing, and never once\n // the card has moved on or the seat was handed over or revoked —\n // a stale kickoff would restart a phase that already finished.\n if (await kickoffLanded()) break;\n if (await kickoffStale()) throw new FactoryDecisionSuperseded();\n // Stopped while the kickoff was queued: resending would restart what was just stopped.\n if (await stopRequested()) throw new FactoryRunStopped();\n run.arm();\n settled = await sendKickoff();\n }\n if (goal) await this.#remindPhaseGoal(record, goal, session, binding, requestContext);\n await this.#recordRunStart(\n session,\n binding,\n deliveryId,\n record.approvedBy ?? undefined,\n run.endReason,\n item?.title,\n );\n this.#reviewWatched.add(record);\n await this.#reviewStatus(record, decision, { phase: 'reviewing', startedAt: since });\n // A landed `deliver` still runs on the in-flight session, so the run's\n // terminal outcome matters as much as a fresh wake's: a run that ends\n // in error after accepting the prompt has still failed this decision.\n try {\n await this.#reportingRunEnd(\n {\n binding,\n startedBy,\n since,\n attempts: record.attempts,\n // A role that handed the card on mid-turn: the failure is its successor's, not ours.\n superseded: async () =>\n (await run.supersededAtEnd()) ?? (await this.#roleSuperseded(record, decision.role)),\n },\n async () => {\n await this.#withOpenRunHeartbeat(session, deliveryId, () => run.settle());\n if (run.endReason() !== 'complete' || workingRevision === null || (await run.supersededAtEnd()))\n return;\n // A final tool result can persist after agent_end. Read this binding's trailing\n // results before deciding the unchanged card means the run did no work.\n await this.#reconcileRunBinding?.(binding);\n const after = await this.#storage.get({ orgId: record.orgId, id: record.workItemId! });\n if (after?.revision === workingRevision && !(await kickoffStale())) {\n const linked = await this.#storage.listLinked({ item: after, limit: 100 });\n const ownCardHandOff = linked.some(card => {\n if (\n card.parentWorkItemId !== after.id ||\n existingLinkedReviewIds.has(card.id) ||\n card.externalSource?.integrationId !== 'github' ||\n card.externalSource.type !== 'pull-request' ||\n card.stages.length !== 1\n )\n return false;\n const review = boards?.get(boardForWorkItem(card))?.phases[card.stages[0]!];\n return review?.kind === 'working' && review.runner.context === 'review';\n });\n if (ownCardHandOff) return;\n throw new FactoryDispatchError(\n 'run_incomplete',\n 'Factory skill run ended before completing the working phase.',\n );\n }\n },\n );\n // Handed on before the turn ended: the run's clean end is the successor's, not\n // a finished review. A move after the turn ended (a merge) keeps the completion.\n if (await run.supersededAtEnd()) {\n this.#reviewWatched.delete(record);\n await this.#reviewStatus(record, decision, { phase: 'cancelled', endedAt: new Date() });\n }\n } catch (error) {\n // Roles share one session. When this role handed the card on\n // mid-turn, the next role's kickoff was delivered onto the same\n // run and the turn never ended for us — its eventual verdict is\n // the successor's to record, not ours. Capture that state when the\n // terminal event arrives so a later hand-on cannot erase our failure.\n const superseded = (await run.supersededAtEnd()) ?? (await this.#roleSuperseded(record, decision.role));\n if (!superseded) throw error;\n this.#reviewWatched.delete(record);\n await this.#reviewStatus(record, decision, { phase: 'cancelled', endedAt: new Date() });\n }\n } finally {\n run.close();\n }\n });\n return;\n }\n case 'sendMessage': {\n const binding = await this.#messageBinding(record, decision);\n // Nobody live on the card means nobody to tell, not a failure to retry.\n if (!binding) return;\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const requestContext = factoryRequestContext({\n session,\n binding,\n userId: startedBy,\n orgId: record.orgId,\n });\n await awaitNotification(\n () =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'rule-message',\n summary: decision.message,\n priority: decision.priority ?? 'high',\n payload: { message: decision.message },\n sourceId: record.id,\n dedupeKey: record.idempotencyKey,\n },\n {\n ifActive: { behavior: 'deliver' },\n ifIdle: { behavior: decision.idleBehavior ?? 'wake' },\n requestContext,\n },\n ),\n // A persist message succeeds by being stored for the idle session;\n // only a message that must wake or reach a live run fails without it.\n decision.idleBehavior !== 'persist',\n );\n return;\n }\n case 'signalActivity': {\n await this.#signalActivity(record, decision);\n return;\n }\n case 'dismissStaleReviews': {\n if (!this.#dismissStaleReviews) throw new Error('GitHub review dismissal is not configured.');\n await this.#dismissStaleReviews(decision);\n return;\n }\n case 'notify': {\n const selected = await this.#requireBinding(record);\n if (\n (await this.#roleSuperseded(record, selected.role)) ||\n (await this.#decisionOvertaken(record, selected.role))\n ) {\n throw new FactoryDecisionSuperseded();\n }\n const binding = await this.#requireOrPrepareBinding(record, selected.role, selected.id);\n // A notification can wake the idle session, so it runs as the session's\n // owner like any other Factory-started run, never as nobody.\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const requestContext = factoryRequestContext({ session, binding, userId: startedBy, orgId: record.orgId });\n await awaitNotification(() =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'rule-notification',\n summary: decision.title,\n payload: { body: decision.body, level: decision.level },\n sourceId: record.id,\n dedupeKey: record.idempotencyKey,\n },\n { requestContext },\n ),\n );\n }\n }\n }\n\n /**\n * The project's card for a Linear issue by its stable id, wherever its identifier now points.\n * A live card wins over finished ones, as in the Linear rules and issue detail route.\n */\n async #linearCardByIssueId(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n boards: BoardRegistry,\n ) {\n const issueId = decision.metadata?.linearIssueId;\n if (decision.source !== 'linear-issue' || typeof issueId !== 'string') return null;\n const items = await this.#storage.listShared({ orgId: record.orgId, factoryProjectId: record.factoryProjectId });\n const cards = items.filter(\n item => item.externalSource?.integrationId === 'linear' && item.workItem.metadata?.linearIssueId === issueId,\n );\n const card = cards.find(item => !isTerminalWorkItem(boards, item)) ?? cards[0];\n // The shared list is the cache itself: hand on a copy of the card.\n return card ? structuredClone(card) : null;\n }\n\n async #upsertLinkedItem(\n record: FactoryDeferredDecisionRecord,\n requested: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n causalChain: FactoryRuleCausalEntry[],\n ): Promise<void> {\n if (\n this.#factoryProjectExists &&\n !(await this.#factoryProjectExists({ orgId: record.orgId, factoryProjectId: record.factoryProjectId }))\n ) {\n return;\n }\n // A lost completion acknowledgement must not reinterpret a committed\n // materialization against a replacement installation.\n const existing = await this.#storage.getByProjectSource({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n source: externalSourceForDecision(requested),\n });\n // A pull request attached to its issue's card is filed already. Re-filing it (a replayed\n // or swept \"opened\") must not write its facts onto the card's primary issue source. A\n // reopen is the one fact it brings: the attached source is open again.\n if (\n existing &&\n externalSourceKey(existing.externalSource) !== externalSourceKey(externalSourceForDecision(requested))\n ) {\n const source = externalSourceForDecision(requested);\n const facts = workItemProviderAdapter(source).toSource(source, requested.metadata ?? null);\n // The card a pull request linked to may not have had its event yet (the delivery that\n // linked it lost a race); the event's key makes this a no-op once it has.\n if (requested.closesIssue?.workItemId === existing.id && record.workItemId === null) {\n await this.#queueLinkedPullRequestOpened(record, requested, existing, causalChain);\n }\n if (facts?.state === 'open') {\n await this.#storage.syncWorkItemSource({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n provider: facts.provider,\n externalId: facts.externalId,\n patch: current =>\n current.state === 'closed' || current.state === 'merged'\n ? { state: facts.state, metadata: { ...current.metadata, ...facts.metadata } }\n : null,\n });\n }\n return;\n }\n if (!existing && requested.attachTo) {\n // A card takes a pull request when its board reviews pull requests; elsewhere the pull\n // request is filed as its own card.\n const attachBoards = await this.#boards.load(record);\n if (\n await this.#attachLinkedItem(record, requested, requested.attachTo.workItemId, causalChain, card =>\n cardBoardFlow(attachBoards, card).pullRequestReview !== undefined ? { phase: null } : undefined,\n )\n ) {\n return;\n }\n }\n if (!existing && requested.closesIssue && (await this.#linkClosedIssue(record, requested, causalChain))) return;\n const materializedHere = existing?.metadata?.[FACTORY_RULE_MATERIALIZATION_KEY] === record.idempotencyKey;\n // Filing the card *was* the placement, so a retry of the same decision has\n // nothing left to apply — and must not drag a card that has since moved\n // back down to the stage this decision filed it at.\n if (materializedHere && requested.skipRules === true) return;\n const boards = await this.#boards.load(record);\n // A Linear identifier changes when its issue moves teams; the card filed\n // under the old one is still this issue's card.\n const renamed = existing ? null : await this.#linearCardByIssueId(record, requested, boards);\n // Intake routes place only a card this decision files (or is still filing,\n // on a retry); a card already on the board stays where it is.\n const current = existing ?? renamed;\n const decision = !current\n ? await this.#routeArrival(record, requested, boards)\n : materializedHere\n ? await this.#resumeRoutedCard(record, current, requested, boards)\n : this.#keepRoutedCard(current, requested, boards);\n // No board took it: logged Not routed, and filed only once a rule takes it (Route again).\n if (!decision) return;\n if (materializedHere) {\n for (const suffix of ['destination', 'initial-entry']) {\n const replay = await this.#storage.getTransitionResultByIngress(\n record.orgId,\n record.factoryProjectId,\n `decision:${record.idempotencyKey}:${existing.id}:${suffix}`,\n );\n if (replay?.status === 'accepted' && replay.stage === decision.stage) {\n await this.#resolveNotRouted(record, decision.sourceKey);\n return;\n }\n }\n }\n assertFactoryDecisionTarget(decision, boards);\n const definition = boards.get(decision.board);\n if (!definition) throw new Error('Factory decision target board is not installed.');\n const initialPhase = definition.initialPhase;\n // `skipRules` files the card at the stage the decision names, as its first\n // entry, and runs none of the board's phase rules. Without it the card\n // enters through the board's initial phase and transitions from there, so\n // arrival and destination-entry rules both run.\n const skipRules = decision.skipRules === true;\n const entryStage = skipRules ? decision.stage : initialPhase;\n const parentWorkItemId =\n record.workItemId ??\n (await this.#resolveLinkedWorkItemParentId?.({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n decision,\n })) ??\n null;\n let result: UpsertWorkItemResult = renamed\n ? {\n created: false,\n item: renamed,\n previous: { stages: renamed.stages, sessionRoles: Object.keys(renamed.sessions) },\n }\n : await this.#storage.upsert({\n orgId: record.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: record.factoryProjectId,\n input: {\n externalSource: externalSourceForDecision(decision),\n parentWorkItemId,\n title: decision.title,\n ...(decision.description ? { description: decision.description } : {}),\n board: decision.board,\n stages: [entryStage],\n sessions: {},\n metadata: { ...decision.metadata, [FACTORY_RULE_MATERIALIZATION_KEY]: record.idempotencyKey },\n },\n reuseMode: 'preserve',\n });\n // The item is filed once its card stands past initial entry; a retry of this decision resolves it too.\n const filed = () => this.#resolveNotRouted(record, decision.sourceKey);\n const itemBoard = boardForWorkItem(result.item);\n // A pull request's own card already on another board that reviews pull requests (the retired\n // Review board, for a project still using it) stays there: filing its pull request again acts\n // on it where it sits, in that board's own review phase.\n const itemFlow = itemBoard === decision.board ? undefined : boardFlow(boards.get(itemBoard));\n const keptReview = isPullRequestCard({ source: workItemSource(result.item.externalSource) })\n ? itemFlow?.pullRequestReview\n : undefined;\n const board = keptReview === undefined ? decision.board : itemBoard;\n const placeStage =\n keptReview !== undefined && decision.stage === boardFlow(definition).pullRequestReview\n ? keptReview\n : decision.stage;\n if (!skipRules && itemBoard !== board) {\n throw new Error(`The work item belongs to board \"${itemBoard}\", not \"${board}\".`);\n }\n // A re-evaluation for an already-filed card (poll/reconcile re-emitting\n // \"opened\") resolves the card itself as the triggering item; it is not\n // its own parent.\n if (!result.item.parentWorkItemId && parentWorkItemId && parentWorkItemId !== result.item.id) {\n const item = await this.#storage.setParentWorkItemIfMissing({\n orgId: record.orgId,\n id: result.item.id,\n userId: 'factory-rule-dispatcher',\n parentWorkItemId,\n });\n if (item) result = { ...result, item };\n }\n // A `skipRules` decision is a placement and nothing else: the backfill would\n // otherwise walk the arrival decision's facts back onto an existing card,\n // restamping trust the sweep deliberately left unanswered.\n if (!result.created && !skipRules) {\n // Backfill source facts (e.g. sourceCreatedAt) that older cards were filed\n // without. Fill-only: never overwrite, and never adopt the card as\n // materialized by this decision.\n const providerKeys = workItemProviderAdapter(result.item.externalSource).providerMetadataKeys;\n const missing = Object.fromEntries(\n Object.entries(decision.metadata ?? {}).filter(\n ([key]) =>\n key !== FACTORY_RULE_MATERIALIZATION_KEY &&\n (providerKeys.includes(key) ? result.item.workItem.metadata?.[key] : result.item.metadata?.[key]) ===\n undefined,\n ),\n );\n if (Object.keys(missing).length > 0) {\n const filled = await this.#storage.syncCard({\n orgId: record.orgId,\n id: result.item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: missing },\n fillOnly: true,\n });\n if (filled) result = { ...result, item: filled.item };\n }\n }\n if (skipRules) {\n // Creation already filed the card at `stage`. An existing card — one a\n // reconcile pass files again, say — is placed there the same way, through\n // a cross-board relocation, so no phase rule runs for it and no transition\n // is recorded.\n // Another decision of the same delivery (a pull request attaching to this card, say) can\n // change the card in between; a placement skipped for that reason is retried on a fresh read.\n let item: Card | null = result.created ? null : result.item;\n for (let attempt = 0; item && attempt < 3; attempt += 1) {\n const outcome = await moveCardToBoard({\n workItems: this.#storage,\n boardRegistry: boards,\n userId: 'factory-rule-dispatcher',\n item,\n targetBoard: board,\n targetStage: placeStage,\n });\n if (outcome !== 'skipped') break;\n const fresh = await this.#storage.get({ orgId: record.orgId, id: item.id });\n item = fresh && fresh.revision !== item.revision ? fresh : null;\n }\n await filed();\n return;\n }\n const materializedByDecision = result.item.metadata?.[FACTORY_RULE_MATERIALIZATION_KEY] === record.idempotencyKey;\n if (!materializedByDecision && (decision.stage === initialPhase || !result.item.stages.includes(initialPhase))) {\n await filed();\n return;\n }\n\n let expectedRevision = result.item.revision;\n if (materializedByDecision) {\n const initial = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: result.item.id,\n board,\n stage: initialPhase,\n expectedRevision,\n actor: deferredActor(record),\n ingress: { type: 'rule', identity: `decision:${record.idempotencyKey}:${result.item.id}:initial-entry` },\n cause: 'linked_item_materialized',\n causalChain,\n initialEntry: true,\n });\n if (initial.status === 'rejected') {\n if (result.created)\n await this.#storage.delete({ orgId: record.orgId, id: result.item.id, purgeRuleState: false });\n throw new FactoryRuleRejectedError(initial.code, initial.reason);\n }\n expectedRevision = initial.revision;\n }\n await filed();\n if (decision.stage === initialPhase) return;\n\n const moved = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: result.item.id,\n board,\n stage: decision.stage,\n expectedRevision,\n actor: { type: 'system', id: 'factory-rule-dispatcher' },\n ingress: { type: 'rule', identity: `decision:${record.idempotencyKey}:${result.item.id}:destination` },\n cause: materializedByDecision ? 'linked_item_materialized' : 'linked_item_reconciled',\n causalChain,\n // The stage is what intake resolved — a route or the project's default — so, as with a\n // route's status-event move, the first phase's next phases don't restrict it. Only for the\n // card this decision files, though: a reconciled card keeps its board's edges.\n ...(materializedByDecision ? { routeFiling: true } : {}),\n });\n if (moved.status === 'rejected') throw new FactoryRuleRejectedError(moved.code, moved.reason);\n }\n\n /**\n * Files a pull or merge request on the existing card `workItemId`, as one more source, when\n * `admit` takes the card as it is now; the card then moves to the phase `admit` names when its\n * board allows it. Returns false when the card can't take it (gone, finished, a pull request's\n * own card, refused by `admit`, or another card took the record first), so the caller files the\n * record as usual. `admit` runs again on a fresh read whenever the card changed in between.\n */\n async #attachLinkedItem(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n workItemId: string,\n causalChain: FactoryRuleCausalEntry[],\n admit: (card: Card) => { phase: string | null } | undefined,\n cardMetadata?: (metadata: Record<string, unknown>, card: Card) => Record<string, unknown>,\n afterAttach?: (card: Card) => Promise<void>,\n ): Promise<boolean> {\n // A dry run of the work item split has no sources table to attach to: the pull request\n // gets its own card, as before.\n if (this.#storage.legacyMode) return false;\n const boards = await this.#boards.load(record);\n let attached: { card: Card; phase: string | null } | undefined;\n for (let attempt = 0; attempt < 3 && !attached; attempt++) {\n const card = await this.#storage.get({ orgId: record.orgId, id: workItemId });\n if (\n !card ||\n card.factoryProjectId !== record.factoryProjectId ||\n isTerminalWorkItem(boards, card) ||\n isPullRequestCard({ source: workItemSource(card.externalSource) })\n ) {\n return false;\n }\n const admitted = admit(card);\n if (!admitted) return false;\n try {\n // At the revision `admit` read: work starting or another pull request landing in between\n // sends the record round again.\n const result = await this.#storage.attachSource({\n orgId: record.orgId,\n id: card.id,\n source: externalSourceForDecision(decision),\n metadata: decision.metadata ?? null,\n expectedRevision: card.revision,\n // The card as `admit` read it: the attach commits at that revision.\n ...(cardMetadata\n ? { cardMetadata: (metadata: Record<string, unknown>) => cardMetadata(metadata, card) }\n : {}),\n });\n if (!result) return false;\n attached = { card: result.item, phase: admitted.phase };\n } catch (error) {\n if (error instanceof WorkItemSourceConflictError) return false;\n if (error instanceof WorkItemUpdateConflictError) continue;\n throw error;\n }\n }\n if (!attached) return false;\n const { card, phase } = attached;\n await afterAttach?.(card);\n const stage = card.stages.length === 1 ? card.stages[0] : undefined;\n const board = boards.get(boardForWorkItem(card));\n if (!phase || !stage || stage === phase) return true;\n if (!board?.allowsTransition(stage, phase)) {\n console.warn(\n `[factory] attached a pull request to ${card.id}, which stays in ${stage}: its board has no move to ${phase}`,\n );\n return true;\n }\n const moved = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: card.id,\n board: board.id,\n stage: phase,\n expectedRevision: card.revision,\n actor: { type: 'system', id: 'factory-rule-dispatcher' },\n ingress: { type: 'rule', identity: `decision:${record.idempotencyKey}:${card.id}:attach` },\n cause: 'linked_item_attached',\n causalChain,\n });\n // The pull request is on the card either way, and a retry would not move it.\n if (moved.status === 'rejected') {\n console.warn(\n `[factory] attached a pull request to ${card.id} but could not move it to ${phase}: ${moved.code}: ${moved.reason}`,\n );\n }\n return true;\n }\n\n /**\n * Links a pull or merge request to the card of the issue it closes, whoever opened it: Factory\n * does this itself, before intake, wherever the card sits, so long as it is unfinished. Linking\n * runs nothing. An outsider's pull request is recorded as untrusted on the card, so it never\n * becomes the card's working pull request on its own; a person picks it. The card then gets the\n * pull request's `pull_request.opened`, so its board's own card-move rules decide whether it moves.\n */\n async #linkClosedIssue(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n causalChain: FactoryRuleCausalEntry[],\n ): Promise<boolean> {\n if (decision.skipRules === true || record.workItemId !== null) return false;\n const trusted = authorTrusted(decision.metadata);\n const trustKey = this.#pullRequestTrustKey(decision);\n return this.#attachLinkedItem(\n record,\n decision,\n decision.closesIssue!.workItemId,\n causalChain,\n () => ({ phase: null }),\n (metadata, card) => {\n const links = linkedPullRequests(metadata);\n const withLink = {\n ...metadata,\n [LINKED_PULL_REQUESTS_KEY]: { ...links, [trustKey]: links[trustKey] ?? linkFacts(card, trusted, trustKey) },\n };\n if (trusted) return withLink;\n const listed = metadata[UNTRUSTED_PULL_REQUESTS_KEY];\n const untrusted = Array.isArray(listed) ? listed.filter(entry => typeof entry === 'string') : [];\n return untrusted.includes(trustKey)\n ? withLink\n : { ...withLink, [UNTRUSTED_PULL_REQUESTS_KEY]: [...untrusted, trustKey] };\n },\n card => this.#queueLinkedPullRequestOpened(record, decision, card, causalChain),\n );\n }\n\n /** The key a card lists an untrusted attached pull request under (see `UNTRUSTED_PULL_REQUESTS_KEY`). */\n #pullRequestTrustKey(decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>): string {\n const source = externalSourceForDecision(decision);\n return pullRequestTrustKey(workItemProviderAdapter(source).toSource(source, decision.metadata ?? null)!);\n }\n\n /**\n * Hands the card a linked pull request's `pull_request.opened`, with the facts saved when it\n * joined (the card's phase then, and whether a trusted open pull request was already on it), so\n * a retry after the card changed still describes the link as it happened. Keyed by the card and\n * the pull request, so whichever delivery files the pull request, and however often, the card\n * gets the event once.\n */\n async #queueLinkedPullRequestOpened(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n card: Card,\n causalChain: FactoryRuleCausalEntry[],\n ): Promise<void> {\n const sourceKey = externalSourceKey(externalSourceForDecision(decision));\n const key = `linked-pull-request:${card.id}:${sourceKey}`;\n const trustKey = this.#pullRequestTrustKey(decision);\n // A link from before the facts were saved with it reads them off the card as it is now.\n const link =\n linkedPullRequests(card.metadata)[trustKey] ?? linkFacts(card, authorTrusted(decision.metadata), trustKey);\n const queued = await this.#storage.commitRuleEvaluation({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: card.id,\n ingress: { identity: `decision:${key}` },\n expectedRevision: card.revision,\n actor: { type: 'system', id: 'factory-rule-dispatcher' },\n outcome: { status: 'accepted' },\n decisions: [\n {\n type: 'routeEvent',\n idempotencyKey: key,\n event: {\n type: 'pull_request.opened',\n pullRequestTrusted: link.trusted,\n // The author opened it, so the opener's trust is the author's.\n actorTrusted: link.trusted,\n closedIssue: { phase: link.phase, hasPullRequest: link.hasPullRequest },\n },\n },\n ],\n causalChain,\n now: new Date(),\n });\n if (queued.status === 'stale') {\n throw new Error('Factory linked pull request event was not queued: the work item changed concurrently.');\n }\n }\n\n /**\n * Leaves a warning in the decision log for each card-move rule that matched but whose target\n * couldn't take the card; a redelivery of the same event replaces it.\n */\n async #logSkippedRoutes(\n record: FactoryDeferredDecisionRecord,\n item: Card,\n event: BoardEventFacts,\n skipped: readonly SkippedEventRoute[],\n ): Promise<void> {\n if (!this.#intakeRoutes || skipped.length === 0) return;\n const scope = { orgId: record.orgId, factoryProjectId: record.factoryProjectId };\n const evaluator = await projectIntakeEvaluator(this.#intakeEvaluator, this.#intakeRoutes, scope);\n for (const skip of skipped) {\n await this.#intakeRoutes.recordIntakeDecision(scope, {\n idempotencyKey: `rule-skipped:${record.idempotencyKey}:${skip.routeId}`,\n outcome: 'rule_skipped',\n evaluator,\n boardKey: skip.boardKey,\n routeId: skip.routeId,\n reason: `The card-move rule matched ${event.type} but was skipped: ${skip.reason}.`,\n sourceKey: item.externalSource?.externalId ?? null,\n title: item.title,\n url: item.externalSource?.url ?? null,\n });\n }\n }\n\n /** Marks the item's Not routed record, if any, resolved: its card is filed. */\n async #resolveNotRouted(record: FactoryDeferredDecisionRecord, sourceKey: string): Promise<void> {\n await this.#intakeRoutes?.resolveNotRouted(\n { orgId: record.orgId, factoryProjectId: record.factoryProjectId },\n sourceKey,\n 'factory-rule-dispatcher',\n );\n }\n\n /**\n * Places an arrival where intake says (see `resolveIntake`). The board and phase an\n * integration's rule named don't count; only a decision placing the card outright (`skipRules`)\n * keeps its own. Undefined when no board takes it: it is logged Not routed and no card is filed.\n * Every decision is logged, keyed by the arrival's decision so a redelivery replaces its row.\n */\n async #routeArrival(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n boards: BoardRegistry,\n ): Promise<Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }> | undefined> {\n if (decision.skipRules === true) return decision;\n // A card another card's rule files (a board's child card) goes where that\n // board put it; routes place only what arrives from outside.\n if (record.workItemId !== null) return decision;\n if (!this.#intakeRoutes) {\n // Only a forced route list may file without the rules: unread, the project's setting could be\n // intake order, which has no board to fall back on. The arrival waits for the rules.\n if (this.#intakeEvaluator !== 'route-list') throw new Error('Intake rules are unavailable right now.');\n return decision;\n }\n const scope = { orgId: record.orgId, factoryProjectId: record.factoryProjectId };\n const evaluator = decision.idempotencyKey.startsWith(ROUTE_AGAIN_KEY_PREFIX)\n ? 'intake-order'\n : await projectIntakeEvaluator(this.#intakeEvaluator, this.#intakeRoutes, scope);\n const [routes, order] = await Promise.all([\n this.#intakeRoutes.listIntakeRoutes(scope),\n evaluator === 'intake-order'\n ? this.#intakeRoutes.readIntakeOrder(scope, { boards: [...boards.keys()] })\n : undefined,\n ]);\n const facts = await arrivalRuleFacts(decision, {\n factoryProjectId: record.factoryProjectId,\n registry: boards,\n card: id => this.#storage.get({ orgId: record.orgId, id }),\n });\n const resolution = resolveIntake({\n evaluator,\n routes,\n order: order?.boardKeys ?? [],\n facts,\n registry: boards,\n });\n const logged = {\n idempotencyKey: record.idempotencyKey,\n evaluator,\n sourceKey: decision.sourceKey,\n title: decision.title,\n url: decision.url,\n };\n if (resolution.outcome === 'not_routed') {\n await this.#intakeRoutes.recordIntakeDecision(scope, {\n ...logged,\n outcome: 'not_routed',\n reason: resolution.reason,\n arrival: { ...decision },\n });\n return undefined;\n }\n await this.#intakeRoutes.recordIntakeDecision(scope, {\n ...logged,\n outcome: 'placed',\n boardKey: resolution.board,\n routeId: resolution.routeId,\n });\n return {\n ...decision,\n board: resolution.board,\n stage: resolution.phase,\n ...(resolution.routeId !== null && {\n metadata: { ...decision.metadata, [INTAKE_ROUTE_METADATA_KEY]: resolution.routeId },\n }),\n };\n }\n\n /**\n * A retry of the decision that filed `existing` finishes the filing where it started: on the\n * card's board, at the phase its route names now, or the board's first phase when the route was\n * deleted, disabled or re-pointed since. Routes are not re-run, so an edit cannot send the card\n * to a board it isn't on.\n */\n async #resumeRoutedCard(\n record: FactoryDeferredDecisionRecord,\n existing: Card,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n boards: BoardRegistry,\n ): Promise<Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>> {\n const routeId = existing.metadata?.[INTAKE_ROUTE_METADATA_KEY];\n if (typeof routeId !== 'string') return decision;\n const board = boards.get(boardForWorkItem(existing));\n if (!board) return decision;\n const routes = this.#intakeRoutes\n ? await this.#intakeRoutes.listIntakeRoutes({ orgId: record.orgId, factoryProjectId: record.factoryProjectId })\n : [];\n const route = routes.find(entry => entry.id === routeId && entry.enabled && entry.target.boardKey === board.id);\n return {\n ...decision,\n board: board.id,\n stage: resumeLandingPhase(board, route?.target.phaseKey, cardRuleFacts(existing), hasPullRequest(existing)),\n metadata: { ...decision.metadata, [INTAKE_ROUTE_METADATA_KEY]: routeId },\n };\n }\n\n /**\n * A card an intake route placed stays on the route's board when its source is filed again\n * (a reconcile replaying \"opened\"): the decision lands on the card's board at its first phase,\n * so it only backfills facts and moves nothing. An explicit placement (`skipRules`) still wins.\n */\n #keepRoutedCard(\n existing: Card,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n boards: BoardRegistry,\n ): Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }> {\n if (decision.skipRules === true || !placedByIntakeRoute(existing)) return decision;\n const board = boards.get(boardForWorkItem(existing));\n if (!board || board.id === decision.board) return decision;\n return { ...decision, board: board.id, stage: board.initialPhase };\n }\n /** Moves the card as a rule decided, then queues the decision's message for the card's session. */\n async #applyTransition(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'transition' }>,\n nextChain: FactoryRuleCausalEntry[],\n ): Promise<void> {\n const item = await this.#requireItem(record);\n const replay = await this.#storage.getTransitionResultByIngress(\n record.orgId,\n record.factoryProjectId,\n `decision:${record.idempotencyKey}`,\n );\n if (!replay) assertFactoryDecisionTarget(decision, await this.#boards.load(record), item.board ?? undefined);\n const result = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: item.id,\n board: decision.board,\n stage: decision.stage,\n expectedRevision: item.revision,\n actor: record.approvedBy\n ? { type: 'human', id: record.approvedBy }\n : { type: 'system', id: 'factory-rule-dispatcher' },\n ingress: { type: 'rule', identity: `decision:${record.idempotencyKey}` },\n cause: 'rule_decision',\n causalChain: nextChain,\n ...(decision.reenter ? { reenter: true } : {}),\n // A default rule's own move (no stored rule handled the event, or none exists) answers the\n // event too: when it is an outside author's pull request event, the run the destination\n // queues waits for a person just as a rule's move does.\n ...(decision.event && untrustedPullRequestEvent(decision.event) ? { untrustedPullRequestEvent: true } : {}),\n });\n if (result.status === 'rejected') throw new FactoryRuleRejectedError(result.code, result.reason);\n const transitionMessage = decision.message;\n if (!transitionMessage) return;\n // The message may wake an idle session and hold it for a whole agent\n // run, so it is queued as its own sendMessage decision for the run\n // pool; the stage change above never waits on run capacity. Keyed by\n // this decision, so a retry replays rather than queueing it twice.\n const moved = await this.#storage.get({ orgId: record.orgId, id: item.id });\n if (!moved) return;\n const messageKey = `${record.idempotencyKey}:message`;\n // Keyed by revision so a retry after a concurrent write commits under a\n // fresh identity at the item's new revision.\n const queued = await this.#storage.commitRuleEvaluation({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: `decision:${messageKey}@${moved.revision}` },\n expectedRevision: moved.revision,\n actor: record.actor ?? { type: 'system', id: 'factory-rule-dispatcher' },\n outcome: { status: 'accepted' },\n decisions: [\n {\n type: 'sendMessage',\n idempotencyKey: messageKey,\n message: transitionMessage.text,\n priority: 'high',\n // The move's message always reaches the card's session, but an outside author's pull\n // request event never wakes an idle one: the message persists in its notifications\n // instead, read when a person (or an approved run) brings the session back.\n idleBehavior: decision.event && untrustedPullRequestEvent(decision.event) ? 'persist' : 'wake',\n ...(transitionMessage.role !== undefined ? { role: transitionMessage.role } : {}),\n },\n ],\n causalChain: nextChain,\n now: new Date(),\n });\n if (queued.status === 'missing') return;\n if (queued.status === 'stale') {\n throw new Error('Factory transition message was not queued: the work item changed concurrently.');\n }\n const queuedStatus = (queued.result as { status?: string }).status;\n if (queuedStatus !== 'accepted') {\n throw new Error(`Factory transition message was not queued: ${queuedStatus ?? 'unknown'}.`);\n }\n }\n\n /**\n * Moves a card where the project's intake routes send it on a status event. A move into a\n * working or resting phase waits for the run in flight on the card to end, going back to the\n * queue without holding a dispatch slot until it has; a move into a\n * terminal phase does not, so terminal cleanup stops that run at once, as a close always has.\n * A close moves only an unfinished card and a reopen only a finished one. When no route on the\n * card's board handles the event at all, the rule's own move (a board's `sourceClosed` phase)\n * applies instead; when one does but none matches, the card stays. A route's move is a system\n * move by the route: recorded in the card's history and audit, keyed so a replayed delivery\n * moves nothing twice.\n */\n async #routeEvent(\n record: FactoryDeferredDecisionRecord,\n event: BoardEventFacts,\n causalChain: FactoryRuleCausalEntry[],\n fallback?: Extract<FactoryCommitDecision, { type: 'transition' }>,\n ): Promise<void> {\n const identity = eventRouteIngress(record.idempotencyKey);\n if (await this.#storage.getTransitionResultByIngress(record.orgId, record.factoryProjectId, identity)) return;\n if (await this.#statusEventOvertaken(record)) throw new FactoryDecisionSuperseded();\n const resolve = async () => {\n const item = await this.#requireItem(record);\n const boards = await this.#boards.load(record);\n const board = boards.get(boardForWorkItem(item));\n if (!board) return undefined;\n const routes = this.#intakeRoutes\n ? await this.#intakeRoutes.listIntakeRoutes({ orgId: record.orgId, factoryProjectId: record.factoryProjectId })\n : [];\n const skipped: SkippedEventRoute[] = [];\n const plan = planEventMove({\n routes,\n event,\n item,\n registry: boards,\n ...(fallback && { fallback: { stage: fallback.stage } }),\n onSkip: skip => skipped.push(skip),\n });\n await this.#logSkippedRoutes(record, item, event, skipped);\n if (plan.outcome === 'rule_default') return { item, board, fallback: true as const };\n if (plan.outcome !== 'moves') return undefined;\n return { item, board, route: plan.move, target: boards.get(plan.move.board)! };\n };\n const first = await resolve();\n if (!first) return;\n if ('fallback' in first) {\n if (fallback) await this.#applyTransition(record, fallback, causalChain);\n return;\n }\n // Checked again on the next claim: the card may have moved, or the routes changed, by then.\n if (!first.target.isTerminal(first.route.phase) && (await this.#cardRunInFlight(record, first.item))) {\n throw new FactoryDecisionPostponed();\n }\n const { item, board, route } = first;\n const crossesBoards = route.board !== board.id;\n const result = await this.#transitionService.transition({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: item.id,\n board: board.id,\n ...(crossesBoards ? { toBoard: route.board } : {}),\n stage: route.phase,\n expectedRevision: item.revision,\n actor: { type: 'system', id: `intake-route:${route.routeId}` },\n ingress: { type: 'rule', identity },\n cause: 'event_route',\n causalChain,\n eventRoute: { routeId: route.routeId },\n // The rule owns the move; a run the destination queues on an outside author's pull\n // request event still waits for a person, whether the card is the pull request's own\n // or an issue's it links to.\n ...(untrustedPullRequestEvent(event) ? { untrustedPullRequestEvent: true } : {}),\n });\n // A refusal is the card's answer (recorded on it); only a lost revision race is worth a retry.\n if (result.status === 'rejected' && result.code === 'stale')\n throw new FactoryRuleRejectedError(result.code, result.reason);\n // Work the old board proposed for the card is not the new board's to run; what the move queued\n // for the new board stays, even once another worker has parked it as a proposal.\n if (result.status === 'accepted' && crossesBoards) {\n await this.#storage.supersedeDecisionsForWorkItem({\n orgId: record.orgId,\n factoryProjectId: record.factoryProjectId,\n workItemId: item.id,\n except: result.decisions.map(decision => String(decision.idempotencyKey)),\n supersededAt: new Date(),\n });\n }\n }\n\n /**\n * Whether the card's session has a run in flight. A binding with no recorded owner never\n * started a run, so it has none.\n */\n async #cardRunInFlight(record: FactoryDeferredDecisionRecord, item: Pick<Card, 'sessions'>): Promise<boolean> {\n const binding = await this.#findBinding(record);\n const startedBy = binding ? item.sessions[binding.role]?.startedBy : undefined;\n if (!binding || !startedBy) return false;\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#findSession(binding, { userId: startedBy, orgId: record.orgId });\n return session !== undefined && (await this.#hasRunInFlight(session, binding));\n }\n\n /**\n * The one update event an update decision stands for, or undefined when it has nothing to do.\n * Updates to the same card of the same kind (work item or pull request, the card's own session\n * or anyone else) and to the same pull request fold into the newest one: an older one gives way to it, and the newest carries\n * the net change of every one since the group last moved the card, so a label added then removed\n * nets out. The newest waits until no update has arrived for {@link UPDATE_BURST_MS}, and one\n * from the card's own session also until the session's run ends.\n */\n async #foldUpdates(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'routeEvent' }>,\n now: Date,\n ): Promise<BoardEventFacts | undefined> {\n if (!record.workItemId) return undefined;\n const group = updateGroup(\n await this.#storage.listDeferredDecisions(record.orgId, record.factoryProjectId, {\n workItemId: record.workItemId,\n }),\n decision,\n );\n const { superseded, since, event } = await foldUpdate(group, record.id, other =>\n this.#moveCommitted(record, other),\n );\n // A newer update not given up on carries this one's change: it folded it, or will.\n if (superseded) throw new FactoryDecisionSuperseded();\n // An older one still leased may be moving the card right now, so wait for it. One claimed in\n // the same batch as this one (same owner, same lease, before any renewal) sees this one and\n // gives way. Lease renewal rewrites `updatedAt`, so it can't tell when the older one was claimed.\n const sameClaim = (other: FactoryDeferredDecisionRecord) =>\n other.leaseOwner === record.leaseOwner && other.leaseExpiresAt?.getTime() === record.leaseExpiresAt?.getTime();\n if (since.some(other => other.status === 'leased' && !sameClaim(other))) {\n throw new FactoryDecisionPostponed();\n }\n const quietAt = record.createdAt.getTime() + UPDATE_BURST_MS;\n if (now.getTime() < quietAt) throw new FactoryDecisionPostponed(new Date(quietAt));\n if (decision.fromCardSession) {\n const item = await this.#requireItem(record);\n if (await this.#cardRunInFlight(record, item)) throw new FactoryDecisionPostponed();\n }\n return event;\n }\n\n /** Whether `other`'s card move committed, even if its decision never finished. */\n async #moveCommitted(record: FactoryDeferredDecisionRecord, other: FactoryDeferredDecisionRecord): Promise<boolean> {\n const identity = eventRouteIngress(other.idempotencyKey);\n return Boolean(await this.#storage.getTransitionResultByIngress(record.orgId, record.factoryProjectId, identity));\n }\n\n /**\n * Whether a later status event was queued for the same card: the source's last word wins, so a\n * close still queued when the issue is reopened moves nothing. Of events queued in the same\n * millisecond, the one with the greatest id is the last; one already settled had its turn.\n */\n async #statusEventOvertaken(record: FactoryDeferredDecisionRecord): Promise<boolean> {\n if (!record.workItemId || !isStatusEventDecision(record.decision)) return false;\n const decisions = await this.#storage.listDeferredDecisions(record.orgId, record.factoryProjectId, {\n workItemId: record.workItemId,\n });\n return decisions.some(\n other =>\n other.id !== record.id &&\n isStatusEventDecision(other.decision) &&\n (other.createdAt.getTime() > record.createdAt.getTime() ||\n (other.createdAt.getTime() === record.createdAt.getTime() &&\n other.completedAt === null &&\n other.id > record.id)),\n );\n }\n\n async #requireItem(record: FactoryDeferredDecisionRecord) {\n if (!record.workItemId) throw new Error('Factory decision is not linked to a work item.');\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n if (!item) throw new Error('Factory work item not found.');\n return item;\n }\n\n async #findBinding(\n record: FactoryDeferredDecisionRecord,\n role?: string,\n ): Promise<FactoryRunBindingRecord | undefined> {\n if (!record.workItemId) throw new Error('Factory decision is not linked to a work item.');\n const bindings = await this.#storage.listRunBindings(record.orgId, record.factoryProjectId, record.workItemId);\n const active = bindings.filter(\n candidate => candidate.status === 'active' && (role === undefined || candidate.role === role),\n );\n // Without a role, the builder's session answers for the card: it owns the work.\n let builder: string | undefined;\n if (role === undefined && active.length > 1) {\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n builder = item ? cardBoardFlow(await this.#boards.load(record), item).buildRole : undefined;\n }\n return active.sort((left, right) => {\n if (builder !== undefined && left.role === builder && right.role !== builder) return -1;\n if (builder !== undefined && right.role === builder && left.role !== builder) return 1;\n return right.createdAt.getTime() - left.createdAt.getTime() || left.id.localeCompare(right.id);\n })[0];\n }\n\n async #requireBinding(record: FactoryDeferredDecisionRecord, role?: string): Promise<FactoryRunBindingRecord> {\n const binding = await this.#findBinding(record, role);\n if (!binding) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n role ? `No active Factory binding for role ${role}.` : 'No active Factory binding.',\n );\n }\n return binding;\n }\n\n /**\n * Points the card's live session at new activity on its source. The message\n * is written here from the decision's pointers, never from provider text.\n * Activity while the session is busy waits as one pending notification per\n * card and kind of activity, counting how many arrived; an idle session is\n * woken unless the decision asks to only persist. A card nobody is working\n * has nobody to tell, so it is dropped.\n */\n async #signalActivity(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'signalActivity' }>,\n ): Promise<void> {\n if (!record.workItemId) return;\n const binding = await this.#findBinding(record);\n if (!binding) return;\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const author = decision.author\n ? `@${decision.author}${decision.authorTrusted ? '' : ' (untrusted author)'}`\n : decision.authorTrusted\n ? undefined\n : 'an untrusted author';\n const message =\n decision.event === 'work_item.commented'\n ? `New comment${author ? ` by ${author}` : ''} on ${decision.reference}: ${decision.url}`\n : `${decision.reference} was edited${author ? ` by ${author}` : ''}: ${decision.url}`;\n // An untrusted author never starts a run, nor does a source that can't tell Factory's own\n // comments apart. Core never wakes a thread for a low-priority notification on any path;\n // a medium one can still wake it through a summary if the busy run ends mid-delivery.\n const wakes = decision.authorTrusted && decision.idleBehavior !== 'persist';\n await awaitNotification(() =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'source-activity',\n summary: message,\n priority: wakes ? 'medium' : 'low',\n sourceId: record.id,\n dedupeKey: record.idempotencyKey,\n coalesceKey: `${record.workItemId}:${decision.event}`,\n },\n {\n ifActive: { behavior: 'persist' },\n ifIdle: { behavior: wakes ? 'wake' : 'persist' },\n requestContext: factoryRequestContext({ session, binding, userId: startedBy, orgId: record.orgId }),\n },\n ),\n );\n }\n\n async #messageBinding(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'sendMessage' }>,\n ): Promise<FactoryRunBindingRecord | undefined> {\n if (decision.prepareBinding && decision.role !== undefined) {\n return this.#requireOrPrepareBinding(record, decision.role);\n }\n return this.#findBinding(record, decision.role);\n }\n\n /**\n * A role is superseded when its binding was revoked by a later role taking\n * the same session (`prepareRunBinding` revokes every other active binding on\n * that session). Only a hand-on — the running agent or a person moving the\n * card — produces that shape, so the role's job is done: its decision is not\n * owed a retry, and whatever ends the shared turn afterwards belongs to the\n * successor's decision. A revoke with no successor (terminal cleanup, an\n * operator pulling the seat) is not supersession and still fails as before.\n * Only a hand-on that happened after this decision was queued counts: a\n * fresh decision for the role (the card came back to it) must still dispatch\n * even though an older revoked binding for that role is on record.\n */\n async #decisionOvertaken(record: FactoryDeferredDecisionRecord, role: string): Promise<boolean> {\n if (!record.workItemId) return false;\n const [item, siblings] = await Promise.all([\n this.#storage.get({ orgId: record.orgId, id: record.workItemId }),\n this.#storage.listDecisionsForEvaluations(record.orgId, record.factoryProjectId, [record.evaluationId]),\n ]);\n return decisionOvertaken({ boards: await this.#boards.load(record), item, record, role, siblings });\n }\n\n async #roleSuperseded(record: FactoryDeferredDecisionRecord, role: string): Promise<boolean> {\n if (!record.workItemId) return false;\n const bindings = await this.#storage.listRunBindings(record.orgId, record.factoryProjectId, record.workItemId);\n const own = bindings.filter(candidate => candidate.role === role);\n // An active seat for this role still runs — a terminal card can legitimately\n // hold one (e.g. a close-out skill dispatched on `done`).\n if (own.some(candidate => candidate.status === 'active')) return false;\n // With no active seat left, a card that has already reached a terminal stage\n // can never mint one for this role again, and its bindings are being revoked\n // out from under the run by terminal-stage cleanup. Treat the decision as\n // superseded so it stops retrying to MAX_ATTEMPTS as `session_unavailable`.\n const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId }).catch(() => null);\n if (item && workItemPhaseSemantics(await this.#boards.load(record), item)?.kind === 'terminal') return true;\n return own.some(\n revoked =>\n revoked.revokedAt !== null &&\n revoked.revokedAt.getTime() >= record.createdAt.getTime() &&\n bindings.some(\n successor =>\n successor.role !== role &&\n successor.status === 'active' &&\n successor.resourceId === revoked.resourceId &&\n successor.sessionId === revoked.sessionId &&\n successor.threadId === revoked.threadId &&\n successor.createdAt.getTime() >= revoked.revokedAt!.getTime(),\n ),\n );\n }\n\n async #requireOrPrepareBinding(\n record: FactoryDeferredDecisionRecord,\n role: string,\n expectedBindingId?: string,\n ): Promise<FactoryRunBindingRecord> {\n const binding = await this.#findBinding(record, role);\n if (expectedBindingId && binding?.id !== expectedBindingId) {\n return this.#sameRoleReplacement(record, role, expectedBindingId);\n }\n if (binding) {\n const session = await this.#controller.getSession(binding.sessionId);\n if (session) return binding;\n }\n if (!this.#prepareBinding) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n binding ? 'Bound Factory session not found.' : `No active Factory binding for role ${role}.`,\n );\n }\n const item = await this.#requireItem(record);\n try {\n await this.#prepareBinding({ record, item, role, expectedBindingId });\n } catch (error) {\n if (error instanceof FactoryRunBindingSupersededError) {\n if (expectedBindingId) return this.#sameRoleReplacement(record, role, expectedBindingId);\n throw new FactoryDecisionSuperseded();\n }\n throw error;\n }\n return this.#requireBinding(record, role);\n }\n\n async #sameRoleReplacement(\n record: FactoryDeferredDecisionRecord,\n role: string,\n expectedBindingId: string,\n ): Promise<FactoryRunBindingRecord> {\n const replacement = await this.#findBinding(record, role);\n if (\n !replacement ||\n replacement.id === expectedBindingId ||\n (await this.#roleSuperseded(record, role)) ||\n (await this.#decisionOvertaken(record, role))\n ) {\n throw new FactoryDecisionSuperseded();\n }\n if (!(await this.#controller.getSession(replacement.sessionId))) {\n throw new FactoryDispatchError('session_unavailable', 'Bound Factory session not found.');\n }\n return replacement;\n }\n\n async #findSession(\n binding: FactoryRunBindingRecord,\n owner: SessionOwner,\n ): Promise<BoundDispatcherSession | undefined> {\n const session = await this.#controller.getSession(binding.sessionId);\n if (!session) return undefined;\n await this.#switchThread(session, binding, owner);\n return session;\n }\n\n /**\n * The tool whose pauses the run answers itself: the exit tool of the card's phase, where the\n * board approves it without a person for this card. Any other pause waits for a person.\n */\n async #autoApprovedExitTool({\n orgId,\n factoryProjectId,\n workItemId,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string | null;\n }): Promise<string | undefined> {\n const item = workItemId ? await this.#storage.get({ orgId, id: workItemId }) : null;\n return item ? autoApprovedExitTool(await this.#boards.load({ orgId, factoryProjectId }), item) : undefined;\n }\n\n /** Whether a run this dispatcher watches is about to approve `toolCallId` itself, so no person needs asking. */\n autoApproves(toolCallId: string): boolean {\n return this.#autoApproving.has(toolCallId);\n }\n\n /**\n * Whether a run is in flight on any of the card's active seats, as the board shows it: a run the\n * registry here holds on a seat's thread, whoever started it, or one live on another dispatcher.\n * A read-only probe: it never switches a session's thread.\n */\n async hasRunInFlightOnCard({\n orgId,\n factoryProjectId,\n workItemId,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n }): Promise<boolean> {\n const bindings = (await this.#storage.listRunBindings(orgId, factoryProjectId, workItemId)).filter(\n binding => binding.status === 'active',\n );\n const liveThreads = new Set(this.#controller.listActiveThreadRuns().map(active => active.threadId));\n for (const binding of bindings) {\n if (liveThreads.has(binding.threadId)) return true;\n const session = await this.#controller.getSession(binding.sessionId);\n if (session && (await this.#hasRunInFlight(session, binding))) return true;\n }\n return false;\n }\n\n /**\n * Whether a run is in flight on `binding`: live here, or live on another dispatcher. An open-run\n * entry with nothing live behind it is an orphan of a dead process and does not count. Reads the\n * binding's own thread, which the session may have switched away from.\n */\n async #hasRunInFlight(session: BoundDispatcherSession, binding: FactoryRunBindingRecord): Promise<boolean> {\n const open = (await listThreadOpenRuns(session, binding.threadId)).filter(entry => entry.bindingId === binding.id);\n if (open.some(entry => isOpenRunLiveElsewhere(entry, this.#ownerId))) return true;\n // A run with no ledger entry (one the dispatcher didn't record) is still live here.\n return this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId);\n }\n\n /** Waits for the run in flight on `binding` to end, so a kickoff never overlaps it. */\n async #waitForOpenRun(session: BoundDispatcherSession, binding: FactoryRunBindingRecord, label: string) {\n const runStillActive = () =>\n this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId);\n // Only a *live* run on this binding can be duplicated by a second\n // kickoff, so that is the only thing worth waiting on. The open-run\n // ledger is shared by every replica, but the run registry is local, so\n // an entry with nothing live here is one of two things:\n // - live on another replica (fresh heartbeat from another owner):\n // hand the decision back to retry, since that owner will clear the\n // entry and only it can observe the run end;\n // - an orphan (stale or missing heartbeat): the run died with its\n // process and no `agent_end` will ever clear it. Waiting would\n // wedge the binding for good; the next observed run end sweeps it.\n while (true) {\n const openRun = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n label,\n runStillActive,\n });\n try {\n const open = (await listSessionOpenRuns(session)).filter(entry => entry.bindingId === binding.id);\n if (open.length === 0) break;\n if (open.some(entry => isOpenRunLiveElsewhere(entry, this.#ownerId))) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Factory binding ${binding.id} has a run in flight on another dispatcher.`,\n );\n }\n if (!runStillActive()) break;\n if (!(await openRun.wait())) break;\n } finally {\n openRun.close();\n }\n await waitForSessionRunAudit(session);\n }\n }\n\n async #requireSession(binding: FactoryRunBindingRecord, owner: SessionOwner): Promise<BoundDispatcherSession> {\n const session = await this.#findSession(binding, owner);\n if (!session) throw new FactoryDispatchError('session_unavailable', 'Bound Factory session not found.');\n return session;\n }\n\n // Switching subscribes to the thread, which resolves memory and model\n // credentials, so it always runs as the session owner.\n async #switchThread(\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n owner: SessionOwner,\n ): Promise<void> {\n if (session.thread.requireId() === binding.threadId) return;\n const requestContext = factoryRequestContext({ session, binding, userId: owner.userId, orgId: owner.orgId });\n await session.thread.switch({ threadId: binding.threadId, requestContext });\n }\n\n async #withBindingSkillRun(bindingId: string, effect: () => Promise<void>): Promise<void> {\n const previous = this.#bindingSkillRuns.get(bindingId);\n const run = (previous ?? Promise.resolve()).catch(() => {}).then(effect);\n this.#bindingSkillRuns.set(bindingId, run);\n try {\n await run;\n } finally {\n if (this.#bindingSkillRuns.get(bindingId) === run) this.#bindingSkillRuns.delete(bindingId);\n }\n }\n\n async #withLease(\n renew: (leaseExpiresAt: Date) => Promise<unknown | null>,\n effect: () => Promise<void>,\n ): Promise<void> {\n let renewalFailure: unknown;\n let renewal = Promise.resolve();\n const timer = setInterval(\n () => {\n renewal = renewal.then(async () => {\n try {\n const renewed = await renew(new Date(Date.now() + LEASE_MS));\n if (!renewed) renewalFailure = new Error('Factory dispatch lease was lost during execution.');\n } catch (error) {\n renewalFailure = error;\n }\n });\n },\n Math.floor(LEASE_MS / 3),\n );\n timer.unref?.();\n try {\n await effect();\n await renewal;\n if (renewalFailure) throw renewalFailure;\n } finally {\n clearInterval(timer);\n await renewal;\n }\n }\n\n /** Keep this process's claim on an open run fresh for as long as it is watching the run. */\n async #withOpenRunHeartbeat<T>(\n session: BoundDispatcherSession,\n kickoffId: string,\n effect: () => Promise<T>,\n ): Promise<T> {\n if (!this.#audit) return effect();\n const timer = setInterval(\n () => void heartbeatSessionOpenRun(session, kickoffId),\n Math.floor(FACTORY_OPEN_RUN_STALE_MS / 3),\n );\n timer.unref?.();\n try {\n return await effect();\n } finally {\n clearInterval(timer);\n }\n }\n\n /**\n * An unreadable stop counts as a stop: retrying would clear the marker and restart a run a person\n * may have just stopped, while a wrongly settled run only leaves the card idle until started again.\n */\n async #runStopRequested(orgId: string, bindingId: string): Promise<boolean> {\n try {\n return await this.#storage.runBindingStopRequested({ orgId, bindingId });\n } catch (error) {\n console.warn(\n `[factory] could not read the stop request for binding ${bindingId}; treating the run as stopped:`,\n error,\n );\n return true;\n }\n }\n\n /**\n * Settle a watched run; when it fails terminally, tell the item's followers.\n * A retryable failure says nothing, since the retry reports. How a run that\n * ran ends (done, blocked, an error) is reported by the session's own\n * listener; this covers failures no run end shows. The reporter skips\n * recipients that already have a final report from this run, and never\n * throws, so reporting can't change the decision's outcome.\n */\n async #reportingRunEnd(\n {\n binding,\n startedBy,\n since,\n attempts,\n superseded,\n }: {\n binding: FactoryRunBindingRecord;\n startedBy: string;\n since: Date;\n attempts: number;\n superseded?: () => Promise<boolean>;\n },\n settle: () => Promise<void>,\n ): Promise<void> {\n try {\n await settle();\n } catch (error) {\n const reportRunEnd = this.#reportRunEnd;\n if (\n reportRunEnd &&\n !(error instanceof RunEndedInError) &&\n !(error instanceof FactoryDecisionSuperseded) &&\n !(await superseded?.())\n ) {\n const failureCode = factoryDispatchFailureCode(error);\n if (isTerminalFailure(attempts, failureCode)) {\n void reportRunEnd({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n role: binding.role,\n sender: { sessionId: binding.sessionId, threadId: binding.threadId, userId: startedBy },\n since,\n outcome: { status: 'failed', failureCode, reason: sanitizeDispatchError(error) },\n }).catch(reportError => {\n console.warn(`[factory] run-end report failed for binding ${binding.id}:`, reportError);\n });\n }\n }\n throw error;\n }\n }\n\n async #recordRunStart(\n session: BoundDispatcherSession,\n binding: FactoryRunBindingRecord,\n kickoffId: string,\n approvedBy: string | undefined,\n observedEnd: ReturnType<typeof watchRun>['endReason'],\n workItemName: string | undefined,\n ): Promise<void> {\n if (!this.#audit) return;\n const humanApproved = isHumanActorId(approvedBy);\n await recordSessionRunStart(session, {\n audit: this.#audit,\n actorType: humanApproved ? 'human' : 'system',\n observedEnd,\n run: {\n kickoffId,\n ownerId: this.#ownerId,\n heartbeatAt: Date.now(),\n bindingId: binding.id,\n role: binding.role,\n startedBy: humanApproved ? approvedBy : 'factory-rule-dispatcher',\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n workItemName,\n sessionId: binding.sessionId,\n threadId: binding.threadId,\n branch: binding.branch,\n },\n });\n }\n\n async #dispatchPendingStart(record: FactoryPendingStartRecord, now: Date): Promise<void> {\n try {\n await this.#withLease(\n async leaseExpiresAt =>\n this.#storage.renewPendingStartLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),\n async () => {\n if (record.message === null) return;\n const bindings = await this.#storage.listRunBindings(record.orgId, record.factoryProjectId);\n const binding = bindings.find(\n candidate => candidate.id === record.bindingId && candidate.status === 'active',\n );\n if (!binding) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n 'Prepared Factory binding is unavailable or revoked.',\n );\n }\n // Wake runs build the Factory workspace, which requires the\n // authenticated session owner on the request context.\n const item = await this.#storage.get({ orgId: record.orgId, id: binding.workItemId });\n const startedBy = item?.sessions[binding.role]?.startedBy;\n if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const session = await this.#requireSession(binding, { userId: startedBy, orgId: record.orgId });\n const requestContext = factoryRequestContext({\n session,\n binding,\n userId: startedBy,\n orgId: record.orgId,\n });\n // The run's own verdict, not the delivery's: a kickoff delivered\n // into a run that is already terminating is consumed without\n // execution, and completing the pending start on the delivery ack\n // alone strands the card with a success ledger entry.\n const since = new Date();\n const stopRequested = () => this.#runStopRequested(record.orgId, binding.id);\n const run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n autoApprovedTool: await this.#autoApprovedExitTool({ ...record, workItemId: binding.workItemId }),\n autoApproving: this.#autoApproving,\n requestContext,\n label: 'Factory kickoff run',\n runStillActive: () =>\n this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId),\n stopRequested,\n });\n const sendKickoff = async (dedupeKey: string) => {\n await this.#storage.clearRunBindingStopRequest({ orgId: record.orgId, bindingId: binding.id });\n return awaitNotification(\n () =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'run-kickoff',\n summary: record.message!,\n priority: 'high',\n payload: { message: record.message },\n sourceId: record.id,\n dedupeKey,\n },\n { ifActive: { behavior: 'deliver' }, ifIdle: { behavior: 'wake' }, requestContext },\n ),\n true,\n );\n };\n try {\n let settled = await sendKickoff(`factory-kickoff:${record.kickoffKey}`);\n let deliveryGeneration = 0;\n while (settled?.action === 'deliver') {\n // `deliver` only proves the signal was queued onto a run already\n // in flight. If that run ends without draining its queue the\n // kickoff is dropped silently. Another run can start while the\n // previous one is finishing, so follow every run boundary until\n // the kickoff wakes an idle session. The generation-scoped\n // dedupeKey defeats inbox dedupe and the kickoff key keeps a\n // duplicate run bounded, while a dropped kickoff strands the card.\n if (!(await run.wait())) {\n throw new Error('Factory kickoff is waiting on a run that has not ended.');\n }\n if (await stopRequested()) throw new FactoryRunStopped();\n run.arm();\n deliveryGeneration += 1;\n settled = await sendKickoff(\n `factory-kickoff:${record.kickoffKey}:retry:${record.attempts}:${deliveryGeneration}`,\n );\n }\n await this.#recordRunStart(\n session,\n binding,\n `factory-kickoff:${record.kickoffKey}:${record.attempts}`,\n startedBy,\n run.endReason,\n item?.title,\n );\n await this.#reportingRunEnd({ binding, startedBy, since, attempts: record.attempts }, () => run.settle());\n } finally {\n run.close();\n }\n },\n );\n const completed = await this.#storage.completePendingStart(leaseIdentity(record, this.#ownerId), new Date());\n if (!completed) throw new Error('Factory kickoff lease was lost before completion.');\n } catch (error) {\n // The kickoff started its run; retrying would undo the stop.\n if (error instanceof FactoryRunStopped) {\n await this.#storage.completePendingStart(leaseIdentity(record, this.#ownerId), new Date());\n return;\n }\n const failureCode = factoryDispatchFailureCode(error);\n await this.#storage.failPendingStart({\n ...leaseIdentity(record, this.#ownerId),\n now: new Date(),\n availableAt: retryAt(now, record.attempts),\n lastError: sanitizeDispatchError(error),\n failureCode,\n terminal: isTerminalFailure(record.attempts, failureCode),\n });\n }\n }\n}\n\nexport const FACTORY_DISPATCH_CONSTANTS = {\n leaseMs: LEASE_MS,\n pollMs: POLL_MS,\n batchSize: BATCH_SIZE,\n maxAttempts: MAX_ATTEMPTS,\n maxErrorLength: MAX_ERROR_LENGTH,\n maxBackoffMs: MAX_BACKOFF_MS,\n skillCompletionObservationTimeoutMs: SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS,\n runRegistryHeartbeatMs: RUN_REGISTRY_HEARTBEAT_MS,\n openRunStaleMs: FACTORY_OPEN_RUN_STALE_MS,\n maxInFlight: MAX_IN_FLIGHT,\n reviewStatusTimeoutMs: REVIEW_STATUS_TIMEOUT_MS,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,MAAM,WAAW;;AAEjB,MAAM,2BAA2B;AAIjC,MAAM,UAAU;AAIhB,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,eAAe;AAIrB,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AAGvB,MAAM,4BAA4B;AAGlC,MAAM,0CAA0C;AAIhD,MAAM,gBAAgB;AACtB,MAAM,yBAAyB,aAA+C,CAAC,qBAAqB,QAAQ;;;;;;;;AAQ5G,MAAa,yBACX,UACA,EAAE,OAAO,mBAER,SAAS,SAAS,iBAAiB,SAAS,SAAS,qBACtD,SAAS,iBAAiB,aAC1B,YAAY,WAAW,KACvB,OAAO,SAAS,YAChB,MAAM,UAAU,QAChB,MAAM,YAAY,QAClB,MAAM,oBAAoB;AAC5B,MAAM,0BAA0B,UAAmC,eACjE,qBAAqB,QAAQ,KAAK,CAAC,sBAAsB,UAAU,UAAU;AAC/E,MAAM,4BAA4B;AAClC,MAA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