@mastra/factory 0.17.3-alpha.6 → 0.18.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/boards/review.d.ts +2 -0
  2. package/dist/boards/review.d.ts.map +1 -1
  3. package/dist/boards/review.js +16 -6
  4. package/dist/boards/review.js.map +1 -1
  5. package/dist/boards/work-transition-policy.d.ts.map +1 -1
  6. package/dist/boards/work-transition-policy.js +10 -0
  7. package/dist/boards/work-transition-policy.js.map +1 -1
  8. package/dist/factory.d.ts.map +1 -1
  9. package/dist/factory.js +9 -1
  10. package/dist/factory.js.map +1 -1
  11. package/dist/integrations/github/default-rules.d.ts +17 -1
  12. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  13. package/dist/integrations/github/default-rules.js +30 -6
  14. package/dist/integrations/github/default-rules.js.map +1 -1
  15. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  16. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  17. package/dist/integrations/github/rules.d.ts.map +1 -1
  18. package/dist/integrations/github/rules.js +48 -2
  19. package/dist/integrations/github/rules.js.map +1 -1
  20. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  21. package/dist/integrations/github/sandbox.js.map +1 -1
  22. package/dist/integrations/gitlab/api.d.ts.map +1 -1
  23. package/dist/integrations/gitlab/api.js.map +1 -1
  24. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  25. package/dist/integrations/gitlab/default-rules.js +1 -0
  26. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  27. package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
  28. package/dist/integrations/gitlab/reconciler.js.map +1 -1
  29. package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
  30. package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
  31. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  32. package/dist/integrations/gitlab/rules.js +66 -0
  33. package/dist/integrations/gitlab/rules.js.map +1 -1
  34. package/dist/integrations/gitlab/version-control.d.ts.map +1 -1
  35. package/dist/integrations/gitlab/version-control.js.map +1 -1
  36. package/dist/integrations/incidentio/api.d.ts.map +1 -1
  37. package/dist/integrations/incidentio/api.js.map +1 -1
  38. package/dist/integrations/incidentio/intake.d.ts.map +1 -1
  39. package/dist/integrations/incidentio/intake.js.map +1 -1
  40. package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
  41. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  42. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  43. package/dist/integrations/slack/emoji-shortcodes.generated.js.map +1 -1
  44. package/dist/integrations/slack/feed-publisher.d.ts.map +1 -1
  45. package/dist/integrations/slack/feed-publisher.js.map +1 -1
  46. package/dist/rules/dispatcher.d.ts.map +1 -1
  47. package/dist/rules/dispatcher.js +11 -2
  48. package/dist/rules/dispatcher.js.map +1 -1
  49. package/dist/rules/review-source-tool.d.ts +103 -0
  50. package/dist/rules/review-source-tool.d.ts.map +1 -0
  51. package/dist/rules/review-source-tool.js +109 -0
  52. package/dist/rules/review-source-tool.js.map +1 -0
  53. package/dist/rules/tools.d.ts +1 -0
  54. package/dist/rules/tools.d.ts.map +1 -1
  55. package/dist/rules/tools.js +107 -32
  56. package/dist/rules/tools.js.map +1 -1
  57. package/dist/skills/service.d.ts.map +1 -1
  58. package/dist/skills/service.js +16 -6
  59. package/dist/skills/service.js.map +1 -1
  60. package/dist/storage/domains/integrations/base.d.ts.map +1 -1
  61. package/dist/storage/domains/integrations/base.js.map +1 -1
  62. package/dist/storage/domains/work-items/base.d.ts +11 -0
  63. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  64. package/dist/storage/domains/work-items/base.js +21 -0
  65. package/dist/storage/domains/work-items/base.js.map +1 -1
  66. package/dist/supervisor/session-messaging.d.ts +4 -1
  67. package/dist/supervisor/session-messaging.d.ts.map +1 -1
  68. package/dist/supervisor/session-messaging.js +8 -2
  69. package/dist/supervisor/session-messaging.js.map +1 -1
  70. package/dist/supervisor/write-tools.d.ts +2 -1
  71. package/dist/supervisor/write-tools.d.ts.map +1 -1
  72. package/dist/supervisor/write-tools.js +9 -2
  73. package/dist/supervisor/write-tools.js.map +1 -1
  74. package/dist/workspace.d.ts +7 -1
  75. package/dist/workspace.d.ts.map +1 -1
  76. package/dist/workspace.js +45 -7
  77. package/dist/workspace.js.map +1 -1
  78. package/factory-skills/factory-gitlab-rereview/SKILL.md +3 -2
  79. package/factory-skills/factory-gitlab-review/SKILL.md +19 -3
  80. package/factory-skills/factory-rereview/SKILL.md +30 -11
  81. package/factory-skills/factory-review/SKILL.md +30 -11
  82. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"dispatcher.js","names":["#audit","#controller","#transitionService","#boards","#storage","#ownerId","#isAutoRunEnabled","#autoApprovePlans","#reconcileToolResults","#prepareBinding","#refreshManagedMemorySettings","#primeCredentials","#feedReader","#resolveLinkedWorkItemParentId","#maxInFlight","#staleBindingSweepIntervalMs","#staleBindingTtlMs","#reconcileIntervalMs","#skillCompletionObservationTimeoutMs","#runInFlight","#bookkeepingInFlight","#backgroundInFlight","#bindingSkillRuns","#timer","#tick","#activeClaim","#claimAndStart","#maybeSweepStaleBindings","#maybeReconcileToolResults","#track","#dispatchPendingStart","#dispatchDecision","#reconcileInFlight","#lastReconcileAt","#lastStaleBindingSweepAt","#needsApproval","#supersedeProposals","#withLease","#executeDecision","#supersedeFailureOnSettledCard","#requireItem","#upsertLinkedItem","#roleSuperseded","#requireOrPrepareBinding","#withBindingSkillRun","#requireSession","#switchThread","#findBinding","#requireBinding","#plansAreAutoApproved","#recordRunStart","#withOpenRunHeartbeat","#messageBinding","#findSession"],"sources":["../../src/rules/dispatcher.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController, AgentControllerEventListener, Session } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { SubmitPlanResumeData } from '@mastra/core/tools';\n\nimport {\n boardForWorkItem,\n createBoardRegistry,\n resolvePhaseSemantics,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { moveCardToBoard } from '../boards/relocate.js';\nimport {\n FACTORY_OPEN_RUN_STALE_MS,\n heartbeatSessionOpenRun,\n isOpenRunLiveElsewhere,\n listSessionOpenRuns,\n recordSessionRunStart,\n waitForSessionRunAudit,\n} from '../session/run-audit.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 { withWorkItemFeed } from '../storage/domains/comments/feed-context.js';\nimport type { FactoryFeedReader } from '../storage/domains/comments/feed-context.js';\nimport { FACTORY_RULE_MATERIALIZATION_KEY, WorkItemClaimConflictError } from '../storage/domains/work-items/base.js';\nimport type {\n FactoryDeferredDecisionRecord,\n FactoryDispatchFailureCode,\n FactoryPendingStartRecord,\n FactoryRunBindingRecord,\n WorkItemRow,\n WorkItemsStorage,\n UpsertWorkItemResult,\n} from '../storage/domains/work-items/base.js';\nimport { FactoryDispatchError, factoryDispatchFailureCode, factoryDispatchFailureMetadata } from './dispatch-errors.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport type { FactoryCommitDecision, FactoryRuleActor, FactoryRuleCausalEntry } from './types.js';\nimport { externalSourceForWorkItem, externallyAuthoredWorkItem, FACTORY_RULE_STAGES } from './types.js';\nimport {\n assertFactoryDecisionTarget,\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n validateFactoryRuleDecision,\n} from './validation.js';\n\nconst LEASE_MS = 30_000;\nconst POLL_MS = 1_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 = 25;\n/**\n * Decisions that may start or wake an agent run and so hold a run slot. A\n * transition's message is queued as a separate sendMessage, so the transition\n * itself stays bookkeeping.\n */\nconst isRunBearingDecision = (decision: Record<string, unknown>): boolean =>\n decision.type === 'invokeSkill' || decision.type === 'sendMessage';\nconst isBookkeepingDecision = (decision: Record<string, unknown>): boolean => !isRunBearingDecision(decision);\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// Rescheduling a failure that can never succeed only delays the moment a person sees why.\nfunction isTerminalFailure(attempts: number, failureCode: FactoryDispatchFailureCode): boolean {\n return attempts >= MAX_ATTEMPTS || !factoryDispatchFailureMetadata(failureCode).canRetry;\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 approvePlans,\n onAgentEnd,\n label,\n runStillActive,\n }: {\n timeoutMs: number;\n approvePlans: boolean;\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 },\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 // 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 // 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 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 === '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 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 close: unsubscribe,\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 if (approvePlans) {\n for (let approvals = 0; parked?.toolName === 'submit_plan' && approvals < MAX_PLAN_APPROVALS; approvals += 1) {\n const { toolCallId } = parked;\n parked = undefined;\n arm();\n await session.respondToToolSuspension({ resumeData: { action: 'approved' }, toolCallId });\n observed = await wait();\n }\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 new Error(`${label} ended in error.`);\n if (endReason === 'aborted') {\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 // Retryable, though an abort reads as deliberate. The stream does not\n // say who aborted, and in practice the dominant cause is the process\n // going away underneath the run — an operator restarting the server —\n // not anyone deciding this work should stop. Treating that as terminal\n // dead-ends the card at attempt 1 with nothing on the board to press. A\n // spurious retry is bounded by MAX_ATTEMPTS; a dead card costs a human\n // a manual nudge.\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 ThreadSwitchSession {\n thread: {\n requireId(): string;\n switch(input: { threadId: string }): Promise<unknown>;\n };\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: { id: string; type: 'user'; tagName: 'user'; contents: string },\n options: { requestContext: RequestContext; requireDelivery?: boolean },\n ): { accepted: Promise<{ accepted: true; runId?: string; action?: string }> };\n subscribe(listener: AgentControllerEventListener): () => void;\n respondToToolSuspension(input: { resumeData: SubmitPlanResumeData; toolCallId?: string }): Promise<void>;\n}\n\ntype FactoryController = Pick<AgentController<MastraCodeState>, 'getSessionByResource' | '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 const modeId = session.mode.get();\n requestContext.set('controller', {\n state: session.state.get(),\n getState: () => session.state.get(),\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modeId,\n modelId: session.model.get() ?? '',\n },\n workspace: session.getWorkspace(),\n });\n return requestContext;\n}\n\nexport interface FactoryBindingPreparationInput {\n record: FactoryDeferredDecisionRecord;\n item: WorkItemRow;\n role: string;\n}\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;\n ownerId?: string;\n /** `false` parks `invokeSkill` effects as `proposed`; every other effect still runs. */\n isAutoRunEnabled: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n /** `true` lets the dispatcher answer a run's plan itself, so started work carries to Done. */\n autoApprovePlans?: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n reconcileToolResults?: () => Promise<void>;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n /**\n * Re-applies the factory project's current observational-memory settings to a\n * reused session before it runs. Fresh preparation hydrates these settings,\n * but a reused binding keeps the models it was created with; without this a\n * project whose OM models changed keeps observing with the stale ones.\n */\n refreshManagedMemorySettings?: (input: {\n binding: FactoryRunBindingRecord;\n session: BoundDispatcherSession;\n }) => Promise<void>;\n primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n /** Injects the work item's recent comments into skill-invocation kickoffs. */\n feedReader?: FactoryFeedReader;\n resolveLinkedWorkItemParentId?: (input: {\n orgId: string;\n factoryProjectId: string;\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>;\n }) => Promise<string | null>;\n maxInFlight?: 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\nfunction sanitizeDispatchError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return message\n .replace(/\\b(?:bearer|token|api[-_ ]?key|authorization)\\s*[:=]?\\s*[^\\s,;]+/gi, '[redacted]')\n .slice(0, MAX_ERROR_LENGTH);\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\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\nexport class FactoryDecisionDispatcher {\n readonly #audit?: AuditRecorder;\n readonly #controller: FactoryController;\n readonly #transitionService: Pick<FactoryTransitionService, 'transition' | 'configVersion'>;\n readonly #boards: BoardRegistry;\n readonly #storage: WorkItemsStorage;\n readonly #ownerId: string;\n readonly #isAutoRunEnabled: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n readonly #autoApprovePlans?: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n readonly #reconcileToolResults?: () => Promise<void>;\n readonly #prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n readonly #refreshManagedMemorySettings?: (input: {\n binding: FactoryRunBindingRecord;\n session: BoundDispatcherSession;\n }) => Promise<void>;\n readonly #primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n readonly #feedReader?: FactoryFeedReader;\n readonly #resolveLinkedWorkItemParentId?: FactoryDecisionDispatcherOptions['resolveLinkedWorkItemParentId'];\n readonly #maxInFlight: 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 #timer?: ReturnType<typeof setInterval>;\n #activeClaim?: Promise<void>;\n /** Starts and run-bearing decisions; capped by `maxInFlight`. */\n readonly #runInFlight = 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 = options.boards ?? createBoardRegistry();\n this.#storage = options.storage;\n this.#ownerId = options.ownerId ?? `factory-dispatcher:${randomUUID()}`;\n this.#isAutoRunEnabled = options.isAutoRunEnabled;\n this.#autoApprovePlans = options.autoApprovePlans;\n this.#reconcileToolResults = options.reconcileToolResults;\n this.#prepareBinding = options.prepareBinding;\n this.#refreshManagedMemorySettings = options.refreshManagedMemorySettings;\n this.#primeCredentials = options.primeCredentials;\n this.#feedReader = options.feedReader;\n this.#resolveLinkedWorkItemParentId = options.resolveLinkedWorkItemParentId;\n const maxInFlight = options.maxInFlight ?? MAX_IN_FLIGHT;\n this.#maxInFlight = Number.isFinite(maxInFlight) && maxInFlight > 0 ? Math.floor(maxInFlight) : MAX_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.#timer) return;\n void this.#tick();\n this.#timer = setInterval(() => void this.#tick(), POLL_MS);\n this.#timer.unref?.();\n }\n\n async stop(): Promise<void> {\n if (this.#timer) clearInterval(this.#timer);\n this.#timer = undefined;\n await this.#activeClaim;\n await Promise.allSettled([...this.#runInFlight, ...this.#bookkeepingInFlight, ...this.#backgroundInFlight]);\n }\n\n async runOnce(now = new Date()): Promise<void> {\n await Promise.all(await this.#claimAndStart(now));\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<Array<Promise<void>>> {\n // Fire-and-forget like the reconcile walk: the sweep reads every active\n // binding, so awaiting it would stretch the tick as the active set grows.\n void this.#maybeSweepStaleBindings(now);\n this.#maybeReconcileToolResults(now);\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 runCapacity = this.#maxInFlight - this.#runInFlight.size;\n if (runCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, runCapacity);\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 const decisionsLimit = limit - starts.length;\n const decisions =\n decisionsLimit > 0\n ? await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit: decisionsLimit,\n decisionFilter: isRunBearingDecision,\n })\n : [];\n dispatches.push(\n ...starts.map(start => this.#track(this.#runInFlight, this.#dispatchPendingStart(start, now))),\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 decisions = await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit: Math.min(BATCH_SIZE, bookkeepingCapacity),\n decisionFilter: isBookkeepingDecision,\n });\n dispatches.push(\n ...decisions.map(decision => this.#track(this.#bookkeepingInFlight, this.#dispatchDecision(decision, now))),\n );\n }\n return dispatches;\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): void {\n if (!this.#reconcileToolResults || this.#reconcileInFlight) return;\n if (this.#lastReconcileAt && now.getTime() - this.#lastReconcileAt.getTime() < this.#reconcileIntervalMs) return;\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 }\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 });\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 #track(pool: Set<Promise<void>>, dispatch: Promise<void>): Promise<void> {\n pool.add(dispatch);\n void dispatch.catch(() => {}).then(() => pool.delete(dispatch));\n return dispatch;\n }\n\n async #tick(): Promise<void> {\n if (this.#activeClaim) return;\n this.#activeClaim = this.#claimAndStart(new Date()).then(\n dispatches => {\n for (const dispatch of dispatches) {\n dispatch.catch(error => {\n console.error('Factory decision dispatch failed', sanitizeDispatchError(error));\n });\n }\n },\n error => {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n },\n );\n try {\n await this.#activeClaim;\n } finally {\n this.#activeClaim = undefined;\n }\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 await this.#withLease(\n async leaseExpiresAt =>\n this.#storage.renewDeferredDecisionLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),\n async () => this.#executeDecision(record, decision),\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 } catch (error) {\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 }\n }\n\n /**\n * Startup repair and terminal cleanup already settle a failed effect on a done or canceled\n * card as superseded; a failure landing after the card settled would otherwise page a person\n * until the next restart.\n */\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(this.#boards, 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 is already failed, and the next restart repairs it.\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.\n async #needsApproval(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): Promise<boolean> {\n if (record.approvedAt !== null || !requestsConsent(this.#boards, record, decision)) return false;\n // Withholding auto-run decides what the Factory may pick up on its own, not\n // whether it may finish work a person already handed it. Once someone starts\n // an item, the runs that carry it to review are that same request continuing.\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n // Neither arming nor auto-run is standing consent for code from outside the write-access\n // circle: only a run pre-approved by a person's gesture or its own agent's governed move passes.\n if (item && externallyAuthoredWorkItem(item)) return true;\n if (item?.autonomyArmedAt != null) return false;\n return !(await this.#isAutoRunEnabled({ orgId: record.orgId, factoryProjectId: record.factoryProjectId }));\n }\n\n async #executeDecision(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): 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 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, this.#boards, 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 });\n if (result.status === 'rejected') throw new Error(`${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 too: a stale commit is recorded as rejected under\n // its identity, so the retry needs a fresh one to queue the message.\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}`, triggerType: 'transition.message' },\n configVersion: this.#transitionService.configVersion,\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 idleBehavior: '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 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 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 if (await this.#roleSuperseded(record, decision.role)) return;\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);\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 resourceId: binding.resourceId,\n prompt: decision.prompt,\n })\n : decision.resume === true\n ? await resolveSkillResumeInvocation(this.#controller, {\n resourceId: binding.resourceId,\n name: decision.skillName,\n arguments: decision.arguments,\n })\n : await resolveSkillInvocation(this.#controller, {\n resourceId: binding.resourceId,\n name: decision.skillName,\n arguments: decision.arguments,\n });\n await this.#switchThread(session, binding);\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 // The card moved on once any stage it now sits in was entered after this\n // decision was made. Anchored on the decision, not on this attempt, so a\n // retry after the move is still recognised as stale.\n const kickoffStale = async () => {\n if (await this.#roleSuperseded(record, decision.role)) return true;\n if ((await this.#findBinding(record, decision.role))?.id !== binding.id) return true;\n if (!record.workItemId) return false;\n const current = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n if (current === null) return true;\n const decidedAt = record.createdAt.getTime();\n const enteredSince = current.stageHistory.filter(\n entry => entry.exitedAt === undefined && new Date(entry.enteredAt).getTime() > decidedAt,\n );\n if (enteredSince.length === 0) return false;\n // A transition from the same rule evaluation lands after this decision\n // was created; entering that stage is part of this kickoff's intent.\n const siblingStages = new Set(\n (await this.#storage.listDeferredDecisions(record.orgId, record.factoryProjectId))\n .filter(\n sibling => sibling.evaluationId === record.evaluationId && sibling.decision.type === 'transition',\n )\n .map(sibling => sibling.decision.stage),\n );\n return enteredSince.some(entry => !siblingStages.has(entry.stage));\n };\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 approvePlans: false,\n label: 'Factory skill run',\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 if (await this.#roleSuperseded(record, decision.role)) return;\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()) return;\n if (await kickoffStale()) return;\n // Safe under the replay guard above: it matches deliveryId, never prompt content.\n const kickoffContents = await withWorkItemFeed(\n this.#feedReader,\n { orgId: record.orgId, factoryProjectId: record.factoryProjectId, workItemId: record.workItemId },\n resolved.message,\n );\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 }\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 run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n approvePlans: await this.#plansAreAutoApproved(record),\n onAgentEnd: () => this.#roleSuperseded(record, decision.role),\n label: 'Factory skill run',\n runStillActive,\n });\n\n const sendKickoff = async () => {\n const result = session.sendSignal(\n {\n id: deliveryId,\n type: 'user',\n tagName: 'user',\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()) return;\n run.arm();\n settled = await sendKickoff();\n }\n await this.#recordRunStart(\n session,\n binding,\n deliveryId,\n record.approvedBy ?? undefined,\n run.endReason,\n item?.title,\n );\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.#withOpenRunHeartbeat(session, deliveryId, () => run.settle());\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 }\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);\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 true,\n );\n return;\n }\n case 'notify': {\n const binding = await this.#requireBinding(record);\n const session = await this.#requireSession(binding);\n await awaitNotification(() =>\n session.sendNotificationSignal({\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 );\n }\n }\n }\n\n async #upsertLinkedItem(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n causalChain: FactoryRuleCausalEntry[],\n ): Promise<void> {\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(decision),\n });\n if (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 (decision.skipRules === true) return;\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) return;\n }\n }\n assertFactoryDecisionTarget(decision, this.#boards);\n const definition = this.#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;\n try {\n result = await this.#storage.upsert({\n orgId: record.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: record.factoryProjectId,\n input: {\n externalSource: externalSourceForDecision(decision),\n ...(decision.claimKey ? { claimKey: decision.claimKey } : {}),\n parentWorkItemId,\n title: decision.title,\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 } catch (error) {\n // Another Factory project in the org holds the live card for this record.\n // The decision is spent, not failed: retrying would only be refused again.\n if (error instanceof WorkItemClaimConflictError) return;\n throw error;\n }\n if (!result.created && decision.claimKey && !result.item.claimKey) {\n // A card filed before claims existed adopts the claim now; a refusal means\n // another project already owns the record, and this card stays as it is.\n const claimed = await this.#storage.claimWorkItem({\n orgId: record.orgId,\n id: result.item.id,\n claimKey: decision.claimKey,\n });\n if (claimed) result = { ...result, item: claimed };\n }\n const itemBoard = boardForWorkItem(result.item);\n if (!skipRules && itemBoard !== decision.board) {\n throw new Error(`The work item belongs to board \"${itemBoard}\", not \"${decision.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 missing = Object.fromEntries(\n Object.entries(decision.metadata ?? {}).filter(\n ([key]) => key !== FACTORY_RULE_MATERIALIZATION_KEY && result.item.metadata?.[key] === undefined,\n ),\n );\n if (Object.keys(missing).length > 0) {\n const filled = await this.#storage.update({\n orgId: record.orgId,\n id: result.item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: missing },\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 — a\n // reconcile pass reacting to a label change, say — is placed there the\n // same way, through the relocation the label routes use, so no phase rule\n // runs for it and no transition is recorded.\n if (!result.created) {\n await moveCardToBoard({\n workItems: this.#storage,\n boardRegistry: this.#boards,\n userId: 'factory-rule-dispatcher',\n item: result.item,\n targetBoard: decision.board,\n targetStage: decision.stage,\n });\n }\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 return;\n\n const board = decision.board;\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 Error(`${initial.code}: ${initial.reason}`);\n }\n expectedRevision = initial.revision;\n }\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 });\n if (moved.status === 'rejected') throw new Error(`${moved.code}: ${moved.reason}`);\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 return bindings\n .filter(candidate => candidate.status === 'active' && (role === undefined || candidate.role === role))\n .sort((left, right) => {\n if (role === undefined && left.role === 'work' && right.role !== 'work') return -1;\n if (role === undefined && right.role === 'work' && left.role !== 'work') 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 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 #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(this.#boards, 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 ): Promise<FactoryRunBindingRecord> {\n const binding = await this.#findBinding(record, role);\n if (binding) {\n const session = await this.#controller.getSessionByResource(binding.resourceId);\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 await this.#prepareBinding({ record, item, role });\n return this.#requireBinding(record, role);\n }\n\n async #findSession(binding: FactoryRunBindingRecord): Promise<BoundDispatcherSession | undefined> {\n const session = await this.#controller.getSessionByResource(binding.resourceId);\n if (!session) return undefined;\n await this.#switchThread(session, binding);\n // A reused session keeps the OM models it was created with; refresh them\n // from the project's current settings so a managed run never observes with\n // models the project has since changed away from.\n await this.#refreshManagedMemorySettings?.({ binding, session });\n return session;\n }\n\n /** Unset means off: a plan nobody asked us to answer is a plan someone should see. */\n async #plansAreAutoApproved({\n orgId,\n factoryProjectId,\n }: {\n orgId: string;\n factoryProjectId: string;\n }): Promise<boolean> {\n return this.#autoApprovePlans ? await this.#autoApprovePlans({ orgId, factoryProjectId }) : false;\n }\n\n async #requireSession(binding: FactoryRunBindingRecord): Promise<BoundDispatcherSession> {\n const session = await this.#findSession(binding);\n if (!session) throw new FactoryDispatchError('session_unavailable', 'Bound Factory session not found.');\n return session;\n }\n\n async #switchThread(session: ThreadSwitchSession, binding: FactoryRunBindingRecord): Promise<void> {\n if (session.thread.requireId() === binding.threadId) return;\n await session.thread.switch({ threadId: binding.threadId });\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 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);\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 run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n approvePlans: await this.#plansAreAutoApproved(record),\n label: 'Factory kickoff run',\n runStillActive: () =>\n this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId),\n });\n const sendKickoff = (dedupeKey: string) =>\n 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 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 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 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 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 stages: FACTORY_RULE_STAGES,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;AAiDA,MAAM,WAAW;AACjB,MAAM,UAAU;AAChB,MAAM,aAAa;AACnB,MAAM,eAAe;AAIrB,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AAGvB,MAAM,4BAA4B,KAAK;AAGvC,MAAM,0CAA0C,MAAS;AAIzD,MAAM,gBAAgB;;;;;;AAMtB,MAAM,wBAAwB,aAC5B,SAAS,SAAS,iBAAiB,SAAS,SAAS;AACvD,MAAM,yBAAyB,aAA+C,CAAC,qBAAqB,QAAQ;AAC5G,MAAM,4BAA4B;AAIlC,MAAM,kCAAkC,KAAK;AAC7C,MAAM,uBA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,UAAU,OAAO;KAAG;IAAe,CACpF,GACF,IACF;IACF,IAAI;KACF,IAAI,UAAU,MAAM,YAAY,mBAAmB,OAAO,YAAY;KACtE,IAAI,qBAAqB;KACzB,OAAO,SAAS,WAAW,WAAW;MAQpC,IAAI,CAAE,MAAM,IAAI,KAAK,GACnB,MAAM,IAAI,MAAM,yDAAyD;MAE3E,IAAI,IAAI;MACR,sBAAsB;MACtB,UAAU,MAAM,YACd,mBAAmB,OAAO,WAAW,SAAS,OAAO,SAAS,GAAG,oBACnE;KACF;KACA,MAAM,KAAKiD,gBACT,SACA,SACA,mBAAmB,OAAO,WAAW,GAAG,OAAO,YAC/C,WACA,IAAI,WACJ,MAAM,KACR;KACA,MAAM,IAAI,OAAO;IACnB,UAAU;KACR,IAAI,MAAM;IACZ;GACF,CACF;GAEA,IAAI,CAAC,MADmB,KAAK9C,SAAS,qBAAqB,cAAc,QAAQ,KAAKC,QAAQ,mBAAG,IAAI,KAAK,CAAC,GAC3F,MAAM,IAAI,MAAM,mDAAmD;EACrF,SAAS,OAAO;GACd,MAAM,cAAc,2BAA2B,KAAK;GACpD,MAAM,KAAKD,SAAS,iBAAiB;IACnC,GAAG,cAAc,QAAQ,KAAKC,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,QAAQ;AACV"}
