@mastra/factory 0.28.0-alpha.3 → 0.28.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -56
- package/dist/boards/board-events.d.ts +1 -1
- package/dist/boards/board-events.d.ts.map +1 -1
- package/dist/boards/card-facts.d.ts +3 -1
- package/dist/boards/card-facts.d.ts.map +1 -1
- package/dist/boards/card-facts.js +26 -4
- package/dist/boards/card-facts.js.map +1 -1
- package/dist/boards/default-board.d.ts +2 -2
- package/dist/boards/default-board.js +2 -2
- package/dist/boards/default-board.js.map +1 -1
- package/dist/boards/define-board.d.ts +1 -1
- package/dist/boards/define-board.d.ts.map +1 -1
- package/dist/boards/define-board.js.map +1 -1
- package/dist/boards/intake-routing.d.ts +3 -5
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js +3 -4
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/project-boards.d.ts +18 -1
- package/dist/boards/project-boards.d.ts.map +1 -1
- package/dist/boards/project-boards.js +40 -3
- package/dist/boards/project-boards.js.map +1 -1
- package/dist/boards/semantics.d.ts +4 -4
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +8 -10
- package/dist/boards/semantics.js.map +1 -1
- package/dist/boards/work-migrations.d.ts +24 -1
- package/dist/boards/work-migrations.d.ts.map +1 -1
- package/dist/boards/work-migrations.js +97 -2
- package/dist/boards/work-migrations.js.map +1 -1
- package/dist/boards/work-routes.d.ts +6 -1
- package/dist/boards/work-routes.d.ts.map +1 -1
- package/dist/boards/work-routes.js +20 -6
- package/dist/boards/work-routes.js.map +1 -1
- package/dist/factory.d.ts +23 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +58 -43
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/integrations/github/default-rules.d.ts.map +1 -1
- package/dist/integrations/github/default-rules.js +3 -5
- package/dist/integrations/github/default-rules.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +0 -6
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +23 -70
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/gitlab/routes.d.ts.map +1 -1
- package/dist/integrations/gitlab/routes.js +1 -3
- package/dist/integrations/gitlab/routes.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +4 -9
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/incidentio/agent-tools.js +5 -5
- package/dist/integrations/incidentio/agent-tools.js.map +1 -1
- package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/default-rules.js.map +1 -1
- package/dist/integrations/incidentio/routes.d.ts +2 -2
- package/dist/integrations/incidentio/routes.d.ts.map +1 -1
- package/dist/integrations/incidentio/routes.js +10 -13
- package/dist/integrations/incidentio/routes.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts +1 -3
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +1 -3
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/jira/binding-scope.d.ts +5 -6
- package/dist/integrations/jira/binding-scope.d.ts.map +1 -1
- package/dist/integrations/jira/binding-scope.js +9 -11
- package/dist/integrations/jira/binding-scope.js.map +1 -1
- package/dist/integrations/jira/default-rules.d.ts.map +1 -1
- package/dist/integrations/jira/default-rules.js.map +1 -1
- package/dist/integrations/jira/routes.d.ts.map +1 -1
- package/dist/integrations/jira/routes.js +3 -5
- package/dist/integrations/jira/routes.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts +1 -3
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +1 -3
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/default-rules.d.ts.map +1 -1
- package/dist/integrations/linear/default-rules.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +11 -14
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts +1 -3
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +1 -3
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/connect/session-tools.d.ts +5 -0
- package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -1
- package/dist/integrations/platform/connect/session-tools.js +5 -0
- package/dist/integrations/platform/connect/session-tools.js.map +1 -1
- package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
- package/dist/integrations/platform/jira/routes.js +3 -5
- package/dist/integrations/platform/jira/routes.js.map +1 -1
- package/dist/routes/automation-runs.d.ts +1 -1
- package/dist/routes/automation-runs.js.map +1 -1
- package/dist/routes/contracts.d.ts +3 -10
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +11 -9
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +6 -1
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/intake.d.ts +0 -23
- package/dist/routes/intake.d.ts.map +1 -1
- package/dist/routes/intake.js +13 -310
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +1 -1
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +0 -2
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +0 -5
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +18 -22
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/rule-group.d.ts +1 -1
- package/dist/rules/rule-group.d.ts.map +1 -1
- package/dist/rules/rule-group.js +13 -5
- package/dist/rules/rule-group.js.map +1 -1
- package/dist/rules/transition-service.d.ts +2 -3
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +0 -1
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +7 -11
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/session/self-review-gate.d.ts +0 -2
- package/dist/session/self-review-gate.d.ts.map +1 -1
- package/dist/session/self-review-gate.js +1 -8
- package/dist/session/self-review-gate.js.map +1 -1
- package/dist/session/source-control-tools.d.ts +39 -13
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +54 -60
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/session/work-item-state-processor.d.ts +1 -4
- package/dist/session/work-item-state-processor.d.ts.map +1 -1
- package/dist/session/work-item-state-processor.js +5 -18
- package/dist/session/work-item-state-processor.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +30 -8
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +43 -25
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/boards/schemas.js.map +1 -1
- package/dist/storage/domains/intake/base.d.ts +5 -45
- package/dist/storage/domains/intake/base.d.ts.map +1 -1
- package/dist/storage/domains/intake/base.js +11 -89
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +17 -9
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +15 -7
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +7 -2
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +4 -0
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/work-items/providers/base.d.ts +4 -1
- package/dist/work-items/providers/base.d.ts.map +1 -1
- package/dist/work-items/providers/base.js +6 -1
- package/dist/work-items/providers/base.js.map +1 -1
- package/dist/work-items/providers/github.d.ts.map +1 -1
- package/dist/work-items/providers/github.js +2 -1
- package/dist/work-items/providers/github.js.map +1 -1
- package/dist/work-items/providers/gitlab.d.ts.map +1 -1
- package/dist/work-items/providers/gitlab.js +2 -1
- package/dist/work-items/providers/gitlab.js.map +1 -1
- package/dist/work-items/providers/jira.d.ts.map +1 -1
- package/dist/work-items/providers/jira.js +3 -2
- package/dist/work-items/providers/jira.js.map +1 -1
- package/dist/work-items/providers/linear.d.ts.map +1 -1
- package/dist/work-items/providers/linear.js +3 -2
- package/dist/work-items/providers/linear.js.map +1 -1
- package/dist/work-items/providers/types.d.ts +6 -0
- package/dist/work-items/providers/types.d.ts.map +1 -1
- package/factory-skills/configure-factory-rules/SKILL.md +2 -2
- package/factory-skills/factory-build/SKILL.md +5 -5
- package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
- package/factory-skills/factory-gitlab-review/SKILL.md +1 -1
- package/factory-skills/factory-rereview/SKILL.md +2 -2
- package/factory-skills/factory-review/SKILL.md +2 -2
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/jira/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Jira intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Jira connections are owned by the caller's Mastra Platform organization;\n * provider requests stay server-side and flow through the integrations v2\n * proxy. Every route re-resolves the authenticated user and scopes intake\n * selections by the caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildPlatformJiraRoutes` returns only `GET /web/jira/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Jira UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { IntakeStorage } from '../../../storage/domains/intake/base.js';\nimport type { WorkItemsStorage } from '../../../storage/domains/work-items/base.js';\nimport { JiraApiError } from '../../jira/api.js';\nimport { scopeJiraSourcesToProject } from '../../jira/binding-scope.js';\nimport { unfilteredJiraScopes } from '../../jira/intake-jql.js';\nimport type { JiraRulesIngress } from '../../jira/rules.js';\nimport type { PlatformJiraIntegration } from './integration.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ISSUE_KEY_RE = /^[A-Za-z][A-Za-z0-9_]*-\\d+$/;\n\n/**\n * Non-secret diagnostic snapshot of every Jira feature gate, mirroring the\n * Linear diagnostics shape. Only booleans — never values.\n */\nexport interface JiraFeatureDiagnostics {\n jiraConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountJiraRoutesOptions {\n /**\n * The integration instance providing REST access. Required for everything\n * beyond the disabled `status` route.\n */\n jira?: PlatformJiraIntegration;\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /** Whether the host configured the application database backing intake state. */\n appDbConfigured: boolean;\n /**\n * Factory rules ingress for observed issues. When present, a board-scoped\n * issue listing also materializes new cards through the Jira event rules —\n * the same automatic intake Linear has.\n */\n ingestFactoryIssues?: (input: JiraRulesIngress) => Promise<unknown>;\n /** Filed cards, so a Factory keeps reading issues it filed after a label filter moves them to another slice. */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource'>;\n}\n\n/**\n * Resolve the org-scoped tenant for a Jira request. Intake selections are\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the Linear routes.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Jira intake requires an organization. Personal accounts cannot use Jira intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Jira pagination cursor from the query string. Cursors are\n * server-issued (`nextPageToken`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Jira.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 512 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map a Jira read failure to the API response for the SPA. */\nfunction jiraFetchError(c: RouteContext, err: unknown) {\n if (err instanceof JiraApiError && err.code === 'jira_auth_failed') {\n return c.json(\n {\n error: 'jira_auth_failed',\n message: 'Jira rejected the connected account. Reconnect it in Mastra Platform.',\n },\n 409,\n );\n }\n return c.json({ error: 'jira_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Jira routes as Mastra `apiRoutes`. When the feature is disabled,\n * returns only the `status` route so the SPA can detect the disabled state.\n */\nexport function buildPlatformJiraRoutes(options: MountJiraRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { jira, auth, intake, workItems } = options;\n const enabled = Boolean(jira) && auth.enabled();\n const diagnostics = (): JiraFeatureDiagnostics => ({\n jiraConfigured: Boolean(jira),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: options.appDbConfigured,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !jira || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(jira),\n mode: 'platform',\n site: null,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: false,\n mode: 'platform',\n organizationRequired: true,\n site: null,\n sites: [],\n connections: [],\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n try {\n const connections = await jira.listConnections();\n const active = connections.filter(connection => connection.status === 'active');\n const sites = active.flatMap(connection => (connection.accountLabel ? [connection.accountLabel] : []));\n return c.json({\n enabled: true,\n configured: active.length > 0,\n mode: 'platform',\n site: sites.length === 1 ? sites[0] : null,\n sites,\n connections,\n reason: active.length > 0 ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !jira || !intake) {\n return routes;\n }\n\n // ── List the site's projects (Settings intake-source picker) ────────────\n routes.push(\n registerApiRoute('/web/jira/projects', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n try {\n const sources = await jira.intake.listSources(resolved.tenant);\n return c.json({\n projects: sources.map(source => ({\n id: source.id,\n name: source.name,\n key: typeof source.metadata?.key === 'string' ? source.metadata.key : null,\n connectionId: typeof source.metadata?.connectionId === 'string' ? source.metadata.connectionId : null,\n site: typeof source.metadata?.site === 'string' ? source.metadata.site : null,\n })),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the site's active issues (cursor-paged) ────────────────────────\n // Respects the caller's intake config: disabled Jira intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/jira/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n\n // No projects selected means nothing is synced — don't fan out to Jira.\n const selectedIds = selection.sourceIds ?? [];\n // A board request only ever sees the projects routed to a board of\n // that Factory project; unscoped listing stays available to callers\n // that don't view a specific board.\n const projectScope = factoryProjectId\n ? await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const intakeBoards = projectScope?.intakeBoards ?? null;\n const scopes = projectScope?.scopes ?? unfilteredJiraScopes(selectedIds);\n if (scopes.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const { issues, nextCursor } = await jira.listActiveIssues(after, scopes);\n const issuePayload = issues.map(issue => ({\n id: issue.externalId,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.author,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee,\n project: issue.source,\n site: issue.site,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId || null,\n }));\n if (factoryProjectId && intakeBoards && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload.map(issue => ({ ...issue, site: issue.site ?? null })),\n intakeBoards,\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/jira/issues/:identifier', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const identifier = c.req.param('identifier');\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!ISSUE_KEY_RE.test(identifier)) return c.json({ error: 'invalid_issue_identifier' }, 400);\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048) return c.json({ error: 'invalid_issue_ref' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n\n const projectScope = await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n const dispatch = await jira.intake.resolveIntakeDispatch?.({\n orgId: resolved.tenant.orgId,\n externalSource: { type: 'issue', externalId: issueRef },\n });\n const sourceId = dispatch?.sourceId;\n if (!dispatch || !sourceId || !(sourceId in projectScope.intakeBoards)) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n\n try {\n const issue = await jira.intake.getIssue(dispatch);\n // An issue in another Factory's slice that this Factory never filed reads like one that doesn't exist.\n if (\n !issue ||\n issue.identifier.toUpperCase() !== identifier.toUpperCase() ||\n !(\n projectScope.takes(sourceId, issue.labels) ||\n !!(await workItems?.getByProjectSource({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n source: { integrationId: 'jira', type: 'issue', externalId: issueRef },\n }))\n )\n ) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n return c.json({\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description,\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return rout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AO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAEjD,OAAO,EAAE,KAAK;KACZ,YAAY,MAAM;KAClB,OAAO,MAAM;KACb,KAAK,MAAM;KACX,aAAa,MAAM;IACrB,CAAC;GACH,SAAS,KAAK;IACZ,OAAO,eAAe,MAAM,CAAC,GAAG,GAAG;GACrC;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/jira/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Jira intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Jira connections are owned by the caller's Mastra Platform organization;\n * provider requests stay server-side and flow through the integrations v2\n * proxy. Every route re-resolves the authenticated user and scopes intake\n * selections by the caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildPlatformJiraRoutes` returns only `GET /web/jira/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Jira UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { IntakeStorage } from '../../../storage/domains/intake/base.js';\nimport type { WorkItemsStorage } from '../../../storage/domains/work-items/base.js';\nimport { JiraApiError } from '../../jira/api.js';\nimport { scopeJiraSourcesToProject } from '../../jira/binding-scope.js';\nimport { unfilteredJiraScopes } from '../../jira/intake-jql.js';\nimport type { JiraRulesIngress } from '../../jira/rules.js';\nimport type { PlatformJiraIntegration } from './integration.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ISSUE_KEY_RE = /^[A-Za-z][A-Za-z0-9_]*-\\d+$/;\n\n/**\n * Non-secret diagnostic snapshot of every Jira feature gate, mirroring the\n * Linear diagnostics shape. Only booleans — never values.\n */\nexport interface JiraFeatureDiagnostics {\n jiraConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountJiraRoutesOptions {\n /**\n * The integration instance providing REST access. Required for everything\n * beyond the disabled `status` route.\n */\n jira?: PlatformJiraIntegration;\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /** Whether the host configured the application database backing intake state. */\n appDbConfigured: boolean;\n /**\n * Factory rules ingress for observed issues. When present, a board-scoped\n * issue listing also materializes new cards through the Jira event rules —\n * the same automatic intake Linear has.\n */\n ingestFactoryIssues?: (input: JiraRulesIngress) => Promise<unknown>;\n /** Filed cards, so a Factory keeps reading issues it filed after a label filter moves them to another slice. */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource'>;\n}\n\n/**\n * Resolve the org-scoped tenant for a Jira request. Intake selections are\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the Linear routes.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Jira intake requires an organization. Personal accounts cannot use Jira intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Jira pagination cursor from the query string. Cursors are\n * server-issued (`nextPageToken`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Jira.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 512 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map a Jira read failure to the API response for the SPA. */\nfunction jiraFetchError(c: RouteContext, err: unknown) {\n if (err instanceof JiraApiError && err.code === 'jira_auth_failed') {\n return c.json(\n {\n error: 'jira_auth_failed',\n message: 'Jira rejected the connected account. Reconnect it in Mastra Platform.',\n },\n 409,\n );\n }\n return c.json({ error: 'jira_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Jira routes as Mastra `apiRoutes`. When the feature is disabled,\n * returns only the `status` route so the SPA can detect the disabled state.\n */\nexport function buildPlatformJiraRoutes(options: MountJiraRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { jira, auth, intake, workItems } = options;\n const enabled = Boolean(jira) && auth.enabled();\n const diagnostics = (): JiraFeatureDiagnostics => ({\n jiraConfigured: Boolean(jira),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: options.appDbConfigured,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !jira || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(jira),\n mode: 'platform',\n site: null,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: false,\n mode: 'platform',\n organizationRequired: true,\n site: null,\n sites: [],\n connections: [],\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n try {\n const connections = await jira.listConnections();\n const active = connections.filter(connection => connection.status === 'active');\n const sites = active.flatMap(connection => (connection.accountLabel ? [connection.accountLabel] : []));\n return c.json({\n enabled: true,\n configured: active.length > 0,\n mode: 'platform',\n site: sites.length === 1 ? sites[0] : null,\n sites,\n connections,\n reason: active.length > 0 ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !jira || !intake) {\n return routes;\n }\n\n // ── List the site's projects (Settings intake-source picker) ────────────\n routes.push(\n registerApiRoute('/web/jira/projects', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n try {\n const sources = await jira.intake.listSources(resolved.tenant);\n return c.json({\n projects: sources.map(source => ({\n id: source.id,\n name: source.name,\n key: typeof source.metadata?.key === 'string' ? source.metadata.key : null,\n connectionId: typeof source.metadata?.connectionId === 'string' ? source.metadata.connectionId : null,\n site: typeof source.metadata?.site === 'string' ? source.metadata.site : null,\n })),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the site's active issues (cursor-paged) ────────────────────────\n // Respects the caller's intake config: disabled Jira intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/jira/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n\n // No projects selected means nothing is synced — don't fan out to Jira.\n const selectedIds = selection.sourceIds ?? [];\n // A board request only ever sees the projects routed to a board of\n // that Factory project; unscoped listing stays available to callers\n // that don't view a specific board.\n const projectScope = factoryProjectId\n ? await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const scopes = projectScope?.scopes ?? unfilteredJiraScopes(selectedIds);\n if (scopes.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const { issues, nextCursor } = await jira.listActiveIssues(after, scopes);\n const issuePayload = issues.map(issue => ({\n id: issue.externalId,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.author,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee,\n project: issue.source,\n site: issue.site,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId || null,\n }));\n if (factoryProjectId && projectScope && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload.map(issue => ({ ...issue, site: issue.site ?? null })),\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/jira/issues/:identifier', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const identifier = c.req.param('identifier');\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!ISSUE_KEY_RE.test(identifier)) return c.json({ error: 'invalid_issue_identifier' }, 400);\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048) return c.json({ error: 'invalid_issue_ref' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n\n const projectScope = await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n const dispatch = await jira.intake.resolveIntakeDispatch?.({\n orgId: resolved.tenant.orgId,\n externalSource: { type: 'issue', externalId: issueRef },\n });\n const sourceId = dispatch?.sourceId;\n if (!dispatch || !sourceId || !projectScope.sourceIds.includes(sourceId)) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n\n try {\n const issue = await jira.intake.getIssue(dispatch);\n // An issue in another Factory's slice that this Factory never filed reads like one that doesn't exist.\n if (\n !issue ||\n issue.identifier.toUpperCase() !== identifier.toUpperCase() ||\n !(\n projectScope.takes(sourceId, issue.labels) ||\n !!(await workItems?.getByProjectSource({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n source: { integrationId: 'jira', type: 'issue', externalId: issueRef },\n }))\n )\n ) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n return c.json({\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description,\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;;;;AA8BA,MAAM,UAAU;AAChB,MAAM,eAAe;;;;;;AA0CrB,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;;;;;;AAOA,SAAS,iBAAi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O,EAAE,KAAK;IAAE,OAAO;IAAwB,SAAS;GAAyC,GAAG,GAAG;GAGzG,MAAM,eAAe,MAAM,0BAA0B;IACnD;IACA,OAAO,SAAS,OAAO;IACvB;IACA,aAAa,UAAU,aAAa,CAAC;GACvC,CAAC;GACD,MAAM,WAAW,MAAM,KAAK,OAAO,wBAAwB;IACzD,OAAO,SAAS,OAAO;IACvB,gBAAgB;KAAE,MAAM;KAAS,YAAY;IAAS;GACxD,CAAC;GACD,MAAM,WAAW,UAAU;GAC3B,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC,aAAa,UAAU,SAAS,QAAQ,GACrE,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;GAGjD,IAAI;IACF,MAAM,QAAQ,MAAM,KAAK,OAAO,SAAS,QAAQ;IAEjD,IACE,CAAC,SACD,MAAM,WAAW,YAAY,MAAM,WAAW,YAAY,KAC1D,EACE,aAAa,MAAM,UAAU,MAAM,MAAM,KACzC,CAAC,CAAE,MAAM,WAAW,mBAAmB;KACrC,OAAO,SAAS,OAAO;KACvB;KACA,QAAQ;MAAE,eAAe;MAAQ,MAAM;MAAS,YAAY;KAAS;IACvE,CAAC,IAGH,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAEjD,OAAO,EAAE,KAAK;KACZ,YAAY,MAAM;KAClB,OAAO,MAAM;KACb,KAAK,MAAM;KACX,aAAa,MAAM;IACrB,CAAC;GACH,SAAS,KAAK;IACZ,OAAO,eAAe,MAAM,CAAC,GAAG,GAAG;GACrC;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* The endpoint is a constrained ingress in front of
|
|
6
6
|
* `WorkItemsStorage.commitRuleEvaluation()`: it commits exactly one
|
|
7
7
|
* `invokeSkill` decision, stamps a non-human system actor, and leaves
|
|
8
|
-
* execution (session creation,
|
|
8
|
+
* execution (session creation, the board's approval policy, retry, restart
|
|
9
9
|
* recovery) to the `FactoryDecisionDispatcher`.
|
|
10
10
|
*
|
|
11
11
|
* Idempotency: the `requestId` becomes the ingress identity, so replaying the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"automation-runs.js","names":[],"sources":["../../src/routes/automation-runs.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for trusted external orchestrators to enqueue an\n * idempotent, deferred skill dispatch against a Factory work item.\n *\n * The endpoint is a constrained ingress in front of\n * `WorkItemsStorage.commitRuleEvaluation()`: it commits exactly one\n * `invokeSkill` decision, stamps a non-human system actor, and leaves\n * execution (session creation, auto-run/approval policy, retry, restart\n * recovery) to the `FactoryDecisionDispatcher`.\n *\n * Idempotency: the `requestId` becomes the ingress identity, so replaying the\n * same request returns the prior result without inserting a second decision.\n * Tenant-mode callers must administer the organization; local (no-auth)\n * deployments run under the shared `local` storage scope without inventing a\n * tenant user.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { boardForWorkItem, createBoardRegistry } from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { workLaneForRole } from '../boards/legacy-plan-role.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { AuditAction } from '../storage/domains/audit/actions.js';\nimport type { AuditTarget } from '../storage/domains/audit/base.js';\nimport type { AuditEmitter, AuditRecorder } from '../storage/domains/audit/domain.js';\nimport { auditRequestContext } from '../storage/domains/audit/domain.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { FACTORY_ROUTE_CONTRACTS } from './contracts.js';\nimport { loose, Route } from './route.js';\nimport type { RouteDependencies } from './route.js';\n\n/** The invokeSkill payload this route commits, matched against a prior replay. */\ninterface AutomationInvokeSkillDecision {\n type: 'invokeSkill';\n idempotencyKey: string;\n role: string;\n skillName: string;\n arguments?: string;\n}\n\n/**\n * Whether a replayed rule-evaluation record describes the SAME operation as the\n * current request. `commitRuleEvaluation` keys idempotency on `(org, project,\n * ingress identity)` alone, so a reused `requestId` replays regardless of the\n * work item or decision payload. We reconstruct the prior `invokeSkill`\n * decision from the stored result and compare the item id, role, skill, and\n * arguments; any divergence is a collision, not a legitimate retry.\n */\nfunction replayMatchesRequest(\n result: { itemId?: string | null; decisions?: unknown[] },\n itemId: string,\n request: AutomationInvokeSkillDecision,\n): boolean {\n if (result.itemId != null && result.itemId !== itemId) return false;\n const decisions = Array.isArray(result.decisions) ? result.decisions : [];\n const prior = decisions.find(\n (candidate): candidate is Record<string, unknown> =>\n typeof candidate === 'object' &&\n candidate !== null &&\n (candidate as Record<string, unknown>).type === 'invokeSkill' &&\n (candidate as Record<string, unknown>).idempotencyKey === request.idempotencyKey,\n );\n if (!prior) return false;\n return (\n prior.role === request.role &&\n prior.skillName === request.skillName &&\n (prior.arguments ?? undefined) === (request.arguments ?? undefined)\n );\n}\n\nexport interface AutomationRunRoutesDeps extends RouteDependencies {\n audit: AuditEmitter & AuditRecorder;\n /** Factory projects domain — validates the `:id` project belongs to the caller's org. */\n projects: FactoryProjectsStorage;\n /** Work-items domain backing `commitRuleEvaluation`. */\n workItems: WorkItemsStorage;\n /** Config version stamped on the committed rule evaluation. */\n configVersion: string;\n /** The project's boards, whose phases name the roles a run can start in; defaults to the built-in boards. */\n boards?: BoardRegistry | ProjectBoardSource;\n}\n\n/** Whether a run decided for `role` has a seat on the board: a working phase runs in its context. */\nfunction boardSeatsRole(board: InstalledBoard | undefined, role: string): boolean {\n if (!board) return false;\n if (workLaneForRole(board, role) !== undefined) return true;\n return Object.values(board.phases).some(phase => phase.kind === 'working' && phase.runner.context === role);\n}\n\n/** Resolved ingress scope for an automation-run request. */\ninterface AutomationRunScope {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n}\n\nexport class AutomationRunRoutes extends Route<AutomationRunRoutesDeps> {\n /**\n * Resolve the `(orgId, userId)` ingress scope. Tenant mode requires a\n * signed-in organization administrator; local (no-auth) mode runs under the\n * shared `local` scope without inventing a user.\n */\n async #resolveScope(c: Context): Promise<{ orgId: string; userId: string } | { response: Response }> {\n const { auth } = this.deps;\n if (!auth.enabled()) {\n return { orgId: 'local', userId: 'local' };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n { error: 'organization_required', message: 'The Factory board requires an organization.' },\n 403,\n ),\n };\n }\n if (!(await auth.isOrganizationAdmin(c, tenant.orgId))) {\n return {\n response: c.json(\n { error: 'forbidden', message: 'Organization administrator access is required for automation ingress.' },\n 403,\n ),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n /** Resolve the ingress scope AND the org-owned project from the `:id` param. */\n async #resolveProject(c: Context): Promise<AutomationRunScope | { response: Response }> {\n const scope = await this.#resolveScope(c);\n if ('response' in scope) return scope;\n\n const parsedPath = FACTORY_ROUTE_CONTRACTS.projectGet.pathSchema.safeParse({ id: c.req.param('id') });\n if (!parsedPath.success) {\n return { response: c.json({ error: 'Project not found' }, 404) };\n }\n const { projects } = this.deps;\n await projects.ensureReady();\n const project = await projects.get({ orgId: scope.orgId, id: parsedPath.data.id });\n if (!project) {\n return { response: c.json({ error: 'Project not found' }, 404) };\n }\n return { ...scope, factoryProjectId: parsedPath.data.id };\n }\n\n /**\n * Persist an audit event under the ingress-resolved scope. This route can run\n * under the synthetic `local` no-auth scope, where the tenant-gated\n * `audit.emit()` derives no org from the request and drops the event; writing\n * through `record()` with the explicit org + system actor keeps traceability\n * in every deployment mode.\n *\n * The `idempotencyKey` (`<action>:<requestId>`) makes the audit write itself\n * idempotent: replaying the same request re-enters this path, but the trail\n * keeps a single event per requestId instead of one duplicate per retry.\n */\n async #writeAudit(\n c: Context,\n scope: AutomationRunScope,\n action: AuditAction,\n requestId: string,\n targets: AuditTarget[],\n metadata: Record<string, unknown>,\n ): Promise<void> {\n await this.deps.audit.record({\n idempotencyKey: `${action}:${requestId}`,\n orgId: scope.orgId,\n actorId: 'factory-external-orchestrator',\n actorType: 'system',\n action,\n targets,\n metadata,\n factoryProjectId: scope.factoryProjectId,\n context: auditRequestContext(c),\n });\n }\n\n routes(): ApiRoute[] {\n const { workItems, configVersion } = this.deps;\n const contract = FACTORY_ROUTE_CONTRACTS.workItemAutomationRun;\n\n return [\n registerApiRoute(contract.path, {\n method: contract.method,\n handler: async c => {\n const context = loose(c);\n const resolved = await this.#resolveProject(context);\n if ('response' in resolved) return resolved.response;\n\n const parsedPath = contract.pathSchema.safeParse({\n id: c.req.param('id'),\n workItemId: c.req.param('workItemId'),\n });\n if (!parsedPath.success) return c.json({ error: 'Work item not found' }, 404);\n\n const body = await c.req.json().catch(() => undefined);\n if (body === undefined) return c.json({ error: 'Invalid JSON body' }, 400);\n const parsed = contract.bodySchema.safeParse(body);\n if (!parsed.success) return c.json({ error: 'invalid_automation_run_request' }, 400);\n const request = parsed.data as {\n requestId: string;\n expectedRevision: number;\n role: string;\n skillName: string;\n arguments?: string;\n };\n\n const item = await workItems.getForProject(\n resolved.orgId,\n resolved.factoryProjectId,\n (parsedPath.data as { workItemId: string }).workItemId,\n );\n if (!item) return c.json({ error: 'Work item not found' }, 404);\n const boards = await toBoardSource(this.deps.boards ?? createBoardRegistry()).load({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n });\n if (!boardSeatsRole(boards.get(boardForWorkItem(item)), request.role)) {\n return c.json({ error: 'invalid_automation_run_request' }, 400);\n }\n\n const idempotencyKey = `external-orchestrator:${request.requestId}`;\n const decision = {\n type: 'invokeSkill' as const,\n idempotencyKey,\n role: request.role,\n skillName: request.skillName,\n ...(request.arguments !== undefined ? { arguments: request.arguments } : {}),\n };\n\n const now = new Date();\n const commit = await workItems.commitRuleEvaluation({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: idempotencyKey, triggerType: 'external-orchestrator.invoke-skill' },\n configVersion,\n expectedRevision: request.expectedRevision,\n actor: { type: 'system', id: 'factory-external-orchestrator' },\n outcome: { status: 'accepted' },\n decisions: [decision],\n causalChain: [],\n now,\n });\n\n if (commit.status === 'missing') return c.json({ error: 'Work item not found' }, 404);\n\n // A stale commit persists nothing, so the caller can retry the same\n // requestId once it has re-read the work item's revision.\n const result = (commit.status === 'stale' ? { status: 'rejected', code: 'stale' } : commit.result) as {\n status?: string;\n code?: string;\n itemId?: string | null;\n decisions?: unknown[];\n };\n const resultStatus = result.status ?? 'accepted';\n const code = typeof result.code === 'string' ? result.code : undefined;\n const targets = [{ type: 'work_item' as const, id: item.id, name: item.title }];\n\n const auditMetadata = {\n requestId: request.requestId,\n role: request.role,\n skillName: request.skillName,\n commitStatus: commit.status,\n resultStatus,\n ...(code ? { code } : {}),\n };\n\n // A replay only means \"this request was already committed\" — it must\n // be the SAME operation. If the caller reused a requestId against a\n // different work item, role, skill, or arguments, returning\n // `replayed` would report durable success for work that was never\n // enqueued. Reject the collision instead of silently swallowing it.\n if (commit.status === 'replayed' && !replayMatchesRequest(result, item.id, decision)) {\n await this.#writeAudit(context, resolved, 'factory.run.rejected', request.requestId, targets, {\n ...auditMetadata,\n resultStatus: 'rejected',\n code: 'request_id_conflict',\n });\n return c.json(\n {\n status: 'rejected',\n code: 'request_id_conflict',\n requestId: request.requestId,\n },\n 409,\n );\n }\n\n if (resultStatus === 'accepted') {\n await this.#writeAudit(context, resolved, 'factory.run.queued', request.requestId, targets, auditMetadata);\n return c.json(\n { status: commit.status === 'replayed' ? 'replayed' : 'committed', requestId: request.requestId },\n commit.status === 'replayed' ? 200 : 202,\n );\n }\n\n await this.#writeAudit(context, resolved, 'factory.run.rejected', request.requestId, targets, auditMetadata);\n return c.json(\n { status: 'rejected', ...(code ? { code } : {}), requestId: request.requestId },\n code === 'stale' ? 409 : 422,\n );\n },\n }),\n ];\n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YAAY,SAAS,UAAU,wBAAwB,QAAQ,WAAW,SAAS,aAAa;IAC3G,OAAO,EAAE,KACP;KAAE,QAAQ;KAAY,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;KAAI,WAAW,QAAQ;IAAU,GAC9E,SAAS,UAAU,MAAM,GAC3B;GACF;EACF,CAAC,CACH;CACF;AACF;AAEA,SAAgB,yBAAyB,MAA2C;CAClF,OAAO,IAAI,oBAAoB,IAAI,CAAC,CAAC,OAAO;AAC9C"}
|
|
1
|
+
{"version":3,"file":"automation-runs.js","names":[],"sources":["../../src/routes/automation-runs.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for trusted external orchestrators to enqueue an\n * idempotent, deferred skill dispatch against a Factory work item.\n *\n * The endpoint is a constrained ingress in front of\n * `WorkItemsStorage.commitRuleEvaluation()`: it commits exactly one\n * `invokeSkill` decision, stamps a non-human system actor, and leaves\n * execution (session creation, the board's approval policy, retry, restart\n * recovery) to the `FactoryDecisionDispatcher`.\n *\n * Idempotency: the `requestId` becomes the ingress identity, so replaying the\n * same request returns the prior result without inserting a second decision.\n * Tenant-mode callers must administer the organization; local (no-auth)\n * deployments run under the shared `local` storage scope without inventing a\n * tenant user.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { boardForWorkItem, createBoardRegistry } from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { workLaneForRole } from '../boards/legacy-plan-role.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { AuditAction } from '../storage/domains/audit/actions.js';\nimport type { AuditTarget } from '../storage/domains/audit/base.js';\nimport type { AuditEmitter, AuditRecorder } from '../storage/domains/audit/domain.js';\nimport { auditRequestContext } from '../storage/domains/audit/domain.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { FACTORY_ROUTE_CONTRACTS } from './contracts.js';\nimport { loose, Route } from './route.js';\nimport type { RouteDependencies } from './route.js';\n\n/** The invokeSkill payload this route commits, matched against a prior replay. */\ninterface AutomationInvokeSkillDecision {\n type: 'invokeSkill';\n idempotencyKey: string;\n role: string;\n skillName: string;\n arguments?: string;\n}\n\n/**\n * Whether a replayed rule-evaluation record describes the SAME operation as the\n * current request. `commitRuleEvaluation` keys idempotency on `(org, project,\n * ingress identity)` alone, so a reused `requestId` replays regardless of the\n * work item or decision payload. We reconstruct the prior `invokeSkill`\n * decision from the stored result and compare the item id, role, skill, and\n * arguments; any divergence is a collision, not a legitimate retry.\n */\nfunction replayMatchesRequest(\n result: { itemId?: string | null; decisions?: unknown[] },\n itemId: string,\n request: AutomationInvokeSkillDecision,\n): boolean {\n if (result.itemId != null && result.itemId !== itemId) return false;\n const decisions = Array.isArray(result.decisions) ? result.decisions : [];\n const prior = decisions.find(\n (candidate): candidate is Record<string, unknown> =>\n typeof candidate === 'object' &&\n candidate !== null &&\n (candidate as Record<string, unknown>).type === 'invokeSkill' &&\n (candidate as Record<string, unknown>).idempotencyKey === request.idempotencyKey,\n );\n if (!prior) return false;\n return (\n prior.role === request.role &&\n prior.skillName === request.skillName &&\n (prior.arguments ?? undefined) === (request.arguments ?? undefined)\n );\n}\n\nexport interface AutomationRunRoutesDeps extends RouteDependencies {\n audit: AuditEmitter & AuditRecorder;\n /** Factory projects domain — validates the `:id` project belongs to the caller's org. */\n projects: FactoryProjectsStorage;\n /** Work-items domain backing `commitRuleEvaluation`. */\n workItems: WorkItemsStorage;\n /** Config version stamped on the committed rule evaluation. */\n configVersion: string;\n /** The project's boards, whose phases name the roles a run can start in; defaults to the built-in boards. */\n boards?: BoardRegistry | ProjectBoardSource;\n}\n\n/** Whether a run decided for `role` has a seat on the board: a working phase runs in its context. */\nfunction boardSeatsRole(board: InstalledBoard | undefined, role: string): boolean {\n if (!board) return false;\n if (workLaneForRole(board, role) !== undefined) return true;\n return Object.values(board.phases).some(phase => phase.kind === 'working' && phase.runner.context === role);\n}\n\n/** Resolved ingress scope for an automation-run request. */\ninterface AutomationRunScope {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n}\n\nexport class AutomationRunRoutes extends Route<AutomationRunRoutesDeps> {\n /**\n * Resolve the `(orgId, userId)` ingress scope. Tenant mode requires a\n * signed-in organization administrator; local (no-auth) mode runs under the\n * shared `local` scope without inventing a user.\n */\n async #resolveScope(c: Context): Promise<{ orgId: string; userId: string } | { response: Response }> {\n const { auth } = this.deps;\n if (!auth.enabled()) {\n return { orgId: 'local', userId: 'local' };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n { error: 'organization_required', message: 'The Factory board requires an organization.' },\n 403,\n ),\n };\n }\n if (!(await auth.isOrganizationAdmin(c, tenant.orgId))) {\n return {\n response: c.json(\n { error: 'forbidden', message: 'Organization administrator access is required for automation ingress.' },\n 403,\n ),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n /** Resolve the ingress scope AND the org-owned project from the `:id` param. */\n async #resolveProject(c: Context): Promise<AutomationRunScope | { response: Response }> {\n const scope = await this.#resolveScope(c);\n if ('response' in scope) return scope;\n\n const parsedPath = FACTORY_ROUTE_CONTRACTS.projectGet.pathSchema.safeParse({ id: c.req.param('id') });\n if (!parsedPath.success) {\n return { response: c.json({ error: 'Project not found' }, 404) };\n }\n const { projects } = this.deps;\n await projects.ensureReady();\n const project = await projects.get({ orgId: scope.orgId, id: parsedPath.data.id });\n if (!project) {\n return { response: c.json({ error: 'Project not found' }, 404) };\n }\n return { ...scope, factoryProjectId: parsedPath.data.id };\n }\n\n /**\n * Persist an audit event under the ingress-resolved scope. This route can run\n * under the synthetic `local` no-auth scope, where the tenant-gated\n * `audit.emit()` derives no org from the request and drops the event; writing\n * through `record()` with the explicit org + system actor keeps traceability\n * in every deployment mode.\n *\n * The `idempotencyKey` (`<action>:<requestId>`) makes the audit write itself\n * idempotent: replaying the same request re-enters this path, but the trail\n * keeps a single event per requestId instead of one duplicate per retry.\n */\n async #writeAudit(\n c: Context,\n scope: AutomationRunScope,\n action: AuditAction,\n requestId: string,\n targets: AuditTarget[],\n metadata: Record<string, unknown>,\n ): Promise<void> {\n await this.deps.audit.record({\n idempotencyKey: `${action}:${requestId}`,\n orgId: scope.orgId,\n actorId: 'factory-external-orchestrator',\n actorType: 'system',\n action,\n targets,\n metadata,\n factoryProjectId: scope.factoryProjectId,\n context: auditRequestContext(c),\n });\n }\n\n routes(): ApiRoute[] {\n const { workItems, configVersion } = this.deps;\n const contract = FACTORY_ROUTE_CONTRACTS.workItemAutomationRun;\n\n return [\n registerApiRoute(contract.path, {\n method: contract.method,\n handler: async c => {\n const context = loose(c);\n const resolved = await this.#resolveProject(context);\n if ('response' in resolved) return resolved.response;\n\n const parsedPath = contract.pathSchema.safeParse({\n id: c.req.param('id'),\n workItemId: c.req.param('workItemId'),\n });\n if (!parsedPath.success) return c.json({ error: 'Work item not found' }, 404);\n\n const body = await c.req.json().catch(() => undefined);\n if (body === undefined) return c.json({ error: 'Invalid JSON body' }, 400);\n const parsed = contract.bodySchema.safeParse(body);\n if (!parsed.success) return c.json({ error: 'invalid_automation_run_request' }, 400);\n const request = parsed.data as {\n requestId: string;\n expectedRevision: number;\n role: string;\n skillName: string;\n arguments?: string;\n };\n\n const item = await workItems.getForProject(\n resolved.orgId,\n resolved.factoryProjectId,\n (parsedPath.data as { workItemId: string }).workItemId,\n );\n if (!item) return c.json({ error: 'Work item not found' }, 404);\n const boards = await toBoardSource(this.deps.boards ?? createBoardRegistry()).load({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n });\n if (!boardSeatsRole(boards.get(boardForWorkItem(item)), request.role)) {\n return c.json({ error: 'invalid_automation_run_request' }, 400);\n }\n\n const idempotencyKey = `external-orchestrator:${request.requestId}`;\n const decision = {\n type: 'invokeSkill' as const,\n idempotencyKey,\n role: request.role,\n skillName: request.skillName,\n ...(request.arguments !== undefined ? { arguments: request.arguments } : {}),\n };\n\n const now = new Date();\n const commit = await workItems.commitRuleEvaluation({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: idempotencyKey, triggerType: 'external-orchestrator.invoke-skill' },\n configVersion,\n expectedRevision: request.expectedRevision,\n actor: { type: 'system', id: 'factory-external-orchestrator' },\n outcome: { status: 'accepted' },\n decisions: [decision],\n causalChain: [],\n now,\n });\n\n if (commit.status === 'missing') return c.json({ error: 'Work item not found' }, 404);\n\n // A stale commit persists nothing, so the caller can retry the same\n // requestId once it has re-read the work item's revision.\n const result = (commit.status === 'stale' ? { status: 'rejected', code: 'stale' } : commit.result) as {\n status?: string;\n code?: string;\n itemId?: string | null;\n decisions?: unknown[];\n };\n const resultStatus = result.status ?? 'accepted';\n const code = typeof result.code === 'string' ? result.code : undefined;\n const targets = [{ type: 'work_item' as const, id: item.id, name: item.title }];\n\n const auditMetadata = {\n requestId: request.requestId,\n role: request.role,\n skillName: request.skillName,\n commitStatus: commit.status,\n resultStatus,\n ...(code ? { code } : {}),\n };\n\n // A replay only means \"this request was already committed\" — it must\n // be the SAME operation. If the caller reused a requestId against a\n // different work item, role, skill, or arguments, returning\n // `replayed` would report durable success for work that was never\n // enqueued. Reject the collision instead of silently swallowing it.\n if (commit.status === 'replayed' && !replayMatchesRequest(result, item.id, decision)) {\n await this.#writeAudit(context, resolved, 'factory.run.rejected', request.requestId, targets, {\n ...auditMetadata,\n resultStatus: 'rejected',\n code: 'request_id_conflict',\n });\n return c.json(\n {\n status: 'rejected',\n code: 'request_id_conflict',\n requestId: request.requestId,\n },\n 409,\n );\n }\n\n if (resultStatus === 'accepted') {\n await this.#writeAudit(context, resolved, 'factory.run.queued', request.requestId, targets, auditMetadata);\n return c.json(\n { status: commit.status === 'replayed' ? 'replayed' : 'committed', requestId: request.requestId },\n commit.status === 'replayed' ? 200 : 202,\n );\n }\n\n await this.#writeAudit(context, resolved, 'factory.run.rejected', request.requestId, targets, auditMetadata);\n return c.json(\n { status: 'rejected', ...(code ? { code } : {}), requestId: request.requestId },\n code === 'stale' ? 409 : 422,\n );\n },\n }),\n ];\n }\n}\n\nexport function buildAutomationRunRoutes(deps: AutomationRunRoutesDeps): ApiRoute[] {\n return new AutomationRunRoutes(deps).routes();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqDA,SAAS,qBACP,QACA,QACA,SACS;CACT,IAAI,OAAO,UAAU,QAAQ,OAAO,WAAW,QAAQ,OAAO;CAE9D,MAAM,SADY,MAAM,QAAQ,OAAO,SAAS,IAAI,OAAO,YAAY,CAAC,EAAA,CAChD,MACrB,cACC,OAAO,cAAc,YACrB,cAAc,QACb,UAAsC,SAAS,iBAC/C,UAAsC,mBAAmB,QAAQ,cACtE;CACA,IAAI,CAAC,OAAO,OAAO;CACnB,OACE,MAAM,SAAS,QAAQ,QACvB,MAAM,cAAc,QAAQ,cAC3B,MAAM,aAAa,KAAA,QAAgB,QAAQ,aAAa,KAAA;AAE7D;;AAeA,SAAS,eAAe,OAAmC,MAAuB;CAChF,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI,gBAAgB,OAAO,IAAI,MAAM,KAAA,GAAW,OAAO;CACvD,OAAO,OAAO,OAAO,MAAM,MAAM,CAAC,CAAC,MAAK,UAAS,MAAM,SAAS,aAAa,MAAM,OAAO,YAAY,IAAI;AAC5G;AASA,IAAa,sBAAb,cAAyC,MAA+B;;;;;;CAMtE,MAAM,cAAc,GAAiF;EACnG,MAAM,EAAE,SAAS,KAAK;EACtB,IAAI,CAAC,KAAK,QAAQ,GAChB,OAAO;GAAE,OAAO;GAAS,QAAQ;EAAQ;EAE3C,MAAM,KAAK,WAAW,CAAC;EACvB,MAAM,SAAS,KAAK,OAAO,CAAC;EAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAA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S,UAAU,sBAAsB,QAAQ,WAAW,SAAS,aAAa;KACzG,OAAO,EAAE,KACP;MAAE,QAAQ,OAAO,WAAW,aAAa,aAAa;MAAa,WAAW,QAAQ;KAAU,GAChG,OAAO,WAAW,aAAa,MAAM,GACvC;IACF;IAEA,MAAM,KAAK,YAAY,SAAS,UAAU,wBAAwB,QAAQ,WAAW,SAAS,aAAa;IAC3G,OAAO,EAAE,KACP;KAAE,QAAQ;KAAY,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;KAAI,WAAW,QAAQ;IAAU,GAC9E,SAAS,UAAU,MAAM,GAC3B;GACF;EACF,CAAC,CACH;CACF;AACF;AAEA,SAAgB,yBAAyB,MAA2C;CAClF,OAAO,IAAI,oBAAoB,IAAI,CAAC,CAAC,OAAO;AAC9C"}
|
|
@@ -74,7 +74,6 @@ export declare const intakeRouteInputSchema: z.ZodObject<{
|
|
|
74
74
|
"work_item.created": "work_item.created";
|
|
75
75
|
"work_item.reopened": "work_item.reopened";
|
|
76
76
|
}>>>;
|
|
77
|
-
allowWorkingPhase: z.ZodOptional<z.ZodBoolean>;
|
|
78
77
|
}, z.core.$strict>;
|
|
79
78
|
/** Changes the named fields; send the `revision` you read so a concurrent edit is not overwritten. */
|
|
80
79
|
export declare const intakeRoutePatchSchema: z.ZodObject<{
|
|
@@ -96,7 +95,6 @@ export declare const intakeRoutePatchSchema: z.ZodObject<{
|
|
|
96
95
|
"work_item.created": "work_item.created";
|
|
97
96
|
"work_item.reopened": "work_item.reopened";
|
|
98
97
|
}>>>;
|
|
99
|
-
allowWorkingPhase: z.ZodOptional<z.ZodBoolean>;
|
|
100
98
|
expectedRevision: z.ZodNumber;
|
|
101
99
|
}, z.core.$strict>;
|
|
102
100
|
export declare const intakeRouteReorderBodySchema: z.ZodObject<{
|
|
@@ -1240,7 +1238,6 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1240
1238
|
"work_item.created": "work_item.created";
|
|
1241
1239
|
"work_item.reopened": "work_item.reopened";
|
|
1242
1240
|
}>>;
|
|
1243
|
-
allowWorkingPhase: z.ZodBoolean;
|
|
1244
1241
|
revision: z.ZodNumber;
|
|
1245
1242
|
createdBy: z.ZodString;
|
|
1246
1243
|
createdAt: z.ZodString;
|
|
@@ -1248,6 +1245,7 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1248
1245
|
updatedAt: z.ZodString;
|
|
1249
1246
|
problems: z.ZodArray<z.ZodString>;
|
|
1250
1247
|
}, z.core.$strip>>;
|
|
1248
|
+
canEdit: z.ZodBoolean;
|
|
1251
1249
|
}, z.core.$strip>;
|
|
1252
1250
|
};
|
|
1253
1251
|
readonly intakeRouteGet: {
|
|
@@ -1280,7 +1278,6 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1280
1278
|
"work_item.created": "work_item.created";
|
|
1281
1279
|
"work_item.reopened": "work_item.reopened";
|
|
1282
1280
|
}>>;
|
|
1283
|
-
allowWorkingPhase: z.ZodBoolean;
|
|
1284
1281
|
revision: z.ZodNumber;
|
|
1285
1282
|
createdBy: z.ZodString;
|
|
1286
1283
|
createdAt: z.ZodString;
|
|
@@ -1293,7 +1290,7 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1293
1290
|
readonly intakeRouteCreate: {
|
|
1294
1291
|
readonly method: 'POST';
|
|
1295
1292
|
readonly path: '/web/factory/projects/:id/intake-routes';
|
|
1296
|
-
readonly description: 'Add an intake route
|
|
1293
|
+
readonly description: 'Add an intake route to a Factory project, after its routes; a route that places new cards goes ahead of the first route that takes every new card';
|
|
1297
1294
|
readonly pathSchema: z.ZodObject<{
|
|
1298
1295
|
id: z.ZodString;
|
|
1299
1296
|
}, z.core.$strip>;
|
|
@@ -1316,7 +1313,6 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1316
1313
|
"work_item.created": "work_item.created";
|
|
1317
1314
|
"work_item.reopened": "work_item.reopened";
|
|
1318
1315
|
}>>>;
|
|
1319
|
-
allowWorkingPhase: z.ZodOptional<z.ZodBoolean>;
|
|
1320
1316
|
}, z.core.$strict>;
|
|
1321
1317
|
readonly responseSchema: z.ZodObject<{
|
|
1322
1318
|
intakeRoute: z.ZodObject<{
|
|
@@ -1340,7 +1336,6 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1340
1336
|
"work_item.created": "work_item.created";
|
|
1341
1337
|
"work_item.reopened": "work_item.reopened";
|
|
1342
1338
|
}>>;
|
|
1343
|
-
allowWorkingPhase: z.ZodBoolean;
|
|
1344
1339
|
revision: z.ZodNumber;
|
|
1345
1340
|
createdBy: z.ZodString;
|
|
1346
1341
|
createdAt: z.ZodString;
|
|
@@ -1377,7 +1372,6 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1377
1372
|
"work_item.created": "work_item.created";
|
|
1378
1373
|
"work_item.reopened": "work_item.reopened";
|
|
1379
1374
|
}>>>;
|
|
1380
|
-
allowWorkingPhase: z.ZodOptional<z.ZodBoolean>;
|
|
1381
1375
|
expectedRevision: z.ZodNumber;
|
|
1382
1376
|
}, z.core.$strict>;
|
|
1383
1377
|
readonly responseSchema: z.ZodObject<{
|
|
@@ -1402,7 +1396,6 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1402
1396
|
"work_item.created": "work_item.created";
|
|
1403
1397
|
"work_item.reopened": "work_item.reopened";
|
|
1404
1398
|
}>>;
|
|
1405
|
-
allowWorkingPhase: z.ZodBoolean;
|
|
1406
1399
|
revision: z.ZodNumber;
|
|
1407
1400
|
createdBy: z.ZodString;
|
|
1408
1401
|
createdAt: z.ZodString;
|
|
@@ -1457,7 +1450,6 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1457
1450
|
"work_item.created": "work_item.created";
|
|
1458
1451
|
"work_item.reopened": "work_item.reopened";
|
|
1459
1452
|
}>>;
|
|
1460
|
-
allowWorkingPhase: z.ZodBoolean;
|
|
1461
1453
|
revision: z.ZodNumber;
|
|
1462
1454
|
createdBy: z.ZodString;
|
|
1463
1455
|
createdAt: z.ZodString;
|
|
@@ -1465,6 +1457,7 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
|
|
|
1465
1457
|
updatedAt: z.ZodString;
|
|
1466
1458
|
problems: z.ZodArray<z.ZodString>;
|
|
1467
1459
|
}, z.core.$strip>>;
|
|
1460
|
+
canEdit: z.ZodBoolean;
|
|
1468
1461
|
}, z.core.$strip>;
|
|
1469
1462
|
};
|
|
1470
1463
|
readonly workItemList: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src/routes/contracts.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEtE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AASxB,eAAO,MAAM,eAAe,EAA4B,CAAC,oBAAoB,EAAE,GAAG,oBAAoB,EAAE,CAAC,CAAC;AAE1G,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC;IACpD,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC;IACvB,WAAW,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC;IACxB,UAAU,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC;IACvB,cAAc,EAAE,CAAC,CAAC,OAAO,CAAC;CAC3B,CAAC;AAEF,eAAO,MAAM,YAAY,kFAAkF,CAAC;AAwB5G,4EAA4E;AAC5E,eAAO,MAAM,oBAAoB;;iBAAsD,CAAC;AACxF,kGAAkG;AAClG,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAAgF,CAAC;AACpH,eAAO,MAAM,sBAAsB;;iBAAiE,CAAC;
|
|
1
|
+
{"version":3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AGd,MAAM,EAAE,MAAM;iBACd,IAAI,EAAE,yEAAyE;iBAC/E,WAAW,EAAE,qCAAqC;iBAClD,UAAU;;;;;;;;;;;;iBACV,cAAc;;;;;iBAGd,MAAM,EAAE,MAAM;iBACd,IAAI,EAAE,yEAAyE;iBAC/E,WAAW,EAAE,+CAA+C;iBAC5D,UAAU;;;;;;;;;;;;iBACV,cAAc;;;;;iBAGd,MAAM,EAAE,KAAK;iBACb,IAAI,EAAE,qBAAqB;iBAC3B,WAAW,EAAE,qEAAqE;iBAClF,WAAW;;;iBACX,cAAc;;;;;;iBAGd,MAAM,EAAE,KAAK;iBACb,IAAI,EAAE,wCAAwC;iBAC9C,WAAW,EAAE,sDAAsD;iBACnE,UAAU;;;;iBACV,UAAU;;;iBACV,cAAc;;;;;iBAGd,MAAM,EAAE,QAAQ;iBAChB,IAAI,EAAE,wCAAwC;iBAC9C,WAAW,EAAE,kEAAkE;iBAC/E,UAAU;;;;iBACV,cAAc;;;;CAEuC,CAAC;AAE1D,MAAM,MAAM,uBAAuB,GAAG,MAAM,OAAO,uBAAuB,CAAC"}
|
package/dist/routes/contracts.js
CHANGED
|
@@ -95,17 +95,14 @@ const intakeRouteFields = {
|
|
|
95
95
|
code: "custom",
|
|
96
96
|
message: problem
|
|
97
97
|
});
|
|
98
|
-
})
|
|
99
|
-
/** Lets an event move an existing card into a working phase, such as Triage. */
|
|
100
|
-
allowWorkingPhase: z.boolean()
|
|
98
|
+
})
|
|
101
99
|
};
|
|
102
100
|
const intakeRouteInputSchema = z.object({
|
|
103
101
|
name: intakeRouteFields.name,
|
|
104
102
|
enabled: intakeRouteFields.enabled.default(true),
|
|
105
103
|
when: intakeRouteFields.when.default(null),
|
|
106
104
|
target: intakeRouteFields.target,
|
|
107
|
-
on: intakeRouteFields.on.optional()
|
|
108
|
-
allowWorkingPhase: intakeRouteFields.allowWorkingPhase.optional()
|
|
105
|
+
on: intakeRouteFields.on.optional()
|
|
109
106
|
}).strict();
|
|
110
107
|
/** Changes the named fields; send the `revision` you read so a concurrent edit is not overwritten. */
|
|
111
108
|
const intakeRoutePatchSchema = z.object({
|
|
@@ -114,7 +111,6 @@ const intakeRoutePatchSchema = z.object({
|
|
|
114
111
|
when: intakeRouteFields.when.optional(),
|
|
115
112
|
target: intakeRouteFields.target.optional(),
|
|
116
113
|
on: intakeRouteFields.on.optional(),
|
|
117
|
-
allowWorkingPhase: intakeRouteFields.allowWorkingPhase.optional(),
|
|
118
114
|
expectedRevision: boardRevisionSchema
|
|
119
115
|
}).strict().refine(({ expectedRevision: _revision, ...fields }) => Object.values(fields).some((value) => value !== void 0), { message: "Change at least one field." });
|
|
120
116
|
const intakeRouteReorderBodySchema = z.object({
|
|
@@ -133,7 +129,6 @@ const intakeRouteSchema = z.object({
|
|
|
133
129
|
joinClosedIssue: z.boolean()
|
|
134
130
|
}),
|
|
135
131
|
on: z.array(z.enum(STATUS_EVENTS)),
|
|
136
|
-
allowWorkingPhase: z.boolean(),
|
|
137
132
|
/** Send it back as `expectedRevision` when editing or deleting. */
|
|
138
133
|
revision: z.number().int(),
|
|
139
134
|
createdBy: z.string(),
|
|
@@ -144,7 +139,11 @@ const intakeRouteSchema = z.object({
|
|
|
144
139
|
problems: z.array(z.string())
|
|
145
140
|
});
|
|
146
141
|
const intakeRouteResponseSchema = z.object({ intakeRoute: intakeRouteSchema });
|
|
147
|
-
const intakeRouteListResponseSchema = z.object({
|
|
142
|
+
const intakeRouteListResponseSchema = z.object({
|
|
143
|
+
intakeRoutes: z.array(intakeRouteSchema),
|
|
144
|
+
/** Whether the caller may add, edit, reorder, or delete routes. */
|
|
145
|
+
canEdit: z.boolean()
|
|
146
|
+
});
|
|
148
147
|
const workItemPathSchema = z.object({ id: uuidSchema });
|
|
149
148
|
const transitionPathSchema = z.object({
|
|
150
149
|
id: uuidSchema,
|
|
@@ -191,10 +190,13 @@ const updateProjectBodySchema = z.object({
|
|
|
191
190
|
defaultModelId: nullableTrimmed(200).optional(),
|
|
192
191
|
modelScope: z.enum(FACTORY_MODEL_SCOPES).optional(),
|
|
193
192
|
defaultThinkingLevel: z.enum(THINKING_LEVELS).optional(),
|
|
193
|
+
/** @deprecated Ignored. Each board phase starts its own runs with `autoStart` and `autoStartWhen`. */
|
|
194
194
|
autoRunEnabled: z.boolean().optional(),
|
|
195
195
|
/** @deprecated Ignored. Plans are approved per board with `exitTool.autoApprove`; Work's always wait for a person. */
|
|
196
196
|
autoApprovePlans: z.boolean().optional(),
|
|
197
|
+
/** @deprecated Ignored. The review skill decides whether to publish its test check. */
|
|
197
198
|
reviewTestChecksEnabled: z.boolean().optional(),
|
|
199
|
+
/** @deprecated Ignored. A card is self-reviewed when its board has a self-review phase. */
|
|
198
200
|
selfReviewEnabled: z.boolean().optional()
|
|
199
201
|
}).refine((input) => Object.keys(input).length > 0, { message: "At least one project field is required" });
|
|
200
202
|
const environmentRepositorySchema = z.object({
|
|
@@ -795,7 +797,7 @@ const FACTORY_ROUTE_CONTRACTS = {
|
|
|
795
797
|
intakeRouteCreate: {
|
|
796
798
|
method: "POST",
|
|
797
799
|
path: "/web/factory/projects/:id/intake-routes",
|
|
798
|
-
description: "Add an intake route
|
|
800
|
+
description: "Add an intake route to a Factory project, after its routes; a route that places new cards goes ahead of the first route that takes every new card",
|
|
799
801
|
pathSchema: projectPathSchema,
|
|
800
802
|
bodySchema: intakeRouteInputSchema,
|
|
801
803
|
responseSchema: intakeRouteResponseSchema
|