@mastra/factory 0.29.0-alpha.3 → 0.29.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.
Files changed (154) hide show
  1. package/README.md +4 -4
  2. package/dist/factory.d.ts.map +1 -1
  3. package/dist/factory.js +2 -10
  4. package/dist/factory.js.map +1 -1
  5. package/dist/index.d.ts +0 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +1 -2
  8. package/dist/integrations/dependabot/rules.d.ts.map +1 -1
  9. package/dist/integrations/dependabot/rules.js +1 -5
  10. package/dist/integrations/dependabot/rules.js.map +1 -1
  11. package/dist/integrations/github/commits.d.ts +0 -21
  12. package/dist/integrations/github/commits.d.ts.map +1 -1
  13. package/dist/integrations/github/commits.js +1 -24
  14. package/dist/integrations/github/commits.js.map +1 -1
  15. package/dist/integrations/github/integration.d.ts +1 -1
  16. package/dist/integrations/github/integration.d.ts.map +1 -1
  17. package/dist/integrations/github/integration.js +2 -6
  18. package/dist/integrations/github/integration.js.map +1 -1
  19. package/dist/integrations/github/routes.d.ts +1 -11
  20. package/dist/integrations/github/routes.d.ts.map +1 -1
  21. package/dist/integrations/github/routes.js +6 -515
  22. package/dist/integrations/github/routes.js.map +1 -1
  23. package/dist/integrations/github/rules.d.ts.map +1 -1
  24. package/dist/integrations/github/rules.js +59 -10
  25. package/dist/integrations/github/rules.js.map +1 -1
  26. package/dist/integrations/gitlab/discovery.d.ts +1 -1
  27. package/dist/integrations/gitlab/discovery.js +1 -1
  28. package/dist/integrations/gitlab/discovery.js.map +1 -1
  29. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  30. package/dist/integrations/gitlab/integration.js +0 -1
  31. package/dist/integrations/gitlab/integration.js.map +1 -1
  32. package/dist/integrations/gitlab/routes.d.ts +0 -2
  33. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  34. package/dist/integrations/gitlab/routes.js +49 -165
  35. package/dist/integrations/gitlab/routes.js.map +1 -1
  36. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/rules.js +20 -7
  38. package/dist/integrations/gitlab/rules.js.map +1 -1
  39. package/dist/integrations/incidentio/routes.d.ts +5 -5
  40. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  41. package/dist/integrations/incidentio/routes.js +3 -59
  42. package/dist/integrations/incidentio/routes.js.map +1 -1
  43. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  44. package/dist/integrations/incidentio/rules.js +1 -5
  45. package/dist/integrations/incidentio/rules.js.map +1 -1
  46. package/dist/integrations/jira/issue-reconciler.d.ts +1 -1
  47. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  48. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  49. package/dist/integrations/jira/routes.d.ts +2 -2
  50. package/dist/integrations/jira/routes.d.ts.map +1 -1
  51. package/dist/integrations/jira/routes.js +0 -68
  52. package/dist/integrations/jira/routes.js.map +1 -1
  53. package/dist/integrations/jira/rules.d.ts.map +1 -1
  54. package/dist/integrations/jira/rules.js +1 -5
  55. package/dist/integrations/jira/rules.js.map +1 -1
  56. package/dist/integrations/linear/routes.d.ts +2 -2
  57. package/dist/integrations/linear/routes.d.ts.map +1 -1
  58. package/dist/integrations/linear/routes.js +0 -83
  59. package/dist/integrations/linear/routes.js.map +1 -1
  60. package/dist/integrations/linear/rules.d.ts.map +1 -1
  61. package/dist/integrations/linear/rules.js +1 -5
  62. package/dist/integrations/linear/rules.js.map +1 -1
  63. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  64. package/dist/integrations/platform/github/integration.js +1 -3
  65. package/dist/integrations/platform/github/integration.js.map +1 -1
  66. package/dist/integrations/platform/jira/routes.d.ts +2 -2
  67. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  68. package/dist/integrations/platform/jira/routes.js +0 -69
  69. package/dist/integrations/platform/jira/routes.js.map +1 -1
  70. package/dist/integrations/vanta/rules.d.ts.map +1 -1
  71. package/dist/integrations/vanta/rules.js +1 -5
  72. package/dist/integrations/vanta/rules.js.map +1 -1
  73. package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
  74. package/dist/routes/automation-runs.d.ts +0 -2
  75. package/dist/routes/automation-runs.d.ts.map +1 -1
  76. package/dist/routes/automation-runs.js +2 -6
  77. package/dist/routes/automation-runs.js.map +1 -1
  78. package/dist/routes/contracts.d.ts +0 -5
  79. package/dist/routes/contracts.d.ts.map +1 -1
  80. package/dist/routes/contracts.js +2 -4
  81. package/dist/routes/contracts.js.map +1 -1
  82. package/dist/routes/fs.d.ts +10 -0
  83. package/dist/routes/fs.d.ts.map +1 -1
  84. package/dist/routes/fs.js +184 -11
  85. package/dist/routes/fs.js.map +1 -1
  86. package/dist/routes/projects.d.ts.map +1 -1
  87. package/dist/routes/projects.js +4 -17
  88. package/dist/routes/projects.js.map +1 -1
  89. package/dist/routes/source-control-sessions.d.ts +0 -3
  90. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  91. package/dist/routes/source-control-sessions.js +0 -19
  92. package/dist/routes/source-control-sessions.js.map +1 -1
  93. package/dist/routes/surface.d.ts +0 -2
  94. package/dist/routes/surface.d.ts.map +1 -1
  95. package/dist/routes/surface.js +1 -12
  96. package/dist/routes/surface.js.map +1 -1
  97. package/dist/rules/dispatcher.d.ts.map +1 -1
  98. package/dist/rules/dispatcher.js +1 -5
  99. package/dist/rules/dispatcher.js.map +1 -1
  100. package/dist/rules/processor.d.ts.map +1 -1
  101. package/dist/rules/processor.js +1 -6
  102. package/dist/rules/processor.js.map +1 -1
  103. package/dist/rules/start-coordinator.js +1 -1
  104. package/dist/rules/start-coordinator.js.map +1 -1
  105. package/dist/rules/transition-service.d.ts.map +1 -1
  106. package/dist/rules/transition-service.js +0 -2
  107. package/dist/rules/transition-service.js.map +1 -1
  108. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  109. package/dist/storage/domains/boards/schemas.js +0 -4
  110. package/dist/storage/domains/boards/schemas.js.map +1 -1
  111. package/dist/storage/domains/intake/base.d.ts +11 -10
  112. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  113. package/dist/storage/domains/intake/base.js +30 -65
  114. package/dist/storage/domains/intake/base.js.map +1 -1
  115. package/dist/storage/domains/integrations/base.d.ts +0 -2
  116. package/dist/storage/domains/integrations/base.d.ts.map +1 -1
  117. package/dist/storage/domains/integrations/base.js +0 -6
  118. package/dist/storage/domains/integrations/base.js.map +1 -1
  119. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  120. package/dist/storage/domains/projects/base.js +0 -12
  121. package/dist/storage/domains/projects/base.js.map +1 -1
  122. package/dist/storage/domains/source-control/base.d.ts +0 -10
  123. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  124. package/dist/storage/domains/source-control/base.js +1 -19
  125. package/dist/storage/domains/source-control/base.js.map +1 -1
  126. package/dist/storage/domains/source-control/inmemory.d.ts +1 -1
  127. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  128. package/dist/storage/domains/source-control/inmemory.js +1 -6
  129. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  130. package/dist/storage/domains/work-items/base.d.ts +1 -36
  131. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  132. package/dist/storage/domains/work-items/base.js +24 -81
  133. package/dist/storage/domains/work-items/base.js.map +1 -1
  134. package/dist/storage/domains/work-items/work-item-schema.d.ts +12 -3
  135. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  136. package/dist/storage/domains/work-items/work-item-schema.js +12 -3
  137. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  138. package/dist/storage/legacy-collections.d.ts +9 -0
  139. package/dist/storage/legacy-collections.d.ts.map +1 -0
  140. package/dist/storage/legacy-collections.js +17 -0
  141. package/dist/storage/legacy-collections.js.map +1 -0
  142. package/dist/workspace.d.ts.map +1 -1
  143. package/dist/workspace.js +1 -3
  144. package/dist/workspace.js.map +1 -1
  145. package/factory-skills/configure-factory-rules/SKILL.md +2 -2
  146. package/package.json +9 -9
  147. package/dist/session/filesystem-capture.d.ts +0 -50
  148. package/dist/session/filesystem-capture.d.ts.map +0 -1
  149. package/dist/session/filesystem-capture.js +0 -229
  150. package/dist/session/filesystem-capture.js.map +0 -1
  151. package/dist/storage/domains/filesystem/base.d.ts +0 -30
  152. package/dist/storage/domains/filesystem/base.d.ts.map +0 -1
  153. package/dist/storage/domains/filesystem/base.js +0 -78
  154. package/dist/storage/domains/filesystem/base.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/incidentio/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryIncidentioRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IncidentioEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface IncidentioIssueIngress {\n /** Stable item reference — the prefixed incident.io follow-up id (`incidentio:follow-up:<ulid>`). */\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 /** Display name of the follow-up creator, when available. */\n author: string | null;\n /** Reference of the incident this follow-up belongs to, when available. */\n incident: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** incident.io source the follow-up was read from. */\n sourceId?: string | null;\n}\n\nexport interface IncidentioRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n incidentioRules: IncidentioEventRules;\n}\n\nexport interface IncidentioRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: IncidentioIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a incident.io sync reports: a follow-up seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open follow-up report none.\n */\nexport function boardEventFor(context: Pick<FactoryIncidentioRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'followUpClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nconst ingressIdFor = (issue: IncidentioIssueIngress) => `incidentio:${issue.id}:${issue.updatedAt}`;\n\nexport class IncidentioRules {\n constructor(private readonly options: IncidentioRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: IncidentioRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'incidentio', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const ingressIds = new Map(input.issues.map(issue => [issue, ingressIdFor(issue)]));\n const recorded = await this.options.storage.listRecordedIngress(\n input.orgId,\n input.factoryProjectId,\n [...ingressIds.values()],\n );\n const statuses: IngressStatus[] = [];\n const failures: unknown[] = [];\n for (const issue of input.issues) {\n if (recorded.has(ingressIds.get(issue)!)) {\n statuses.push('replayed');\n continue;\n }\n // One card per follow-up per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id);\n try {\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n } catch (error) {\n failures.push(error);\n }\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) throw new AggregateError(failures, `${failures.length} incident.io follow-ups failed`);\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: IncidentioRulesIngress,\n issue: IncidentioIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = ingressIdFor(issue);\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed follow-ups without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'followUpClosed' : 'followUpObserved';\n const context: FactoryIncidentioRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'incidentio', id: ingressId },\n cause: `incidentio.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'incidentio-follow-up',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.incidentioRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'incidentio'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.incidentioRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'incidentio'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory incident.io rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: `incidentio.${event}` },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory incident.io rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,MAAM,0BAA0B;;;;;AA6ChC,SAAgB,cAAc,SAAsG;CAClI,IAAI,QAAQ,UAAU,kBACpB,OAAO;EAAE,MAAM;EAAoB,QAAQ,YAAY,QAAQ,MAAM,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iB,QACf,MAAM,QAAQ,MAAM,GAAG,GAAK,IAC5B;GACR;EACF;EACA,IAAI,mBAAmB,YAAY,UAAU,IAAI,iBAAiB;EAClE,IAAI,CAAC,YAAY,CAAC,qBAAqB,QAAQ,WAAW,YAAY;GACpE,MAAM,SAAS,MAAM,mBAAmB,SAAS,KAAK,QAAQ,SAAS;IACrE,OAAO,MAAM;IACb,kBAAkB,MAAM;GAC1B,CAAC;GACD,IAAI,QAAQ,YAAY,CAAC,EAAE,GAAG,OAAO,CAAC;EACxC;EAEA,MAAM,YAAY,MAAM,KAAK,QAAQ,QAAQ,qBAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,aAAa,MAAM;GAC/B,SAAS;IAAE,UAAU;IAAW,aAAa,cAAc;GAAQ;GACnE,eAAe,KAAK,QAAQ;GAC5B,kBAAkB,aAAa,YAAY;GAC3C;GACA;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC;EACD,IAAI,UAAU,WAAW,SAAS;GAEhC,IAAI,WAAW,yBACb,MAAM,IAAI,MAAM,2CAA2C,UAAU,6BAA6B;GAEpG,MAAM,QAAQ,cAAc,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,YAAY;GAAG,CAAC,IAAI;GACzG,IAAI,eAAe,CAAC,OAAO,OAAO;GAClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF"}
1
+ {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/incidentio/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryIncidentioRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IncidentioEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface IncidentioIssueIngress {\n /** Stable item reference — the prefixed incident.io follow-up id (`incidentio:follow-up:<ulid>`). */\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 /** Display name of the follow-up creator, when available. */\n author: string | null;\n /** Reference of the incident this follow-up belongs to, when available. */\n incident: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** incident.io source the follow-up was read from. */\n sourceId?: string | null;\n}\n\nexport interface IncidentioRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n incidentioRules: IncidentioEventRules;\n}\n\nexport interface IncidentioRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: IncidentioIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a incident.io sync reports: a follow-up seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open follow-up report none.\n */\nexport function boardEventFor(context: Pick<FactoryIncidentioRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'followUpClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nconst ingressIdFor = (issue: IncidentioIssueIngress) => `incidentio:${issue.id}:${issue.updatedAt}`;\n\nexport class IncidentioRules {\n constructor(private readonly options: IncidentioRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: IncidentioRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'incidentio', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const ingressIds = new Map(input.issues.map(issue => [issue, ingressIdFor(issue)]));\n const recorded = await this.options.storage.listRecordedIngress(\n input.orgId,\n input.factoryProjectId,\n [...ingressIds.values()],\n );\n const statuses: IngressStatus[] = [];\n const failures: unknown[] = [];\n for (const issue of input.issues) {\n if (recorded.has(ingressIds.get(issue)!)) {\n statuses.push('replayed');\n continue;\n }\n // One card per follow-up per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id);\n try {\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n } catch (error) {\n failures.push(error);\n }\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) throw new AggregateError(failures, `${failures.length} incident.io follow-ups failed`);\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: IncidentioRulesIngress,\n issue: IncidentioIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = ingressIdFor(issue);\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed follow-ups without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'followUpClosed' : 'followUpObserved';\n const context: FactoryIncidentioRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'incidentio', id: ingressId },\n cause: `incidentio.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'incidentio-follow-up',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.incidentioRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'incidentio'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.incidentioRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'incidentio'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory incident.io rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId },\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory incident.io rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,MAAM,0BAA0B;;;;;AA6ChC,SAAgB,cAAc,SAAsG;CAClI,IAAI,QAAQ,UAAU,kBACpB,OAAO;EAAE,MAAM;EAAoB,QAAQ,YAAY,QAAQ,MAAM,cAAc,UAAU;CAAE;CAEjG,OAAO,QAAQ,OAAO,KAAA,IAAY,EAAE,MAAM,oBAAoB;AAChE;AAEA,MAAM,gBAAgB,UAAkC,cAAc,MAAM,GAAG,GAAG,MAAM;AAExF,IAAa,kBAAb,MAA6B;CACE;CAA7B,YAAY,SAAkD;EAAjC,KAAA,UAAA;CAAkC;;CAG/D,QAAQ,OAAwC;EAC9C,OAAO,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,WAAW,KAAK;CAC5D;CAEA,MAAM,OAAO,OAAqF;EAEhG,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAiB,CAAC,GACpF,OAAO;GAAE,QAAQ;GAAW,UAAU;EAAE;EACtD,MAAM,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,KAAK,KAAK;EAGnD,MAAM,KAAK,QAAQ,QAAQ,gBAAgB;GACzC,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,S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AM,IAAI,MAAM,2CAA2C,UAAU,6BAA6B;GAEpG,MAAM,QAAQ,cAAc,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,YAAY;GAAG,CAAC,IAAI;GACzG,IAAI,eAAe,CAAC,OAAO,OAAO;GAClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF"}
@@ -4,7 +4,7 @@ import type { IssueReconciler } from '../issue-reconciler.js';
4
4
  import type { JiraEventRules } from './default-rules.js';
5
5
  import type { JiraIntakeScope } from './intake-jql.js';
6
6
  export type JiraIssueReconciler = IssueReconciler;
7
- /** One page of what a board lists; `externalId` and `site` are set by the Platform integration only. */
7
+ /** One page of the site's active issues; `externalId` and `site` are set by the Platform integration only. */
8
8
  type ListActiveIssues = (cursor: string | undefined, scopes: JiraIntakeScope[]) => Promise<{
9
9
  issues: Array<IntakeIssue & {
10
10
  externalId?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"issue-reconciler.d.ts","sourceRoot":"","sources":["../../../src/integrations/jira/issue-reconciler.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAGrD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAIvD,MAAM,MAAM,mBAAmB,GAAG,eAAe,CAAC;AAqBlD,wGAAwG;AACxG,KAAK,gBAAgB,GAAG,CACtB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,MAAM,EAAE,eAAe,EAAE,KACtB,OAAO,CAAC;IAAE,MAAM,EAAE,KAAK,CAAC,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,KAAK,EAAE,cAAc,CAAC;IAAC,gBAAgB,EAAE,gBAAgB,CAAA;CAAE,EACnF,OAAO,EAAE,kBAAkB,GAC1B,mBAAmB,GAAG,SAAS,CAuEjC"}
@@ -1 +1 @@
1
- {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/jira/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { Intake, IntakeIssue } from '../../capabilities/intake.js';\nimport type { IntegrationContext } from '../base.js';\nimport { withIntakeDiscovery } from '../intake-discovery.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport { scopeJiraSourcesToProject } from './binding-scope.js';\nimport type { JiraEventRules } from './default-rules.js';\nimport type { JiraIntakeScope } from './intake-jql.js';\nimport { JiraRules } from './rules.js';\nimport type { JiraIssueIngress } from './rules.js';\n\nexport type JiraIssueReconciler = IssueReconciler;\n\nfunction issueToIngress(issueRef: string, issue: IntakeIssue): JiraIssueIngress {\n return {\n id: issueRef,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n author: issue.author ?? null,\n project: issue.source ?? null,\n site: null,\n labels: [...(issue.labels ?? [])],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\n/** One page of what a board lists; `externalId` and `site` are set by the Platform integration only. */\ntype ListActiveIssues = (\n cursor: string | undefined,\n scopes: JiraIntakeScope[],\n) => Promise<{ issues: Array<IntakeIssue & { externalId?: string; site?: string }>; nextCursor: string | null }>;\n\n/**\n * One Jira sweep: refresh carded issues (metadata, closes), then list what\n * every project's board shows so issues nobody has carded yet get their card.\n * Jira sends Factory no events, so this is the only first-sight path.\n */\nexport function attachJiraIssueReconciler(\n jira: { intake: Intake; rules: JiraEventRules; listActiveIssues: ListActiveIssues },\n context: IntegrationContext,\n): JiraIssueReconciler | undefined {\n if (!context.runtime || !jira.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new JiraRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n jiraRules: jira.rules,\n });\n\n const reconcile = createIssueReconciler({\n integrationId: 'jira',\n intake: jira.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n ...(context.runtime.keptCards ? { cards: context.runtime.keptCards } : {}),\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => item.externalSource?.externalId,\n metadata: (item, issue) => ({\n identifier: issue.identifier,\n issueRef: item.externalSource?.externalId ?? issue.id,\n autoStartCandidate: issue.stateType === 'unstarted' || issue.stateType === 'started',\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priority,\n project: issue.source,\n assignee: issue.assignee,\n assignees: issue.assignees ?? [],\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(item.externalSource?.externalId ?? issue.id, issue)],\n });\n },\n });\n\n return withIntakeDiscovery(reconcile, {\n integrationId: 'jira',\n intake: context.storage.intake,\n projects: context.storage.projects,\n open: async (project, selectedIds) => {\n const { scopes } = await scopeJiraSourcesToProject({\n intake: context.storage.intake,\n orgId: project.orgId,\n factoryProjectId: project.id,\n selectedIds,\n });\n return scopes.map(scope => async (cursor: string | undefined) => {\n const page = await jira.listActiveIssues(cursor, [scope]);\n return {\n issues: page.issues.map(issue => ({\n ...issueToIngress(issue.externalId ?? issue.id, issue),\n site: issue.site ?? null,\n sourceId: issue.sourceId,\n })),\n nextCursor: page.nextCursor,\n };\n });\n },\n ingest: input => rules.ingest(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a,CAAC;GAC/B,SAAS,MAAM;GACf,QAAQ,MAAM;GACd,QAAQ,MAAM,UAAU,CAAC;GACzB,WAAW,MAAM;GACjB,WAAW,MAAM;EACnB;EACA,UAAU,OAAO,MAAM,OAAO,YAAY;GACxC,MAAM,MAAM,OAAO;IACjB,OAAO,QAAQ;IACf,QAAQ;IACR,kBAAkB,QAAQ;IAC1B,QAAQ,CAAC,eAAe,KAAK,gBAAgB,cAAc,MAAM,IAAI,KAAK,CAAC;GAC7E,CAAC;EACH;CACF,CAAC;CAED,OAAO,oBAAoB,WAAW;EACpC,eAAe;EACf,QAAQ,QAAQ,QAAQ;EACxB,UAAU,QAAQ,QAAQ;EAC1B,MAAM,OAAO,SAAS,gBAAgB;GACpC,MAAM,EAAE,WAAW,MAAM,0BAA0B;IACjD,QAAQ,QAAQ,QAAQ;IACxB,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B;GACF,CAAC;GACD,OAAO,OAAO,KAAI,UAAS,OAAO,WAA+B;IAC/D,MAAM,OAAO,MAAM,KAAK,iBAAiB,QAAQ,CAAC,KAAK,CAAC;IACxD,OAAO;KACL,QAAQ,KAAK,OAAO,KAAI,WAAU;MAChC,GAAG,eAAe,MAAM,cAAc,MAAM,IAAI,KAAK;MACrD,MAAM,MAAM,QAAQ;MACpB,UAAU,MAAM;KAClB,EAAE;KACF,YAAY,KAAK;IACnB;GACF,CAAC;EACH;EACA,SAAQ,UAAS,MAAM,OAAO,KAAK;CACrC,CAAC;AACH"}
1
+ {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/jira/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { Intake, IntakeIssue } from '../../capabilities/intake.js';\nimport type { IntegrationContext } from '../base.js';\nimport { withIntakeDiscovery } from '../intake-discovery.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport { scopeJiraSourcesToProject } from './binding-scope.js';\nimport type { JiraEventRules } from './default-rules.js';\nimport type { JiraIntakeScope } from './intake-jql.js';\nimport { JiraRules } from './rules.js';\nimport type { JiraIssueIngress } from './rules.js';\n\nexport type JiraIssueReconciler = IssueReconciler;\n\nfunction issueToIngress(issueRef: string, issue: IntakeIssue): JiraIssueIngress {\n return {\n id: issueRef,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n author: issue.author ?? null,\n project: issue.source ?? null,\n site: null,\n labels: [...(issue.labels ?? [])],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\n/** One page of the site's active issues; `externalId` and `site` are set by the Platform integration only. */\ntype ListActiveIssues = (\n cursor: string | undefined,\n scopes: JiraIntakeScope[],\n) => Promise<{ issues: Array<IntakeIssue & { externalId?: string; site?: string }>; nextCursor: string | null }>;\n\n/**\n * One Jira sweep: refresh carded issues (metadata, closes), then list what\n * every project's board shows so issues nobody has carded yet get their card.\n * Jira sends Factory no events, so this is the only first-sight path.\n */\nexport function attachJiraIssueReconciler(\n jira: { intake: Intake; rules: JiraEventRules; listActiveIssues: ListActiveIssues },\n context: IntegrationContext,\n): JiraIssueReconciler | undefined {\n if (!context.runtime || !jira.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new JiraRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n jiraRules: jira.rules,\n });\n\n const reconcile = createIssueReconciler({\n integrationId: 'jira',\n intake: jira.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n ...(context.runtime.keptCards ? { cards: context.runtime.keptCards } : {}),\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => item.externalSource?.externalId,\n metadata: (item, issue) => ({\n identifier: issue.identifier,\n issueRef: item.externalSource?.externalId ?? issue.id,\n autoStartCandidate: issue.stateType === 'unstarted' || issue.stateType === 'started',\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priority,\n project: issue.source,\n assignee: issue.assignee,\n assignees: issue.assignees ?? [],\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(item.externalSource?.externalId ?? issue.id, issue)],\n });\n },\n });\n\n return withIntakeDiscovery(reconcile, {\n integrationId: 'jira',\n intake: context.storage.intake,\n projects: context.storage.projects,\n open: async (project, selectedIds) => {\n const { scopes } = await scopeJiraSourcesToProject({\n intake: context.storage.intake,\n orgId: project.orgId,\n factoryProjectId: project.id,\n selectedIds,\n });\n return scopes.map(scope => async (cursor: string | undefined) => {\n const page = await jira.listActiveIssues(cursor, [scope]);\n return {\n issues: page.issues.map(issue => ({\n ...issueToIngress(issue.externalId ?? issue.id, issue),\n site: issue.site ?? null,\n sourceId: issue.sourceId,\n })),\n nextCursor: page.nextCursor,\n };\n });\n },\n ingest: input => rules.ingest(input),\n });\n}\n"],"mappings":";;;;;;;;AAeA,SAAS,eAAe,UAAkB,OAAsC;CAC9E,OAAO;EACL,IAAI;EACJ,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,KAAK,MAAM;EACX,OAAO,MAAM,SAAS;EACtB,WAAW,MAAM,aAAa;EAC9B,eAAe,MAAM,YAAY;EACjC,UAAU,MAAM,YAAY;EAC5B,QAAQ,MAAM,UAAU;EACxB,SAAS,MAAM,UAAU;EACzB,MAAM;EACN,QAAQ,CAAC,GAAI,MAAM,UAAU,CAAC,CAAE;EAChC,WAAW,MAAM;EACjB,WAAW,MAAM;CACnB;AACF;;;;;;AAaA,SAAgB,0BACd,MACA,SACiC;CACjC,IAAI,CAAC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AAgB;GACpC,MAAM,EAAE,WAAW,MAAM,0BAA0B;IACjD,QAAQ,QAAQ,QAAQ;IACxB,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B;GACF,CAAC;GACD,OAAO,OAAO,KAAI,UAAS,OAAO,WAA+B;IAC/D,MAAM,OAAO,MAAM,KAAK,iBAAiB,QAAQ,CAAC,KAAK,CAAC;IACxD,OAAO;KACL,QAAQ,KAAK,OAAO,KAAI,WAAU;MAChC,GAAG,eAAe,MAAM,cAAc,MAAM,IAAI,KAAK;MACrD,MAAM,MAAM,QAAQ;MACpB,UAAU,MAAM;KAClB,EAAE;KACF,YAAY,KAAK;IACnB;GACF,CAAC;EACH;EACA,SAAQ,UAAS,MAAM,OAAO,KAAK;CACrC,CAAC;AACH"}
@@ -35,8 +35,8 @@ export interface MountJiraRoutesOptions {
35
35
  /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */
36
36
  auth: RouteAuth;
37
37
  /**
38
- * Cross-integration intake selection domain. Required for the issues route's
39
- * project filter; when absent, only the disabled `status` route is served.
38
+ * Cross-integration intake selection domain. Required for the issue detail
39
+ * route's project filter; when absent, only the disabled `status` route is served.
40
40
  */
41
41
  intake?: IntakeStorage;
42
42
  /** Filed cards, so a Factory keeps reading issues it filed after a label filter moves them to another slice. */
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/integrations/jira/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAKjF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAOxD;;;GAGG;AACH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,gBAAgB,EAAE,oBAAoB,CAAC,CAAC;CAC1D;AA0CD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,QAAQ,EAAE,CAqJ3E"}
@@ -1,7 +1,6 @@
1
1
  import { loose } from "../../routes/route.js";
2
2
  import { JiraApiError } from "./api.js";
3
3
  import { scopeJiraSourcesToProject } from "./binding-scope.js";
4
- import { unfilteredJiraScopes } from "./intake-jql.js";
5
4
  import { DEPLOYMENT_CONNECTION } from "./integration.js";
6
5
  import { registerApiRoute } from "@mastra/core/server";
7
6
  // src/integrations/jira/routes.ts
@@ -25,16 +24,6 @@ async function resolveOrgTenant(c, auth) {
25
24
  userId: tenant.userId
26
25
  } };
27
26
  }
28
- /**
29
- * Validate an opaque Jira pagination cursor from the query string. Cursors are
30
- * server-issued (`nextPageToken`), so anything outside a conservative
31
- * charset/length is rejected rather than forwarded to Jira.
32
- */
33
- function parseAfterCursor(raw) {
34
- if (raw === void 0 || raw === "") return void 0;
35
- if (raw.length > 512 || !/^[\w+/=.:-]+$/.test(raw)) return null;
36
- return raw;
37
- }
38
27
  /** Map a Jira read failure to the API response for the SPA. */
39
28
  function jiraFetchError(c, err) {
40
29
  if (err instanceof JiraApiError && err.code === "jira_auth_failed") return c.json({
@@ -116,63 +105,6 @@ function buildJiraRoutes(options) {
116
105
  }
117
106
  }
118
107
  }));
119
- routes.push(registerApiRoute("/web/jira/issues", {
120
- method: "GET",
121
- requiresAuth: false,
122
- handler: async (c) => {
123
- const resolved = await resolveOrgTenant(loose(c), auth);
124
- if ("response" in resolved) return resolved.response;
125
- const after = parseAfterCursor(c.req.query("after"));
126
- if (after === null) return c.json({ error: "invalid_cursor" }, 400);
127
- const factoryProjectId = c.req.query("factoryProjectId");
128
- if (factoryProjectId && !UUID_RE.test(factoryProjectId)) return c.json({ error: "invalid_factory_project_id" }, 400);
129
- await intake.ensureReady();
130
- const selection = (await intake.getConfig({
131
- orgId: resolved.tenant.orgId,
132
- integrationIds: ["jira"]
133
- })).jira;
134
- if (!selection.enabled) return c.json({
135
- error: "jira_intake_disabled",
136
- message: "Jira intake is turned off in Settings."
137
- }, 404);
138
- const selectedIds = selection.sourceIds ?? [];
139
- const scopes = (factoryProjectId ? await scopeJiraSourcesToProject({
140
- intake,
141
- orgId: resolved.tenant.orgId,
142
- factoryProjectId,
143
- selectedIds
144
- }) : null)?.scopes ?? unfilteredJiraScopes(selectedIds);
145
- if (scopes.length === 0) return c.json({
146
- issues: [],
147
- nextCursor: null
148
- });
149
- try {
150
- const { issues, nextCursor } = await jira.listActiveIssues(after, scopes);
151
- const issuePayload = issues.map((issue) => ({
152
- id: issue.id,
153
- identifier: issue.identifier,
154
- title: issue.title,
155
- url: issue.url,
156
- author: issue.author,
157
- state: issue.state ?? "",
158
- stateType: issue.stateType ?? "",
159
- priorityLabel: issue.priority ?? "",
160
- assignee: issue.assignee,
161
- project: issue.source,
162
- labels: issue.labels,
163
- createdAt: issue.createdAt,
164
- updatedAt: issue.updatedAt,
165
- sourceId: issue.sourceId || null
166
- }));
167
- return c.json({
168
- issues: issuePayload,
169
- nextCursor
170
- });
171
- } catch (err) {
172
- return jiraFetchError(loose(c), err);
173
- }
174
- }
175
- }));
176
108
  routes.push(registerApiRoute("/web/jira/issues/:identifier", {
177
109
  method: "GET",
178
110
  requiresAuth: false,
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/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 * Mirrors the Linear module minus everything OAuth: there is no\n * connect/callback flow, no state signer, and no per-org connection storage —\n * Jira credentials are deployment-global constructor config on the\n * integration instance. Every route still re-resolves the authenticated user\n * from the request and scopes intake selections by the caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildJiraRoutes` 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 './api.js';\nimport { scopeJiraSourcesToProject } from './binding-scope.js';\nimport { unfilteredJiraScopes } from './intake-jql.js';\nimport { DEPLOYMENT_CONNECTION } from './integration.js';\nimport type { JiraIntegration } 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?: JiraIntegration;\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 /** 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 configured credentials. Check JIRA_EMAIL and JIRA_API_TOKEN.',\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 buildJiraRoutes(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: true,\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: 'direct',\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 const site = new URL(jira.baseUrl).host;\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: true,\n mode: 'direct',\n organizationRequired: true,\n site,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n // Deployment-global credentials: configured means ready — there is no\n // per-org connection step like Linear's OAuth.\n return c.json({\n enabled: true,\n configured: true,\n mode: 'direct',\n site,\n reason: 'ready',\n diagnostics: diagnostics(),\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 })),\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.id,\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 labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId || null,\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 const projectScope = await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (projectScope.scopes.length === 0) return c.json({ error: 'issue_not_found' }, 404);\n\n try {\n const issue = await jira.intake.getIssue({ connection: DEPLOYMENT_CONNECTION, issueId: issueRef });\n // An unbound project's issue, or one in another Factory's slice that this\n // Factory never filed, reads like one that doesn't exist (as on Linear).\n const routed =\n issue?.sourceId != null &&\n projectScope.sourceIds.includes(issue.sourceId) &&\n (projectScope.takes(issue.sourceId, issue.labels) ||\n !!(await workItems?.getByProjectSource({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n source: { integrationId: 'jira', type: 'issue', externalId: issue.id },\n })));\n if (!issue || issue.identifier.toUpperCase() !== identifier.toUpperCase() || !routed) {\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":";;;;;;;AA+BA,MAAM,UAAU;AAChB,MAAM,eAAe;;;;;;AAkCrB,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,iBAAiB,KAAoD;CAC5E,IAAI,QAAQ,KAAA,KAAa,QAAQ,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ACZ,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/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 * Mirrors the Linear module minus everything OAuth: there is no\n * connect/callback flow, no state signer, and no per-org connection storage —\n * Jira credentials are deployment-global constructor config on the\n * integration instance. Every route still re-resolves the authenticated user\n * from the request and scopes intake selections by the caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildJiraRoutes` 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 './api.js';\nimport { scopeJiraSourcesToProject } from './binding-scope.js';\nimport { DEPLOYMENT_CONNECTION } from './integration.js';\nimport type { JiraIntegration } 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?: JiraIntegration;\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 issue detail\n * route's project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\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/** 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 configured credentials. Check JIRA_EMAIL and JIRA_API_TOKEN.',\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 buildJiraRoutes(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: true,\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: 'direct',\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 const site = new URL(jira.baseUrl).host;\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: true,\n mode: 'direct',\n organizationRequired: true,\n site,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n // Deployment-global credentials: configured means ready — there is no\n // per-org connection step like Linear's OAuth.\n return c.json({\n enabled: true,\n configured: true,\n mode: 'direct',\n site,\n reason: 'ready',\n diagnostics: diagnostics(),\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 })),\n });\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 const projectScope = await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (projectScope.scopes.length === 0) return c.json({ error: 'issue_not_found' }, 404);\n\n try {\n const issue = await jira.intake.getIssue({ connection: DEPLOYMENT_CONNECTION, issueId: issueRef });\n // An unbound project's issue, or one in another Factory's slice that this\n // Factory never filed, reads like one that doesn't exist (as on Linear).\n const routed =\n issue?.sourceId != null &&\n projectScope.sourceIds.includes(issue.sourceId) &&\n (projectScope.takes(issue.sourceId, issue.labels) ||\n !!(await workItems?.getByProjectSource({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n source: { integrationId: 'jira', type: 'issue', externalId: issue.id },\n })));\n if (!issue || issue.identifier.toUpperCase() !== identifier.toUpperCase() || !routed) {\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;;;;;;AAkCrB,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QA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AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,IAAI,CAAC,sBAAsB,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC,GAAG,eAAe,GAAG,SAAS,CAK5H;AAED,qBAAa,SAAS;;IACR,OAAO,CAAC,QAAQ,CAAC,OAAO;IAApC,YAA6B,OAAO,EAAE,gBAAgB,EAAI;IAOpD,MAAM,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,aAAa,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CA4B1F;CA2HF"}
@@ -161,11 +161,7 @@ var JiraRules = class {
161
161
  orgId: input.orgId,
162
162
  factoryProjectId: input.factoryProjectId,
163
163
  workItemId: relatedItem?.id ?? null,
164
- ingress: {
165
- identity: ingressId,
166
- triggerType: "jira.issueObserved"
167
- },
168
- configVersion: this.options.configVersion,
164
+ ingress: { identity: ingressId },
169
165
  expectedRevision: relatedItem?.revision ?? null,
170
166
  actor,
171
167
  outcome,
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/jira/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryJiraRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { JiraEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface JiraIssueIngress {\n /** Stable issue reference — direct Jira id or the Platform-encoded issue reference. */\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 /** Display name of the Jira reporter, when available. */\n author: string | null;\n /** Jira project key the issue belongs to, when available. */\n project: string | null;\n /** Jira site host the issue was read from, when available. */\n site: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Jira source the issue was read from. */\n sourceId?: string | null;\n}\n\nexport interface JiraRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n jiraRules: JiraEventRules;\n}\n\nexport interface JiraRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: JiraIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Jira sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryJiraRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nexport class JiraRules {\n constructor(private readonly options: JiraRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: JiraRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'jira', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n // A card filed by hand from Settings › Intake holds the issue key, while the\n // sweep names the issue by its id. Its browse URL names both the site and the key.\n const itemsByUrl = new Map(\n items.flatMap(item => (item.externalSource?.url ? [[item.externalSource.url, item] as const] : [])),\n );\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Jira issue per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id) ?? itemsByUrl.get(issue.url);\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: JiraRulesIngress,\n issue: JiraIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `jira:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const context: FactoryJiraRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'jira', id: ingressId },\n cause: `jira.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'jira-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Jira rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: 'jira.issueObserved' },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Jira rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,MAAM,0BAA0B;;;;;AA+ChC,SAAgB,cAAc,SAAgG;CAC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AE,GAAG,OAAO,CAAC;EACxC;EAEA,MAAM,YAAY,MAAM,KAAK,QAAQ,QAAQ,qBAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,aAAa,MAAM;GAC/B,SAAS;IAAE,UAAU;IAAW,aAAa;GAAqB;GAClE,eAAe,KAAK,QAAQ;GAC5B,kBAAkB,aAAa,YAAY;GAC3C;GACA;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC;EACD,IAAI,UAAU,WAAW,SAAS;GAEhC,IAAI,WAAW,yBACb,MAAM,IAAI,MAAM,oCAAoC,UAAU,6BAA6B;GAE7F,MAAM,QAAQ,cAAc,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,YAAY;GAAG,CAAC,IAAI;GACzG,IAAI,eAAe,CAAC,OAAO,OAAO;GAClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF"}
1
+ {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/jira/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryJiraRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { JiraEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface JiraIssueIngress {\n /** Stable issue reference — direct Jira id or the Platform-encoded issue reference. */\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 /** Display name of the Jira reporter, when available. */\n author: string | null;\n /** Jira project key the issue belongs to, when available. */\n project: string | null;\n /** Jira site host the issue was read from, when available. */\n site: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Jira source the issue was read from. */\n sourceId?: string | null;\n}\n\nexport interface JiraRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n jiraRules: JiraEventRules;\n}\n\nexport interface JiraRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: JiraIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Jira sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryJiraRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nexport class JiraRules {\n constructor(private readonly options: JiraRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: JiraRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'jira', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n // A card filed by hand from Settings › Intake holds the issue key, while the\n // sweep names the issue by its id. Its browse URL names both the site and the key.\n const itemsByUrl = new Map(\n items.flatMap(item => (item.externalSource?.url ? [[item.externalSource.url, item] as const] : [])),\n );\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Jira issue per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id) ?? itemsByUrl.get(issue.url);\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: JiraRulesIngress,\n issue: JiraIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `jira:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const context: FactoryJiraRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'jira', id: ingressId },\n cause: `jira.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'jira-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Jira rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId },\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Jira rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,MAAM,0BAA0B;;;;;AA+ChC,SAAgB,cAAc,SAAgG;CAC5H,IAAI,QAAQ,UAAU,eACpB,OAAO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MAAM,YAAY,MAAM,KAAK,QAAQ,QAAQ,qBAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,aAAa,MAAM;GAC/B,SAAS,EAAE,UAAU,UAAU;GAC/B,kBAAkB,aAAa,YAAY;GAC3C;GACA;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC;EACD,IAAI,UAAU,WAAW,SAAS;GAEhC,IAAI,WAAW,yBACb,MAAM,IAAI,MAAM,oCAAoC,UAAU,6BAA6B;GAE7F,MAAM,QAAQ,cAAc,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,YAAY;GAAG,CAAC,IAAI;GACzG,IAAI,eAAe,CAAC,OAAO,OAAO;GAClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF"}
@@ -69,8 +69,8 @@ export interface MountLinearRoutesOptions {
69
69
  */
70
70
  stateSigner?: StateSigner;
71
71
  /**
72
- * Cross-integration intake selection domain. Required for the issues route's
73
- * project filter; when absent, only the disabled `status` route is served.
72
+ * Cross-integration intake selection domain. Required for the issue detail route's
73
+ * routing check; when absent, only the disabled `status` route is served.
74
74
  */
75
75
  intake?: IntakeStorage;
76
76
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEzE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,C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,GAAG,kBAAkB,CAAC;CAC7C;AAuGD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,QAAQ,EAAE,CAwQ/E"}
@@ -41,16 +41,6 @@ async function resolveOrgTenant(c, auth) {
41
41
  userId: tenant.userId
42
42
  } };
43
43
  }
44
- /**
45
- * Validate an opaque Linear pagination cursor from the query string. Cursors
46
- * are server-issued (`pageInfo.endCursor`), so anything outside a conservative
47
- * charset/length is rejected rather than forwarded to Linear.
48
- */
49
- function parseAfterCursor(raw) {
50
- if (raw === void 0 || raw === "") return void 0;
51
- if (raw.length > 8192 || !/^[\w+/=.:-]+$/.test(raw)) return null;
52
- return raw;
53
- }
54
44
  /** Human issue key as it appears on a card (`ENG-123`). */
55
45
  const ISSUE_IDENTIFIER_RE = /^[A-Za-z][A-Za-z0-9]{0,9}-\d{1,7}$/;
56
46
  /** Project sources are more specific than their team and win every routed read. */
@@ -249,79 +239,6 @@ function buildLinearRoutes(options) {
249
239
  }
250
240
  }
251
241
  }));
252
- routes.push(registerApiRoute("/web/linear/issues", {
253
- method: "GET",
254
- requiresAuth: false,
255
- handler: async (c) => {
256
- const resolved = await resolveOrgTenant(loose(c), auth);
257
- if ("response" in resolved) return resolved.response;
258
- const after = parseAfterCursor(c.req.query("after"));
259
- if (after === null) return c.json({ error: "invalid_cursor" }, 400);
260
- const factoryProjectId = c.req.query("factoryProjectId");
261
- if (factoryProjectId && !UUID_RE.test(factoryProjectId)) return c.json({ error: "invalid_factory_project_id" }, 400);
262
- const connection = await linear.loadConnection(resolved.tenant.orgId);
263
- if (!connection) return c.json({
264
- error: "linear_not_connected",
265
- message: "Connect Linear to see intake issues."
266
- }, 409);
267
- await intake.ensureReady();
268
- const selection = (await intake.getConfig({
269
- orgId: resolved.tenant.orgId,
270
- integrationIds: ["linear"]
271
- })).linear;
272
- if (!selection.enabled) return c.json({
273
- error: "linear_intake_disabled",
274
- message: "Linear intake is turned off in Settings."
275
- }, 404);
276
- const selectedIds = selection.sourceIds ?? [];
277
- const boundSourceIds = factoryProjectId ? await scopeSourceIdsToProject({
278
- intake,
279
- orgId: resolved.tenant.orgId,
280
- factoryProjectId,
281
- selectedIds
282
- }) : null;
283
- const routedSourceIds = boundSourceIds ?? selectedIds;
284
- if (routedSourceIds.length === 0) return c.json({
285
- issues: [],
286
- nextCursor: null
287
- });
288
- try {
289
- const accessToken = await linear.getFreshAccessToken(connection);
290
- const { issues, nextCursor } = await linear.intake.listIssues({
291
- connection: {
292
- type: "oauth",
293
- accessToken
294
- },
295
- sourceIds: routedSourceIds,
296
- attributionSourceIds: selectedIds,
297
- cursor: after
298
- });
299
- const issuePayload = (boundSourceIds ? issues.filter((issue) => issue.sourceId != null && routedSourceIds.includes(issue.sourceId)) : issues).map((issue) => ({
300
- id: issue.id,
301
- identifier: issue.identifier,
302
- title: issue.title,
303
- url: issue.url,
304
- state: issue.state ?? "",
305
- stateType: issue.stateType ?? "",
306
- priorityLabel: issue.priority ?? "",
307
- assignee: issue.assignee,
308
- creator: issue.author,
309
- team: issue.source,
310
- labels: issue.labels,
311
- createdAt: issue.createdAt,
312
- updatedAt: issue.updatedAt,
313
- sourceId: issue.sourceId ?? null,
314
- projectId: issue.projectId ?? null
315
- }));
316
- return c.json({
317
- issues: issuePayload,
318
- nextCursor
319
- });
320
- } catch (err) {
321
- return linearFetchError(loose(c), err);
322
- }
323
- }
324
- }));
325
242
  routes.push(registerApiRoute("/web/linear/issues/:identifier", {
326
243
  method: "GET",
327
244
  requiresAuth: false,