@mastra/factory 0.10.2-alpha.3 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/factory.d.ts.map +1 -1
  3. package/dist/factory.js +18 -2
  4. package/dist/factory.js.map +1 -1
  5. package/dist/routes/attention-providers.d.ts +101 -0
  6. package/dist/routes/attention-providers.d.ts.map +1 -0
  7. package/dist/routes/attention-providers.js +384 -0
  8. package/dist/routes/attention-providers.js.map +1 -0
  9. package/dist/routes/attention.d.ts +11 -9
  10. package/dist/routes/attention.d.ts.map +1 -1
  11. package/dist/routes/attention.js +143 -193
  12. package/dist/routes/attention.js.map +1 -1
  13. package/dist/routes/surface.d.ts +2 -0
  14. package/dist/routes/surface.d.ts.map +1 -1
  15. package/dist/routes/surface.js +3 -1
  16. package/dist/routes/surface.js.map +1 -1
  17. package/dist/routes/work-items.d.ts +3 -0
  18. package/dist/routes/work-items.d.ts.map +1 -1
  19. package/dist/routes/work-items.js +3 -1
  20. package/dist/routes/work-items.js.map +1 -1
  21. package/dist/rules/dispatcher.d.ts +3 -0
  22. package/dist/rules/dispatcher.d.ts.map +1 -1
  23. package/dist/rules/dispatcher.js +9 -1
  24. package/dist/rules/dispatcher.js.map +1 -1
  25. package/dist/rules/start-coordinator.d.ts +2 -1
  26. package/dist/rules/start-coordinator.d.ts.map +1 -1
  27. package/dist/rules/start-coordinator.js +10 -2
  28. package/dist/rules/start-coordinator.js.map +1 -1
  29. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  30. package/dist/storage/domains/audit/domain.js +2 -5
  31. package/dist/storage/domains/audit/domain.js.map +1 -1
  32. package/dist/storage/domains/channel-identity/base.d.ts +4 -0
  33. package/dist/storage/domains/channel-identity/base.d.ts.map +1 -1
  34. package/dist/storage/domains/channel-identity/base.js +15 -0
  35. package/dist/storage/domains/channel-identity/base.js.map +1 -1
  36. package/dist/storage/domains/comments/actor.d.ts +51 -0
  37. package/dist/storage/domains/comments/actor.d.ts.map +1 -0
  38. package/dist/storage/domains/comments/actor.js +38 -0
  39. package/dist/storage/domains/comments/actor.js.map +1 -0
  40. package/dist/storage/domains/comments/base.d.ts +230 -0
  41. package/dist/storage/domains/comments/base.d.ts.map +1 -0
  42. package/dist/storage/domains/comments/base.js +490 -0
  43. package/dist/storage/domains/comments/base.js.map +1 -0
  44. package/dist/storage/domains/comments/domain.d.ts +125 -0
  45. package/dist/storage/domains/comments/domain.d.ts.map +1 -0
  46. package/dist/storage/domains/comments/domain.js +270 -0
  47. package/dist/storage/domains/comments/domain.js.map +1 -0
  48. package/dist/storage/domains/comments/feed-context.d.ts +20 -0
  49. package/dist/storage/domains/comments/feed-context.d.ts.map +1 -0
  50. package/dist/storage/domains/comments/feed-context.js +74 -0
  51. package/dist/storage/domains/comments/feed-context.js.map +1 -0
  52. package/dist/storage/domains/comments/feed-sync.d.ts +38 -0
  53. package/dist/storage/domains/comments/feed-sync.d.ts.map +1 -0
  54. package/dist/storage/domains/comments/feed-sync.js +1 -0
  55. package/dist/storage/domains/comments/parse.d.ts +22 -0
  56. package/dist/storage/domains/comments/parse.d.ts.map +1 -0
  57. package/dist/storage/domains/comments/parse.js +90 -0
  58. package/dist/storage/domains/comments/parse.js.map +1 -0
  59. package/dist/storage/domains/comments/routes.d.ts +22 -0
  60. package/dist/storage/domains/comments/routes.d.ts.map +1 -0
  61. package/dist/storage/domains/comments/routes.js +248 -0
  62. package/dist/storage/domains/comments/routes.js.map +1 -0
  63. package/dist/storage/domains/comments/schema.d.ts +4 -0
  64. package/dist/storage/domains/comments/schema.d.ts.map +1 -0
  65. package/dist/storage/domains/comments/schema.js +135 -0
  66. package/dist/storage/domains/comments/schema.js.map +1 -0
  67. package/dist/storage/domains/comments/wire.d.ts +40 -0
  68. package/dist/storage/domains/comments/wire.d.ts.map +1 -0
  69. package/dist/storage/domains/comments/wire.js +37 -0
  70. package/dist/storage/domains/comments/wire.js.map +1 -0
  71. package/dist/storage/domains/work-items/base.d.ts +14 -10
  72. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  73. package/dist/storage/domains/work-items/base.js +109 -22
  74. package/dist/storage/domains/work-items/base.js.map +1 -1
  75. package/factory-skills/factory-rereview/SKILL.md +20 -12
  76. package/factory-skills/factory-review/SKILL.md +17 -12
  77. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"dispatcher.js","names":["#controller","#transitionService","#storage","#ownerId","#isAutoRunEnabled","#reconcileToolResults","#prepareBinding","#primeCredentials","#resolveLinkedWorkItemParentId","#maxInFlight","#staleBindingSweepIntervalMs","#staleBindingTtlMs","#reconcileIntervalMs","#skillCompletionObservationTimeoutMs","#inFlight","#timer","#tick","#activeClaim","#claimAndStart","#maybeSweepStaleBindings","#maybeReconcileToolResults","#track","#dispatchPendingStart","#dispatchDecision","#reconcileInFlight","#lastReconcileAt","#lastStaleBindingSweepAt","#needsApproval","#supersedeProposals","#withLease","#executeDecision","#requireItem","#findBinding","#findSession","#upsertLinkedItem","#requireOrPrepareBinding","#switchThread","#requireBinding","#requireSession"],"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';\n\nimport { resolvePromptInvocation, resolveSkillInvocation } from '../skills/service.js';\nimport type { SkillSession } from '../skills/service.js';\nimport type {\n FactoryDeferredDecisionRecord,\n FactoryPendingStartRecord,\n FactoryRunBindingRecord,\n WorkItemRow,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport { FACTORY_RULE_MATERIALIZATION_KEY } from '../storage/domains/work-items/base.js';\nimport { FactoryDispatchError, factoryDispatchFailureCode } from './dispatch-errors.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport type { FactoryCommitDecision, FactoryRuleActor, FactoryRuleCausalEntry } from './types.js';\nimport { FACTORY_RULE_STAGES } from './types.js';\nimport { MAX_FACTORY_RULE_CAUSAL_DEPTH, validateFactoryRuleDecision } from './validation.js';\n\nconst LEASE_MS = 30_000;\nconst POLL_MS = 1_000;\nconst BATCH_SIZE = 10;\nconst MAX_ATTEMPTS = 5;\nconst MAX_ERROR_LENGTH = 512;\nconst MAX_BACKOFF_MS = 60_000;\nconst SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS = 10 * 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// 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\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 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 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}\n\ntype FactoryController = Pick<AgentController<MastraCodeState>, 'getSessionByResource'>;\ntype BoundDispatcherSession = Session<MastraCodeState>;\n\nexport interface FactoryBindingPreparationInput {\n record: FactoryDeferredDecisionRecord;\n item: WorkItemRow;\n role: string;\n}\n\nexport interface FactoryDecisionDispatcherOptions {\n controller: FactoryController;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n storage: WorkItemsStorage;\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 reconcileToolResults?: () => Promise<void>;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n resolveLinkedWorkItemParentId?: (input: {\n orgId: 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 /** How long to wait for a run's terminal event before failing for retry. Defaults to 10 minutes. */\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 const [integrationId, type] =\n decision.source === 'github-pr'\n ? ['github', 'pull-request']\n : decision.source === 'github-issue'\n ? ['github', 'issue']\n : decision.source === 'linear-issue'\n ? ['linear', 'issue']\n : ['factory', 'manual'];\n return { integrationId, type, externalId: decision.sourceKey, url: 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 return { type: 'system', id: 'factory-rule-dispatcher' };\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 #controller: FactoryController;\n readonly #transitionService: Pick<FactoryTransitionService, 'transition'>;\n readonly #storage: WorkItemsStorage;\n readonly #ownerId: string;\n readonly #isAutoRunEnabled: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n readonly #reconcileToolResults?: () => Promise<void>;\n readonly #prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n readonly #primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\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 readonly #inFlight = new Set<Promise<void>>();\n\n constructor(options: FactoryDecisionDispatcherOptions) {\n this.#controller = options.controller;\n this.#transitionService = options.transitionService;\n this.#storage = options.storage;\n this.#ownerId = options.ownerId ?? `factory-dispatcher:${randomUUID()}`;\n this.#isAutoRunEnabled = options.isAutoRunEnabled;\n this.#reconcileToolResults = options.reconcileToolResults;\n this.#prepareBinding = options.prepareBinding;\n this.#primeCredentials = options.primeCredentials;\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.#inFlight]);\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 capacity = this.#maxInFlight - this.#inFlight.size;\n if (capacity <= 0) return [];\n const limit = Math.min(BATCH_SIZE, capacity);\n const leaseExpiresAt = new Date(now.getTime() + LEASE_MS);\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 })\n : [];\n return [\n ...starts.map(start => this.#track(this.#dispatchPendingStart(start, now))),\n ...decisions.map(decision => this.#track(this.#dispatchDecision(decision, now))),\n ];\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(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(dispatch: Promise<void>): Promise<void> {\n this.#inFlight.add(dispatch);\n void dispatch.catch(() => {}).then(() => this.#inFlight.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 terminal = record.attempts >= MAX_ATTEMPTS;\n 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: factoryDispatchFailureCode(error),\n terminal,\n advanceDeliveryGeneration: !executionCompleted,\n });\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 /** Starting an agent run spends the project's compute and executes its code — the one effect a human owns. */\n async #needsApproval(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): Promise<boolean> {\n if (decision.type !== 'invokeSkill' || record.approvedAt !== null) return false;\n if (await this.#isAutoRunEnabled({ orgId: record.orgId, factoryProjectId: record.factoryProjectId })) 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 return item?.autonomyArmedAt == null;\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 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: { 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 // Best-effort recipient lookup: no active binding (or no authenticated\n // session owner) means nobody is engaged with this item, so the\n // transition itself is the whole effect. A retry after a delivery\n // failure is safe because the transition replays by ingress identity.\n const binding = await this.#findBinding(record, transitionMessage.role);\n if (!binding) return;\n const startedBy = item.sessions[binding.role]?.startedBy;\n if (!startedBy) return;\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const requestContext = new RequestContext();\n requestContext.set('user', { workosId: startedBy, organizationId: record.orgId });\n const session = await this.#findSession(binding);\n if (!session) return;\n await awaitNotification(\n () =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'rule-message',\n summary: transitionMessage.text,\n priority: 'high',\n payload: { message: transitionMessage.text },\n sourceId: record.id,\n dedupeKey: record.idempotencyKey,\n },\n {\n ifActive: { behavior: 'deliver' },\n ifIdle: { behavior: 'wake' },\n requestContext,\n },\n ),\n true,\n );\n return;\n }\n case 'upsertLinkedWorkItem': {\n await this.#upsertLinkedItem(record, decision, nextChain);\n return;\n }\n case 'invokeSkill': {\n const binding = await this.#requireOrPrepareBinding(record, decision.role);\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 requestContext = new RequestContext();\n requestContext.set('user', { workosId: startedBy, organizationId: record.orgId });\n const resolved =\n decision.skillName === undefined\n ? await resolvePromptInvocation(this.#controller, {\n resourceId: binding.resourceId,\n prompt: decision.prompt,\n })\n : await resolveSkillInvocation(this.#controller, {\n resourceId: binding.resourceId,\n name: decision.skillName,\n arguments: decision.arguments,\n });\n const session = resolved.session as DispatcherSession;\n await this.#switchThread(session, binding);\n const deliveryId =\n record.deliveryGeneration === 0 ? record.id : `${record.id}:retry:${record.deliveryGeneration}`;\n const delivered = await session.thread.listActiveMessages();\n if (delivered.some(message => message.id === deliveryId)) return;\n if (decision.cancelInFlight) 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 let resolveAgentEnd!: () => void;\n let agentEnd!: Promise<void>;\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 let endReason: 'complete' | 'aborted' | 'error' | 'suspended' | 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 armAgentEnd = () => {\n endReason = undefined;\n agentEnd = new Promise<void>(resolve => {\n resolveAgentEnd = resolve;\n });\n };\n armAgentEnd();\n const unsubscribe = session.subscribe(event => {\n if (event.type === 'agent_end') {\n endReason = event.reason;\n resolveAgentEnd();\n }\n });\n\n const sendKickoff = async () => {\n const result = session.sendSignal(\n {\n id: deliveryId,\n type: 'user',\n tagName: 'user',\n contents: resolved.message,\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 // An undefined action means the session did not verify delivery at\n // all — with `requireDelivery` set that is a contract violation, not\n // a success.\n throw new Error(`Factory skill invocation signal did not reach the agent (${String(settled.action)}).`);\n }\n return settled;\n };\n\n try {\n let settled = await sendKickoff();\n if (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 const landed = await session.thread.listActiveMessages();\n if (!landed.some(message => message.id === deliveryId)) {\n // The condition that resolves this is the in-flight run ending, so\n // wait for exactly that and redeliver into the idle session. A\n // backoff cannot work here: retries are sized in seconds and a turn\n // takes minutes, so every attempt lands on the same busy run and\n // the card burns its whole budget without the session ever having\n // had a chance to be free.\n if (!(await waitForAgentEndOrTimeout(agentEnd, this.#skillCompletionObservationTimeoutMs))) {\n throw new Error('Factory skill invocation is waiting on a run that has not ended.');\n }\n armAgentEnd();\n settled = await sendKickoff();\n if (settled.action !== 'wake') {\n throw new Error('Factory skill invocation was queued onto an ending run and never reached the agent.');\n }\n }\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 {\n const observed = await waitForAgentEndOrTimeout(agentEnd, this.#skillCompletionObservationTimeoutMs);\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\n // works it. Fail non-terminally so the attempts/backoff\n // machinery redelivers — the delivery generation guarantees the\n // retry sends a fresh kickoff instead of hitting the replay\n // guard.\n throw new Error('Factory skill run terminal event was not observed before timeout.');\n } else if (endReason === 'error') {\n throw new Error('Factory skill run ended in error.');\n } else if (endReason === 'aborted') {\n // Retryable, though an abort reads as deliberate. The stream does\n // not say who aborted, and in practice the dominant cause is the\n // process going away underneath the run — an operator restarting\n // the server — not anyone deciding this work should stop. Treating\n // that as terminal dead-ends the card at attempt 1 with nothing on\n // the board to press. A spurious retry is bounded by MAX_ATTEMPTS;\n // a dead card costs a human a manual nudge.\n throw new Error('Factory skill run was aborted before it finished.');\n }\n }\n } finally {\n unsubscribe();\n }\n return;\n }\n case 'sendMessage': {\n const binding = decision.prepareBinding\n ? await this.#requireOrPrepareBinding(record, decision.role)\n : await this.#requireBinding(record, decision.role);\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 requestContext = new RequestContext();\n requestContext.set('user', { workosId: startedBy, organizationId: record.orgId });\n const session = await this.#requireSession(binding);\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 const parentWorkItemId =\n record.workItemId ??\n (await this.#resolveLinkedWorkItemParentId?.({\n orgId: record.orgId,\n decision,\n })) ??\n null;\n let 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 parentWorkItemId,\n title: decision.title,\n stages: ['intake'],\n sessions: {},\n metadata: { ...decision.metadata, [FACTORY_RULE_MATERIALIZATION_KEY]: record.idempotencyKey },\n },\n reuseMode: 'preserve',\n });\n if (!result.item.parentWorkItemId && parentWorkItemId) {\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 const materializedByDecision = result.item.metadata?.[FACTORY_RULE_MATERIALIZATION_KEY] === record.idempotencyKey;\n if (!materializedByDecision && (decision.stage === 'intake' || !result.item.stages.includes('intake'))) 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: 'intake',\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) await this.#storage.delete({ orgId: record.orgId, id: result.item.id });\n throw new Error(`${initial.code}: ${initial.reason}`);\n }\n expectedRevision = initial.revision;\n }\n if (decision.stage === 'intake') 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 #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 return session;\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 await session.thread.switch({ threadId: binding.threadId });\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 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 requestContext = new RequestContext();\n requestContext.set('user', { workosId: startedBy, organizationId: record.orgId });\n const session = await this.#requireSession(binding);\n let resolveAgentEnd!: () => void;\n let agentEnd!: Promise<void>;\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 let endReason: 'complete' | 'aborted' | 'error' | 'suspended' | undefined;\n const armAgentEnd = () => {\n endReason = undefined;\n agentEnd = new Promise<void>(resolve => {\n resolveAgentEnd = resolve;\n });\n };\n armAgentEnd();\n const unsubscribe = session.subscribe(event => {\n if (event.type === 'agent_end') {\n endReason = event.reason;\n resolveAgentEnd();\n }\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 if (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. There is no per-notification\n // \"processed\" signal, so wait for the in-flight run to end and\n // redeliver into the idle session unconditionally — the\n // generation-scoped dedupeKey defeats inbox dedupe and the\n // kickoff key keeps a duplicate run bounded, while a dropped\n // kickoff strands the card forever.\n if (!(await waitForAgentEndOrTimeout(agentEnd, this.#skillCompletionObservationTimeoutMs))) {\n throw new Error('Factory kickoff is waiting on a run that has not ended.');\n }\n armAgentEnd();\n settled = await sendKickoff(`factory-kickoff:${record.kickoffKey}:retry:${record.attempts}`);\n if (settled?.action !== 'wake') {\n throw new Error('Factory kickoff was queued onto an ending run and never reached the agent.');\n }\n }\n const observed = await waitForAgentEndOrTimeout(agentEnd, this.#skillCompletionObservationTimeoutMs);\n if (!observed) {\n throw new Error('Factory kickoff run terminal event was not observed before timeout.');\n } else if (endReason === 'error') {\n throw new Error('Factory kickoff run ended in error.');\n } else if (endReason === 'aborted') {\n // Retryable for the same reason as skill decisions: the dominant\n // cause is the process going away underneath the run, not a\n // deliberate stop, and a spurious retry is bounded by\n // MAX_ATTEMPTS while a dead card costs a human a manual nudge.\n throw new Error('Factory kickoff run was aborted before it finished.');\n }\n } finally {\n unsubscribe();\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 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: factoryDispatchFailureCode(error),\n terminal: record.attempts >= MAX_ATTEMPTS,\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 maxInFlight: MAX_IN_FLIGHT,\n stages: FACTORY_RULE_STAGES,\n} as const;\n"],"mappings":";;;;;;;;AAsBA,MAAM,WAAW;AACjB,MAAM,UAAU;AAChB,MAAM,aAAa;AACnB,MAAM,eAAe;AACrB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,0CAA0C,KAAK;AAIrD,MAAM,gBAAgB;AAItB,MAAM,kCAAkC,KAAK;AAC7C,MAAM,uBAAuB,OAAU;AAIvC,MAAM,wBAAwB;AAE9B,SAAS,yBAAyB,UAAyB,WAAqC;CAC9F,OAAO,IAAI,SAAQ,YAAW;EAC5B,MAAM,UAAU,iBAAiB,QAAQ,KAAK,GAAG,SAAS;EAC1D,QAAQ,QAAQ;EAChB,SAAc,WAAW;GACvB,aAAa,OAAO;GACpB,QAAQ,IAAI;EACd,CAAC;CACH,CAAC;AACH;AA+DA,SAAS,WAAW,OAA2B,UAA0B;CACvE,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,QAAQ,IAAI,KAAK,MAAM,KAAK,IAAI;AAChG;AAEA,SAAS,sBAAsB,OAAwB;CAErD,QADgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAA,CAElE,QAAQ,sEAAsE,YAAY,CAAC,CAC3F,MAAM,GAAG,gBAAgB;AAC9B;AAEA,SAAS,QAAQ,KAAW,UAAwB;CAClD,OAAO,IAAI,KAAK,IAAI,QAAQ,IAAI,KAAK,IAAI,MAAQ,KAAK,KAAK,IAAI,GAAG,WAAW,C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,GAEjG,MAAM,IAAI,MAAM,qEAAqE;UAChF,IAAI,cAAc,SACvB,MAAM,IAAI,MAAM,qCAAqC;UAChD,IAAI,cAAc,WAKvB,MAAM,IAAI,MAAM,qDAAqD;IAEzE,UAAU;KACR,YAAY;IACd;GACF,CACF;GAEA,IAAI,CAAC,MADmB,KAAKX,SAAS,qBAAqB,cAAc,QAAQ,KAAKC,QAAQ,mBAAG,IAAI,KAAK,CAAC,GAC3F,MAAM,IAAI,MAAM,mDAAmD;EACrF,SAAS,OAAO;GACd,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,aAAa,2BAA2B,KAAK;IAC7C,UAAU,OAAO,YAAY;GAC/B,CAAC;EACH;CACF;AACF;AAEA,MAAa,6BAA6B;CACxC,SAAS;CACT,QAAQ;CACR,WAAW;CACX,aAAa;CACb,gBAAgB;CAChB,cAAc;CACd,qCAAqC;CACrC,aAAa;CACb,QAAQ;AACV"}
