@mastra/factory 0.2.1 → 0.2.2-alpha.1

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 (59) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/auth.d.ts +2 -2
  3. package/dist/auth.d.ts.map +1 -1
  4. package/dist/auth.js +22 -2
  5. package/dist/auth.js.map +1 -1
  6. package/dist/factory.d.ts.map +1 -1
  7. package/dist/factory.js +411 -244
  8. package/dist/factory.js.map +1 -1
  9. package/dist/index.js +411 -244
  10. package/dist/index.js.map +1 -1
  11. package/dist/integrations/github/integration.js +85 -37
  12. package/dist/integrations/github/integration.js.map +1 -1
  13. package/dist/integrations/github/routes.d.ts.map +1 -1
  14. package/dist/integrations/github/routes.js +85 -37
  15. package/dist/integrations/github/routes.js.map +1 -1
  16. package/dist/integrations/github/sandbox.d.ts +2 -0
  17. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  18. package/dist/integrations/github/sandbox.js +28 -8
  19. package/dist/integrations/github/sandbox.js.map +1 -1
  20. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  21. package/dist/integrations/platform/github/integration.js +119 -39
  22. package/dist/integrations/platform/github/integration.js.map +1 -1
  23. package/dist/routes/config.d.ts.map +1 -1
  24. package/dist/routes/config.js +1 -4
  25. package/dist/routes/config.js.map +1 -1
  26. package/dist/routes/surface.js +1 -4
  27. package/dist/routes/surface.js.map +1 -1
  28. package/dist/routes/work-items.js.map +1 -1
  29. package/dist/rules/binding-context.js.map +1 -1
  30. package/dist/rules/dispatcher.d.ts.map +1 -1
  31. package/dist/rules/dispatcher.js +7 -1
  32. package/dist/rules/dispatcher.js.map +1 -1
  33. package/dist/rules/processor.js.map +1 -1
  34. package/dist/rules/tools.js.map +1 -1
  35. package/dist/spa-static.d.ts.map +1 -1
  36. package/dist/spa-static.js +1 -0
  37. package/dist/spa-static.js.map +1 -1
  38. package/dist/storage/domains/source-control/base.d.ts +9 -0
  39. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  40. package/dist/storage/domains/source-control/base.js +4 -0
  41. package/dist/storage/domains/source-control/base.js.map +1 -1
  42. package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
  43. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  44. package/dist/storage/domains/source-control/inmemory.js +4 -0
  45. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  46. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  47. package/dist/storage/domains/work-items/base.js +20 -4
  48. package/dist/storage/domains/work-items/base.js.map +1 -1
  49. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  50. package/dist/timing.d.ts +15 -0
  51. package/dist/timing.d.ts.map +1 -0
  52. package/dist/timing.js +27 -0
  53. package/dist/timing.js.map +1 -0
  54. package/dist/workspace.d.ts +2 -3
  55. package/dist/workspace.d.ts.map +1 -1
  56. package/dist/workspace.js +104 -65
  57. package/dist/workspace.js.map +1 -1
  58. package/factory-skills/factory-review/SKILL.md +9 -2
  59. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth.ts","../../src/rules/binding-context.ts"],"sourcesContent":["import { MastraAuthWorkos } from '@mastra/auth-workos';\nimport {\n registerApiRoute,\n isAuthHttpHandler,\n isCredentialsProvider,\n isOrganizationsProvider,\n isSessionProvider,\n isSSOProvider,\n} from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, ISessionProvider } from '@mastra/core/server';\nimport type { Context, Hono } from 'hono';\n\nimport type { RouteAuth } from './routes/route.js';\n\n/**\n * Provider-neutral factory auth gating for the MastraCode web server.\n *\n * When an auth provider is active (a `MastraAuthProvider` instance passed to\n * `MastraFactory`'s `auth` slot, or — back-compat for suites/paths that never\n * boot the factory — implied by the WorkOS env vars), every route on the web\n * server is placed behind it: unauthenticated browser navigations are\n * redirected to the SPA's `/signin` page, API/XHR calls receive a 401, and a\n * small set of public routes stay reachable while signed out — the provider's\n * `/auth/*` routes plus `/auth/me`, the `/signin` page and its `/assets/*`\n * bundle. When no provider is active, `mountFactoryAuth` is a no-op and the server\n * behaves exactly as it does without auth.\n *\n * Provider specifics stay in the providers (`@mastra/auth-workos`,\n * `@mastra/auth-better-auth`, or any custom `IMastraAuthProvider`); this\n * module composes them capability-first via the core type guards:\n * - `authenticateToken` — session/bearer validation (all providers)\n * - `ISSOProvider` — hosted-login `/auth/login`, `/auth/callback`, `/auth/logout`\n * - `IAuthHttpHandler` — provider-owned `/auth/api/*` endpoints (better-auth)\n * - `IOrganizationsProvider` — personal-org bootstrap + admin checks\n * - `ICredentialsProvider.isSignUpEnabled` — SPA sign-up affordance\n * - `getClearSessionHeaders` — session cookie clearing on logout\n */\n\n/** Minimal shape of the signed-in user surfaced to the SPA (no tokens). */\nexport interface FactoryAuthUser {\n /** Stable WorkOS user id used to scope per-user data (GitHub installs etc.). */\n workosId?: string;\n /** Provider user id; WorkOS shapes may use `workosId` instead (see {@link workosId}). */\n id?: string;\n email?: string;\n name?: string;\n /**\n * Organization id. The org is the top-level tenant: it owns the GitHub\n * App installation and connected projects, while each user inside the org gets\n * isolated building instances. Absent for personal (no-org) accounts.\n */\n organizationId?: string;\n}\n\n/**\n * Tenant identity: the org is the top-level tenant, and each user inside it is\n * an isolated builder. Agent state, worktrees and sandboxes are scoped per\n * `(orgId, userId)`. Personal (no-org) users have `orgId === undefined`.\n */\nexport interface FactoryAuthTenant {\n /** Organization id, or `undefined` for personal (no-org) accounts. */\n orgId?: string;\n /** Stable provider user id. */\n userId: string;\n}\n\n/**\n * Validate that a `returnTo` value is a safe same-site path, to prevent\n * open-redirect attacks. Only absolute local paths (`/foo`) are allowed;\n * protocol-relative (`//evil.com`) and absolute URLs are rejected.\n */\nexport function sanitizeReturnTo(raw: string | undefined): string {\n if (!raw) return '/';\n if (!raw.startsWith('/')) return '/';\n // Reject protocol-relative URLs like \"//evil.com\" and \"/\\evil.com\".\n if (raw.startsWith('//') || raw.startsWith('/\\\\')) return '/';\n return raw;\n}\n\n/** Extract a bearer token from the Authorization header, if present. */\nexport function getBearerToken(authorization: string | undefined): string {\n if (!authorization) return '';\n const match = /^Bearer\\s+(.+)$/i.exec(authorization);\n return match?.[1] ?? '';\n}\n\n/**\n * Whether the SPA is served cross-origin from this API (platform deploy). When\n * `MASTRACODE_ALLOWED_ORIGINS` is set the browser talks to us cross-site, so\n * session cookies must be `SameSite=None; Secure` for the browser to send them.\n * Same-origin local dev leaves this unset and keeps the stricter `SameSite=Lax`.\n */\nexport function isCrossSiteAuth(): boolean {\n return Boolean(process.env.MASTRACODE_ALLOWED_ORIGINS?.trim());\n}\n\n/** Hono context variables set by the auth gate. */\nexport interface FactoryAuthVariables {\n factoryAuthUser: FactoryAuthUser;\n}\n\n/** Context key under which the gate stashes the authenticated user. */\nconst FACTORY_AUTH_USER_KEY = 'factoryAuthUser';\n\n/**\n * Read the authenticated user the gate stashed on the context, or\n * `undefined` when unauthenticated / auth disabled. Used by downstream routes\n * (e.g. GitHub) to scope rows per user.\n */\nexport function getFactoryAuthUser(c: Context): FactoryAuthUser | undefined {\n return c.get(FACTORY_AUTH_USER_KEY) as FactoryAuthUser | undefined;\n}\n\n/** Resolve the stable user id from an authenticated user shape. */\nexport function getFactoryAuthUserId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.workosId ?? user?.id;\n}\n\n/** Resolve the organization id from a user shape, if present. */\nexport function getFactoryAuthOrgId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.organizationId;\n}\n\n/**\n * Resolve the tenant identity `(orgId, userId)` from the authenticated user on\n * the context. Returns `undefined` when there is no signed-in user (auth\n * disabled or unauthenticated). `orgId` is `undefined` for personal accounts;\n * callers gate org-scoped GitHub features on its presence while agent state\n * falls back to a user-only tenant.\n */\nexport function factoryAuthTenant(c: Context): FactoryAuthTenant | undefined {\n const user = getFactoryAuthUser(c);\n const userId = getFactoryAuthUserId(user);\n if (!userId) return undefined;\n return { orgId: getFactoryAuthOrgId(user), userId };\n}\n\n/** True when both WorkOS credential env vars are present (legacy env gate). */\nfunction envWorkosConfigured(): boolean {\n return Boolean(process.env.WORKOS_API_KEY && process.env.WORKOS_CLIENT_ID);\n}\n\n/**\n * WorkOS provider implied by the `WORKOS_*` env vars — back-compat for test\n * suites exercised without booting the factory (route suites set `WORKOS_*`\n * directly and call {@link mountFactoryAuth} without an explicit provider).\n * `fetchMemberships: true` lets `authenticateToken` resolve `organizationId`\n * from a single membership when the JWT has no org claim — required so a\n * bootstrapped personal org resolves without re-auth.\n */\nfunction envFallbackAuthProvider(redirectUri: string | undefined): MastraAuthWorkos | undefined {\n if (!envWorkosConfigured()) return undefined;\n return new MastraAuthWorkos({\n redirectUri: redirectUri ?? process.env.WORKOS_REDIRECT_URI,\n fetchMemberships: true,\n });\n}\n\n/**\n * Map a provider `authenticateToken` result onto the neutral SPA user shape.\n *\n * Two result families exist today:\n * - flat provider users (WorkOS `WorkOSUser` et al.): `id`/`workosId`/`email`/\n * `name`/`organizationId` directly on the object;\n * - session-shaped results (better-auth `BetterAuthUser`): `{ session, user }`\n * with the active org on the session.\n */\nfunction toFactoryAuthUser(result: unknown): FactoryAuthUser | null {\n if (!result || typeof result !== 'object') return null;\n const record = result as Record<string, unknown>;\n\n // Session-shaped results: { session, user }.\n if (record.user && typeof record.user === 'object' && record.session && typeof record.session === 'object') {\n const user = record.user as { id?: unknown; email?: unknown; name?: unknown };\n const session = record.session as { activeOrganizationId?: unknown };\n if (typeof user.id !== 'string') return null;\n return {\n id: user.id,\n email: typeof user.email === 'string' ? user.email : undefined,\n name: typeof user.name === 'string' ? user.name : undefined,\n organizationId: typeof session.activeOrganizationId === 'string' ? session.activeOrganizationId : undefined,\n };\n }\n\n // Flat provider users.\n const flat = record as {\n id?: unknown;\n workosId?: unknown;\n email?: unknown;\n name?: unknown;\n organizationId?: unknown;\n };\n const id = typeof flat.id === 'string' ? flat.id : undefined;\n const workosId = typeof flat.workosId === 'string' ? flat.workosId : undefined;\n if (!id && !workosId) return null;\n return {\n id,\n workosId,\n email: typeof flat.email === 'string' ? flat.email : undefined,\n name: typeof flat.name === 'string' ? flat.name : undefined,\n organizationId: typeof flat.organizationId === 'string' ? flat.organizationId : undefined,\n };\n}\n\n/**\n * Resolve the authenticated user for a request via the provider. Never throws:\n * ordinary invalid/expired sessions resolve to `null`.\n */\nasync function authenticateRequest(\n provider: IMastraAuthProvider,\n token: string,\n raw: Request,\n): Promise<FactoryAuthUser | null> {\n try {\n const result = await provider.authenticateToken(token, raw);\n return toFactoryAuthUser(result);\n } catch {\n return null;\n }\n}\n\n/**\n * Bootstrap a personal org for no-org accounts so org-scoped features (GitHub\n * connect) work without leaving the app. Mutates the resolved user so the\n * current request sees the org immediately; subsequent requests resolve it via\n * the provider's own session/membership lookup (providers cache internally).\n * Best-effort: providers swallow their own bootstrap failures, and any\n * unexpected throw leaves the user no-org.\n */\nasync function ensureUserOrg(provider: IMastraAuthProvider, user: FactoryAuthUser): Promise<void> {\n if (getFactoryAuthOrgId(user)) return;\n if (!isOrganizationsProvider(provider)) return;\n const userId = getFactoryAuthUserId(user);\n if (!userId) return;\n try {\n const orgId = await provider.ensureOrganization(userId);\n if (orgId) user.organizationId = orgId;\n } catch {\n // Best-effort: the user stays no-org until a later request succeeds.\n }\n}\n\n/**\n * `Set-Cookie` values that clear the provider's session cookie(s), from the\n * provider's (possibly partial) `ISessionProvider.getClearSessionHeaders`.\n */\nfunction providerClearCookies(provider: IMastraAuthProvider): string[] {\n const getClearSessionHeaders = (provider as Partial<ISessionProvider>).getClearSessionHeaders;\n if (typeof getClearSessionHeaders !== 'function') return [];\n const headers = getClearSessionHeaders.call(provider) ?? {};\n const setCookie = headers['Set-Cookie'];\n if (!setCookie) return [];\n // A provider may join several clearing cookies into one header value.\n return setCookie.split(/,(?=\\s*[^;=,\\s]+=)/).map(cookie => cookie.trim());\n}\n\n/**\n * Fail-closed authorization for organization-level administrative mutations.\n * The caller must belong to the same active organization and the provider must\n * explicitly confirm an admin/owner role.\n */\nexport async function isOrganizationAdmin(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n organizationId: string,\n): Promise<boolean> {\n const user = await ensureFactoryAuthUser(provider, c);\n if (!user || user.organizationId !== organizationId || !provider || !isOrganizationsProvider(provider)) {\n return false;\n }\n const userId = getFactoryAuthUserId(user);\n if (!userId) return false;\n try {\n return await provider.isOrganizationAdmin(organizationId, userId);\n } catch {\n return false;\n }\n}\n\n/**\n * Build the factory's implementation of the `RouteAuth` seam over the\n * resolved provider (`undefined` = auth disabled). Constructed once per boot\n * by `MastraFactory.prepare()` and handed to factory route modules at\n * construction — they never import the factory auth module directly.\n */\nexport function createFactoryRouteAuth(provider: IMastraAuthProvider | undefined): RouteAuth {\n return {\n enabled: () => provider !== undefined,\n ensureUser: (c: Context) => ensureFactoryAuthUser(provider, c),\n tenant: (c: Context) => factoryAuthTenant(c),\n isOrganizationAdmin: (c: Context, organizationId: string) => isOrganizationAdmin(provider, c, organizationId),\n };\n}\n\n/** True when the given provider is WorkOS. Gates WorkOS-only capabilities. */\nexport function isWorkOSAuth(provider: IMastraAuthProvider | undefined): boolean {\n return provider instanceof MastraAuthWorkos;\n}\n\n/**\n * The raw WorkOS provider, for features that need the WorkOS client directly\n * (audit-log export, Admin Portal links). Callers must gate on\n * {@link isWorkOSAuth} first — throws when the provider is not WorkOS.\n */\nexport function getWorkOSProvider(provider: IMastraAuthProvider | undefined): MastraAuthWorkos {\n if (provider instanceof MastraAuthWorkos) return provider;\n throw new Error('WorkOS provider requested but the active factory auth provider is not WorkOS');\n}\n\n/**\n * Resolve the authenticated user for a request, stashing it on the context.\n *\n * The gate only authenticates non-`/auth/*` requests via the `Authorization`\n * header, so cookie-based browser navigations to public `/auth/*` routes (the\n * GitHub connect/callback flow) arrive without a gate-stashed user. This reads\n * the session cookie from the raw request the same way `/auth/me` does,\n * caches the result on the context, and returns it so downstream helpers like\n * {@link factoryAuthTenant} work uniformly on both gated and public routes.\n *\n * Returns `undefined` when there is no valid session (or auth is disabled).\n */\nexport async function ensureFactoryAuthUser(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n): Promise<FactoryAuthUser | undefined> {\n const existing = getFactoryAuthUser(c);\n if (existing) return existing;\n if (!provider) return undefined;\n\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n if (!user) return undefined;\n\n await ensureUserOrg(provider, user);\n\n c.set(FACTORY_AUTH_USER_KEY, user);\n return user;\n}\n\nexport interface MountFactoryAuthOptions {\n /**\n * Explicit auth provider to mount. When omitted, falls back to a WorkOS\n * provider implied by the `WORKOS_*` env vars (back-compat for suites that\n * never boot the factory).\n */\n provider?: IMastraAuthProvider;\n /**\n * Absolute URL the identity provider redirects back to after login (WorkOS\n * env-fallback path only). Defaults to the `WORKOS_REDIRECT_URI` env var.\n */\n redirectUri?: string;\n /** Browser-facing origin used to derive the SSO callback URL. */\n publicUrl?: string;\n}\n\n/**\n * Decide whether a request is a top-level browser navigation (which should be\n * redirected to `/signin`) versus an API/XHR call (which should get a 401 JSON\n * response the SPA can react to).\n */\nfunction isNavigationRequest(path: string, accept: string | undefined): boolean {\n if (path.startsWith('/api/')) return false;\n return (accept ?? '').includes('text/html');\n}\n\n/**\n * Handle the provider-neutral `/auth/me` route: validate the session with the\n * active provider and report the signed-in user (no tokens) to the SPA.\n * `/auth/me` is public (the gate skips `/auth/*`), so it validates the session\n * itself rather than reading a value the gate would have stashed.\n */\nasync function handleAuthMe(provider: IMastraAuthProvider, c: Context): Promise<Response> {\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n // Provider identity for the SPA: `/signin` renders the hosted-login button\n // for WorkOS and an email/password form for better-auth (with sign-up hidden\n // when the provider disables it).\n const signUpDisabled = isCredentialsProvider(provider) && provider.isSignUpEnabled?.() === false;\n const meta = { provider: provider.name, ...(signUpDisabled ? { signUpDisabled: true } : {}) };\n if (!user) {\n return c.json({ authenticated: false, user: null, ...meta });\n }\n // Resolve the org the same way gated requests do (providers cache, so this\n // is a lookup — not a create — after first bootstrap).\n await ensureUserOrg(provider, user);\n return c.json({\n authenticated: true,\n user: {\n userId: getFactoryAuthUserId(user),\n email: user.email,\n name: user.name,\n organizationId: user.organizationId,\n },\n ...meta,\n });\n}\n\n/** Encode a validated returnTo path into the OAuth `state` parameter. */\nfunction encodeState(returnTo: string): string {\n return Buffer.from(JSON.stringify({ returnTo }), 'utf8').toString('base64url');\n}\n\n/** Decode the OAuth `state` parameter back into a sanitized returnTo path. */\nfunction decodeState(state: string | undefined): string {\n if (!state) return '/';\n try {\n const parsed = JSON.parse(Buffer.from(state, 'base64url').toString('utf8')) as { returnTo?: string };\n return sanitizeReturnTo(parsed.returnTo);\n } catch {\n return '/';\n }\n}\n\n/** HTTP methods supported for public auth routes. */\ntype AuthRouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL';\n\n/** A public `/auth/*` route derived from the provider's capabilities. */\ninterface AuthRouteSpec {\n path: string;\n method: AuthRouteMethod;\n handler: (c: Context) => Response | Promise<Response>;\n}\n\n/**\n * Derive the public `/auth/*` routes from the provider's capabilities:\n *\n * - `IAuthHttpHandler` → `ALL /auth/api/*` proxy to the provider's own HTTP\n * surface (better-auth sign-in/up/out/session — what the SPA's\n * email/password form posts to).\n * - `ISSOProvider` → hosted-login `GET /auth/login` / `GET /auth/callback` /\n * `GET /auth/logout` (returnTo preserved through the OAuth `state` param).\n * - handler-shaped, non-SSO providers → `GET /auth/login` redirects to the\n * SPA's `/signin` form, `GET /auth/logout` revokes via the provider's\n * sign-out endpoint and clears the session cookie.\n */\nfunction providerAuthRoutes(provider: IMastraAuthProvider, publicUrl?: string): AuthRouteSpec[] {\n const routes: AuthRouteSpec[] = [];\n\n if (isAuthHttpHandler(provider)) {\n routes.push({\n path: '/auth/api/*',\n method: 'ALL',\n handler: c => provider.handleAuthRequest(c.req.raw),\n });\n }\n\n if (isSSOProvider(provider)) {\n routes.push(\n {\n path: '/auth/login',\n method: 'GET',\n handler: async c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n const state = encodeState(returnTo);\n // Build the callback URL from the browser-facing public origin so\n // the OAuth round-trip lands back on the SPA's origin (in dev the\n // SPA is on :5173 and Vite proxies /auth/* to the API on :4111 —\n // deriving from c.req.url would use :4111 and the post-callback\n // redirect to `/` would miss the SPA). Providers that ignore the\n // caller's URI in favor of their own config (e.g. MastraAuthWorkos\n // with an explicit `redirectUri` option) still take precedence.\n const redirectUri = publicUrl ? new URL('/auth/callback', publicUrl).toString() : '';\n const loginUrl = await provider.getLoginUrl(redirectUri, state);\n for (const cookie of (await provider.getLoginCookies?.(redirectUri, state)) ?? []) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(loginUrl);\n },\n },\n {\n path: '/auth/callback',\n method: 'GET',\n handler: async c => {\n const code = c.req.query('code');\n const returnTo = decodeState(c.req.query('state'));\n if (!code) {\n return c.redirect('/auth/login');\n }\n try {\n const result = await provider.handleCallback(code, c.req.query('state') ?? '');\n if (result.cookies?.length) {\n // Provider populated cookies directly (e.g. WorkOS AuthKit builds\n // its own sealed session cookie inside handleCallback).\n for (const cookie of result.cookies) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } else if (isSessionProvider(provider) && result.tokens) {\n // Fallback for providers that expose ISessionProvider but leave\n // cookie construction to the server (e.g. MastraAuthStudio, which\n // returns just the sealed session as accessToken so\n // getSessionHeaders can scope the cookie to this deployment's\n // domain via MASTRA_COOKIE_DOMAIN / sharedApiUrl auto-detection).\n // Mirrors packages/server/src/server/handlers/auth.ts:492-503.\n const resultUser = result.user as { id: string; organizationId?: string };\n const session = await provider.createSession(resultUser.id, {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n expiresAt: result.tokens.expiresAt,\n organizationId: resultUser.organizationId,\n });\n for (const [key, value] of Object.entries(provider.getSessionHeaders(session))) {\n c.header(key, value, { append: true });\n }\n }\n return c.redirect(returnTo);\n } catch {\n // Code exchange failed (expired/replayed code, misconfig). Send the\n // user back to login rather than surfacing a raw error.\n return c.redirect('/auth/login');\n }\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n let logoutUrl: string | null = null;\n try {\n logoutUrl = (await provider.getLogoutUrl?.('/', c.req.raw)) ?? null;\n } catch {\n logoutUrl = null;\n }\n // Clear the session cookie regardless of whether the provider\n // returned a logout URL.\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(logoutUrl ?? '/');\n },\n },\n );\n } else if (isAuthHttpHandler(provider)) {\n routes.push(\n {\n // Hosted-login equivalent: no hosted page, so send the browser to the\n // SPA's /signin form, preserving returnTo.\n path: '/auth/login',\n method: 'GET',\n handler: c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n // Revoke the session server-side through the provider's own sign-out\n // endpoint and forward its clearing cookies; fall back to our clear\n // cookies regardless.\n try {\n const origin = new URL(c.req.url).origin;\n const response = await provider.handleAuthRequest(\n new Request(`${origin}/auth/api/sign-out`, { method: 'POST', headers: c.req.raw.headers }),\n );\n for (const cookie of response.headers.getSetCookie()) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } catch {\n // No/invalid session: nothing to revoke.\n }\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect('/');\n },\n },\n );\n }\n\n return routes;\n}\n\n/**\n * Register the public `/auth/*` routes on a Hono app: the capability-derived\n * provider routes (login/callback/logout/provider APIs) plus the\n * provider-neutral `/auth/me`. Split out from `mountFactoryAuth` so both the local\n * Hono server and the platform Mastra entry can reuse the exact same handlers.\n */\nexport function registerAuthRoutes(\n app: Hono<any>,\n provider: IMastraAuthProvider,\n options: { publicUrl?: string } = {},\n): void {\n for (const route of providerAuthRoutes(provider, options.publicUrl)) {\n const methods = route.method === 'ALL' ? ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] : [route.method];\n app.on(methods, route.path, c => route.handler(c));\n }\n app.get('/auth/me', c => handleAuthMe(provider, c));\n}\n\n/**\n * Build the public `/auth/*` routes (provider routes + `/auth/me`) as Mastra\n * `server.apiRoutes`. Used by the platform Mastra entry (`src/mastra/index.ts`),\n * which can't register plain Hono routes on the deployer-generated app the way\n * the local server does via {@link registerAuthRoutes}.\n *\n * Handlers are identical to {@link registerAuthRoutes}. All are `requiresAuth: false`\n * (they must be reachable while unauthenticated), and the gate middleware skips\n * `/auth/*` so it never blocks them. `/auth/*` is not under `/api`, so it is a\n * valid custom-route path.\n */\nexport function buildAuthRoutes(provider: IMastraAuthProvider, options: { publicUrl?: string } = {}): ApiRoute[] {\n return [\n // `registerApiRoute` handlers see @mastra/core's bundled hono Context type,\n // which is structurally identical to (but nominally distinct from) the\n // local hono version the route handlers are typed against — cast across\n // the seam.\n ...providerAuthRoutes(provider, options.publicUrl).map(route =>\n registerApiRoute(route.path, {\n method: route.method,\n requiresAuth: false,\n handler: c => route.handler(c as unknown as Context),\n }),\n ),\n registerApiRoute('/auth/me', {\n method: 'GET',\n requiresAuth: false,\n handler: c => handleAuthMe(provider, c as unknown as Context),\n }),\n ];\n}\n\n/**\n * Build the auth gate as a plain Hono middleware handler `(c, next)`. Protects\n * everything that is not a public `/auth/*` route: authenticated requests stash\n * the user on the context and continue; unauthenticated navigations redirect to\n * login and XHR/API calls get a 401 JSON. Shared by the local Hono server\n * (`mountFactoryAuth`) and the platform Mastra entry (`server.middleware`).\n */\nexport function createFactoryAuthGate(provider: IMastraAuthProvider) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n const path = c.req.path;\n if (path.startsWith('/auth/')) {\n return next();\n }\n if (c.req.method === 'POST' && path === '/web/github/webhook') {\n return next();\n }\n // The SPA sign-in page and the static bundle it needs must be reachable\n // while signed out; no user is stashed, so `/api/*` stays protected.\n if (path === '/signin' || path.startsWith('/assets/')) {\n return next();\n }\n\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n\n if (user) {\n // Bootstrap a personal org for no-org accounts so the org id resolves on\n // this request (see ensureFactoryAuthUser for the rationale).\n await ensureUserOrg(provider, user);\n c.set(FACTORY_AUTH_USER_KEY, user);\n c.get('requestContext')?.set('user', user);\n return next();\n }\n\n if (isNavigationRequest(path, c.req.header('Accept'))) {\n const url = new URL(c.req.url);\n const returnTo = sanitizeReturnTo(url.pathname + url.search);\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n }\n\n return c.json({ error: 'unauthorized' }, 401);\n };\n}\n\n/**\n * Mount factory auth gating onto the host app. No-op when auth is disabled\n * (no provider active).\n *\n * Must be called before the Mastra adapter routes, the `/web/*` routes, and\n * the static UI handlers so the gate covers every request. Composes the shared\n * `registerAuthRoutes` + `createFactoryAuthGate` factories so the local Hono server\n * and the platform Mastra entry stay behavior-identical.\n */\nexport function mountFactoryAuth(app: Hono<any>, options: MountFactoryAuthOptions = {}): boolean {\n const provider = options.provider ?? envFallbackAuthProvider(options.redirectUri);\n if (!provider) return false;\n\n registerAuthRoutes(app, provider, { publicUrl: options.publicUrl });\n app.use('*', createFactoryAuthGate(provider));\n return true;\n}\n","import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport type { FactoryAuthUser } from '../auth.js';\nimport { getFactoryAuthOrgId } from '../auth.js';\nimport type { FactoryRunBindingAddress, FactoryRunBindingSessionAddress } from '../storage/domains/work-items/base.js';\n\ninterface FactorySessionState {\n factoryProjectId?: string;\n}\n\nexport function getFactorySessionCoordinates(\n requestContext: RequestContext | undefined,\n): FactoryRunBindingSessionAddress | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const context = requestContext.get('controller') as AgentControllerRequestContext<FactorySessionState> | undefined;\n const factoryProjectId = context?.getState().factoryProjectId;\n if (!context?.threadId || !context.resourceId || !factoryProjectId) return null;\n return {\n factoryProjectId,\n threadId: context.threadId,\n resourceId: context.resourceId,\n sessionId: context.resourceId,\n };\n}\n\nexport function getFactorySessionAddress(requestContext: RequestContext | undefined): FactoryRunBindingAddress | null {\n const coordinates = getFactorySessionCoordinates(requestContext);\n if (!coordinates || !requestContext || typeof requestContext.get !== 'function') return null;\n const user = requestContext.get('user') as FactoryAuthUser | undefined;\n const orgId = getFactoryAuthOrgId(user);\n if (!orgId) return null;\n return { orgId, ...coordinates };\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA+GA,SAAS,oBAAoB,MAAuD;AACzF,SAAO,MAAM;AACf;;;AC9GO,SAAS,6BACd,gBACwC;AACxC,MAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,WAAY,QAAO;AACxE,QAAM,UAAU,eAAe,IAAI,YAAY;AAC/C,QAAM,mBAAmB,SAAS,SAAS,EAAE;AAC7C,MAAI,CAAC,SAAS,YAAY,CAAC,QAAQ,cAAc,CAAC,iBAAkB,QAAO;AAC3E,SAAO;AAAA,IACL;AAAA,IACA,UAAU,QAAQ;AAAA,IAClB,YAAY,QAAQ;AAAA,IACpB,WAAW,QAAQ;AAAA,EACrB;AACF;AAEO,SAAS,yBAAyB,gBAA6E;AACpH,QAAM,cAAc,6BAA6B,cAAc;AAC/D,MAAI,CAAC,eAAe,CAAC,kBAAkB,OAAO,eAAe,QAAQ,WAAY,QAAO;AACxF,QAAM,OAAO,eAAe,IAAI,MAAM;AACtC,QAAM,QAAQ,oBAAoB,IAAI;AACtC,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,EAAE,OAAO,GAAG,YAAY;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/auth.ts","../../src/rules/binding-context.ts"],"sourcesContent":["import { MastraAuthWorkos } from '@mastra/auth-workos';\nimport {\n registerApiRoute,\n isAuthHttpHandler,\n isCredentialsProvider,\n isOrganizationsProvider,\n isSessionProvider,\n isSSOProvider,\n} from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, ISessionProvider } from '@mastra/core/server';\nimport type { Context, Hono } from 'hono';\n\nimport type { RouteAuth } from './routes/route.js';\nimport { timedAboveThreshold } from './timing.js';\n\n/**\n * Provider-neutral factory auth gating for the MastraCode web server.\n *\n * When an auth provider is active (a `MastraAuthProvider` instance passed to\n * `MastraFactory`'s `auth` slot, or — back-compat for suites/paths that never\n * boot the factory — implied by the WorkOS env vars), every route on the web\n * server is placed behind it: unauthenticated browser navigations are\n * redirected to the SPA's `/signin` page, API/XHR calls receive a 401, and a\n * small set of public routes stay reachable while signed out — the provider's\n * `/auth/*` routes plus `/auth/me`, the `/signin` page, its `/assets/*` bundle,\n * and the SPA manifest metadata. When no provider is active, `mountFactoryAuth` is a no-op and the server\n * behaves exactly as it does without auth.\n *\n * Provider specifics stay in the providers (`@mastra/auth-workos`,\n * `@mastra/auth-better-auth`, or any custom `IMastraAuthProvider`); this\n * module composes them capability-first via the core type guards:\n * - `authenticateToken` — session/bearer validation (all providers)\n * - `ISSOProvider` — hosted-login `/auth/login`, `/auth/callback`, `/auth/logout`\n * - `IAuthHttpHandler` — provider-owned `/auth/api/*` endpoints (better-auth)\n * - `IOrganizationsProvider` — personal-org bootstrap + admin checks\n * - `ICredentialsProvider.isSignUpEnabled` — SPA sign-up affordance\n * - `getClearSessionHeaders` — session cookie clearing on logout\n */\n\n/** Minimal shape of the signed-in user surfaced to the SPA (no tokens). */\nexport interface FactoryAuthUser {\n /** Stable WorkOS user id used to scope per-user data (GitHub installs etc.). */\n workosId?: string;\n /** Provider user id; WorkOS shapes may use `workosId` instead (see {@link workosId}). */\n id?: string;\n email?: string;\n name?: string;\n /**\n * Organization id. The org is the top-level tenant: it owns the GitHub\n * App installation and connected projects, while each user inside the org gets\n * isolated building instances. Absent for personal (no-org) accounts.\n */\n organizationId?: string;\n}\n\n/**\n * Tenant identity: the org is the top-level tenant, and each user inside it is\n * an isolated builder. Agent state, worktrees and sandboxes are scoped per\n * `(orgId, userId)`. Personal (no-org) users have `orgId === undefined`.\n */\nexport interface FactoryAuthTenant {\n /** Organization id, or `undefined` for personal (no-org) accounts. */\n orgId?: string;\n /** Stable provider user id. */\n userId: string;\n}\n\n/**\n * Validate that a `returnTo` value is a safe same-site path, to prevent\n * open-redirect attacks. Only absolute local paths (`/foo`) are allowed;\n * protocol-relative (`//evil.com`) and absolute URLs are rejected.\n */\nexport function sanitizeReturnTo(raw: string | undefined): string {\n if (!raw) return '/';\n if (!raw.startsWith('/')) return '/';\n // Reject protocol-relative URLs like \"//evil.com\" and \"/\\evil.com\".\n if (raw.startsWith('//') || raw.startsWith('/\\\\')) return '/';\n return raw;\n}\n\n/** Extract a bearer token from the Authorization header, if present. */\nexport function getBearerToken(authorization: string | undefined): string {\n if (!authorization) return '';\n const match = /^Bearer\\s+(.+)$/i.exec(authorization);\n return match?.[1] ?? '';\n}\n\n/**\n * Whether the SPA is served cross-origin from this API (platform deploy). When\n * `MASTRACODE_ALLOWED_ORIGINS` is set the browser talks to us cross-site, so\n * session cookies must be `SameSite=None; Secure` for the browser to send them.\n * Same-origin local dev leaves this unset and keeps the stricter `SameSite=Lax`.\n */\nexport function isCrossSiteAuth(): boolean {\n return Boolean(process.env.MASTRACODE_ALLOWED_ORIGINS?.trim());\n}\n\n/** Hono context variables set by the auth gate. */\nexport interface FactoryAuthVariables {\n factoryAuthUser: FactoryAuthUser;\n}\n\n/** Context key under which the gate stashes the authenticated user. */\nconst FACTORY_AUTH_USER_KEY = 'factoryAuthUser';\n\n/**\n * Read the authenticated user the gate stashed on the context, or\n * `undefined` when unauthenticated / auth disabled. Used by downstream routes\n * (e.g. GitHub) to scope rows per user.\n */\nexport function getFactoryAuthUser(c: Context): FactoryAuthUser | undefined {\n return c.get(FACTORY_AUTH_USER_KEY) as FactoryAuthUser | undefined;\n}\n\n/** Resolve the stable user id from an authenticated user shape. */\nexport function getFactoryAuthUserId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.workosId ?? user?.id;\n}\n\n/** Resolve the organization id from a user shape, if present. */\nexport function getFactoryAuthOrgId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.organizationId;\n}\n\n/**\n * Resolve the tenant identity `(orgId, userId)` from the authenticated user on\n * the context. Returns `undefined` when there is no signed-in user (auth\n * disabled or unauthenticated). `orgId` is `undefined` for personal accounts;\n * callers gate org-scoped GitHub features on its presence while agent state\n * falls back to a user-only tenant.\n */\nexport function factoryAuthTenant(c: Context): FactoryAuthTenant | undefined {\n const user = getFactoryAuthUser(c);\n const userId = getFactoryAuthUserId(user);\n if (!userId) return undefined;\n return { orgId: getFactoryAuthOrgId(user), userId };\n}\n\n/** True when both WorkOS credential env vars are present (legacy env gate). */\nfunction envWorkosConfigured(): boolean {\n return Boolean(process.env.WORKOS_API_KEY && process.env.WORKOS_CLIENT_ID);\n}\n\n/**\n * WorkOS provider implied by the `WORKOS_*` env vars — back-compat for test\n * suites exercised without booting the factory (route suites set `WORKOS_*`\n * directly and call {@link mountFactoryAuth} without an explicit provider).\n * `fetchMemberships: true` lets `authenticateToken` resolve `organizationId`\n * from a single membership when the JWT has no org claim — required so a\n * bootstrapped personal org resolves without re-auth.\n */\nfunction envFallbackAuthProvider(redirectUri: string | undefined): MastraAuthWorkos | undefined {\n if (!envWorkosConfigured()) return undefined;\n return new MastraAuthWorkos({\n redirectUri: redirectUri ?? process.env.WORKOS_REDIRECT_URI,\n fetchMemberships: true,\n });\n}\n\n/**\n * Map a provider `authenticateToken` result onto the neutral SPA user shape.\n *\n * Two result families exist today:\n * - flat provider users (WorkOS `WorkOSUser` et al.): `id`/`workosId`/`email`/\n * `name`/`organizationId` directly on the object;\n * - session-shaped results (better-auth `BetterAuthUser`): `{ session, user }`\n * with the active org on the session.\n */\nfunction toFactoryAuthUser(result: unknown): FactoryAuthUser | null {\n if (!result || typeof result !== 'object') return null;\n const record = result as Record<string, unknown>;\n\n // Session-shaped results: { session, user }.\n if (record.user && typeof record.user === 'object' && record.session && typeof record.session === 'object') {\n const user = record.user as { id?: unknown; email?: unknown; name?: unknown };\n const session = record.session as { activeOrganizationId?: unknown };\n if (typeof user.id !== 'string') return null;\n return {\n id: user.id,\n email: typeof user.email === 'string' ? user.email : undefined,\n name: typeof user.name === 'string' ? user.name : undefined,\n organizationId: typeof session.activeOrganizationId === 'string' ? session.activeOrganizationId : undefined,\n };\n }\n\n // Flat provider users.\n const flat = record as {\n id?: unknown;\n workosId?: unknown;\n email?: unknown;\n name?: unknown;\n organizationId?: unknown;\n };\n const id = typeof flat.id === 'string' ? flat.id : undefined;\n const workosId = typeof flat.workosId === 'string' ? flat.workosId : undefined;\n if (!id && !workosId) return null;\n return {\n id,\n workosId,\n email: typeof flat.email === 'string' ? flat.email : undefined,\n name: typeof flat.name === 'string' ? flat.name : undefined,\n organizationId: typeof flat.organizationId === 'string' ? flat.organizationId : undefined,\n };\n}\n\n/**\n * Resolve the authenticated user for a request via the provider. Never throws:\n * ordinary invalid/expired sessions resolve to `null`.\n */\nasync function authenticateRequest(\n provider: IMastraAuthProvider,\n token: string,\n raw: Request,\n): Promise<FactoryAuthUser | null> {\n try {\n const result = await provider.authenticateToken(token, raw);\n return toFactoryAuthUser(result);\n } catch {\n return null;\n }\n}\n\n/**\n * Bootstrap a personal org for no-org accounts so org-scoped features (GitHub\n * connect) work without leaving the app. Mutates the resolved user so the\n * current request sees the org immediately; subsequent requests resolve it via\n * the provider's own session/membership lookup (providers cache internally).\n * Best-effort: providers swallow their own bootstrap failures, and any\n * unexpected throw leaves the user no-org.\n */\nasync function ensureUserOrg(provider: IMastraAuthProvider, user: FactoryAuthUser): Promise<void> {\n if (getFactoryAuthOrgId(user)) return;\n if (!isOrganizationsProvider(provider)) return;\n const userId = getFactoryAuthUserId(user);\n if (!userId) return;\n try {\n const orgId = await provider.ensureOrganization(userId);\n if (orgId) user.organizationId = orgId;\n } catch {\n // Best-effort: the user stays no-org until a later request succeeds.\n }\n}\n\n/**\n * `Set-Cookie` values that clear the provider's session cookie(s), from the\n * provider's (possibly partial) `ISessionProvider.getClearSessionHeaders`.\n */\nfunction providerClearCookies(provider: IMastraAuthProvider): string[] {\n const getClearSessionHeaders = (provider as Partial<ISessionProvider>).getClearSessionHeaders;\n if (typeof getClearSessionHeaders !== 'function') return [];\n const headers = getClearSessionHeaders.call(provider) ?? {};\n const setCookie = headers['Set-Cookie'];\n if (!setCookie) return [];\n // A provider may join several clearing cookies into one header value.\n return setCookie.split(/,(?=\\s*[^;=,\\s]+=)/).map(cookie => cookie.trim());\n}\n\n/**\n * Fail-closed authorization for organization-level administrative mutations.\n * The caller must belong to the same active organization and the provider must\n * explicitly confirm an admin/owner role.\n */\nexport async function isOrganizationAdmin(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n organizationId: string,\n): Promise<boolean> {\n const user = await ensureFactoryAuthUser(provider, c);\n if (!user || user.organizationId !== organizationId || !provider || !isOrganizationsProvider(provider)) {\n return false;\n }\n const userId = getFactoryAuthUserId(user);\n if (!userId) return false;\n try {\n return await provider.isOrganizationAdmin(organizationId, userId);\n } catch {\n return false;\n }\n}\n\n/**\n * Build the factory's implementation of the `RouteAuth` seam over the\n * resolved provider (`undefined` = auth disabled). Constructed once per boot\n * by `MastraFactory.prepare()` and handed to factory route modules at\n * construction — they never import the factory auth module directly.\n */\nexport function createFactoryRouteAuth(provider: IMastraAuthProvider | undefined): RouteAuth {\n return {\n enabled: () => provider !== undefined,\n ensureUser: (c: Context) => ensureFactoryAuthUser(provider, c),\n tenant: (c: Context) => factoryAuthTenant(c),\n isOrganizationAdmin: (c: Context, organizationId: string) => isOrganizationAdmin(provider, c, organizationId),\n };\n}\n\n/** True when the given provider is WorkOS. Gates WorkOS-only capabilities. */\nexport function isWorkOSAuth(provider: IMastraAuthProvider | undefined): boolean {\n return provider instanceof MastraAuthWorkos;\n}\n\n/**\n * The raw WorkOS provider, for features that need the WorkOS client directly\n * (audit-log export, Admin Portal links). Callers must gate on\n * {@link isWorkOSAuth} first — throws when the provider is not WorkOS.\n */\nexport function getWorkOSProvider(provider: IMastraAuthProvider | undefined): MastraAuthWorkos {\n if (provider instanceof MastraAuthWorkos) return provider;\n throw new Error('WorkOS provider requested but the active factory auth provider is not WorkOS');\n}\n\n/**\n * Resolve the authenticated user for a request, stashing it on the context.\n *\n * The gate only authenticates non-`/auth/*` requests via the `Authorization`\n * header, so cookie-based browser navigations to public `/auth/*` routes (the\n * GitHub connect/callback flow) arrive without a gate-stashed user. This reads\n * the session cookie from the raw request the same way `/auth/me` does,\n * caches the result on the context, and returns it so downstream helpers like\n * {@link factoryAuthTenant} work uniformly on both gated and public routes.\n *\n * Returns `undefined` when there is no valid session (or auth is disabled).\n */\nexport async function ensureFactoryAuthUser(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n): Promise<FactoryAuthUser | undefined> {\n const existing = getFactoryAuthUser(c);\n if (existing) return existing;\n if (!provider) return undefined;\n\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n if (!user) return undefined;\n\n await ensureUserOrg(provider, user);\n\n c.set(FACTORY_AUTH_USER_KEY, user);\n return user;\n}\n\nexport interface MountFactoryAuthOptions {\n /**\n * Explicit auth provider to mount. When omitted, falls back to a WorkOS\n * provider implied by the `WORKOS_*` env vars (back-compat for suites that\n * never boot the factory).\n */\n provider?: IMastraAuthProvider;\n /**\n * Absolute URL the identity provider redirects back to after login (WorkOS\n * env-fallback path only). Defaults to the `WORKOS_REDIRECT_URI` env var.\n */\n redirectUri?: string;\n /** Browser-facing origin used to derive the SSO callback URL. */\n publicUrl?: string;\n}\n\n/**\n * Decide whether a request is a top-level browser navigation (which should be\n * redirected to `/signin`) versus an API/XHR call (which should get a 401 JSON\n * response the SPA can react to).\n */\nfunction isNavigationRequest(path: string, accept: string | undefined): boolean {\n if (path.startsWith('/api/')) return false;\n return (accept ?? '').includes('text/html');\n}\n\n/**\n * Handle the provider-neutral `/auth/me` route: validate the session with the\n * active provider and report the signed-in user (no tokens) to the SPA.\n * `/auth/me` is public (the gate skips `/auth/*`), so it validates the session\n * itself rather than reading a value the gate would have stashed.\n */\nasync function handleAuthMe(provider: IMastraAuthProvider, c: Context): Promise<Response> {\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n // Provider identity for the SPA: `/signin` renders the hosted-login button\n // for WorkOS and an email/password form for better-auth (with sign-up hidden\n // when the provider disables it).\n const signUpDisabled = isCredentialsProvider(provider) && provider.isSignUpEnabled?.() === false;\n const meta = { provider: provider.name, ...(signUpDisabled ? { signUpDisabled: true } : {}) };\n if (!user) {\n return c.json({ authenticated: false, user: null, ...meta });\n }\n // Resolve the org the same way gated requests do (providers cache, so this\n // is a lookup — not a create — after first bootstrap).\n await ensureUserOrg(provider, user);\n return c.json({\n authenticated: true,\n user: {\n userId: getFactoryAuthUserId(user),\n email: user.email,\n name: user.name,\n organizationId: user.organizationId,\n },\n ...meta,\n });\n}\n\n/** Encode a validated returnTo path into the OAuth `state` parameter. */\nfunction encodeState(returnTo: string): string {\n return Buffer.from(JSON.stringify({ returnTo }), 'utf8').toString('base64url');\n}\n\n/** Decode the OAuth `state` parameter back into a sanitized returnTo path. */\nfunction decodeState(state: string | undefined): string {\n if (!state) return '/';\n try {\n const parsed = JSON.parse(Buffer.from(state, 'base64url').toString('utf8')) as { returnTo?: string };\n return sanitizeReturnTo(parsed.returnTo);\n } catch {\n return '/';\n }\n}\n\n/** HTTP methods supported for public auth routes. */\ntype AuthRouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL';\n\n/** A public `/auth/*` route derived from the provider's capabilities. */\ninterface AuthRouteSpec {\n path: string;\n method: AuthRouteMethod;\n handler: (c: Context) => Response | Promise<Response>;\n}\n\n/**\n * Derive the public `/auth/*` routes from the provider's capabilities:\n *\n * - `IAuthHttpHandler` → `ALL /auth/api/*` proxy to the provider's own HTTP\n * surface (better-auth sign-in/up/out/session — what the SPA's\n * email/password form posts to).\n * - `ISSOProvider` → hosted-login `GET /auth/login` / `GET /auth/callback` /\n * `GET /auth/logout` (returnTo preserved through the OAuth `state` param).\n * - handler-shaped, non-SSO providers → `GET /auth/login` redirects to the\n * SPA's `/signin` form, `GET /auth/logout` revokes via the provider's\n * sign-out endpoint and clears the session cookie.\n */\nfunction providerAuthRoutes(provider: IMastraAuthProvider, publicUrl?: string): AuthRouteSpec[] {\n const routes: AuthRouteSpec[] = [];\n\n if (isAuthHttpHandler(provider)) {\n routes.push({\n path: '/auth/api/*',\n method: 'ALL',\n handler: c => provider.handleAuthRequest(c.req.raw),\n });\n }\n\n if (isSSOProvider(provider)) {\n routes.push(\n {\n path: '/auth/login',\n method: 'GET',\n handler: async c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n const state = encodeState(returnTo);\n // Build the callback URL from the browser-facing public origin so\n // the OAuth round-trip lands back on the SPA's origin (in dev the\n // SPA is on :5173 and Vite proxies /auth/* to the API on :4111 —\n // deriving from c.req.url would use :4111 and the post-callback\n // redirect to `/` would miss the SPA). Providers that ignore the\n // caller's URI in favor of their own config (e.g. MastraAuthWorkos\n // with an explicit `redirectUri` option) still take precedence.\n const redirectUri = publicUrl ? new URL('/auth/callback', publicUrl).toString() : '';\n const loginUrl = await provider.getLoginUrl(redirectUri, state);\n for (const cookie of (await provider.getLoginCookies?.(redirectUri, state)) ?? []) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(loginUrl);\n },\n },\n {\n path: '/auth/callback',\n method: 'GET',\n handler: async c => {\n const code = c.req.query('code');\n const returnTo = decodeState(c.req.query('state'));\n if (!code) {\n return c.redirect('/auth/login');\n }\n try {\n const result = await provider.handleCallback(code, c.req.query('state') ?? '');\n if (result.cookies?.length) {\n // Provider populated cookies directly (e.g. WorkOS AuthKit builds\n // its own sealed session cookie inside handleCallback).\n for (const cookie of result.cookies) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } else if (isSessionProvider(provider) && result.tokens) {\n // Fallback for providers that expose ISessionProvider but leave\n // cookie construction to the server (e.g. MastraAuthStudio, which\n // returns just the sealed session as accessToken so\n // getSessionHeaders can scope the cookie to this deployment's\n // domain via MASTRA_COOKIE_DOMAIN / sharedApiUrl auto-detection).\n // Mirrors packages/server/src/server/handlers/auth.ts:492-503.\n const resultUser = result.user as { id: string; organizationId?: string };\n const session = await provider.createSession(resultUser.id, {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n expiresAt: result.tokens.expiresAt,\n organizationId: resultUser.organizationId,\n });\n for (const [key, value] of Object.entries(provider.getSessionHeaders(session))) {\n c.header(key, value, { append: true });\n }\n }\n return c.redirect(returnTo);\n } catch {\n // Code exchange failed (expired/replayed code, misconfig). Send the\n // user back to login rather than surfacing a raw error.\n return c.redirect('/auth/login');\n }\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n let logoutUrl: string | null = null;\n try {\n logoutUrl = (await provider.getLogoutUrl?.('/', c.req.raw)) ?? null;\n } catch {\n logoutUrl = null;\n }\n // Clear the session cookie regardless of whether the provider\n // returned a logout URL.\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(logoutUrl ?? '/');\n },\n },\n );\n } else if (isAuthHttpHandler(provider)) {\n routes.push(\n {\n // Hosted-login equivalent: no hosted page, so send the browser to the\n // SPA's /signin form, preserving returnTo.\n path: '/auth/login',\n method: 'GET',\n handler: c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n // Revoke the session server-side through the provider's own sign-out\n // endpoint and forward its clearing cookies; fall back to our clear\n // cookies regardless.\n try {\n const origin = new URL(c.req.url).origin;\n const response = await provider.handleAuthRequest(\n new Request(`${origin}/auth/api/sign-out`, { method: 'POST', headers: c.req.raw.headers }),\n );\n for (const cookie of response.headers.getSetCookie()) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } catch {\n // No/invalid session: nothing to revoke.\n }\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect('/');\n },\n },\n );\n }\n\n return routes;\n}\n\n/**\n * Register the public `/auth/*` routes on a Hono app: the capability-derived\n * provider routes (login/callback/logout/provider APIs) plus the\n * provider-neutral `/auth/me`. Split out from `mountFactoryAuth` so both the local\n * Hono server and the platform Mastra entry can reuse the exact same handlers.\n */\nexport function registerAuthRoutes(\n app: Hono<any>,\n provider: IMastraAuthProvider,\n options: { publicUrl?: string } = {},\n): void {\n for (const route of providerAuthRoutes(provider, options.publicUrl)) {\n const methods = route.method === 'ALL' ? ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] : [route.method];\n app.on(methods, route.path, c => route.handler(c));\n }\n app.get('/auth/me', c => handleAuthMe(provider, c));\n}\n\n/**\n * Build the public `/auth/*` routes (provider routes + `/auth/me`) as Mastra\n * `server.apiRoutes`. Used by the platform Mastra entry (`src/mastra/index.ts`),\n * which can't register plain Hono routes on the deployer-generated app the way\n * the local server does via {@link registerAuthRoutes}.\n *\n * Handlers are identical to {@link registerAuthRoutes}. All are `requiresAuth: false`\n * (they must be reachable while unauthenticated), and the gate middleware skips\n * `/auth/*` so it never blocks them. `/auth/*` is not under `/api`, so it is a\n * valid custom-route path.\n */\nexport function buildAuthRoutes(provider: IMastraAuthProvider, options: { publicUrl?: string } = {}): ApiRoute[] {\n return [\n // `registerApiRoute` handlers see @mastra/core's bundled hono Context type,\n // which is structurally identical to (but nominally distinct from) the\n // local hono version the route handlers are typed against — cast across\n // the seam.\n ...providerAuthRoutes(provider, options.publicUrl).map(route =>\n registerApiRoute(route.path, {\n method: route.method,\n requiresAuth: false,\n handler: c => route.handler(c as unknown as Context),\n }),\n ),\n registerApiRoute('/auth/me', {\n method: 'GET',\n requiresAuth: false,\n handler: c => handleAuthMe(provider, c as unknown as Context),\n }),\n ];\n}\n\n/**\n * Build the auth gate as a plain Hono middleware handler `(c, next)`. Protects\n * everything that is not a public `/auth/*` route: authenticated requests stash\n * the user on the context and continue; unauthenticated navigations redirect to\n * login and XHR/API calls get a 401 JSON. Shared by the local Hono server\n * (`mountFactoryAuth`) and the platform Mastra entry (`server.middleware`).\n */\nexport function createFactoryAuthGate(provider: IMastraAuthProvider) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n const path = c.req.path;\n if (path.startsWith('/auth/')) {\n return next();\n }\n if (c.req.method === 'POST' && path === '/web/github/webhook') {\n return next();\n }\n // The SPA sign-in page, its static bundle, and browser-fetched metadata\n // must be reachable while signed out; no user is stashed, so `/api/*`\n // stays protected.\n if (\n path === '/signin' ||\n path.startsWith('/assets/') ||\n path === '/manifest.webmanifest' ||\n path === '/mastra.svg'\n ) {\n return next();\n }\n\n const token = getBearerToken(c.req.header('Authorization'));\n // A slow verification here delays EVERY protected request — surface\n // outliers so auth-backend latency is attributable from server logs.\n const user = await timedAboveThreshold('auth.gate.authenticate', 1_000, () =>\n authenticateRequest(provider, token, c.req.raw),\n );\n\n if (user) {\n // Bootstrap a personal org for no-org accounts so the org id resolves on\n // this request (see ensureFactoryAuthUser for the rationale).\n await ensureUserOrg(provider, user);\n c.set(FACTORY_AUTH_USER_KEY, user);\n c.get('requestContext')?.set('user', user);\n return next();\n }\n\n if (isNavigationRequest(path, c.req.header('Accept'))) {\n const url = new URL(c.req.url);\n const returnTo = sanitizeReturnTo(url.pathname + url.search);\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n }\n\n return c.json({ error: 'unauthorized' }, 401);\n };\n}\n\n/**\n * Mount factory auth gating onto the host app. No-op when auth is disabled\n * (no provider active).\n *\n * Must be called before the Mastra adapter routes, the `/web/*` routes, and\n * the static UI handlers so the gate covers every request. Composes the shared\n * `registerAuthRoutes` + `createFactoryAuthGate` factories so the local Hono server\n * and the platform Mastra entry stay behavior-identical.\n */\nexport function mountFactoryAuth(app: Hono<any>, options: MountFactoryAuthOptions = {}): boolean {\n const provider = options.provider ?? envFallbackAuthProvider(options.redirectUri);\n if (!provider) return false;\n\n registerAuthRoutes(app, provider, { publicUrl: options.publicUrl });\n app.use('*', createFactoryAuthGate(provider));\n return true;\n}\n","import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport type { FactoryAuthUser } from '../auth.js';\nimport { getFactoryAuthOrgId } from '../auth.js';\nimport type { FactoryRunBindingAddress, FactoryRunBindingSessionAddress } from '../storage/domains/work-items/base.js';\n\ninterface FactorySessionState {\n factoryProjectId?: string;\n}\n\nexport function getFactorySessionCoordinates(\n requestContext: RequestContext | undefined,\n): FactoryRunBindingSessionAddress | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const context = requestContext.get('controller') as AgentControllerRequestContext<FactorySessionState> | undefined;\n const factoryProjectId = context?.getState().factoryProjectId;\n if (!context?.threadId || !context.resourceId || !factoryProjectId) return null;\n return {\n factoryProjectId,\n threadId: context.threadId,\n resourceId: context.resourceId,\n sessionId: context.resourceId,\n };\n}\n\nexport function getFactorySessionAddress(requestContext: RequestContext | undefined): FactoryRunBindingAddress | null {\n const coordinates = getFactorySessionCoordinates(requestContext);\n if (!coordinates || !requestContext || typeof requestContext.get !== 'function') return null;\n const user = requestContext.get('user') as FactoryAuthUser | undefined;\n const orgId = getFactoryAuthOrgId(user);\n if (!orgId) return null;\n return { orgId, ...coordinates };\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAgHA,SAAS,oBAAoB,MAAuD;AACzF,SAAO,MAAM;AACf;;;AC/GO,SAAS,6BACd,gBACwC;AACxC,MAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,WAAY,QAAO;AACxE,QAAM,UAAU,eAAe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E,IAAI,CAAC,wBAAwB,EAAE,YAAY,CAAC,CAAC;IAChE,OAAO,EAAE,gBAAgB,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oBAAoB,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,8BAA8B,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1E,gBAAgB,CAAC,EAAE,CAAC,MAAM,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACjF;AAsED,qBAAa,yBAAyB;;gBAWxB,OAAO,EAAE,gCAAgC;IAUrD,KAAK,IAAI,IAAI;IAOP,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAMrB,OAAO,CAAC,GAAG,OAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CA8X/C;AAED,eAAO,MAAM,0BAA0B;;;;;;;;CAQ7B,CAAC"}
@@ -648,6 +648,12 @@ var FactoryDecisionDispatcher = class {
648
648
  (candidate) => candidate.id === record.bindingId && candidate.status === "active"
649
649
  );
650
650
  if (!binding) throw new Error("Prepared Factory binding is unavailable or revoked.");
651
+ const item = await this.#storage.get({ orgId: record.orgId, id: binding.workItemId });
652
+ const startedBy = item?.sessions[binding.role]?.startedBy;
653
+ if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);
654
+ await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });
655
+ const requestContext = new RequestContext();
656
+ requestContext.set("user", { workosId: startedBy, organizationId: record.orgId });
651
657
  const session = await this.#requireSession(binding);