1
+ {"version":3,"file":"dispatcher.js","names":["#audit","#controller","#transitionService","#boards","#storage","#ownerId","#isAutoRunEnabled","#autoApprovePlans","#reconcileToolResults","#prepareBinding","#refreshManagedMemorySettings","#primeCredentials","#feedReader","#resolveLinkedWorkItemParentId","#maxInFlight","#staleBindingSweepIntervalMs","#staleBindingTtlMs","#reconcileIntervalMs","#skillCompletionObservationTimeoutMs","#runInFlight","#bookkeepingInFlight","#backgroundInFlight","#bindingSkillRuns","#timer","#tick","#activeClaim","#claimAndStart","#maybeSweepStaleBindings","#maybeReconcileToolResults","#track","#dispatchPendingStart","#dispatchDecision","#reconcileInFlight","#lastReconcileAt","#lastStaleBindingSweepAt","#needsApproval","#supersedeProposals","#withLease","#executeDecision","#supersedeFailureOnSettledCard","#requireItem","#upsertLinkedItem","#roleSuperseded","#requireOrPrepareBinding","#withBindingSkillRun","#requireSession","#switchThread","#findBinding","#requireBinding","#plansAreAutoApproved","#recordRunStart","#withOpenRunHeartbeat","#messageBinding","#findSession"],"sources":["../../src/rules/dispatcher.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController, AgentControllerEventListener, Session } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { SubmitPlanResumeData } from '@mastra/core/tools';\n\nimport {\n boardForWorkItem,\n createBoardRegistry,\n resolvePhaseSemantics,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { moveCardToBoard } from '../boards/relocate.js';\nimport {\n FACTORY_OPEN_RUN_STALE_MS,\n heartbeatSessionOpenRun,\n isOpenRunLiveElsewhere,\n listSessionOpenRuns,\n recordSessionRunStart,\n waitForSessionRunAudit,\n} from '../session/run-audit.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 { withWorkItemFeed } from '../storage/domains/comments/feed-context.js';\nimport type { FactoryFeedReader } from '../storage/domains/comments/feed-context.js';\nimport { FACTORY_RULE_MATERIALIZATION_KEY, WorkItemClaimConflictError } from '../storage/domains/work-items/base.js';\nimport type {\n FactoryDeferredDecisionRecord,\n FactoryDispatchFailureCode,\n FactoryPendingStartRecord,\n FactoryRunBindingRecord,\n WorkItemRow,\n WorkItemsStorage,\n UpsertWorkItemResult,\n} from '../storage/domains/work-items/base.js';\nimport { FactoryDispatchError, factoryDispatchFailureCode, factoryDispatchFailureMetadata } from './dispatch-errors.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport type { FactoryCommitDecision, FactoryRuleActor, FactoryRuleCausalEntry } from './types.js';\nimport { externalSourceForWorkItem, externallyAuthoredWorkItem, FACTORY_RULE_STAGES } from './types.js';\nimport {\n assertFactoryDecisionTarget,\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n validateFactoryRuleDecision,\n} from './validation.js';\n\nconst LEASE_MS = 30_000;\nconst POLL_MS = 1_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 = 25;\n/**\n * Decisions that may start or wake an agent run and so hold a run slot. A\n * transition's message is queued as a separate sendMessage, so the transition\n * itself stays bookkeeping.\n */\nconst isRunBearingDecision = (decision: Record<string, unknown>): boolean =>\n decision.type === 'invokeSkill' || decision.type === 'sendMessage';\nconst isBookkeepingDecision = (decision: Record<string, unknown>): boolean => !isRunBearingDecision(decision);\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// Rescheduling a failure that can never succeed only delays the moment a person sees why.\nfunction isTerminalFailure(attempts: number, failureCode: FactoryDispatchFailureCode): boolean {\n return attempts >= MAX_ATTEMPTS || !factoryDispatchFailureMetadata(failureCode).canRetry;\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 approvePlans,\n onAgentEnd,\n label,\n runStillActive,\n }: {\n timeoutMs: number;\n approvePlans: boolean;\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 },\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 // 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 // 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 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 === '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 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 close: unsubscribe,\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 if (approvePlans) {\n for (let approvals = 0; parked?.toolName === 'submit_plan' && approvals < MAX_PLAN_APPROVALS; approvals += 1) {\n const { toolCallId } = parked;\n parked = undefined;\n arm();\n await session.respondToToolSuspension({ resumeData: { action: 'approved' }, toolCallId });\n observed = await wait();\n }\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 new Error(`${label} ended in error.`);\n if (endReason === 'aborted') {\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 // Retryable, though an abort reads as deliberate. The stream does not\n // say who aborted, and in practice the dominant cause is the process\n // going away underneath the run — an operator restarting the server —\n // not anyone deciding this work should stop. Treating that as terminal\n // dead-ends the card at attempt 1 with nothing on the board to press. A\n // spurious retry is bounded by MAX_ATTEMPTS; a dead card costs a human\n // a manual nudge.\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 ThreadSwitchSession {\n thread: {\n requireId(): string;\n switch(input: { threadId: string }): Promise<unknown>;\n };\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: { id: string; type: 'user'; tagName: 'user'; contents: string },\n options: { requestContext: RequestContext; requireDelivery?: boolean },\n ): { accepted: Promise<{ accepted: true; runId?: string; action?: string }> };\n subscribe(listener: AgentControllerEventListener): () => void;\n respondToToolSuspension(input: { resumeData: SubmitPlanResumeData; toolCallId?: string }): Promise<void>;\n}\n\ntype FactoryController = Pick<AgentController<MastraCodeState>, 'getSessionByResource' | '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 const modeId = session.mode.get();\n requestContext.set('controller', {\n state: session.state.get(),\n getState: () => session.state.get(),\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modeId,\n modelId: session.model.get() ?? '',\n },\n workspace: session.getWorkspace(),\n });\n return requestContext;\n}\n\nexport interface FactoryBindingPreparationInput {\n record: FactoryDeferredDecisionRecord;\n item: WorkItemRow;\n role: string;\n}\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;\n ownerId?: string;\n /** `false` parks `invokeSkill` effects as `proposed`; every other effect still runs. */\n isAutoRunEnabled: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n /** `true` lets the dispatcher answer a run's plan itself, so started work carries to Done. */\n autoApprovePlans?: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n reconcileToolResults?: () => Promise<void>;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n /**\n * Re-applies the factory project's current observational-memory settings to a\n * reused session before it runs. Fresh preparation hydrates these settings,\n * but a reused binding keeps the models it was created with; without this a\n * project whose OM models changed keeps observing with the stale ones.\n */\n refreshManagedMemorySettings?: (input: {\n binding: FactoryRunBindingRecord;\n session: BoundDispatcherSession;\n }) => Promise<void>;\n primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n /** Injects the work item's recent comments into skill-invocation kickoffs. */\n feedReader?: FactoryFeedReader;\n resolveLinkedWorkItemParentId?: (input: {\n orgId: string;\n factoryProjectId: string;\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>;\n }) => Promise<string | null>;\n maxInFlight?: 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\nfunction sanitizeDispatchError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return message\n .replace(/\\b(?:bearer|token|api[-_ ]?key|authorization)\\s*[:=]?\\s*[^\\s,;]+/gi, '[redacted]')\n .slice(0, MAX_ERROR_LENGTH);\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 item: { metadata: Record<string, unknown> | null },\n decision: FactoryCommitDecision,\n): boolean {\n if (item.metadata?.factoryAuthored !== true) return false;\n if (decision.type === 'transition') return decision.board === 'review' && decision.stage === 'review';\n return decision.type === 'invokeSkill' && decision.role === 'review';\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\nexport class FactoryDecisionDispatcher {\n readonly #audit?: AuditRecorder;\n readonly #controller: FactoryController;\n readonly #transitionService: Pick<FactoryTransitionService, 'transition' | 'configVersion'>;\n readonly #boards: BoardRegistry;\n readonly #storage: WorkItemsStorage;\n readonly #ownerId: string;\n readonly #isAutoRunEnabled: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n readonly #autoApprovePlans?: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n readonly #reconcileToolResults?: () => Promise<void>;\n readonly #prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n readonly #refreshManagedMemorySettings?: (input: {\n binding: FactoryRunBindingRecord;\n session: BoundDispatcherSession;\n }) => Promise<void>;\n readonly #primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n readonly #feedReader?: FactoryFeedReader;\n readonly #resolveLinkedWorkItemParentId?: FactoryDecisionDispatcherOptions['resolveLinkedWorkItemParentId'];\n readonly #maxInFlight: 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 #timer?: ReturnType<typeof setInterval>;\n #activeClaim?: Promise<void>;\n /** Starts and run-bearing decisions; capped by `maxInFlight`. */\n readonly #runInFlight = 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 = options.boards ?? createBoardRegistry();\n this.#storage = options.storage;\n this.#ownerId = options.ownerId ?? `factory-dispatcher:${randomUUID()}`;\n this.#isAutoRunEnabled = options.isAutoRunEnabled;\n this.#autoApprovePlans = options.autoApprovePlans;\n this.#reconcileToolResults = options.reconcileToolResults;\n this.#prepareBinding = options.prepareBinding;\n this.#refreshManagedMemorySettings = options.refreshManagedMemorySettings;\n this.#primeCredentials = options.primeCredentials;\n this.#feedReader = options.feedReader;\n this.#resolveLinkedWorkItemParentId = options.resolveLinkedWorkItemParentId;\n const maxInFlight = options.maxInFlight ?? MAX_IN_FLIGHT;\n this.#maxInFlight = Number.isFinite(maxInFlight) && maxInFlight > 0 ? Math.floor(maxInFlight) : MAX_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.#timer) return;\n void this.#tick();\n this.#timer = setInterval(() => void this.#tick(), POLL_MS);\n this.#timer.unref?.();\n }\n\n async stop(): Promise<void> {\n if (this.#timer) clearInterval(this.#timer);\n this.#timer = undefined;\n await this.#activeClaim;\n await Promise.allSettled([...this.#runInFlight, ...this.#bookkeepingInFlight, ...this.#backgroundInFlight]);\n }\n\n async runOnce(now = new Date()): Promise<void> {\n await Promise.all(await this.#claimAndStart(now));\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<Array<Promise<void>>> {\n // Fire-and-forget like the reconcile walk: the sweep reads every active\n // binding, so awaiting it would stretch the tick as the active set grows.\n void this.#maybeSweepStaleBindings(now);\n this.#maybeReconcileToolResults(now);\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 runCapacity = this.#maxInFlight - this.#runInFlight.size;\n if (runCapacity > 0) {\n const limit = Math.min(BATCH_SIZE, runCapacity);\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 const decisionsLimit = limit - starts.length;\n const decisions =\n decisionsLimit > 0\n ? await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit: decisionsLimit,\n decisionFilter: isRunBearingDecision,\n })\n : [];\n dispatches.push(\n ...starts.map(start => this.#track(this.#runInFlight, this.#dispatchPendingStart(start, now))),\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 decisions = await this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit: Math.min(BATCH_SIZE, bookkeepingCapacity),\n decisionFilter: isBookkeepingDecision,\n });\n dispatches.push(\n ...decisions.map(decision => this.#track(this.#bookkeepingInFlight, this.#dispatchDecision(decision, now))),\n );\n }\n return dispatches;\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): void {\n if (!this.#reconcileToolResults || this.#reconcileInFlight) return;\n if (this.#lastReconcileAt && now.getTime() - this.#lastReconcileAt.getTime() < this.#reconcileIntervalMs) return;\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 }\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 });\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 #track(pool: Set<Promise<void>>, dispatch: Promise<void>): Promise<void> {\n pool.add(dispatch);\n void dispatch.catch(() => {}).then(() => pool.delete(dispatch));\n return dispatch;\n }\n\n async #tick(): Promise<void> {\n if (this.#activeClaim) return;\n this.#activeClaim = this.#claimAndStart(new Date()).then(\n dispatches => {\n for (const dispatch of dispatches) {\n dispatch.catch(error => {\n console.error('Factory decision dispatch failed', sanitizeDispatchError(error));\n });\n }\n },\n error => {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n },\n );\n try {\n await this.#activeClaim;\n } finally {\n this.#activeClaim = undefined;\n }\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 await this.#withLease(\n async leaseExpiresAt =>\n this.#storage.renewDeferredDecisionLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),\n async () => this.#executeDecision(record, decision),\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 } catch (error) {\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 }\n }\n\n /**\n * Startup repair and terminal cleanup already settle a failed effect on a done or canceled\n * card as superseded; a failure landing after the card settled would otherwise page a person\n * until the next restart.\n */\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(this.#boards, 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 is already failed, and the next restart repairs it.\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.\n async #needsApproval(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): Promise<boolean> {\n if (record.approvedAt !== null || !requestsConsent(this.#boards, record, decision)) return false;\n // Withholding auto-run decides what the Factory may pick up on its own, not\n // whether it may finish work a person already handed it. Once someone starts\n // an item, the runs that carry it to review are that same request continuing.\n const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;\n // Neither arming nor auto-run is standing consent for code from outside the write-access\n // circle: only a run pre-approved by a person's gesture or its own agent's governed move passes.\n if (item && externallyAuthoredWorkItem(item)) return true;\n if (item?.autonomyArmedAt != null) return false;\n if (item && reviewsFactoryAuthoredCode(item, decision)) return false;\n return !(await this.#isAutoRunEnabled({ orgId: record.orgId, factoryProjectId: record.factoryProjectId }));\n }\n\n async #executeDecision(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): 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 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, this.#boards, 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 });\n if (result.status === 'rejected') throw new Error(`${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 too: a stale commit is recorded as rejected under\n // its identity, so the retry needs a fresh one to queue the message.\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}`, triggerType: 'transition.message' },\n configVersion: this.#transitionService.configVersion,\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 idleBehavior: '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 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 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 if (await this.#roleSuperseded(record, decision.role)) return;\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);\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 resourceId: binding.resourceId,\n prompt: decision.prompt,\n })\n : decision.resume === true\n ? await resolveSkillResumeInvocation(this.#controller, {\n resourceId: binding.resourceId,\n name: decision.skillName,\n arguments: decision.arguments,\n })\n : await resolveSkillInvocation(this.#controller, {\n resourceId: binding.resourceId,\n name: decision.skillName,\n arguments: decision.arguments,\n });\n await this.#switchThread(session, binding);\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 // The card moved on once any stage it now sits in was entered after this\n // decision was made. Anchored on the decision, not on this attempt, so a\n // retry after the move is still recognised as stale.\n const kickoffStale = async () => {\n if (await this.#roleSuperseded(record, decision.role)) return true;\n if ((await this.#findBinding(record, decision.role))?.id !== binding.id) return true;\n if (!record.workItemId) return false;\n const current = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });\n if (current === null) return true;\n const decidedAt = record.createdAt.getTime();\n const enteredSince = current.stageHistory.filter(\n entry => entry.exitedAt === undefined && new Date(entry.enteredAt).getTime() > decidedAt,\n );\n // A run decided while the card sat outside its seat's stages (a held\n // triage in Intake) is fulfilled, not overtaken, when the card first\n // enters a stage that seat carries — e.g. the Investigate click.\n const board = boardForWorkItem(current);\n const carriesRole = (stage: string) =>\n resolvePhaseSemantics(this.#boards, board, stage)?.role === decision.role;\n const decidedOutsideRole = !current.stageHistory.some(\n entry =>\n new Date(entry.enteredAt).getTime() <= decidedAt &&\n (entry.exitedAt === undefined || new Date(entry.exitedAt).getTime() > decidedAt) &&\n carriesRole(entry.stage),\n );\n const movedOn = decidedOutsideRole ? enteredSince.filter(entry => !carriesRole(entry.stage)) : enteredSince;\n if (movedOn.length === 0) return false;\n // A transition from the same rule evaluation lands after this decision\n // was created; entering that stage is part of this kickoff's intent.\n const siblingStages = new Set(\n (await this.#storage.listDeferredDecisions(record.orgId, record.factoryProjectId))\n .filter(\n sibling => sibling.evaluationId === record.evaluationId && sibling.decision.type === 'transition',\n )\n .map(sibling => sibling.decision.stage),\n );\n return movedOn.some(entry => !siblingStages.has(entry.stage));\n };\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 approvePlans: false,\n label: 'Factory skill run',\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 if (await this.#roleSuperseded(record, decision.role)) return;\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()) return;\n if (await kickoffStale()) return;\n // Safe under the replay guard above: it matches deliveryId, never prompt content.\n const kickoffContents = await withWorkItemFeed(\n this.#feedReader,\n { orgId: record.orgId, factoryProjectId: record.factoryProjectId, workItemId: record.workItemId },\n resolved.message,\n );\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 }\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 run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n approvePlans: await this.#plansAreAutoApproved(record),\n onAgentEnd: () => this.#roleSuperseded(record, decision.role),\n label: 'Factory skill run',\n runStillActive,\n });\n\n const sendKickoff = async () => {\n const result = session.sendSignal(\n {\n id: deliveryId,\n type: 'user',\n tagName: 'user',\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()) return;\n run.arm();\n settled = await sendKickoff();\n }\n await this.#recordRunStart(\n session,\n binding,\n deliveryId,\n record.approvedBy ?? undefined,\n run.endReason,\n item?.title,\n );\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.#withOpenRunHeartbeat(session, deliveryId, () => run.settle());\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 }\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);\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 true,\n );\n return;\n }\n case 'notify': {\n const binding = await this.#requireBinding(record);\n const session = await this.#requireSession(binding);\n await awaitNotification(() =>\n session.sendNotificationSignal({\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 );\n }\n }\n }\n\n async #upsertLinkedItem(\n record: FactoryDeferredDecisionRecord,\n decision: Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>,\n causalChain: FactoryRuleCausalEntry[],\n ): Promise<void> {\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(decision),\n });\n if (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 (decision.skipRules === true) return;\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) return;\n }\n }\n assertFactoryDecisionTarget(decision, this.#boards);\n const definition = this.#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;\n try {\n result = await this.#storage.upsert({\n orgId: record.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: record.factoryProjectId,\n input: {\n externalSource: externalSourceForDecision(decision),\n ...(decision.claimKey ? { claimKey: decision.claimKey } : {}),\n parentWorkItemId,\n title: decision.title,\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 } catch (error) {\n // Another Factory project in the org holds the live card for this record.\n // The decision is spent, not failed: retrying would only be refused again.\n if (error instanceof WorkItemClaimConflictError) return;\n throw error;\n }\n if (!result.created && decision.claimKey && !result.item.claimKey) {\n // A card filed before claims existed adopts the claim now; a refusal means\n // another project already owns the record, and this card stays as it is.\n const claimed = await this.#storage.claimWorkItem({\n orgId: record.orgId,\n id: result.item.id,\n claimKey: decision.claimKey,\n });\n if (claimed) result = { ...result, item: claimed };\n }\n const itemBoard = boardForWorkItem(result.item);\n if (!skipRules && itemBoard !== decision.board) {\n throw new Error(`The work item belongs to board \"${itemBoard}\", not \"${decision.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 missing = Object.fromEntries(\n Object.entries(decision.metadata ?? {}).filter(\n ([key]) => key !== FACTORY_RULE_MATERIALIZATION_KEY && result.item.metadata?.[key] === undefined,\n ),\n );\n if (Object.keys(missing).length > 0) {\n const filled = await this.#storage.update({\n orgId: record.orgId,\n id: result.item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: missing },\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 — a\n // reconcile pass reacting to a label change, say — is placed there the\n // same way, through the relocation the label routes use, so no phase rule\n // runs for it and no transition is recorded.\n if (!result.created) {\n await moveCardToBoard({\n workItems: this.#storage,\n boardRegistry: this.#boards,\n userId: 'factory-rule-dispatcher',\n item: result.item,\n targetBoard: decision.board,\n targetStage: decision.stage,\n });\n }\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 return;\n\n const board = decision.board;\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 Error(`${initial.code}: ${initial.reason}`);\n }\n expectedRevision = initial.revision;\n }\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 });\n if (moved.status === 'rejected') throw new Error(`${moved.code}: ${moved.reason}`);\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 return bindings\n .filter(candidate => candidate.status === 'active' && (role === undefined || candidate.role === role))\n .sort((left, right) => {\n if (role === undefined && left.role === 'work' && right.role !== 'work') return -1;\n if (role === undefined && right.role === 'work' && left.role !== 'work') 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 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 #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(this.#boards, 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 ): Promise<FactoryRunBindingRecord> {\n const binding = await this.#findBinding(record, role);\n if (binding) {\n const session = await this.#controller.getSessionByResource(binding.resourceId);\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 await this.#prepareBinding({ record, item, role });\n return this.#requireBinding(record, role);\n }\n\n async #findSession(binding: FactoryRunBindingRecord): Promise<BoundDispatcherSession | undefined> {\n const session = await this.#controller.getSessionByResource(binding.resourceId);\n if (!session) return undefined;\n await this.#switchThread(session, binding);\n // A reused session keeps the OM models it was created with; refresh them\n // from the project's current settings so a managed run never observes with\n // models the project has since changed away from.\n await this.#refreshManagedMemorySettings?.({ binding, session });\n return session;\n }\n\n /** Unset means off: a plan nobody asked us to answer is a plan someone should see. */\n async #plansAreAutoApproved({\n orgId,\n factoryProjectId,\n }: {\n orgId: string;\n factoryProjectId: string;\n }): Promise<boolean> {\n return this.#autoApprovePlans ? await this.#autoApprovePlans({ orgId, factoryProjectId }) : false;\n }\n\n async #requireSession(binding: FactoryRunBindingRecord): Promise<BoundDispatcherSession> {\n const session = await this.#findSession(binding);\n if (!session) throw new FactoryDispatchError('session_unavailable', 'Bound Factory session not found.');\n return session;\n }\n\n async #switchThread(session: ThreadSwitchSession, binding: FactoryRunBindingRecord): Promise<void> {\n if (session.thread.requireId() === binding.threadId) return;\n await session.thread.switch({ threadId: binding.threadId });\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 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);\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 run = watchRun(session, {\n timeoutMs: this.#skillCompletionObservationTimeoutMs,\n approvePlans: await this.#plansAreAutoApproved(record),\n label: 'Factory kickoff run',\n runStillActive: () =>\n this.#controller.listActiveThreadRuns().some(active => active.threadId === binding.threadId),\n });\n const sendKickoff = (dedupeKey: string) =>\n 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 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 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 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 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 stages: FACTORY_RULE_STAGES,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;AAiDA,MAAM,WAAW;AACjB,MAAM,UAAU;AAChB,MAAM,aAAa;AACnB,MAAM,eAAe;AAIrB,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AAGvB,MAAM,4BAA4B,KAAK;AAGvC,MAAM,0CAA0C,MAAS;AAIzD,MAAM,gBAAgB;;;;;;AAMtB,MAAM,wBAAwB,aAC5B,SAAS,SAAS,iBAAiB,SAAS,SAAS;AACvD,MAAM,yBAAyB,aAA+C,CAAC,qBAAqB,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