1
+ {"version":3,"file":"dispatcher.js","names":["#controller","#transitionService","#storage","#ownerId","#isAutoRunEnabled","#reconcileToolResults","#prepareBinding","#primeCredentials","#feedReader","#resolveLinkedWorkItemParentId","#maxInFlight","#staleBindingSweepIntervalMs","#staleBindingTtlMs","#reconcileIntervalMs","#skillCompletionObservationTimeoutMs","#inFlight","#timer","#tick","#activeClaim","#claimAndStart","#maybeSweepStaleBindings","#maybeReconcileToolResults","#track","#dispatchPendingStart","#dispatchDecision","#reconcileInFlight","#lastReconcileAt","#lastStaleBindingSweepAt","#needsApproval","#supersedeProposals","#withLease","#executeDecision","#requireItem","#findBinding","#findSession","#upsertLinkedItem","#requireOrPrepareBinding","#switchThread","#requireBinding","#requireSession"],"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';\n\nimport { resolvePromptInvocation, resolveSkillInvocation } from '../skills/service.js';\nimport type { SkillSession } from '../skills/service.js';\nimport { withWorkItemFeed } from '../storage/domains/comments/feed-context.js';\nimport type { FactoryFeedReader } from '../storage/domains/comments/feed-context.js';\nimport type {\n FactoryDeferredDecisionRecord,\n FactoryPendingStartRecord,\n FactoryRunBindingRecord,\n WorkItemRow,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport { FACTORY_RULE_MATERIALIZATION_KEY } from '../storage/domains/work-items/base.js';\nimport { FactoryDispatchError, factoryDispatchFailureCode } from './dispatch-errors.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport type { FactoryCommitDecision, FactoryRuleActor, FactoryRuleCausalEntry } from './types.js';\nimport { FACTORY_RULE_STAGES } from './types.js';\nimport { MAX_FACTORY_RULE_CAUSAL_DEPTH, validateFactoryRuleDecision } from './validation.js';\n\nconst LEASE_MS = 30_000;\nconst POLL_MS = 1_000;\nconst BATCH_SIZE = 10;\nconst MAX_ATTEMPTS = 5;\nconst MAX_ERROR_LENGTH = 512;\nconst MAX_BACKOFF_MS = 60_000;\nconst SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS = 10 * 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// 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\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 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 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}\n\ntype FactoryController = Pick<AgentController<MastraCodeState>, 'getSessionByResource'>;\ntype BoundDispatcherSession = Session<MastraCodeState>;\n\nexport interface FactoryBindingPreparationInput {\n record: FactoryDeferredDecisionRecord;\n item: WorkItemRow;\n role: string;\n}\n\nexport interface FactoryDecisionDispatcherOptions {\n controller: FactoryController;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n storage: WorkItemsStorage;\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 reconcileToolResults?: () => Promise<void>;\n prepareBinding?: (input: FactoryBindingPreparationInput) => 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 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 /** How long to wait for a run's terminal event before failing for retry. Defaults to 10 minutes. */\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 const [integrationId, type] =\n decision.source === 'github-pr'\n ? ['github', 'pull-request']\n : decision.source === 'github-issue'\n ? ['github', 'issue']\n : decision.source === 'linear-issue'\n ? ['linear', 'issue']\n : ['factory', 'manual'];\n return { integrationId, type, externalId: decision.sourceKey, url: 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 return { type: 'system', id: 'factory-rule-dispatcher' };\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 #controller: FactoryController;\n readonly #transitionService: Pick<FactoryTransitionService, 'transition'>;\n readonly #storage: WorkItemsStorage;\n readonly #ownerId: string;\n readonly #isAutoRunEnabled: (tenant: { orgId: string; factoryProjectId: string }) => Promise<boolean>;\n readonly #reconcileToolResults?: () => Promise<void>;\n readonly #prepareBinding?: (input: FactoryBindingPreparationInput) => 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 readonly #inFlight = new Set<Promise<void>>();\n\n constructor(options: FactoryDecisionDispatcherOptions) {\n this.#controller = options.controller;\n this.#transitionService = options.transitionService;\n this.#storage = options.storage;\n this.#ownerId = options.ownerId ?? `factory-dispatcher:${randomUUID()}`;\n this.#isAutoRunEnabled = options.isAutoRunEnabled;\n this.#reconcileToolResults = options.reconcileToolResults;\n this.#prepareBinding = options.prepareBinding;\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.#inFlight]);\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 capacity = this.#maxInFlight - this.#inFlight.size;\n if (capacity <= 0) return [];\n const limit = Math.min(BATCH_SIZE, capacity);\n const leaseExpiresAt = new Date(now.getTime() + LEASE_MS);\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 })\n : [];\n return [\n ...starts.map(start => this.#track(this.#dispatchPendingStart(start, now))),\n ...decisions.map(decision => this.#track(this.#dispatchDecision(decision, now))),\n ];\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(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(dispatch: Promise<void>): Promise<void> {\n this.#inFlight.add(dispatch);\n void dispatch.catch(() => {}).then(() => this.#inFlight.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 terminal = record.attempts >= MAX_ATTEMPTS;\n 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: factoryDispatchFailureCode(error),\n terminal,\n advanceDeliveryGeneration: !executionCompleted,\n });\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 /** Starting an agent run spends the project's compute and executes its code — the one effect a human owns. */\n async #needsApproval(record: FactoryDeferredDecisionRecord, decision: FactoryCommitDecision): Promise<boolean> {\n if (decision.type !== 'invokeSkill' || record.approvedAt !== null) return false;\n if (await this.#isAutoRunEnabled({ orgId: record.orgId, factoryProjectId: record.factoryProjectId })) 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 return item?.autonomyArmedAt == null;\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 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: { 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 // Best-effort recipient lookup: no active binding (or no authenticated\n // session owner) means nobody is engaged with this item, so the\n // transition itself is the whole effect. A retry after a delivery\n // failure is safe because the transition replays by ingress identity.\n const binding = await this.#findBinding(record, transitionMessage.role);\n if (!binding) return;\n const startedBy = item.sessions[binding.role]?.startedBy;\n if (!startedBy) return;\n await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });\n const requestContext = new RequestContext();\n requestContext.set('user', { workosId: startedBy, organizationId: record.orgId });\n const session = await this.#findSession(binding);\n if (!session) return;\n await awaitNotification(\n () =>\n session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'rule-message',\n summary: transitionMessage.text,\n priority: 'high',\n payload: { message: transitionMessage.text },\n sourceId: record.id,\n dedupeKey: record.idempotencyKey,\n },\n {\n ifActive: { behavior: 'deliver' },\n ifIdle: { behavior: 'wake' },\n requestContext,\n },\n ),\n true,\n );\n return;\n }\n case 'upsertLinkedWorkItem': {\n await this.#upsertLinkedItem(record, decision, nextChain);\n return;\n }\n case 'invokeSkill': {\n const binding = await this.#requireOrPrepareBinding(record, decision.role);\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 requestContext = new RequestContext();\n requestContext.set('user', { workosId: startedBy, organizationId: record.orgId });\n const resolved =\n decision.skillName === undefined\n ? await resolvePromptInvocation(this.#controller, {\n resourceId: binding.resourceId,\n prompt: decision.prompt,\n })\n : await resolveSkillInvocation(this.#controller, {\n resourceId: binding.resourceId,\n name: decision.skillName,\n arguments: decision.arguments,\n });\n const session = resolved.session as DispatcherSession;\n await this.#switchThread(session, binding);\n const deliveryId =\n record.deliveryGeneration === 0 ? record.id : `${record.id}:retry:${record.deliveryGeneration}`;\n const delivered = await session.thread.listActiveMessages();\n if (delivered.some(message => message.id === deliveryId)) 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.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 let resolveAgentEnd!: () => void;\n let agentEnd!: Promise<void>;\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 let endReason: 'complete' | 'aborted' | 'error' | 'suspended' | 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 armAgentEnd = () => {\n endReason = undefined;\n agentEnd = new Promise<void>(resolve => {\n resolveAgentEnd = resolve;\n });\n };\n armAgentEnd();\n const unsubscribe = session.subscribe(event => {\n if (event.type === 'agent_end') {\n endReason = event.reason;\n resolveAgentEnd();\n }\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 // An undefined action means the session did not verify delivery at\n // all — with `requireDelivery` set that is a contract violation, not\n // a success.\n throw new Error(`Factory skill invocation signal did not reach the agent (${String(settled.action)}).`);\n }\n return settled;\n };\n\n try {\n let settled = await sendKickoff();\n if (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 const landed = await session.thread.listActiveMessages();\n if (!landed.some(message => message.id === deliveryId)) {\n // The condition that resolves this is the in-flight run ending, so\n // wait for exactly that and redeliver into the idle session. A\n // backoff cannot work here: retries are sized in seconds and a turn\n // takes minutes, so every attempt lands on the same busy run and\n // the card burns its whole budget without the session ever having\n // had a chance to be free.\n if (!(await waitForAgentEndOrTimeout(agentEnd, this.#skillCompletionObservationTimeoutMs))) {\n throw new Error('Factory skill invocation is waiting on a run that has not ended.');\n }\n armAgentEnd();\n settled = await sendKickoff();\n if (settled.action !== 'wake') {\n throw new Error('Factory skill invocation was queued onto an ending run and never reached the agent.');\n }\n }\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 {\n const observed = await waitForAgentEndOrTimeout(agentEnd, this.#skillCompletionObservationTimeoutMs);\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\n // works it. Fail non-terminally so the attempts/backoff\n // machinery redelivers — the delivery generation guarantees the\n // retry sends a fresh kickoff instead of hitting the replay\n // guard.\n throw new Error('Factory skill run terminal event was not observed before timeout.');\n } else if (endReason === 'error') {\n throw new Error('Factory skill run ended in error.');\n } else if (endReason === 'aborted') {\n // Retryable, though an abort reads as deliberate. The stream does\n // not say who aborted, and in practice the dominant cause is the\n // process going away underneath the run — an operator restarting\n // the server — not anyone deciding this work should stop. Treating\n // that as terminal dead-ends the card at attempt 1 with nothing on\n // the board to press. A spurious retry is bounded by MAX_ATTEMPTS;\n // a dead card costs a human a manual nudge.\n throw new Error('Factory skill run was aborted before it finished.');\n }\n }\n } finally {\n unsubscribe();\n }\n return;\n }\n case 'sendMessage': {\n const binding = decision.prepareBinding\n ? await this.#requireOrPrepareBinding(record, decision.role)\n : await this.#requireBinding(record, decision.role);\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 requestContext = new RequestContext();\n requestContext.set('user', { workosId: startedBy, organizationId: record.orgId });\n const session = await this.#requireSession(binding);\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 const parentWorkItemId =\n record.workItemId ??\n (await this.#resolveLinkedWorkItemParentId?.({\n orgId: record.orgId,\n decision,\n })) ??\n null;\n let 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 parentWorkItemId,\n title: decision.title,\n stages: ['intake'],\n sessions: {},\n metadata: { ...decision.metadata, [FACTORY_RULE_MATERIALIZATION_KEY]: record.idempotencyKey },\n },\n reuseMode: 'preserve',\n });\n if (!result.item.parentWorkItemId && parentWorkItemId) {\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 const materializedByDecision = result.item.metadata?.[FACTORY_RULE_MATERIALIZATION_KEY] === record.idempotencyKey;\n if (!materializedByDecision && (decision.stage === 'intake' || !result.item.stages.includes('intake'))) 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: 'intake',\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) await this.#storage.delete({ orgId: record.orgId, id: result.item.id });\n throw new Error(`${initial.code}: ${initial.reason}`);\n }\n expectedRevision = initial.revision;\n }\n if (decision.stage === 'intake') 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 #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 return session;\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 await session.thread.switch({ threadId: binding.threadId });\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 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 requestContext = new RequestContext();\n requestContext.set('user', { workosId: startedBy, organizationId: record.orgId });\n const session = await this.#requireSession(binding);\n let resolveAgentEnd!: () => void;\n let agentEnd!: Promise<void>;\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 let endReason: 'complete' | 'aborted' | 'error' | 'suspended' | undefined;\n const armAgentEnd = () => {\n endReason = undefined;\n agentEnd = new Promise<void>(resolve => {\n resolveAgentEnd = resolve;\n });\n };\n armAgentEnd();\n const unsubscribe = session.subscribe(event => {\n if (event.type === 'agent_end') {\n endReason = event.reason;\n resolveAgentEnd();\n }\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 if (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. There is no per-notification\n // \"processed\" signal, so wait for the in-flight run to end and\n // redeliver into the idle session unconditionally — the\n // generation-scoped dedupeKey defeats inbox dedupe and the\n // kickoff key keeps a duplicate run bounded, while a dropped\n // kickoff strands the card forever.\n if (!(await waitForAgentEndOrTimeout(agentEnd, this.#skillCompletionObservationTimeoutMs))) {\n throw new Error('Factory kickoff is waiting on a run that has not ended.');\n }\n armAgentEnd();\n settled = await sendKickoff(`factory-kickoff:${record.kickoffKey}:retry:${record.attempts}`);\n if (settled?.action !== 'wake') {\n throw new Error('Factory kickoff was queued onto an ending run and never reached the agent.');\n }\n }\n const observed = await waitForAgentEndOrTimeout(agentEnd, this.#skillCompletionObservationTimeoutMs);\n if (!observed) {\n throw new Error('Factory kickoff run terminal event was not observed before timeout.');\n } else if (endReason === 'error') {\n throw new Error('Factory kickoff run ended in error.');\n } else if (endReason === 'aborted') {\n // Retryable for the same reason as skill decisions: the dominant\n // cause is the process going away underneath the run, not a\n // deliberate stop, and a spurious retry is bounded by\n // MAX_ATTEMPTS while a dead card costs a human a manual nudge.\n throw new Error('Factory kickoff run was aborted before it finished.');\n }\n } finally {\n unsubscribe();\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 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: factoryDispatchFailureCode(error),\n terminal: record.attempts >= MAX_ATTEMPTS,\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 maxInFlight: MAX_IN_FLIGHT,\n stages: FACTORY_RULE_STAGES,\n} as const;\n"],"mappings":";;;;;;;;;AAwBA,MAAM,WAAW;AACjB,MAAM,UAAU;AAChB,MAAM,aAAa;AACnB,MAAM,eAAe;AACrB,MAAM,mBAAm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AM,mDAAmD;EACrF,SAAS,OAAO;GACd,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,aAAa,2BAA2B,KAAK;IAC7C,UAAU,OAAO,YAAY;GAC/B,CAAC;EACH;CACF;AACF;AAEA,MAAa,6BAA6B;CACxC,SAAS;CACT,QAAQ;CACR,WAAW;CACX,aAAa;CACb,gBAAgB;CAChB,cAAc;CACd,qCAAqC;CACrC,aAAa;CACb,QAAQ;AACV"}
@@ -1,6 +1,7 @@
1
1
  import type { MastraCodeState } from '@mastra/code-sdk/schema';