652
658
  await awaitNotification(
653
659
  await session.sendNotificationSignal(
@@ -660,7 +666,7 @@ var FactoryDecisionDispatcher = class {
660
666
  sourceId: record.id,
661
667
  dedupeKey: `factory-kickoff:${record.kickoffKey}`
662
668
  },
663
- { ifActive: { behavior: "deliver" }, ifIdle: { behavior: "wake" } }
669
+ { ifActive: { behavior: "deliver" }, ifIdle: { behavior: "wake" }, requestContext }
664
670
  ),
665
671
  true
666
672
  );
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/rules/dispatcher.ts","../../src/skills/service.ts","../../src/rules/types.ts","../../src/rules/validation.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\n\nimport { 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 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;\n\ninterface DispatcherSession extends SkillSession {\n thread: {\n switch(input: { threadId: string }): Promise<unknown>;\n listActiveMessages(): Promise<Array<{ id: string }>>;\n };\n sendSignal(\n input: { id: string; type: 'user'; tagName: 'user'; contents: string },\n options: { requestContext: RequestContext },\n ): { accepted: Promise<unknown> };\n}\n\ntype FactoryController = Pick<AgentController<MastraCodeState>, 'getSessionByResource'>;\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 reconcileToolResults?: () => Promise<void>;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\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 result: Awaited<ReturnType<SkillSession['sendNotificationSignal']>>,\n requireDelivery = false,\n): Promise<void> {\n await result.persisted;\n if (!result.accepted) {\n if (requireDelivery) throw new Error('Factory notification was persisted without agent delivery.');\n return;\n }\n const accepted = await result.accepted;\n if (!requireDelivery) return;\n if (accepted.action === 'wake') {\n await accepted.output.consumeStream();\n return;\n }\n if (accepted.action !== 'deliver') {\n throw new Error(`Factory notification did not reach the agent (${String(accepted.action)}).`);\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 #reconcileToolResults?: () => Promise<void>;\n readonly #prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n readonly #primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n #timer?: ReturnType<typeof setInterval>;\n #activeRun?: 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.#reconcileToolResults = options.reconcileToolResults;\n this.#prepareBinding = options.prepareBinding;\n this.#primeCredentials = options.primeCredentials;\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.#activeRun;\n }\n\n async runOnce(now = new Date()): Promise<void> {\n await this.#reconcileToolResults?.();\n const leaseExpiresAt = new Date(now.getTime() + LEASE_MS);\n const [decisions, starts] = await Promise.all([\n this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit: BATCH_SIZE,\n }),\n this.#storage.claimPendingStarts({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit: BATCH_SIZE,\n }),\n ]);\n await Promise.all([\n ...decisions.map(decision => this.#dispatchDecision(decision, now)),\n ...starts.map(start => this.#dispatchPendingStart(start, now)),\n ]);\n }\n\n async #tick(): Promise<void> {\n if (this.#activeRun) return;\n this.#activeRun = this.runOnce().catch(error => {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n });\n try {\n await this.#activeRun;\n } finally {\n this.#activeRun = undefined;\n }\n }\n\n async #dispatchDecision(record: FactoryDeferredDecisionRecord, now: Date): Promise<void> {\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 await this.#withLease(\n async leaseExpiresAt =>\n this.#storage.renewDeferredDecisionLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),\n async () => this.#executeDecision(record, decision),\n );\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 terminal,\n });\n }\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 });\n if (result.status === 'rejected') throw new Error(`${result.code}: ${result.reason}`);\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 = 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 delivered = await session.thread.listActiveMessages();\n if (delivered.some(message => message.id === record.id)) return;\n if (decision.precedingMessage) {\n await awaitNotification(\n await session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'stage-transition',\n summary: decision.precedingMessage,\n priority: 'medium',\n payload: { message: decision.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 const result = session.sendSignal(\n {\n id: record.id,\n type: 'user',\n tagName: 'user',\n contents: resolved.message,\n },\n { requestContext },\n );\n await result.accepted;\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 await 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 await 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 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: record.workItemId,\n title: decision.title,\n stages: ['intake'],\n sessions: {},\n metadata: { ...decision.metadata, factoryRuleMaterializationKey: record.idempotencyKey },\n },\n reuseMode: 'preserve',\n });\n const materializedByDecision = result.item.metadata?.factoryRuleMaterializationKey === 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) throw new Error(role ? `No active Factory binding for role ${role}.` : 'No active Factory binding.');\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 Error(binding ? 'Bound Factory session not found.' : `No active Factory binding for role ${role}.`);\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 #requireSession(binding: FactoryRunBindingRecord): Promise<DispatcherSession> {\n const session = (await this.#controller.getSessionByResource(binding.resourceId)) as DispatcherSession | undefined;\n if (!session) throw new Error('Bound Factory session not found.');\n await this.#switchThread(session, binding);\n return session;\n }\n\n async #switchThread(session: SkillSession, binding: FactoryRunBindingRecord): Promise<void> {\n await (session as DispatcherSession).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) throw new Error('Prepared Factory binding is unavailable or revoked.');\n const session = await this.#requireSession(binding);\n await awaitNotification(\n await 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: `factory-kickoff:${record.kickoffKey}`,\n },\n { ifActive: { behavior: 'deliver' }, ifIdle: { behavior: 'wake' } },\n ),\n true,\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 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 stages: FACTORY_RULE_STAGES,\n} as const;\n","import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { SendAgentSignalResult } from '@mastra/core/agent';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { formatSkillActivation } from '@mastra/core/workspace';\nimport type { Workspace } from '@mastra/core/workspace';\n\nexport interface SkillInvocationInput {\n resourceId: string;\n scope?: string;\n name: string;\n arguments?: string;\n}\n\nexport interface SkillSession {\n getWorkspace(): Workspace;\n sendMessage(input: { content: string }): Promise<unknown>;\n sendNotificationSignal(\n input: {\n source: string;\n kind: string;\n summary: string;\n priority?: 'low' | 'medium' | 'high' | 'urgent';\n payload?: unknown;\n dedupeKey?: string;\n sourceId?: string;\n },\n options?: {\n ifActive?: { behavior?: 'deliver' | 'persist' };\n ifIdle?: { behavior?: 'persist' | 'wake' };\n requestContext?: RequestContext;\n },\n ): Promise<Pick<SendAgentSignalResult, 'persisted' | 'accepted'>>;\n}\n\nexport class SkillInvocationError extends Error {\n readonly code: 'session_not_found' | 'skill_not_found';\n\n constructor(code: SkillInvocationError['code'], message: string) {\n super(message);\n this.name = 'SkillInvocationError';\n this.code = code;\n }\n}\n\nfunction escapeSkillBoundary(value: string): string {\n return value.replaceAll('</skill>', '&lt;/skill&gt;');\n}\n\nexport async function resolveSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ session: SkillSession; skillName: string; message: string }> {\n const session = (await controller.getSessionByResource(input.resourceId, input.scope)) as SkillSession | undefined;\n if (!session) throw new SkillInvocationError('session_not_found', 'Agent controller session not found.');\n\n const skills = session.getWorkspace().skills;\n await skills?.maybeRefresh();\n const skill = await skills?.get(input.name);\n if (!skill || skill['user-invocable'] === false) {\n throw new SkillInvocationError('skill_not_found', `Skill not found: ${input.name}.`);\n }\n\n const args = input.arguments?.trim();\n const content = `${formatSkillActivation(skill)}${args ? `\\n\\nARGUMENTS: ${args}` : ''}`.trim();\n return {\n session,\n skillName: skill.name,\n message: `<skill name=\"${skill.name}\">\\n${escapeSkillBoundary(content)}\\n</skill>`,\n };\n}\n\nexport async function dispatchSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ skillName: string; message: string }> {\n const resolved = await resolveSkillInvocation(controller, input);\n await resolved.session.sendMessage({ content: resolved.message });\n return { skillName: resolved.skillName, message: resolved.message };\n}\n","export type WorkItemSource = 'github-issue' | 'github-pr' | 'linear-issue' | 'manual';\n\nexport const FACTORY_RULE_STAGES = ['intake', 'triage', 'planning', 'execute', 'review', 'done', 'canceled'] as const;\nexport type FactoryRuleStage = (typeof FACTORY_RULE_STAGES)[number];\n\nexport const FACTORY_RULE_BOARDS = ['work', 'review'] as const;\nexport type FactoryRuleBoard = (typeof FACTORY_RULE_BOARDS)[number];\n\nexport const FACTORY_RULE_SOURCES = ['issue', 'pullRequest', 'linearIssue', 'manual'] as const;\nexport type FactoryRuleSource = (typeof FACTORY_RULE_SOURCES)[number];\n\nexport const FACTORY_GITHUB_EVENTS = [\n 'issueOpened',\n 'pullRequestOpened',\n 'pullRequestUpdated',\n 'pullRequestReviewRequested',\n 'pullRequestMerged',\n] as const;\nexport type FactoryGithubEventName = (typeof FACTORY_GITHUB_EVENTS)[number];\n\nexport const FACTORY_LINEAR_EVENTS = ['issueObserved'] as const;\nexport type FactoryLinearEventName = (typeof FACTORY_LINEAR_EVENTS)[number];\n\nexport type FactoryRuleJsonValue =\n | null\n | boolean\n | number\n | string\n | FactoryRuleJsonValue[]\n | { [key: string]: FactoryRuleJsonValue };\n\nexport interface FactoryRuleItemContext {\n id: string;\n source: WorkItemSource;\n sourceKey: string | null;\n parentWorkItemId: string | null;\n title: string;\n url: string | null;\n stages: readonly string[];\n}\n\nexport type FactoryRuleActor =\n | { type: 'human'; id: string }\n | { type: 'agent'; bindingId: string; role: string }\n | { type: 'github'; login: string; trusted: boolean; factoryAuthored: boolean }\n | { type: 'system'; id: string };\n\nexport interface FactoryRuleIngressIdentity {\n type: 'human' | 'agent' | 'toolResult' | 'github' | 'linear' | 'rule';\n id: string;\n}\n\nexport interface FactoryRuleCausalEntry {\n ingressId: string;\n decisionType: FactoryCommitDecision['type'];\n}\n\nexport interface FactoryRuleContextBase {\n tenant: { orgId: string; projectId: string };\n actor: FactoryRuleActor;\n ingress: FactoryRuleIngressIdentity;\n cause: string;\n causalChain: readonly FactoryRuleCausalEntry[];\n ruleSetVersion: string;\n}\n\nexport interface FactoryBoundRuleContext extends FactoryRuleContextBase {\n item: FactoryRuleItemContext;\n board: FactoryRuleBoard;\n itemRevision: number;\n}\n\nexport interface FactoryStageRuleContext extends FactoryBoundRuleContext {\n source: FactoryRuleSource;\n stage: FactoryRuleStage;\n fromStage: FactoryRuleStage;\n toStage: FactoryRuleStage;\n}\n\nexport interface FactoryToolResultRuleContext extends FactoryBoundRuleContext {\n toolName: string;\n threadId: string;\n assistantMessageId: string;\n toolCallId: string;\n result: {\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n };\n}\n\nexport interface FactoryGithubRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryGithubEventName;\n deliveryId: string;\n factory: { createdAt: string };\n repository: { id: number; fullName: string };\n issue?: { number: number; title: string; url: string; createdAt?: string };\n pullRequest?: {\n number: number;\n title: string;\n url: string;\n createdAt?: string;\n state: 'open' | 'closed';\n merged: boolean;\n headBranch: string;\n baseBranch: string;\n };\n}\n\nexport interface FactoryLinearRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryLinearEventName;\n issue: {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n team: string | null;\n labels: readonly string[];\n createdAt: string;\n updatedAt: string;\n };\n}\n\nexport type FactoryRuleHandler<TContext> = (\n context: Readonly<TContext>,\n) => FactoryRuleDecision | void | Promise<FactoryRuleDecision | void>;\n\nexport interface FactoryBoardRuleLeaf {\n onEnter?: FactoryRuleHandler<FactoryStageRuleContext>;\n onExit?: FactoryRuleHandler<FactoryStageRuleContext>;\n}\n\nexport interface FactoryToolRuleLeaf {\n onResult?: FactoryRuleHandler<FactoryToolResultRuleContext>;\n}\n\nexport interface FactoryGithubRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryGithubRuleContext>;\n}\n\nexport interface FactoryLinearRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryLinearRuleContext>;\n}\n\nexport type FactoryBoardRules = Partial<\n Record<FactoryRuleStage, Partial<Record<FactoryRuleSource, FactoryBoardRuleLeaf>>>\n>;\n\nexport interface FactoryRules {\n version: string;\n work: FactoryBoardRules;\n review: FactoryBoardRules;\n tools: Record<string, FactoryToolRuleLeaf>;\n github: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport interface FactoryRulesOverrides {\n work?: FactoryBoardRules;\n review?: FactoryBoardRules;\n tools?: Record<string, FactoryToolRuleLeaf>;\n github?: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear?: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport type FactoryRuleRejectionCode =\n | 'forbidden'\n | 'invalid_transition'\n | 'missing_binding'\n | 'stale'\n | 'timeout'\n | 'rule_error'\n | 'causal_depth_exceeded'\n | 'repeated_transition';\n\nexport interface FactoryRuleRejectDecision {\n type: 'reject';\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\ninterface FactoryCommitDecisionBase {\n idempotencyKey: string;\n}\n\nexport interface FactoryTransitionDecision extends FactoryCommitDecisionBase {\n type: 'transition';\n board: FactoryRuleBoard;\n stage: FactoryRuleStage;\n}\n\nexport interface FactoryUpsertLinkedWorkItemDecision extends FactoryCommitDecisionBase {\n type: 'upsertLinkedWorkItem';\n board: FactoryRuleBoard;\n source: WorkItemSource;\n sourceKey: string;\n title: string;\n url: string | null;\n stage: FactoryRuleStage;\n metadata?: Record<string, FactoryRuleJsonValue>;\n}\n\nexport interface FactoryInvokeSkillDecision extends FactoryCommitDecisionBase {\n type: 'invokeSkill';\n role: string;\n skillName: string;\n arguments?: string;\n precedingMessage?: string;\n}\n\nexport interface FactorySendMessageDecision extends FactoryCommitDecisionBase {\n type: 'sendMessage';\n role: string;\n message: string;\n priority?: 'medium' | 'high' | 'urgent';\n idleBehavior?: 'persist' | 'wake';\n prepareBinding?: boolean;\n}\n\nexport interface FactoryNotifyDecision extends FactoryCommitDecisionBase {\n type: 'notify';\n title: string;\n body?: string;\n level?: 'info' | 'warning' | 'error';\n}\n\nexport type FactoryCommitDecision =\n | FactoryTransitionDecision\n | FactoryUpsertLinkedWorkItemDecision\n | FactoryInvokeSkillDecision\n | FactorySendMessageDecision\n | FactoryNotifyDecision;\n\nexport type FactoryRuleDecision = FactoryRuleRejectDecision | FactoryCommitDecision;\n\nexport interface FactoryTransitionResultAccepted {\n status: 'accepted';\n transitionId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n decisions: FactoryCommitDecision[];\n}\n\nexport interface FactoryTransitionResultRejected {\n status: 'rejected';\n transitionId: string;\n itemId: string;\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\nexport type FactoryTransitionResult = FactoryTransitionResultAccepted | FactoryTransitionResultRejected;\n\nexport function factoryRuleSourceForWorkItem(source: WorkItemSource): FactoryRuleSource {\n switch (source) {\n case 'github-issue':\n return 'issue';\n case 'github-pr':\n return 'pullRequest';\n case 'linear-issue':\n return 'linearIssue';\n case 'manual':\n return 'manual';\n }\n}\n","import {\n FACTORY_GITHUB_EVENTS,\n FACTORY_LINEAR_EVENTS,\n FACTORY_RULE_BOARDS,\n FACTORY_RULE_SOURCES,\n FACTORY_RULE_STAGES,\n} from './types.js';\nimport type {\n FactoryBoardRules,\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRules,\n FactoryRuleRejectionCode,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nconst MAX_ROLE_LENGTH = 32;\nconst MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nconst IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nconst SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = ['github-issue', 'github-pr', 'linear-issue', 'manual'];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nfunction validateBoardRules(rules: unknown, label: string): asserts rules is FactoryBoardRules {\n if (!isPlainObject(rules)) throw new FactoryRuleValidationError(`${label} must be an object.`);\n for (const [stage, sources] of Object.entries(rules)) {\n enumValue(stage, FACTORY_RULE_STAGES, `${label} stage`);\n if (!isPlainObject(sources)) throw new FactoryRuleValidationError(`${label}.${stage} must be an object.`);\n for (const [source, leaf] of Object.entries(sources)) {\n enumValue(source, FACTORY_RULE_SOURCES, `${label}.${stage} source`);\n if (!isPlainObject(leaf)) throw new FactoryRuleValidationError(`${label}.${stage}.${source} must be an object.`);\n assertExactKeys(leaf, ['onEnter', 'onExit'], `${label}.${stage}.${source}`);\n for (const handler of Object.values(leaf)) {\n if (handler !== undefined && typeof handler !== 'function') {\n throw new FactoryRuleValidationError(`${label}.${stage}.${source} handlers must be functions.`);\n }\n }\n }\n }\n}\n\nexport function assertFactoryRules(rules: unknown): asserts rules is FactoryRules {\n if (!isPlainObject(rules)) throw new FactoryRuleValidationError('Factory rules must be an object.');\n assertExactKeys(rules, ['version', 'work', 'review', 'tools', 'github', 'linear'], 'Factory rules');\n boundedString(rules.version, 'Factory rule version', MAX_VERSION_LENGTH);\n validateBoardRules(rules.work, 'Factory rules.work');\n validateBoardRules(rules.review, 'Factory rules.review');\n\n if (!isPlainObject(rules.tools)) throw new FactoryRuleValidationError('Factory rules.tools must be an object.');\n for (const [toolName, leaf] of Object.entries(rules.tools)) {\n boundedString(toolName, 'Factory tool name', 128, IDENTIFIER_RE);\n if (!isPlainObject(leaf))\n throw new FactoryRuleValidationError(`Factory rules.tools.${toolName} must be an object.`);\n assertExactKeys(leaf, ['onResult'], `Factory rules.tools.${toolName}`);\n if (leaf.onResult !== undefined && typeof leaf.onResult !== 'function') {\n throw new FactoryRuleValidationError(`Factory rules.tools.${toolName}.onResult must be a function.`);\n }\n }\n\n if (!isPlainObject(rules.github)) throw new FactoryRuleValidationError('Factory rules.github must be an object.');\n for (const [event, leaf] of Object.entries(rules.github)) {\n enumValue(event, FACTORY_GITHUB_EVENTS, 'Factory GitHub event');\n if (!isPlainObject(leaf)) throw new FactoryRuleValidationError(`Factory rules.github.${event} must be an object.`);\n assertExactKeys(leaf, ['onEvent'], `Factory rules.github.${event}`);\n if (leaf.onEvent !== undefined && typeof leaf.onEvent !== 'function') {\n throw new FactoryRuleValidationError(`Factory rules.github.${event}.onEvent must be a function.`);\n }\n }\n\n if (!isPlainObject(rules.linear)) throw new FactoryRuleValidationError('Factory rules.linear must be an object.');\n for (const [event, leaf] of Object.entries(rules.linear)) {\n enumValue(event, FACTORY_LINEAR_EVENTS, 'Factory Linear event');\n if (!isPlainObject(leaf)) throw new FactoryRuleValidationError(`Factory rules.linear.${event} must be an object.`);\n assertExactKeys(leaf, ['onEvent'], `Factory rules.linear.${event}`);\n if (leaf.onEvent !== undefined && typeof leaf.onEvent !== 'function') {\n throw new FactoryRuleValidationError(`Factory rules.linear.${event}.onEvent must be a function.`);\n }\n }\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'board', 'stage'], 'Factory transition decision');\n return {\n type,\n ...commonCommitFields(value),\n board: enumValue(value.board, FACTORY_RULE_BOARDS, 'Factory transition board'),\n stage: enumValue(value.stage, FACTORY_RULE_STAGES, 'Factory transition stage'),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'source', 'sourceKey', 'title', 'url', 'stage', 'metadata'],\n 'Factory linked work item decision',\n );\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n return {\n type,\n ...commonCommitFields(value),\n board: enumValue(value.board, FACTORY_RULE_BOARDS, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n url,\n stage: enumValue(value.stage, FACTORY_RULE_STAGES, 'Factory linked work item stage'),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'skillName', 'arguments', 'precedingMessage'],\n 'Factory invoke skill decision',\n );\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAI3B,SAAS,sBAAsB;;;ACA/B,SAAS,6BAA6B;AA+B/B,IAAM,uBAAN,cAAmC,MAAM;AAAA,EACrC;AAAA,EAET,YAAY,MAAoC,SAAiB;AAC/D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,E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EAAE,SAAS,OAAO,QAAQ;AAAA,gBACnC,UAAU,OAAO;AAAA,gBACjB,WAAW,mBAAmB,OAAO,UAAU;AAAA,cACjD;AAAA,cACA,EAAE,UAAU,EAAE,UAAU,UAAU,GAAG,QAAQ,EAAE,UAAU,OAAO,EAAE;AAAA,YACpE;AAAA,YACA;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACA,YAAM,YAAY,MAAM,KAAK,SAAS,qBAAqB,cAAc,QAAQ,KAAK,QAAQ,GAAG,oBAAI,KAAK,CAAC;AAC3G,UAAI,CAAC,UAAW,OAAM,IAAI,MAAM,mDAAmD;AAAA,IACrF,SAAS,OAAO;AACd,YAAM,KAAK,SAAS,iBAAiB;AAAA,QACnC,GAAG,cAAc,QAAQ,KAAK,QAAQ;AAAA,QACtC,KAAK,oBAAI,KAAK;AAAA,QACd,aAAa,QAAQ,KAAK,OAAO,QAAQ;AAAA,QACzC,WAAW,sBAAsB,KAAK;AAAA,QACtC,UAAU,OAAO,YAAY;AAAA,MAC/B,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEO,IAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,QAAQ;AACV;","names":[]}
1
+ {"version":3,"sources":["../../src/rules/dispatcher.ts","../../src/skills/service.ts","../../src/rules/types.ts","../../src/rules/validation.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\n\nimport { 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 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;\n\ninterface DispatcherSession extends SkillSession {\n thread: {\n switch(input: { threadId: string }): Promise<unknown>;\n listActiveMessages(): Promise<Array<{ id: string }>>;\n };\n sendSignal(\n input: { id: string; type: 'user'; tagName: 'user'; contents: string },\n options: { requestContext: RequestContext },\n ): { accepted: Promise<unknown> };\n}\n\ntype FactoryController = Pick<AgentController<MastraCodeState>, 'getSessionByResource'>;\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 reconcileToolResults?: () => Promise<void>;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\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 result: Awaited<ReturnType<SkillSession['sendNotificationSignal']>>,\n requireDelivery = false,\n): Promise<void> {\n await result.persisted;\n if (!result.accepted) {\n if (requireDelivery) throw new Error('Factory notification was persisted without agent delivery.');\n return;\n }\n const accepted = await result.accepted;\n if (!requireDelivery) return;\n if (accepted.action === 'wake') {\n await accepted.output.consumeStream();\n return;\n }\n if (accepted.action !== 'deliver') {\n throw new Error(`Factory notification did not reach the agent (${String(accepted.action)}).`);\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 #reconcileToolResults?: () => Promise<void>;\n readonly #prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n readonly #primeCredentials?: (tenant: { orgId: string; userId: string }) => Promise<void>;\n #timer?: ReturnType<typeof setInterval>;\n #activeRun?: 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.#reconcileToolResults = options.reconcileToolResults;\n this.#prepareBinding = options.prepareBinding;\n this.#primeCredentials = options.primeCredentials;\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.#activeRun;\n }\n\n async runOnce(now = new Date()): Promise<void> {\n await this.#reconcileToolResults?.();\n const leaseExpiresAt = new Date(now.getTime() + LEASE_MS);\n const [decisions, starts] = await Promise.all([\n this.#storage.claimDeferredDecisions({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit: BATCH_SIZE,\n }),\n this.#storage.claimPendingStarts({\n ownerId: this.#ownerId,\n now,\n leaseExpiresAt,\n limit: BATCH_SIZE,\n }),\n ]);\n await Promise.all([\n ...decisions.map(decision => this.#dispatchDecision(decision, now)),\n ...starts.map(start => this.#dispatchPendingStart(start, now)),\n ]);\n }\n\n async #tick(): Promise<void> {\n if (this.#activeRun) return;\n this.#activeRun = this.runOnce().catch(error => {\n console.error('Factory decision dispatch cycle failed', sanitizeDispatchError(error));\n });\n try {\n await this.#activeRun;\n } finally {\n this.#activeRun = undefined;\n }\n }\n\n async #dispatchDecision(record: FactoryDeferredDecisionRecord, now: Date): Promise<void> {\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 await this.#withLease(\n async leaseExpiresAt =>\n this.#storage.renewDeferredDecisionLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),\n async () => this.#executeDecision(record, decision),\n );\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 terminal,\n });\n }\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 });\n if (result.status === 'rejected') throw new Error(`${result.code}: ${result.reason}`);\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 = 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 delivered = await session.thread.listActiveMessages();\n if (delivered.some(message => message.id === record.id)) return;\n if (decision.precedingMessage) {\n await awaitNotification(\n await session.sendNotificationSignal(\n {\n source: 'factory',\n kind: 'stage-transition',\n summary: decision.precedingMessage,\n priority: 'medium',\n payload: { message: decision.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 const result = session.sendSignal(\n {\n id: record.id,\n type: 'user',\n tagName: 'user',\n contents: resolved.message,\n },\n { requestContext },\n );\n await result.accepted;\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 await 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 await 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 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: record.workItemId,\n title: decision.title,\n stages: ['intake'],\n sessions: {},\n metadata: { ...decision.metadata, factoryRuleMaterializationKey: record.idempotencyKey },\n },\n reuseMode: 'preserve',\n });\n const materializedByDecision = result.item.metadata?.factoryRuleMaterializationKey === 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) throw new Error(role ? `No active Factory binding for role ${role}.` : 'No active Factory binding.');\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 Error(binding ? 'Bound Factory session not found.' : `No active Factory binding for role ${role}.`);\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 #requireSession(binding: FactoryRunBindingRecord): Promise<DispatcherSession> {\n const session = (await this.#controller.getSessionByResource(binding.resourceId)) as DispatcherSession | undefined;\n if (!session) throw new Error('Bound Factory session not found.');\n await this.#switchThread(session, binding);\n return session;\n }\n\n async #switchThread(session: SkillSession, binding: FactoryRunBindingRecord): Promise<void> {\n await (session as DispatcherSession).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) throw new Error('Prepared Factory binding is unavailable or revoked.');\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 await awaitNotification(\n await 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: `factory-kickoff:${record.kickoffKey}`,\n },\n { ifActive: { behavior: 'deliver' }, ifIdle: { behavior: 'wake' }, requestContext },\n ),\n true,\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 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 stages: FACTORY_RULE_STAGES,\n} as const;\n","import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { SendAgentSignalResult } from '@mastra/core/agent';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { formatSkillActivation } from '@mastra/core/workspace';\nimport type { Workspace } from '@mastra/core/workspace';\n\nexport interface SkillInvocationInput {\n resourceId: string;\n scope?: string;\n name: string;\n arguments?: string;\n}\n\nexport interface SkillSession {\n getWorkspace(): Workspace;\n sendMessage(input: { content: string }): Promise<unknown>;\n sendNotificationSignal(\n input: {\n source: string;\n kind: string;\n summary: string;\n priority?: 'low' | 'medium' | 'high' | 'urgent';\n payload?: unknown;\n dedupeKey?: string;\n sourceId?: string;\n },\n options?: {\n ifActive?: { behavior?: 'deliver' | 'persist' };\n ifIdle?: { behavior?: 'persist' | 'wake' };\n requestContext?: RequestContext;\n },\n ): Promise<Pick<SendAgentSignalResult, 'persisted' | 'accepted'>>;\n}\n\nexport class SkillInvocationError extends Error {\n readonly code: 'session_not_found' | 'skill_not_found';\n\n constructor(code: SkillInvocationError['code'], message: string) {\n super(message);\n this.name = 'SkillInvocationError';\n this.code = code;\n }\n}\n\nfunction escapeSkillBoundary(value: string): string {\n return value.replaceAll('</skill>', '&lt;/skill&gt;');\n}\n\nexport async function resolveSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ session: SkillSession; skillName: string; message: string }> {\n const session = (await controller.getSessionByResource(input.resourceId, input.scope)) as SkillSession | undefined;\n if (!session) throw new SkillInvocationError('session_not_found', 'Agent controller session not found.');\n\n const skills = session.getWorkspace().skills;\n await skills?.maybeRefresh();\n const skill = await skills?.get(input.name);\n if (!skill || skill['user-invocable'] === false) {\n throw new SkillInvocationError('skill_not_found', `Skill not found: ${input.name}.`);\n }\n\n const args = input.arguments?.trim();\n const content = `${formatSkillActivation(skill)}${args ? `\\n\\nARGUMENTS: ${args}` : ''}`.trim();\n return {\n session,\n skillName: skill.name,\n message: `<skill name=\"${skill.name}\">\\n${escapeSkillBoundary(content)}\\n</skill>`,\n };\n}\n\nexport async function dispatchSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ skillName: string; message: string }> {\n const resolved = await resolveSkillInvocation(controller, input);\n await resolved.session.sendMessage({ content: resolved.message });\n return { skillName: resolved.skillName, message: resolved.message };\n}\n","export type WorkItemSource = 'github-issue' | 'github-pr' | 'linear-issue' | 'manual';\n\nexport const FACTORY_RULE_STAGES = ['intake', 'triage', 'planning', 'execute', 'review', 'done', 'canceled'] as const;\nexport type FactoryRuleStage = (typeof FACTORY_RULE_STAGES)[number];\n\nexport const FACTORY_RULE_BOARDS = ['work', 'review'] as const;\nexport type FactoryRuleBoard = (typeof FACTORY_RULE_BOARDS)[number];\n\nexport const FACTORY_RULE_SOURCES = ['issue', 'pullRequest', 'linearIssue', 'manual'] as const;\nexport type FactoryRuleSource = (typeof FACTORY_RULE_SOURCES)[number];\n\nexport const FACTORY_GITHUB_EVENTS = [\n 'issueOpened',\n 'pullRequestOpened',\n 'pullRequestUpdated',\n 'pullRequestReviewRequested',\n 'pullRequestMerged',\n] as const;\nexport type FactoryGithubEventName = (typeof FACTORY_GITHUB_EVENTS)[number];\n\nexport const FACTORY_LINEAR_EVENTS = ['issueObserved'] as const;\nexport type FactoryLinearEventName = (typeof FACTORY_LINEAR_EVENTS)[number];\n\nexport type FactoryRuleJsonValue =\n | null\n | boolean\n | number\n | string\n | FactoryRuleJsonValue[]\n | { [key: string]: FactoryRuleJsonValue };\n\nexport interface FactoryRuleItemContext {\n id: string;\n source: WorkItemSource;\n sourceKey: string | null;\n parentWorkItemId: string | null;\n title: string;\n url: string | null;\n stages: readonly string[];\n}\n\nexport type FactoryRuleActor =\n | { type: 'human'; id: string }\n | { type: 'agent'; bindingId: string; role: string }\n | { type: 'github'; login: string; trusted: boolean; factoryAuthored: boolean }\n | { type: 'system'; id: string };\n\nexport interface FactoryRuleIngressIdentity {\n type: 'human' | 'agent' | 'toolResult' | 'github' | 'linear' | 'rule';\n id: string;\n}\n\nexport interface FactoryRuleCausalEntry {\n ingressId: string;\n decisionType: FactoryCommitDecision['type'];\n}\n\nexport interface FactoryRuleContextBase {\n tenant: { orgId: string; projectId: string };\n actor: FactoryRuleActor;\n ingress: FactoryRuleIngressIdentity;\n cause: string;\n causalChain: readonly FactoryRuleCausalEntry[];\n ruleSetVersion: string;\n}\n\nexport interface FactoryBoundRuleContext extends FactoryRuleContextBase {\n item: FactoryRuleItemContext;\n board: FactoryRuleBoard;\n itemRevision: number;\n}\n\nexport interface FactoryStageRuleContext extends FactoryBoundRuleContext {\n source: FactoryRuleSource;\n stage: FactoryRuleStage;\n fromStage: FactoryRuleStage;\n toStage: FactoryRuleStage;\n}\n\nexport interface FactoryToolResultRuleContext extends FactoryBoundRuleContext {\n toolName: string;\n threadId: string;\n assistantMessageId: string;\n toolCallId: string;\n result: {\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n };\n}\n\nexport interface FactoryGithubRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryGithubEventName;\n deliveryId: string;\n factory: { createdAt: string };\n repository: { id: number; fullName: string };\n issue?: { number: number; title: string; url: string; createdAt?: string };\n pullRequest?: {\n number: number;\n title: string;\n url: string;\n createdAt?: string;\n state: 'open' | 'closed';\n merged: boolean;\n headBranch: string;\n baseBranch: string;\n };\n}\n\nexport interface FactoryLinearRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryLinearEventName;\n issue: {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n team: string | null;\n labels: readonly string[];\n createdAt: string;\n updatedAt: string;\n };\n}\n\nexport type FactoryRuleHandler<TContext> = (\n context: Readonly<TContext>,\n) => FactoryRuleDecision | void | Promise<FactoryRuleDecision | void>;\n\nexport interface FactoryBoardRuleLeaf {\n onEnter?: FactoryRuleHandler<FactoryStageRuleContext>;\n onExit?: FactoryRuleHandler<FactoryStageRuleContext>;\n}\n\nexport interface FactoryToolRuleLeaf {\n onResult?: FactoryRuleHandler<FactoryToolResultRuleContext>;\n}\n\nexport interface FactoryGithubRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryGithubRuleContext>;\n}\n\nexport interface FactoryLinearRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryLinearRuleContext>;\n}\n\nexport type FactoryBoardRules = Partial<\n Record<FactoryRuleStage, Partial<Record<FactoryRuleSource, FactoryBoardRuleLeaf>>>\n>;\n\nexport interface FactoryRules {\n version: string;\n work: FactoryBoardRules;\n review: FactoryBoardRules;\n tools: Record<string, FactoryToolRuleLeaf>;\n github: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport interface FactoryRulesOverrides {\n work?: FactoryBoardRules;\n review?: FactoryBoardRules;\n tools?: Record<string, FactoryToolRuleLeaf>;\n github?: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear?: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport type FactoryRuleRejectionCode =\n | 'forbidden'\n | 'invalid_transition'\n | 'missing_binding'\n | 'stale'\n | 'timeout'\n | 'rule_error'\n | 'causal_depth_exceeded'\n | 'repeated_transition';\n\nexport interface FactoryRuleRejectDecision {\n type: 'reject';\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\ninterface FactoryCommitDecisionBase {\n idempotencyKey: string;\n}\n\nexport interface FactoryTransitionDecision extends FactoryCommitDecisionBase {\n type: 'transition';\n board: FactoryRuleBoard;\n stage: FactoryRuleStage;\n}\n\nexport interface FactoryUpsertLinkedWorkItemDecision extends FactoryCommitDecisionBase {\n type: 'upsertLinkedWorkItem';\n board: FactoryRuleBoard;\n source: WorkItemSource;\n sourceKey: string;\n title: string;\n url: string | null;\n stage: FactoryRuleStage;\n metadata?: Record<string, FactoryRuleJsonValue>;\n}\n\nexport interface FactoryInvokeSkillDecision extends FactoryCommitDecisionBase {\n type: 'invokeSkill';\n role: string;\n skillName: string;\n arguments?: string;\n precedingMessage?: string;\n}\n\nexport interface FactorySendMessageDecision extends FactoryCommitDecisionBase {\n type: 'sendMessage';\n role: string;\n message: string;\n priority?: 'medium' | 'high' | 'urgent';\n idleBehavior?: 'persist' | 'wake';\n prepareBinding?: boolean;\n}\n\nexport interface FactoryNotifyDecision extends FactoryCommitDecisionBase {\n type: 'notify';\n title: string;\n body?: string;\n level?: 'info' | 'warning' | 'error';\n}\n\nexport type FactoryCommitDecision =\n | FactoryTransitionDecision\n | FactoryUpsertLinkedWorkItemDecision\n | FactoryInvokeSkillDecision\n | FactorySendMessageDecision\n | FactoryNotifyDecision;\n\nexport type FactoryRuleDecision = FactoryRuleRejectDecision | FactoryCommitDecision;\n\nexport interface FactoryTransitionResultAccepted {\n status: 'accepted';\n transitionId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n decisions: FactoryCommitDecision[];\n}\n\nexport interface FactoryTransitionResultRejected {\n status: 'rejected';\n transitionId: string;\n itemId: string;\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\nexport type FactoryTransitionResult = FactoryTransitionResultAccepted | FactoryTransitionResultRejected;\n\nexport function factoryRuleSourceForWorkItem(source: WorkItemSource): FactoryRuleSource {\n switch (source) {\n case 'github-issue':\n return 'issue';\n case 'github-pr':\n return 'pullRequest';\n case 'linear-issue':\n return 'linearIssue';\n case 'manual':\n return 'manual';\n }\n}\n","import {\n FACTORY_GITHUB_EVENTS,\n FACTORY_LINEAR_EVENTS,\n FACTORY_RULE_BOARDS,\n FACTORY_RULE_SOURCES,\n FACTORY_RULE_STAGES,\n} from './types.js';\nimport type {\n FactoryBoardRules,\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRules,\n FactoryRuleRejectionCode,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nconst MAX_ROLE_LENGTH = 32;\nconst MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nconst IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nconst SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = ['github-issue', 'github-pr', 'linear-issue', 'manual'];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nfunction validateBoardRules(rules: unknown, label: string): asserts rules is FactoryBoardRules {\n if (!isPlainObject(rules)) throw new FactoryRuleValidationError(`${label} must be an object.`);\n for (const [stage, sources] of Object.entries(rules)) {\n enumValue(stage, FACTORY_RULE_STAGES, `${label} stage`);\n if (!isPlainObject(sources)) throw new FactoryRuleValidationError(`${label}.${stage} must be an object.`);\n for (const [source, leaf] of Object.entries(sources)) {\n enumValue(source, FACTORY_RULE_SOURCES, `${label}.${stage} source`);\n if (!isPlainObject(leaf)) throw new FactoryRuleValidationError(`${label}.${stage}.${source} must be an object.`);\n assertExactKeys(leaf, ['onEnter', 'onExit'], `${label}.${stage}.${source}`);\n for (const handler of Object.values(leaf)) {\n if (handler !== undefined && typeof handler !== 'function') {\n throw new FactoryRuleValidationError(`${label}.${stage}.${source} handlers must be functions.`);\n }\n }\n }\n }\n}\n\nexport function assertFactoryRules(rules: unknown): asserts rules is FactoryRules {\n if (!isPlainObject(rules)) throw new FactoryRuleValidationError('Factory rules must be an object.');\n assertExactKeys(rules, ['version', 'work', 'review', 'tools', 'github', 'linear'], 'Factory rules');\n boundedString(rules.version, 'Factory rule version', MAX_VERSION_LENGTH);\n validateBoardRules(rules.work, 'Factory rules.work');\n validateBoardRules(rules.review, 'Factory rules.review');\n\n if (!isPlainObject(rules.tools)) throw new FactoryRuleValidationError('Factory rules.tools must be an object.');\n for (const [toolName, leaf] of Object.entries(rules.tools)) {\n boundedString(toolName, 'Factory tool name', 128, IDENTIFIER_RE);\n if (!isPlainObject(leaf))\n throw new FactoryRuleValidationError(`Factory rules.tools.${toolName} must be an object.`);\n assertExactKeys(leaf, ['onResult'], `Factory rules.tools.${toolName}`);\n if (leaf.onResult !== undefined && typeof leaf.onResult !== 'function') {\n throw new FactoryRuleValidationError(`Factory rules.tools.${toolName}.onResult must be a function.`);\n }\n }\n\n if (!isPlainObject(rules.github)) throw new FactoryRuleValidationError('Factory rules.github must be an object.');\n for (const [event, leaf] of Object.entries(rules.github)) {\n enumValue(event, FACTORY_GITHUB_EVENTS, 'Factory GitHub event');\n if (!isPlainObject(leaf)) throw new FactoryRuleValidationError(`Factory rules.github.${event} must be an object.`);\n assertExactKeys(leaf, ['onEvent'], `Factory rules.github.${event}`);\n if (leaf.onEvent !== undefined && typeof leaf.onEvent !== 'function') {\n throw new FactoryRuleValidationError(`Factory rules.github.${event}.onEvent must be a function.`);\n }\n }\n\n if (!isPlainObject(rules.linear)) throw new FactoryRuleValidationError('Factory rules.linear must be an object.');\n for (const [event, leaf] of Object.entries(rules.linear)) {\n enumValue(event, FACTORY_LINEAR_EVENTS, 'Factory Linear event');\n if (!isPlainObject(leaf)) throw new FactoryRuleValidationError(`Factory rules.linear.${event} must be an object.`);\n assertExactKeys(leaf, ['onEvent'], `Factory rules.linear.${event}`);\n if (leaf.onEvent !== undefined && typeof leaf.onEvent !== 'function') {\n throw new FactoryRuleValidationError(`Factory rules.linear.${event}.onEvent must be a function.`);\n }\n }\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'board', 'stage'], 'Factory transition decision');\n return {\n type,\n ...commonCommitFields(value),\n board: enumValue(value.board, FACTORY_RULE_BOARDS, 'Factory transition board'),\n stage: enumValue(value.stage, FACTORY_RULE_STAGES, 'Factory transition stage'),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'source', 'sourceKey', 'title', 'url', 'stage', 'metadata'],\n 'Factory linked work item decision',\n );\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n return {\n type,\n ...commonCommitFields(value),\n board: enumValue(value.board, FACTORY_RULE_BOARDS, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n url,\n stage: enumValue(value.stage, FACTORY_RULE_STAGES, 'Factory linked work item stage'),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'skillName', 'arguments', 'precedingMessage'],\n 'Factory invoke skill decision',\n );\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAI3B,SAAS,sBAAsB;;;ACA/B,SAAS,6BAA6B;AA+B/B,IAAM,uBAAN,cAAmC,MAAM;AAAA,EACrC;AAAA,EAET,YAAY,MAAoC,SAAiB;AAC/D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,oBAAoB,OAAuB;AAClD,SAAO,MAAM,WAAW,YAAY,gBAAgB;AACtD;AAEA,eAAsB,uBACpB,YACA,OACwE;AACxE,QAAM,UAAW,MAAM,WAAW,qBAAqB,MAAM,YAAY,MAAM,KAAK;AACpF,MAAI,CAAC,QAAS,OAAM,IAAI,qBAAqB,qBAAqB,qCAAqC;AAEvG,QAAM,SAAS,QA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