2
2
  import type { AgentController } from '@mastra/core/agent-controller';
3
3
  import { RequestContext } from '@mastra/core/request-context';
4
+ import type { FactoryFeedReader } from '../storage/domains/comments/feed-context.js';
4
5
  import type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';
5
6
  import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
6
7
  import type { CreateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';
@@ -55,7 +56,7 @@ export interface FactoryStartPreparedResult {
55
56
  type FactoryController = AgentController<MastraCodeState>;
56
57
  export declare class FactoryStartCoordinator {
57
58
  #private;
58
- constructor(controller: FactoryController, storage: WorkItemsStorage, transitionService?: Pick<FactoryTransitionService, 'transition'>, sourceControl?: SourceControlStorageHandle, memorySettings?: MemorySettingsStorage);
59
+ constructor(controller: FactoryController, storage: WorkItemsStorage, transitionService?: Pick<FactoryTransitionService, 'transition'>, sourceControl?: SourceControlStorageHandle, memorySettings?: MemorySettingsStorage, feedReader?: FactoryFeedReader);
59
60
  prepare(request: FactoryStartRequest): Promise<FactoryStartPreparedResult>;
60
61
  }
61
62
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"start-coordinator.d.ts","sourceRoot":"","sources":["../../src/rules/start-coordinator.ts"],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E;QAAE,MAAM,EAAE,UAAU,CAAA;KAAE,CAAC,CAAC;gBAE9D,MAAM,EAAE,OAAO,CAAC,uBAAuB,EAAE;QAAE,MAAM,EAAE,UAAU,CAAA;KAAE,CAAC;CAK7E;AAED,MAAM,WAAW,0BAA0B;IACzC,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,SAAS,GAAG,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,CAAC;IAClE,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,KAAK,iBAAiB,GAAG,eAAe,CAAC,eAAe,CAAC,CAAC;AAqD1D,qBAAa,uBAAuB;;gBAShC,UAAU,EAAE,iBAAiB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,iBAAiB,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,YAAY,CAAC,EAChE,aAAa,CAAC,EAAE,0BAA0B,EAC1C,cAAc,CAAC,EAAE,qBAAqB,EACtC,UAAU,CAAC,EAAE,iBAAiB;IAU1B,OAAO,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,0BAA0B,CAAC;CAoIjF"}
@@ -1,4 +1,5 @@
1
1
  import { hydrateFactorySession } from "../session/factory-session.js";
2
+ import { withWorkItemFeed } from "../storage/domains/comments/feed-context.js";
2
3
  import { RequestContext } from "@mastra/core/request-context";
3
4
  import { formatSkillActivation } from "@mastra/core/workspace";
4
5
  //#region src/rules/start-coordinator.ts
@@ -58,12 +59,14 @@ var FactoryStartCoordinator = class {
58
59
  #transitionService;
59
60
  #sourceControl;
60
61
  #memorySettings;
61
- constructor(controller, storage, transitionService, sourceControl, memorySettings) {
62
+ #feedReader;
63
+ constructor(controller, storage, transitionService, sourceControl, memorySettings, feedReader) {
62
64
  this.#controller = controller;
63
65
  this.#storage = storage;
64
66
  this.#transitionService = transitionService;
65
67
  this.#sourceControl = sourceControl;
66
68
  this.#memorySettings = memorySettings;
69
+ this.#feedReader = feedReader;
67
70
  }
68
71
  async prepare(request) {
69
72
  const storage = this.#storage;
@@ -110,7 +113,12 @@ var FactoryStartCoordinator = class {
110
113
  memorySettings: this.#memorySettings
111
114
  });
112
115
  const threadId = await configureThread(session, request);
113
- const kickoffMessage = await resolveKickoffMessage(session, request.invocation);
116
+ let kickoffMessage = await resolveKickoffMessage(session, request.invocation);
117
+ if (kickoffMessage !== null) kickoffMessage = await withWorkItemFeed(this.#feedReader, {
118
+ orgId: request.orgId,
119
+ factoryProjectId: request.factoryProjectId,
120
+ workItemId: request.workItem.id
121
+ }, kickoffMessage);
114
122
  const prepared = await storage.prepareRunStart({
115
123
  orgId: request.orgId,
116
124
  userId: request.userId,
@@ -1 +1 @@
1
- {"version":3,"file":"start-coordinator.js","names":["#controller","#storage","#transitionService","#sourceControl","#memorySettings"],"sources":["../../src/rules/start-coordinator.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { formatSkillActivation } from '@mastra/core/workspace';\n\nimport { hydrateFactorySession } from '../session/factory-session.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { SourceControlSession, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { CreateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport type { FactoryRuleStage, FactoryTransitionResult } from './types.js';\n\nexport interface FactoryStartRequest {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n sessionId: string;\n threadTitle: string;\n threadTags?: Record<string, string>;\n kickoffKey: string;\n invocation?: { type: 'prompt'; prompt: string } | { type: 'skill'; skillName: string; arguments: string };\n destinationStage: FactoryRuleStage;\n defaultModelId?: string;\n workItem: {\n id?: string;\n role: string;\n input: CreateWorkItemInput;\n };\n requestContext?: RequestContext;\n /** Arm the item's autonomy in the same transaction that prepares the run. */\n armAutonomy?: boolean;\n}\n\nexport class FactoryStartTransitionError extends Error {\n readonly result: Extract<FactoryTransitionResult, { status: 'rejected' }>;\n\n constructor(result: Extract<FactoryTransitionResult, { status: 'rejected' }>) {\n super(result.reason);\n this.name = 'FactoryStartTransitionError';\n this.result = result;\n }\n}\n\nexport interface FactoryStartPreparedResult {\n workItemId: string;\n bindingId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n revision: number;\n kickoffStatus: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n replayed: boolean;\n}\n\ntype FactoryController = AgentController<MastraCodeState>;\ntype FactorySession = Awaited<ReturnType<FactoryController['createSession']>>;\n\nfunction escapeSkillBoundary(value: string): string {\n return value.replaceAll('</skill>', '&lt;/skill&gt;');\n}\n\nasync function resolveKickoffMessage(\n session: FactorySession,\n invocation: FactoryStartRequest['invocation'],\n): Promise<string | null> {\n if (!invocation) return null;\n if (invocation.type === 'prompt') return invocation.prompt;\n\n const skills = session.getWorkspace()?.skills;\n await skills?.maybeRefresh();\n const skill = await skills?.get(invocation.skillName);\n if (!skill || skill['user-invocable'] === false) {\n throw new Error(`Skill not found: ${invocation.skillName}.`);\n }\n const args = invocation.arguments.trim();\n const content = `${formatSkillActivation(skill)}${args ? `\\n\\nARGUMENTS: ${args}` : ''}`.trim();\n return `<skill name=\"${skill.name}\">\\n${escapeSkillBoundary(content)}\\n</skill>`;\n}\n\nasync function resolveSourceSession(\n storage: SourceControlStorageHandle,\n request: FactoryStartRequest,\n): Promise<SourceControlSession> {\n const session = await storage.sessions.getBySessionId(request.sessionId);\n if (!session || session.orgId !== request.orgId || session.userId !== request.userId) {\n throw new Error('Factory session not found');\n }\n const projectRepository = await storage.projectRepositories.get({\n orgId: request.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) throw new Error('Factory session repository not found');\n const connection = await storage.connections.get({ orgId: request.orgId, id: projectRepository.connectionId });\n if (!connection || connection.factoryProjectId !== request.factoryProjectId) {\n throw new Error('Factory session does not belong to this project');\n }\n return session;\n}\n\nasync function configureThread(session: FactorySession, request: FactoryStartRequest): Promise<string> {\n const threadId = session.thread.requireId();\n await session.thread.rename({ title: request.threadTitle });\n const settings = { ...(request.threadTags ?? {}), factorySessionId: request.sessionId };\n await Promise.all(Object.entries(settings).map(([key, value]) => session.thread.setSetting({ key, value })));\n return threadId;\n}\n\nexport class FactoryStartCoordinator {\n readonly #controller: FactoryController;\n readonly #storage: WorkItemsStorage;\n readonly #transitionService?: Pick<FactoryTransitionService, 'transition'>;\n readonly #sourceControl?: SourceControlStorageHandle;\n readonly #memorySettings?: MemorySettingsStorage;\n\n constructor(\n controller: FactoryController,\n storage: WorkItemsStorage,\n transitionService?: Pick<FactoryTransitionService, 'transition'>,\n sourceControl?: SourceControlStorageHandle,\n memorySettings?: MemorySettingsStorage,\n ) {\n this.#controller = controller;\n this.#storage = storage;\n this.#transitionService = transitionService;\n this.#sourceControl = sourceControl;\n this.#memorySettings = memorySettings;\n }\n\n async prepare(request: FactoryStartRequest): Promise<FactoryStartPreparedResult> {\n const storage = this.#storage;\n if (!this.#sourceControl) throw new Error('Factory source control storage is unavailable');\n const sourceSession = await resolveSourceSession(this.#sourceControl, request);\n const requestContext = request.requestContext ?? new RequestContext();\n // Factory runs resolve model credentials org > user: the org's shared keys\n // win, with the acting user's personal credentials as a fallback — a board\n // run should never silently prefer whoever kicked it off. The flag rides\n // the stashed user even when a caller-provided context already has one.\n const existingUser = requestContext.get('user');\n if (existingUser && typeof existingUser === 'object') {\n requestContext.set('user', { ...existingUser, orgFirstCredentials: true });\n } else {\n requestContext.set('user', {\n workosId: request.userId,\n organizationId: request.orgId,\n orgFirstCredentials: true,\n });\n }\n // Sessions kicked off against third-party content (a PR under review, or\n // any pull-request-sourced work item) get `untrustedCheckout` so the SDK\n // never ingests the checkout's AGENTS.md/CLAUDE.md into the system prompt\n // or reminders — those files are attacker-writable in a PR branch.\n const untrustedCheckout =\n request.workItem.input.externalSource?.type === 'pull-request' ||\n (request.invocation?.type === 'skill' &&\n (request.invocation.skillName === 'factory-review' || request.invocation.skillName === 'factory-rereview'));\n // The trusted ref the SDK may serve project instruction files from on an\n // untrusted checkout (the PR's base branch). Prefer the session record's\n // base branch; fall back to the intake metadata captured from the PR.\n const metadataBaseBranch = request.workItem.input.metadata?.baseBranch;\n const baseRef =\n (sourceSession.baseBranch || undefined) ??\n (typeof metadataBaseBranch === 'string' && metadataBaseBranch ? metadataBaseBranch : undefined);\n const sessionTags = {\n factoryProjectId: request.factoryProjectId,\n projectRepositoryId: sourceSession.projectRepositoryId,\n };\n const session = await this.#controller.createSession({\n id: sourceSession.sessionId,\n ownerId: request.userId,\n resourceId: sourceSession.sessionId,\n threadId: sourceSession.sessionId,\n requestContext,\n tags: sessionTags,\n });\n // Bound-agent authority gates (the transition tool, the factory-phase\n // processor, workspace token selection) resolve the session address from\n // controller state. Seed it server-side — `tags` covers fresh creation,\n // the explicit setState covers get-or-create returning a session another\n // caller created without them — so autonomous runs never depend on a\n // browser connecting to populate the state. `untrustedCheckout` is a\n // boolean so it rides only on state (tags are string-valued).\n await session.state.set({\n ...sessionTags,\n // The authoritative org id for every downstream identity read (the\n // memory seam's organizationId): the session owner is a USER id, not an\n // org, so it must never be improvised from ownerId.\n factoryOrgId: request.orgId,\n ...(untrustedCheckout ? { untrustedCheckout: true, ...(baseRef ? { baseRef } : {}) } : {}),\n });\n // Board runs are org-shared: hydrate with the factory's default model and\n // the project's shared memory settings (falling back to the built-in\n // defaults), never any individual user's stored settings.\n await hydrateFactorySession(session, {\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n defaultModelId: request.defaultModelId,\n memorySettings: this.#memorySettings,\n });\n const threadId = await configureThread(session, request);\n const kickoffMessage = await resolveKickoffMessage(session, request.invocation);\n const prepared = await storage.prepareRunStart({\n orgId: request.orgId,\n userId: request.userId,\n factoryProjectId: request.factoryProjectId,\n workItem: { id: request.workItem.id, input: request.workItem.input },\n role: request.workItem.role,\n session: { sessionId: sourceSession.sessionId, branch: sourceSession.branch, threadId },\n resourceId: sourceSession.sessionId,\n kickoffKey: request.kickoffKey,\n kickoffMessage,\n armAutonomy: request.armAutonomy === true,\n });\n await session.thread.setSetting({ key: 'factoryWorkItemId', value: prepared.item.id });\n\n let revision = prepared.item.revision;\n if (prepared.item.stages.length !== 1 || prepared.item.stages[0] !== request.destinationStage) {\n if (!this.#transitionService) throw new Error('Factory transition service is unavailable.');\n const transition = await this.#transitionService.transition({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: prepared.item.id,\n board: prepared.item.externalSource?.type === 'pull-request' ? 'review' : 'work',\n stage: request.destinationStage,\n expectedRevision: prepared.item.revision,\n actor: { type: 'human', id: request.userId },\n ingress: { type: 'human', identity: `start:${request.kickoffKey}:transition` },\n cause: 'run_start',\n });\n if (transition.status === 'rejected') {\n await storage.markPendingStart(prepared.binding.id, 'failed', transition.reason);\n throw new FactoryStartTransitionError(transition);\n }\n revision = transition.revision;\n }\n\n if (kickoffMessage === null) {\n await storage.markPendingStart(prepared.binding.id, 'sent');\n prepared.pendingStart.status = 'sent';\n }\n\n return {\n workItemId: prepared.item.id,\n bindingId: prepared.binding.id,\n threadId,\n resourceId: sourceSession.sessionId,\n sessionId: sourceSession.sessionId,\n branch: sourceSession.branch,\n revision,\n kickoffStatus: prepared.pendingStart.status,\n replayed: prepared.replayed,\n };\n }\n}\n"],"mappings":";;;;AAiCA,IAAa,8BAAb,cAAiD,MAAM;CACrD;CAEA,YAAY,QAAkE;EAC5E,MAAM,OAAO,MAAM;EACnB,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAiBA,SAAS,oBAAoB,OAAuB;CAClD,OAAO,MAAM,WAAW,YAAY,gBAAgB;AACtD;A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QAAQ;IACf,kBAAkB,SAAS,KAAK;IAChC,OAAO;KAAE,MAAM;KAAS,IAAI,QAAQ;IAAO;IAC3C,SAAS;KAAE,MAAM;KAAS,UAAU,SAAS,QAAQ,WAAW;IAAa;IAC7E,OAAO;GACT,CAAC;GACD,IAAI,WAAW,WAAW,YAAY;IACpC,MAAM,QAAQ,iBAAiB,SAAS,QAAQ,IAAI,UAAU,WAAW,MAAM;IAC/E,MAAM,IAAI,4BAA4B,UAAU;GAClD;GACA,WAAW,WAAW;EACxB;EAEA,IAAI,mBAAmB,MAAM;GAC3B,MAAM,QAAQ,iBAAiB,SAAS,QAAQ,IAAI,MAAM;GAC1D,SAAS,aAAa,SAAS;EACjC;EAEA,OAAO;GACL,YAAY,SAAS,KAAK;GAC1B,WAAW,SAAS,QAAQ;GAC5B;GACA,YAAY,cAAc;GAC1B,WAAW,cAAc;GACzB,QAAQ,cAAc;GACtB;GACA,eAAe,SAAS,aAAa;GACrC,UAAU,SAAS;EACrB;CACF;AACF"}
1
+ {"version":3,"file":"start-coordinator.js","names":["#controller","#storage","#transitionService","#sourceControl","#memorySettings","#feedReader"],"sources":["../../src/rules/start-coordinator.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { formatSkillActivation } from '@mastra/core/workspace';\n\nimport { hydrateFactorySession } from '../session/factory-session.js';\nimport { withWorkItemFeed } from '../storage/domains/comments/feed-context.js';\nimport type { FactoryFeedReader } from '../storage/domains/comments/feed-context.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { SourceControlSession, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { CreateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport type { FactoryRuleStage, FactoryTransitionResult } from './types.js';\n\nexport interface FactoryStartRequest {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n sessionId: string;\n threadTitle: string;\n threadTags?: Record<string, string>;\n kickoffKey: string;\n invocation?: { type: 'prompt'; prompt: string } | { type: 'skill'; skillName: string; arguments: string };\n destinationStage: FactoryRuleStage;\n defaultModelId?: string;\n workItem: {\n id?: string;\n role: string;\n input: CreateWorkItemInput;\n };\n requestContext?: RequestContext;\n /** Arm the item's autonomy in the same transaction that prepares the run. */\n armAutonomy?: boolean;\n}\n\nexport class FactoryStartTransitionError extends Error {\n readonly result: Extract<FactoryTransitionResult, { status: 'rejected' }>;\n\n constructor(result: Extract<FactoryTransitionResult, { status: 'rejected' }>) {\n super(result.reason);\n this.name = 'FactoryStartTransitionError';\n this.result = result;\n }\n}\n\nexport interface FactoryStartPreparedResult {\n workItemId: string;\n bindingId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n revision: number;\n kickoffStatus: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n replayed: boolean;\n}\n\ntype FactoryController = AgentController<MastraCodeState>;\ntype FactorySession = Awaited<ReturnType<FactoryController['createSession']>>;\n\nfunction escapeSkillBoundary(value: string): string {\n return value.replaceAll('</skill>', '&lt;/skill&gt;');\n}\n\nasync function resolveKickoffMessage(\n session: FactorySession,\n invocation: FactoryStartRequest['invocation'],\n): Promise<string | null> {\n if (!invocation) return null;\n if (invocation.type === 'prompt') return invocation.prompt;\n\n const skills = session.getWorkspace()?.skills;\n await skills?.maybeRefresh();\n const skill = await skills?.get(invocation.skillName);\n if (!skill || skill['user-invocable'] === false) {\n throw new Error(`Skill not found: ${invocation.skillName}.`);\n }\n const args = invocation.arguments.trim();\n const content = `${formatSkillActivation(skill)}${args ? `\\n\\nARGUMENTS: ${args}` : ''}`.trim();\n return `<skill name=\"${skill.name}\">\\n${escapeSkillBoundary(content)}\\n</skill>`;\n}\n\nasync function resolveSourceSession(\n storage: SourceControlStorageHandle,\n request: FactoryStartRequest,\n): Promise<SourceControlSession> {\n const session = await storage.sessions.getBySessionId(request.sessionId);\n if (!session || session.orgId !== request.orgId || session.userId !== request.userId) {\n throw new Error('Factory session not found');\n }\n const projectRepository = await storage.projectRepositories.get({\n orgId: request.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) throw new Error('Factory session repository not found');\n const connection = await storage.connections.get({ orgId: request.orgId, id: projectRepository.connectionId });\n if (!connection || connection.factoryProjectId !== request.factoryProjectId) {\n throw new Error('Factory session does not belong to this project');\n }\n return session;\n}\n\nasync function configureThread(session: FactorySession, request: FactoryStartRequest): Promise<string> {\n const threadId = session.thread.requireId();\n await session.thread.rename({ title: request.threadTitle });\n const settings = { ...(request.threadTags ?? {}), factorySessionId: request.sessionId };\n await Promise.all(Object.entries(settings).map(([key, value]) => session.thread.setSetting({ key, value })));\n return threadId;\n}\n\nexport class FactoryStartCoordinator {\n readonly #controller: FactoryController;\n readonly #storage: WorkItemsStorage;\n readonly #transitionService?: Pick<FactoryTransitionService, 'transition'>;\n readonly #sourceControl?: SourceControlStorageHandle;\n readonly #memorySettings?: MemorySettingsStorage;\n readonly #feedReader?: FactoryFeedReader;\n\n constructor(\n controller: FactoryController,\n storage: WorkItemsStorage,\n transitionService?: Pick<FactoryTransitionService, 'transition'>,\n sourceControl?: SourceControlStorageHandle,\n memorySettings?: MemorySettingsStorage,\n feedReader?: FactoryFeedReader,\n ) {\n this.#controller = controller;\n this.#storage = storage;\n this.#transitionService = transitionService;\n this.#sourceControl = sourceControl;\n this.#memorySettings = memorySettings;\n this.#feedReader = feedReader;\n }\n\n async prepare(request: FactoryStartRequest): Promise<FactoryStartPreparedResult> {\n const storage = this.#storage;\n if (!this.#sourceControl) throw new Error('Factory source control storage is unavailable');\n const sourceSession = await resolveSourceSession(this.#sourceControl, request);\n const requestContext = request.requestContext ?? new RequestContext();\n // Factory runs resolve model credentials org > user: the org's shared keys\n // win, with the acting user's personal credentials as a fallback — a board\n // run should never silently prefer whoever kicked it off. The flag rides\n // the stashed user even when a caller-provided context already has one.\n const existingUser = requestContext.get('user');\n if (existingUser && typeof existingUser === 'object') {\n requestContext.set('user', { ...existingUser, orgFirstCredentials: true });\n } else {\n requestContext.set('user', {\n workosId: request.userId,\n organizationId: request.orgId,\n orgFirstCredentials: true,\n });\n }\n // Sessions kicked off against third-party content (a PR under review, or\n // any pull-request-sourced work item) get `untrustedCheckout` so the SDK\n // never ingests the checkout's AGENTS.md/CLAUDE.md into the system prompt\n // or reminders — those files are attacker-writable in a PR branch.\n const untrustedCheckout =\n request.workItem.input.externalSource?.type === 'pull-request' ||\n (request.invocation?.type === 'skill' &&\n (request.invocation.skillName === 'factory-review' || request.invocation.skillName === 'factory-rereview'));\n // The trusted ref the SDK may serve project instruction files from on an\n // untrusted checkout (the PR's base branch). Prefer the session record's\n // base branch; fall back to the intake metadata captured from the PR.\n const metadataBaseBranch = request.workItem.input.metadata?.baseBranch;\n const baseRef =\n (sourceSession.baseBranch || undefined) ??\n (typeof metadataBaseBranch === 'string' && metadataBaseBranch ? metadataBaseBranch : undefined);\n const sessionTags = {\n factoryProjectId: request.factoryProjectId,\n projectRepositoryId: sourceSession.projectRepositoryId,\n };\n const session = await this.#controller.createSession({\n id: sourceSession.sessionId,\n ownerId: request.userId,\n resourceId: sourceSession.sessionId,\n threadId: sourceSession.sessionId,\n requestContext,\n tags: sessionTags,\n });\n // Bound-agent authority gates (the transition tool, the factory-phase\n // processor, workspace token selection) resolve the session address from\n // controller state. Seed it server-side — `tags` covers fresh creation,\n // the explicit setState covers get-or-create returning a session another\n // caller created without them — so autonomous runs never depend on a\n // browser connecting to populate the state. `untrustedCheckout` is a\n // boolean so it rides only on state (tags are string-valued).\n await session.state.set({\n ...sessionTags,\n // The authoritative org id for every downstream identity read (the\n // memory seam's organizationId): the session owner is a USER id, not an\n // org, so it must never be improvised from ownerId.\n factoryOrgId: request.orgId,\n ...(untrustedCheckout ? { untrustedCheckout: true, ...(baseRef ? { baseRef } : {}) } : {}),\n });\n // Board runs are org-shared: hydrate with the factory's default model and\n // the project's shared memory settings (falling back to the built-in\n // defaults), never any individual user's stored settings.\n await hydrateFactorySession(session, {\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n defaultModelId: request.defaultModelId,\n memorySettings: this.#memorySettings,\n });\n const threadId = await configureThread(session, request);\n let kickoffMessage = await resolveKickoffMessage(session, request.invocation);\n // A null kickoff is a deliberate no-send branch and must stay null.\n if (kickoffMessage !== null) {\n kickoffMessage = await withWorkItemFeed(\n this.#feedReader,\n { orgId: request.orgId, factoryProjectId: request.factoryProjectId, workItemId: request.workItem.id },\n kickoffMessage,\n );\n }\n const prepared = await storage.prepareRunStart({\n orgId: request.orgId,\n userId: request.userId,\n factoryProjectId: request.factoryProjectId,\n workItem: { id: request.workItem.id, input: request.workItem.input },\n role: request.workItem.role,\n session: { sessionId: sourceSession.sessionId, branch: sourceSession.branch, threadId },\n resourceId: sourceSession.sessionId,\n kickoffKey: request.kickoffKey,\n kickoffMessage,\n armAutonomy: request.armAutonomy === true,\n });\n await session.thread.setSetting({ key: 'factoryWorkItemId', value: prepared.item.id });\n\n let revision = prepared.item.revision;\n if (prepared.item.stages.length !== 1 || prepared.item.stages[0] !== request.destinationStage) {\n if (!this.#transitionService) throw new Error('Factory transition service is unavailable.');\n const transition = await this.#transitionService.transition({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: prepared.item.id,\n board: prepared.item.externalSource?.type === 'pull-request' ? 'review' : 'work',\n stage: request.destinationStage,\n expectedRevision: prepared.item.revision,\n actor: { type: 'human', id: request.userId },\n ingress: { type: 'human', identity: `start:${request.kickoffKey}:transition` },\n cause: 'run_start',\n });\n if (transition.status === 'rejected') {\n await storage.markPendingStart(prepared.binding.id, 'failed', transition.reason);\n throw new FactoryStartTransitionError(transition);\n }\n revision = transition.revision;\n }\n\n if (kickoffMessage === null) {\n await storage.markPendingStart(prepared.binding.id, 'sent');\n prepared.pendingStart.status = 'sent';\n }\n\n return {\n workItemId: prepared.item.id,\n bindingId: prepared.binding.id,\n threadId,\n resourceId: sourceSession.sessionId,\n sessionId: sourceSession.sessionId,\n branch: sourceSession.branch,\n revision,\n kickoffStatus: prepared.pendingStart.status,\n replayed: prepared.replayed,\n };\n }\n}\n"],"mappings":";;;;;AAmCA,IAAa,8BAAb,cAAiD,MAAM;CACrD;CAEA,YAAY,QAAkE;EAC5E,MAAM,OAAO,MAAM;EACnB,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAiBA,SAAS,oBAAoB,OAAuB;CAClD,OAAO,MAAM,WAAW,YAAY,gBAAgB;AACtD;AAEA,eAAe,sBACb,SACA,YACwB;CACxB,IAAI,CAAC,YAAY,OAAO;CACxB,IAAI,WAAW,SAAS,UAAU,OAAO,WAAW;CAEpD,MAAM,SAAS,QAAQ,aAAa,CAAC,EAAE;CACvC,MAAM,QAAQ,aAAa;CAC3B,MAAM,QAAQ,MAAM,QAAQ,IAAI,WAAW,SAAS;CACpD,IAAI,CAAC,SAAS,MAAM,sBAAsB,OACxC,MAAM,IAAI,MAAM,oBAAoB,WAAW,UAAU,EAAE;CAE7D,MAAM,OAAO,WAAW,UAAU,KAAK;CACvC,MAAM,UAAU,GAAG,sBAAsB,KAAK,IAAI,OAAO,kBAAkB,SAAS,KAAK,KAAK;CAC9F,OAAO,gBAAgB,MAAM,KAAK,MAAM,oBAAoB,OAAO,EAAE;AACvE;AAEA,eAAe,qBACb,SACA,SAC+B;CAC/B,MAAM,UAAU,MAAM,QAAQ,SAAS,eAAe,QAAQ,SAAS;CACvE,IAAI,CAAC,WAAW,QAAQ,UAAU,QAAQ,SAAS,QAAQ,WAAW,QAAQ,QAC5E,MAAM,IAAI,MAAM,2BAA2B;CAE7C,MAAM,oBAAoB,MAAM,QAAQ,oBAAoB,IAAI;EAC9D,OAAO,QAAQ;EACf,IAAI,QAAQ;CACd,CAAC;CACD,IAAI,CAAC,mBAAmB,MAAM,IAAI,MAAM,sCAAsC;CAC9E,MAAM,aAAa,MAAM,QAAQ,YAAY,IAAI;EAAE,OA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AAkB;IAgBnF,MAAM,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;IA0BnE,IAAI,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,cAAc,CAAC;IAK1D,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,cAAc,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IA2BpF,SAAS,CAAC,EACd,cAAc,EACd,KAAK,GACN,EAAE;QACD,cAAc,EAAE,cAAc,CAAC;QAC/B,KAAK,EAAE,mBAAmB,CAAC;KAC5B,GAAG,OAAO,CAAC,IAAI,CAAC;IA+FjB,MAAM,IAAI,QAAQ,EAAE;CAyCrB"}
@@ -1,3 +1,4 @@
1
+ import { getFactoryAuthUser } from "../../../auth.js";
1
2
  import { registerApiRoute } from "@mastra/core/server";
2
3
  //#region src/storage/domains/audit/domain.ts
3
4
  /**
@@ -22,10 +23,6 @@ function readStoredActorProfile(metadata) {
22
23
  ...avatarUrl ? { avatarUrl } : {}
23
24
  };
24
25
  }
25
- /** Read the auth gate's stashed user directly from the Hono context. */
26
- function readFactoryAuthUserFromContext(context) {
27
- return context.get("factoryAuthUser") ?? void 0;
28
- }
29
26
  function buildActorProfileMetadata(user) {
30
27
  const name = user.name?.trim() || user.email?.trim();
31
28
  const avatarUrl = user.avatarUrl?.trim();
@@ -127,7 +124,7 @@ var AuditDomain = class {
127
124
  try {
128
125
  const tenant = this.#auth.tenant(context);
129
126
  if (!tenant?.orgId) return;
130
- const user = readFactoryAuthUserFromContext(context);
127
+ const user = getFactoryAuthUser(context);
131
128
  const actorProfile = user ? buildActorProfileMetadata(user) : void 0;
132
129
  const metadata = actorProfile ? {
133
130
  ...input.metadata,