@mastra/factory 0.29.0-alpha.0 → 0.29.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -4
- package/dist/board-changes.d.ts +16 -0
- package/dist/board-changes.d.ts.map +1 -0
- package/dist/board-changes.js +40 -0
- package/dist/board-changes.js.map +1 -0
- package/dist/boards/index.js +2 -1
- package/dist/boards/semantics.d.ts +1 -3
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +1 -5
- package/dist/boards/semantics.js.map +1 -1
- package/dist/factory.d.ts +4 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +51 -3
- package/dist/factory.js.map +1 -1
- package/dist/integrations/base.d.ts +9 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/pull-request-source.js +2 -1
- package/dist/integrations/github/pull-request-source.js.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +1 -1
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +5 -2
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +16 -13
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.js +2 -2
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/gitlab/default-rules.js +2 -1
- package/dist/integrations/gitlab/default-rules.js.map +1 -1
- package/dist/integrations/gitlab/discovery.d.ts +16 -0
- package/dist/integrations/gitlab/discovery.d.ts.map +1 -0
- package/dist/integrations/gitlab/discovery.js +107 -0
- package/dist/integrations/gitlab/discovery.js.map +1 -0
- package/dist/integrations/gitlab/integration.d.ts.map +1 -1
- package/dist/integrations/gitlab/integration.js +1 -2
- package/dist/integrations/gitlab/integration.js.map +1 -1
- package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/issue-reconciler.js +1 -0
- package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.js +26 -10
- package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/reconciler.js +4 -2
- package/dist/integrations/gitlab/reconciler.js.map +1 -1
- package/dist/integrations/gitlab/reconciliation-config.d.ts +0 -1
- package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/gitlab/reconciliation-config.js +2 -8
- package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
- package/dist/integrations/gitlab/routes.d.ts +17 -0
- package/dist/integrations/gitlab/routes.d.ts.map +1 -1
- package/dist/integrations/gitlab/routes.js +28 -22
- package/dist/integrations/gitlab/routes.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts +10 -4
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +32 -8
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/incidentio/integration.d.ts +2 -1
- package/dist/integrations/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/incidentio/integration.js +7 -7
- package/dist/integrations/incidentio/integration.js.map +1 -1
- package/dist/integrations/incidentio/issue-reconciler.d.ts +7 -0
- package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/incidentio/issue-reconciler.js +36 -1
- package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
- package/dist/integrations/incidentio/reconciliation-config.d.ts +0 -1
- package/dist/integrations/incidentio/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/incidentio/reconciliation-config.js +2 -5
- package/dist/integrations/incidentio/reconciliation-config.js.map +1 -1
- package/dist/integrations/incidentio/routes.d.ts +24 -8
- package/dist/integrations/incidentio/routes.d.ts.map +1 -1
- package/dist/integrations/incidentio/routes.js +33 -35
- package/dist/integrations/incidentio/routes.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts +0 -4
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +17 -14
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/intake-discovery.d.ts +44 -0
- package/dist/integrations/intake-discovery.d.ts.map +1 -0
- package/dist/integrations/intake-discovery.js +60 -0
- package/dist/integrations/intake-discovery.js.map +1 -0
- package/dist/integrations/issue-reconcile-worker.js +1 -1
- package/dist/integrations/issue-reconcile-worker.js.map +1 -1
- package/dist/integrations/issue-reconciler.d.ts +7 -0
- package/dist/integrations/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/issue-reconciler.js +47 -12
- package/dist/integrations/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/integration.d.ts +3 -2
- package/dist/integrations/jira/integration.d.ts.map +1 -1
- package/dist/integrations/jira/integration.js +5 -7
- package/dist/integrations/jira/integration.js.map +1 -1
- package/dist/integrations/jira/issue-reconciler.d.ts +17 -1
- package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/jira/issue-reconciler.js +34 -1
- package/dist/integrations/jira/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/reconciliation-config.d.ts +0 -1
- package/dist/integrations/jira/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/jira/reconciliation-config.js +2 -5
- package/dist/integrations/jira/reconciliation-config.js.map +1 -1
- package/dist/integrations/jira/routes.d.ts +0 -7
- package/dist/integrations/jira/routes.d.ts.map +1 -1
- package/dist/integrations/jira/routes.js +2 -12
- package/dist/integrations/jira/routes.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts +0 -4
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +3 -13
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/kept-cards.d.ts +49 -0
- package/dist/integrations/kept-cards.d.ts.map +1 -0
- package/dist/integrations/kept-cards.js +97 -0
- package/dist/integrations/kept-cards.js.map +1 -0
- package/dist/integrations/linear/intake-discovery.d.ts +34 -0
- package/dist/integrations/linear/intake-discovery.d.ts.map +1 -0
- package/dist/integrations/linear/intake-discovery.js +112 -0
- package/dist/integrations/linear/intake-discovery.js.map +1 -0
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +1 -4
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/issue-reconciler.d.ts +13 -4
- package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/linear/issue-reconciler.js +24 -20
- package/dist/integrations/linear/issue-reconciler.js.map +1 -1
- package/dist/integrations/linear/reconciliation-config.d.ts +0 -1
- package/dist/integrations/linear/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/linear/reconciliation-config.js +2 -8
- package/dist/integrations/linear/reconciliation-config.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts +0 -2
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +3 -9
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/platform/api-client.d.ts +2 -0
- package/dist/integrations/platform/api-client.d.ts.map +1 -1
- package/dist/integrations/platform/api-client.js +6 -1
- package/dist/integrations/platform/api-client.js.map +1 -1
- package/dist/integrations/platform/connect/routes.js +4 -1
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.d.ts +12 -0
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +56 -5
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +1 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +8 -3
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/gitlab/event-worker.js +1 -1
- package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
- package/dist/integrations/platform/incidentio/integration.d.ts +3 -2
- package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/platform/incidentio/integration.js +7 -7
- package/dist/integrations/platform/incidentio/integration.js.map +1 -1
- package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
- package/dist/integrations/platform/jira/integration.js +4 -7
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/integrations/platform/jira/routes.d.ts +0 -7
- package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
- package/dist/integrations/platform/jira/routes.js +2 -12
- package/dist/integrations/platform/jira/routes.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +1 -1
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts +1 -0
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +7 -7
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/platform/vanta/integration.d.ts +7 -2
- package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
- package/dist/integrations/platform/vanta/integration.js +22 -6
- package/dist/integrations/platform/vanta/integration.js.map +1 -1
- package/dist/integrations/reconciliation-config.d.ts +0 -1
- package/dist/integrations/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/reconciliation-config.js +1 -8
- package/dist/integrations/reconciliation-config.js.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.js +1 -1
- package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
- package/dist/integrations/startup-summary.d.ts +8 -0
- package/dist/integrations/startup-summary.d.ts.map +1 -0
- package/dist/integrations/startup-summary.js +36 -0
- package/dist/integrations/startup-summary.js.map +1 -0
- package/dist/integrations/vanta/sync.d.ts +9 -5
- package/dist/integrations/vanta/sync.d.ts.map +1 -1
- package/dist/integrations/vanta/sync.js +16 -8
- package/dist/integrations/vanta/sync.js.map +1 -1
- package/dist/linked-repositories-changed.d.ts +14 -0
- package/dist/linked-repositories-changed.d.ts.map +1 -0
- package/dist/linked-repositories-changed.js +48 -0
- package/dist/linked-repositories-changed.js.map +1 -0
- package/dist/routes/contracts.d.ts +117 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +44 -1
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/run-queue.d.ts +17 -0
- package/dist/routes/run-queue.d.ts.map +1 -0
- package/dist/routes/run-queue.js +69 -0
- package/dist/routes/run-queue.js.map +1 -0
- package/dist/routes/surface.d.ts +8 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +4 -2
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-item-selection.d.ts +4 -1
- package/dist/routes/work-item-selection.d.ts.map +1 -1
- package/dist/routes/work-item-selection.js +7 -2
- package/dist/routes/work-item-selection.js.map +1 -1
- package/dist/routes/work-items.d.ts +5 -0
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +17 -0
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +13 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +9 -2
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/review-source-tool.js +2 -1
- package/dist/rules/review-source-tool.js.map +1 -1
- package/dist/rules/types.d.ts +2 -2
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +4 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +1 -0
- package/dist/rules/validation.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +2 -0
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +13 -1
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +32 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +54 -4
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +3 -0
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +17 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +1 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +10 -1
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/timing.d.ts +8 -1
- package/dist/timing.d.ts.map +1 -1
- package/dist/timing.js +10 -2
- package/dist/timing.js.map +1 -1
- package/dist/work-item-branch.d.ts +1 -1
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +1 -0
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/source-external-id.d.ts +4 -0
- package/dist/work-items/source-external-id.d.ts.map +1 -0
- package/dist/work-items/source-external-id.js +9 -0
- package/dist/work-items/source-external-id.js.map +1 -0
- package/package.json +9 -9
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intake-discovery.js","names":[],"sources":["../../src/integrations/intake-discovery.ts"],"sourcesContent":["import type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { IssueReconcileSummary } from './issue-reconciler.js';\n\nexport const INTAKE_DISCOVERY_MAX_PAGES = 5;\n\nexport type IntakeDiscoverySummary = IssueReconcileSummary & {\n /** Listed issues replayed through the provider rules (first sight creates the card). */\n observed: number;\n};\n\ninterface IntakePage<TIssue> {\n issues: TIssue[];\n nextCursor: string | null;\n}\n\ntype IntakePager<TIssue> = (cursor: string | undefined) => Promise<IntakePage<TIssue>>;\n\nexport interface IntakeDiscoveryOptions<TIssue> {\n integrationId: string;\n intake: Pick<IntakeStorage, 'ensureReady' | 'getConfig'>;\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n /**\n * One pager per source bound to the project, so a busy source cannot spend\n * the pages of the others. Empty when no selected source feeds the project.\n */\n open(project: FactoryProject, selectedIds: string[]): Promise<Array<IntakePager<TIssue>>>;\n /**\n * Pages read from each source per sweep. Five suits a provider that lists its\n * most recently updated issues first; one that cannot sort must read them all.\n */\n maxPages?: number;\n ingest(input: { orgId: string; userId: string; factoryProjectId: string; issues: TIssue[] }): Promise<unknown>;\n}\n\n/**\n * Extend a provider's reconcile sweep so it also files issues nobody has\n * carded yet: after refreshing existing cards, list what each project's board\n * shows and replay it through the provider rules. Providers that send Factory\n * no events have no other first-sight path. A failing project or source is\n * recorded and the sweep moves on.\n */\nexport function withIntakeDiscovery<TIssue>(\n reconcile: () => Promise<IssueReconcileSummary>,\n options: IntakeDiscoveryOptions<TIssue>,\n): () => Promise<IntakeDiscoverySummary> {\n return async () => {\n const summary: IntakeDiscoverySummary = { ...(await reconcile()), observed: 0 };\n for (const project of await options.projects.listAll()) {\n try {\n await options.intake.ensureReady();\n const config = await options.intake.getConfig({\n orgId: project.orgId,\n integrationIds: [options.integrationId],\n });\n const selection = config[options.integrationId];\n if (!selection?.enabled) continue;\n for (const listPage of await options.open(project, selection.sourceIds ?? [])) {\n // A failing source, such as a revoked connection, must not skip the project's other sources.\n try {\n let cursor: string | undefined;\n const seenCursors = new Set<string>();\n for (let page = 0; page < (options.maxPages ?? INTAKE_DISCOVERY_MAX_PAGES); page += 1) {\n const { issues, nextCursor } = await listPage(cursor);\n if (issues.length > 0) {\n await options.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues,\n });\n summary.observed += issues.length;\n }\n if (!nextCursor) break;\n if (seenCursors.has(nextCursor)) throw new Error(`${options.integrationId} repeated a page cursor`);\n seenCursors.add(nextCursor);\n cursor = nextCursor;\n }\n } catch (error) {\n recordFailure(summary, project, error);\n }\n }\n } catch (error) {\n recordFailure(summary, project, error);\n }\n }\n return summary;\n };\n}\n\nfunction recordFailure(summary: IntakeDiscoverySummary, project: FactoryProject, error: unknown): void {\n summary.failed += 1;\n summary.errors.push({ projectId: project.id, error: error instanceof Error ? error.message : String(error) });\n}\n"],"mappings":";AAIA,MAAa,6BAA6B;;;;;;;;AAsC1C,SAAgB,oBACd,WACA,SACuC;CACvC,OAAO,YAAY;EACjB,MAAM,UAAkC;GAAE,GAAI,MAAM,UAAU;GAAI,UAAU;EAAE;EAC9E,KAAK,MAAM,WAAW,MAAM,QAAQ,SAAS,QAAQ,GACnD,IAAI;GACF,MAAM,QAAQ,OAAO,YAAY;GAKjC,MAAM,aAAY,MAJG,QAAQ,OAAO,UAAU;IAC5C,OAAO,QAAQ;IACf,gBAAgB,CAAC,QAAQ,aAAa;GACxC,CAAC,EAAA,CACwB,QAAQ;GACjC,IAAI,CAAC,WAAW,SAAS;GACzB,KAAK,MAAM,YAAY,MAAM,QAAQ,KAAK,SAAS,UAAU,aAAa,CAAC,CAAC,GAE1E,IAAI;IACF,IAAI;IACJ,MAAM,8BAAc,IAAI,IAAY;IACpC,KAAK,IAAI,OAAO,GAAG,QAAQ,QAAQ,YAAA,IAAyC,QAAQ,GAAG;KACrF,MAAM,EAAE,QAAQ,eAAe,MAAM,SAAS,MAAM;KACpD,IAAI,OAAO,SAAS,GAAG;MACrB,MAAM,QAAQ,OAAO;OACnB,OAAO,QAAQ;OACf,QAAQ;OACR,kBAAkB,QAAQ;OAC1B;MACF,CAAC;MACD,QAAQ,YAAY,OAAO;KAC7B;KACA,IAAI,CAAC,YAAY;KACjB,IAAI,YAAY,IAAI,UAAU,GAAG,MAAM,IAAI,MAAM,GAAG,QAAQ,cAAc,wBAAwB;KAClG,YAAY,IAAI,UAAU;KAC1B,SAAS;IACX;GACF,SAAS,OAAO;IACd,cAAc,SAAS,SAAS,KAAK;GACvC;EAEJ,SAAS,OAAO;GACd,cAAc,SAAS,SAAS,KAAK;EACvC;EAEF,OAAO;CACT;AACF;AAEA,SAAS,cAAc,SAAiC,SAAyB,OAAsB;CACrG,QAAQ,UAAU;CAClB,QAAQ,OAAO,KAAK;EAAE,WAAW,QAAQ;EAAI,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAAE,CAAC;AAC9G"}
|
|
@@ -33,7 +33,7 @@ var IssueReconcileWorker = class extends MastraWorker {
|
|
|
33
33
|
if (this.#running) return;
|
|
34
34
|
if (!this.deps) throw new Error("IssueReconcileWorker: call init() before start()");
|
|
35
35
|
this.#running = true;
|
|
36
|
-
this.deps.logger.
|
|
36
|
+
this.deps.logger.debug(`${this.#integrationId} issue reconcile worker started`, { intervalMs: this.#intervalMs });
|
|
37
37
|
this.#schedule(0);
|
|
38
38
|
}
|
|
39
39
|
async stop() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"issue-reconcile-worker.js","names":[],"sources":["../../src/integrations/issue-reconcile-worker.ts"],"sourcesContent":["import { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IssueReconciler } from './issue-reconciler.js';\n\nexport const DEFAULT_ISSUE_RECONCILE_INTERVAL_MS = 5 * 60_000;\nconst MIN_LEASE_TTL_MS = 30_000;\n\nexport interface IssueReconcileWorkerConfig {\n integrationId: string;\n reconcile: IssueReconciler;\n intervalMs?: number;\n}\n\nexport class IssueReconcileWorker extends MastraWorker {\n readonly name: string;\n\n readonly #integrationId: string;\n readonly #reconcile: IssueReconciler;\n readonly #intervalMs: number;\n readonly #leaseTtlMs: number;\n readonly #leaseKey: string;\n readonly #leaseOwner = globalThis.crypto.randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n\n constructor(config: IssueReconcileWorkerConfig) {\n super();\n this.#integrationId = config.integrationId;\n this.name = `${config.integrationId}-issue-reconcile`;\n this.#leaseKey = `${config.integrationId}:issue-reconcile`;\n this.#reconcile = config.reconcile;\n this.#intervalMs = config.intervalMs ?? DEFAULT_ISSUE_RECONCILE_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error(`${config.integrationId} issue reconcile interval must be a positive number.`);\n }\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('IssueReconcileWorker: call init() before start()');\n this.#running = true;\n this.deps.logger.
|
|
1
|
+
{"version":3,"file":"issue-reconcile-worker.js","names":[],"sources":["../../src/integrations/issue-reconcile-worker.ts"],"sourcesContent":["import { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IssueReconciler } from './issue-reconciler.js';\n\nexport const DEFAULT_ISSUE_RECONCILE_INTERVAL_MS = 5 * 60_000;\nconst MIN_LEASE_TTL_MS = 30_000;\n\nexport interface IssueReconcileWorkerConfig {\n integrationId: string;\n reconcile: IssueReconciler;\n intervalMs?: number;\n}\n\nexport class IssueReconcileWorker extends MastraWorker {\n readonly name: string;\n\n readonly #integrationId: string;\n readonly #reconcile: IssueReconciler;\n readonly #intervalMs: number;\n readonly #leaseTtlMs: number;\n readonly #leaseKey: string;\n readonly #leaseOwner = globalThis.crypto.randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n\n constructor(config: IssueReconcileWorkerConfig) {\n super();\n this.#integrationId = config.integrationId;\n this.name = `${config.integrationId}-issue-reconcile`;\n this.#leaseKey = `${config.integrationId}:issue-reconcile`;\n this.#reconcile = config.reconcile;\n this.#intervalMs = config.intervalMs ?? DEFAULT_ISSUE_RECONCILE_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error(`${config.integrationId} issue reconcile interval must be a positive number.`);\n }\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('IssueReconcileWorker: call init() before start()');\n this.#running = true;\n this.deps.logger.debug(`${this.#integrationId} issue reconcile worker started`, { intervalMs: this.#intervalMs });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n await this.#inFlight;\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick().finally(() => {\n this.#inFlight = undefined;\n this.#schedule(this.#intervalMs);\n });\n this.#inFlight = run;\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n const lease = await this.#leaseProvider\n .acquireLease(this.#leaseKey, this.#leaseOwner, this.#leaseTtlMs)\n .catch(() => ({ acquired: false }));\n if (!lease.acquired) return;\n\n // A sweep that traverses many projects/orgs can outrun the lease TTL;\n // renew periodically so a replica can't grab the expired lease and start\n // an overlapping sweep partway through this one.\n const renewalTimer = setInterval(\n () => {\n void this.#leaseProvider.renewLease(this.#leaseKey, this.#leaseOwner, this.#leaseTtlMs).catch(error => {\n this.deps?.logger.warn(`${this.#integrationId} issue reconcile lease renewal failed`, {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.max(1_000, Math.floor(this.#leaseTtlMs / 3)),\n );\n renewalTimer.unref?.();\n\n try {\n const startedAt = Date.now();\n const { errors, ...counts } = await this.#reconcile();\n const context = { ...counts, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn(`${this.#integrationId} issue reconcile sweep completed with failures`, {\n ...context,\n errors,\n });\n } else {\n this.deps?.logger.debug(`${this.#integrationId} issue reconcile sweep completed`, context);\n }\n } catch (error) {\n this.deps?.logger.warn(`${this.#integrationId} issue reconcile sweep failed`, {\n error: error instanceof Error ? error.message : String(error),\n });\n } finally {\n clearInterval(renewalTimer);\n await this.#leaseProvider.releaseLease(this.#leaseKey, this.#leaseOwner).catch(() => undefined);\n }\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : ((pubsub as PubSub & { lease?: LeaseProvider }).lease ?? NoopLeaseProvider);\n}\n"],"mappings":";;;AAOA,MAAa,sCAAsC;AACnD,MAAM,mBAAmB;AAQzB,IAAa,uBAAb,cAA0C,aAAa;CACrD;CAEA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW,OAAO,WAAW;CAEpD,WAAW;CACX;CACA;CACA,iBAAgC;CAEhC,YAAY,QAAoC;EAC9C,MAAM;EACN,KAAK,iBAAiB,OAAO;EAC7B,KAAK,OAAO,GAAG,OAAO,cAAc;EACpC,KAAK,YAAY,GAAG,OAAO,cAAc;EACzC,KAAK,aAAa,OAAO;EACzB,KAAK,cAAc,OAAO,cAAA;EAC1B,IAAI,CAAC,OAAO,SAAS,KAAK,WAAW,KAAK,KAAK,eAAe,GAC5D,MAAM,IAAI,MAAM,GAAG,OAAO,cAAc,qDAAqD;EAE/F,KAAK,cAAc,KAAK,IAAI,kBAAkB,KAAK,cAAc,CAAC;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ACA,KAAK,IAAI,KAAO,KAAK,MAAM,KAAK,cAAc,CAAC,CAAC,CAClD;EACA,aAAa,QAAQ;EAErB,IAAI;GACF,MAAM,YAAY,KAAK,IAAI;GAC3B,MAAM,EAAE,QAAQ,GAAG,WAAW,MAAM,KAAK,WAAW;GACpD,MAAM,UAAU;IAAE,GAAG;IAAQ,YAAY,KAAK,IAAI,IAAI;GAAU;GAChE,IAAI,OAAO,SAAS,GAClB,KAAK,MAAM,OAAO,KAAK,GAAG,KAAK,eAAe,iDAAiD;IAC7F,GAAG;IACH;GACF,CAAC;QAED,KAAK,MAAM,OAAO,MAAM,GAAG,KAAK,eAAe,mCAAmC,OAAO;EAE7F,SAAS,OAAO;GACd,KAAK,MAAM,OAAO,KAAK,GAAG,KAAK,eAAe,gCAAgC,EAC5E,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAC9D,CAAC;EACH,UAAU;GACR,cAAc,YAAY;GAC1B,MAAM,KAAK,eAAe,aAAa,KAAK,WAAW,KAAK,WAAW,CAAC,CAAC,YAAY,KAAA,CAAS;EAChG;CACF;AACF;AAEA,SAAS,iBAAiB,QAA+B;CACvD,MAAM,cAAe,OAA2E;CAChG,IAAI,OAAO,gBAAgB,YAAY,OAAO,YAAY,KAAK,MAAM,KAAK;CAC1E,OAAO,gBAAgB,MAAM,IAAI,SAAW,OAA8C,SAAS;AACrG"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Intake, IntakeIssue, ResolvedIntakeDispatch } from '../capabilities/intake.js';
|
|
2
2
|
import type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';
|
|
3
3
|
import type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
4
|
+
import type { CardSource } from './kept-cards.js';
|
|
4
5
|
export declare const EXTERNAL_SOURCE_MISSING_KEY = "externalSourceMissingAt";
|
|
5
6
|
export interface IssueReconcileSummary {
|
|
6
7
|
projects: number;
|
|
@@ -30,6 +31,12 @@ export interface IssueReconcilerOptions<TScope = void> {
|
|
|
30
31
|
intake: Intake;
|
|
31
32
|
projects: Pick<FactoryProjectsStorage, 'listAll'>;
|
|
32
33
|
storage: WorkItemsStorage;
|
|
34
|
+
/**
|
|
35
|
+
* Every project's provider-backed cards, kept between sweeps. With it a sweep
|
|
36
|
+
* that finds nothing to change reads nothing from storage. Without it every
|
|
37
|
+
* sweep lists the projects and reads each board.
|
|
38
|
+
*/
|
|
39
|
+
cards?: CardSource;
|
|
33
40
|
externalSource?(item: Card): {
|
|
34
41
|
type: string;
|
|
35
42
|
externalId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"issue-reconciler.d.ts","sourceRoot":"","sources":["../../src/integrations/issue-reconciler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAC7F,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClG,OAAO,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAEpF,eAAO,MAAM,2BAA2B,4BAA4B,CAAC;AAGrE,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,KAAK,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC1E;AAED;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB,CAAC,MAAM;IACzC,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,OAAO,CAAC,IAAI,EAAE,IAAI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U,EAAE,MAAM,CAAA;KAAE,CAAC;IAClE,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,GAAG,SAAS,CAAC;IACxC,QAAQ,CACN,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,WAAW,EAClB,QAAQ,EAAE,sBAAsB,GAC/B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAC9D;;;;OAIG;IACH,QAAQ,CAAC,CACP,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,cAAc,EACvB,QAAQ,EAAE,sBAAsB,GAC/B,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;IAC3C,wGAAwG;IACxG,UAAU,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC;IAChC,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AAED,MAAM,MAAM,eAAe,CAAC,MAAM,GAAG,IAAI,IAAI,MAAM,SAAS,IAAI,GAC5D,MAAM,OAAO,CAAC,qBAAqB,CAAC,GACpC,CAAC,KAAK,EAAE,mBAAmB,CAAC,MAAM,CAAC,KAAK,OAAO,CAAC,qBAAqB,CAAC,CAAC;AAiF3E,wBAAgB,qBAAqB,CAAC,MAAM,GAAG,IAAI,EAAE,OAAO,EAAE,sBAAsB,CAAC,MAAM,CAAC,GAAG,eAAe,CAAC,MAAM,CAAC,CAoIrH"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { storageCards } from "./kept-cards.js";
|
|
1
2
|
// src/integrations/issue-reconciler.ts
|
|
2
3
|
const EXTERNAL_SOURCE_MISSING_KEY = "externalSourceMissingAt";
|
|
3
4
|
const MISSING_RECHECK_MS = 864e5;
|
|
@@ -38,6 +39,25 @@ function withoutMissingMarker(record) {
|
|
|
38
39
|
function issueItems(project, items, integrationId) {
|
|
39
40
|
return items.filter((item) => item.factoryProjectId === project.id && item.externalSource?.integrationId === integrationId && item.externalSource.type === "issue");
|
|
40
41
|
}
|
|
42
|
+
function cardMetadata(item) {
|
|
43
|
+
return withoutMissingMarker({
|
|
44
|
+
...item.workItem.metadata,
|
|
45
|
+
...item.metadata
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The metadata a write of `item` builds on. A kept card may be older than the
|
|
50
|
+
* stored one, and writing its metadata back would undo what changed since, so
|
|
51
|
+
* the card is read again. Null when the card is gone.
|
|
52
|
+
*/
|
|
53
|
+
async function storedCardMetadata(options, project, item) {
|
|
54
|
+
if (!options.cards) return cardMetadata(item);
|
|
55
|
+
const stored = await options.storage.get({
|
|
56
|
+
orgId: project.orgId,
|
|
57
|
+
id: item.id
|
|
58
|
+
});
|
|
59
|
+
return stored ? cardMetadata(stored) : null;
|
|
60
|
+
}
|
|
41
61
|
function createIssueReconciler(options) {
|
|
42
62
|
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
43
63
|
const run = async (scope) => {
|
|
@@ -51,12 +71,26 @@ function createIssueReconciler(options) {
|
|
|
51
71
|
errors: []
|
|
52
72
|
};
|
|
53
73
|
if (scope && scope.scopes.length === 0) return summary;
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
74
|
+
const cards = options.cards ?? storageCards({
|
|
75
|
+
projects: options.projects,
|
|
76
|
+
workItems: options.storage
|
|
77
|
+
});
|
|
78
|
+
for (const project of await cards.projects()) {
|
|
79
|
+
let all;
|
|
80
|
+
try {
|
|
81
|
+
all = await cards.cards({
|
|
82
|
+
orgId: project.orgId,
|
|
83
|
+
factoryProjectId: project.id
|
|
84
|
+
});
|
|
85
|
+
} catch (error) {
|
|
86
|
+
summary.failed += 1;
|
|
87
|
+
summary.errors.push({
|
|
88
|
+
projectId: project.id,
|
|
89
|
+
error: error instanceof Error ? error.message : String(error)
|
|
90
|
+
});
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const candidates = issueItems(project, all, options.integrationId);
|
|
60
94
|
const items = scope ? candidates.filter((item) => scope.scopes.some((target) => scope.matches(item, target))) : candidates;
|
|
61
95
|
if (items.length === 0) continue;
|
|
62
96
|
summary.projects += 1;
|
|
@@ -100,19 +134,18 @@ function createIssueReconciler(options) {
|
|
|
100
134
|
continue;
|
|
101
135
|
}
|
|
102
136
|
const hadMissingMarker = typeof missingAt === "string";
|
|
103
|
-
const baseMetadata =
|
|
104
|
-
...item.workItem.metadata,
|
|
105
|
-
...item.metadata
|
|
106
|
-
});
|
|
137
|
+
const baseMetadata = cardMetadata(item);
|
|
107
138
|
if ((issue.stateType === "completed" || issue.stateType === "canceled") && !options.isTerminal(item) && options.onClosed) {
|
|
108
139
|
const closedMetadata = withoutUndefined(await options.onClosed(item, issue, project, resolved) ?? {});
|
|
109
140
|
if (hadMissingMarker || !metadataMatches(baseMetadata, closedMetadata)) {
|
|
141
|
+
const storedMetadata = await storedCardMetadata(options, project, item);
|
|
142
|
+
if (!storedMetadata) continue;
|
|
110
143
|
await options.storage.syncCard({
|
|
111
144
|
orgId: project.orgId,
|
|
112
145
|
id: item.id,
|
|
113
146
|
userId: "factory-rule-dispatcher",
|
|
114
147
|
patch: { metadata: {
|
|
115
|
-
...
|
|
148
|
+
...storedMetadata,
|
|
116
149
|
...closedMetadata,
|
|
117
150
|
...hadMissingMarker ? { [EXTERNAL_SOURCE_MISSING_KEY]: void 0 } : {}
|
|
118
151
|
} }
|
|
@@ -124,12 +157,14 @@ function createIssueReconciler(options) {
|
|
|
124
157
|
}
|
|
125
158
|
const metadata = withoutUndefined(await options.metadata(item, issue, resolved));
|
|
126
159
|
if (!hadMissingMarker && metadataMatches(baseMetadata, metadata)) continue;
|
|
160
|
+
const storedMetadata = await storedCardMetadata(options, project, item);
|
|
161
|
+
if (!storedMetadata) continue;
|
|
127
162
|
await options.storage.syncCard({
|
|
128
163
|
orgId: project.orgId,
|
|
129
164
|
id: item.id,
|
|
130
165
|
userId: "factory-rule-dispatcher",
|
|
131
166
|
patch: { metadata: {
|
|
132
|
-
...
|
|
167
|
+
...storedMetadata,
|
|
133
168
|
...metadata,
|
|
134
169
|
...hadMissingMarker ? { [EXTERNAL_SOURCE_MISSING_KEY]: void 0 } : {}
|
|
135
170
|
} }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../src/integrations/issue-reconciler.ts"],"sourcesContent":["import type { Intake, IntakeIssue, ResolvedIntakeDispatch } from '../capabilities/intake.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\n\nexport const EXTERNAL_SOURCE_MISSING_KEY = 'externalSourceMissingAt';\nconst MISSING_RECHECK_MS = 24 * 60 * 60_000;\n\nexport interface IssueReconcileSummary {\n projects: number;\n checked: number;\n updated: number;\n closed: number;\n missing: number;\n failed: number;\n errors: Array<{ projectId: string; workItemId?: string; error: string }>;\n}\n\n/**\n * Scope passed in by the caller. Providers that reconcile per-repository (like\n * GitHub, sharing target discovery with the PR reconciler) pass a target set\n * and a `matches(item, scope)` predicate. Providers with no repository concept\n * (Linear) pass no scope and every issue item is considered.\n */\nexport interface IssueReconcileScope<TScope> {\n scopes: TScope[];\n matches(item: Card, scope: TScope): boolean;\n}\n\nexport interface IssueReconcilerOptions<TScope = void> {\n integrationId: string;\n intake: Intake;\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n storage: WorkItemsStorage;\n externalSource?(item: Card): { type: string; externalId: string };\n issueId(item: Card): string | undefined;\n metadata(\n item: Card,\n issue: IntakeIssue,\n dispatch: ResolvedIntakeDispatch,\n ): Record<string, unknown> | Promise<Record<string, unknown>>;\n /**\n * Called when a closed issue (stateType 'completed' or 'canceled') is detected\n * on a non-terminal work item. Use this to replay the close event through\n * the provider's rules ingress.\n */\n onClosed?(\n item: Card,\n issue: IntakeIssue,\n project: FactoryProject,\n dispatch: ResolvedIntakeDispatch,\n ): Promise<Record<string, unknown> | void>;\n /** Whether the item already rests in a terminal phase of its board. Unknown phases are not terminal. */\n isTerminal(item: Card): boolean;\n now?: () => Date;\n}\n\nexport type IssueReconciler<TScope = void> = TScope extends void\n ? () => Promise<IssueReconcileSummary>\n : (scope: IssueReconcileScope<TScope>) => Promise<IssueReconcileSummary>;\n\nfunction sameValue(left: unknown, right: unknown): boolean {\n if (Array.isArray(right)) {\n if (!Array.isArray(left)) return right.length === 0;\n const leftStrings = left\n .filter((value): value is string => typeof value === 'string')\n .slice()\n .sort();\n const rightStrings = right\n .filter((value): value is string => typeof value === 'string')\n .slice()\n .sort();\n return (\n leftStrings.length === rightStrings.length && leftStrings.every((value, index) => value === rightStrings[index])\n );\n }\n if (right !== null && typeof right === 'object') {\n if (left === null || typeof left !== 'object' || Array.isArray(left)) return false;\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n return (\n leftKeys.length === rightKeys.length &&\n rightKeys.every(key => Object.hasOwn(leftRecord, key) && sameValue(leftRecord[key], rightRecord[key]))\n );\n }\n return left === right;\n}\n\nfunction metadataMatches(current: Record<string, unknown> | null, desired: Record<string, unknown>): boolean {\n return Object.entries(desired).every(([key, value]) => sameValue(current?.[key], value));\n}\n\n/**\n * Drop `undefined` entries so we never spread them into stored metadata. An\n * `undefined` field on the desired patch means \"no signal from the live issue\"\n * — we must preserve whatever was already stored, not clobber it.\n */\nfunction withoutUndefined(record: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n if (value !== undefined) out[key] = value;\n }\n return out;\n}\n\nfunction withoutMissingMarker(record: Record<string, unknown> | null): Record<string, unknown> {\n const { [EXTERNAL_SOURCE_MISSING_KEY]: _missingAt, ...metadata } = record ?? {};\n return metadata;\n}\n\nfunction issueItems(project: FactoryProject, items: readonly Card[], integrationId: string): Card[] {\n return items.filter(\n item =>\n item.factoryProjectId === project.id &&\n item.externalSource?.integrationId === integrationId &&\n item.externalSource.type === 'issue',\n );\n}\n\nexport function createIssueReconciler<TScope = void>(options: IssueReconcilerOptions<TScope>): IssueReconciler<TScope> {\n const now = options.now ?? (() => new Date());\n const run = async (scope?: IssueReconcileScope<TScope>): Promise<IssueReconcileSummary> => {\n const summary: IssueReconcileSummary = {\n projects: 0,\n checked: 0,\n updated: 0,\n closed: 0,\n missing: 0,\n failed: 0,\n errors: [],\n };\n\n // A scoped sweep with zero targets is a no-op: the caller is telling us\n // there are no configured repositories to consider.\n if (scope && scope.scopes.length === 0) return summary;\n\n const projects = await options.projects.listAll();\n for (const project of projects) {\n const all = await options.storage.listShared({ orgId: project.orgId, factoryProjectId: project.id });\n const candidates = issueItems(project, all, options.integrationId);\n const items = scope\n ? candidates.filter(item => scope.scopes.some(target => scope.matches(item, target)))\n : candidates;\n if (items.length === 0) continue;\n summary.projects += 1;\n\n for (const item of items) {\n summary.checked += 1;\n try {\n const missingAt = item.workItem.metadata?.[EXTERNAL_SOURCE_MISSING_KEY];\n const missingTime = typeof missingAt === 'string' ? Date.parse(missingAt) : Number.NaN;\n const missingAge = now().getTime() - missingTime;\n if (Number.isFinite(missingTime) && missingAge >= 0 && missingAge < MISSING_RECHECK_MS) {\n summary.missing += 1;\n continue;\n }\n\n const resolved = await options.intake.resolveIntakeDispatch?.({\n orgId: project.orgId,\n externalSource: options.externalSource?.(item) ?? item.externalSource!,\n });\n if (!resolved) {\n await options.storage.syncCard({\n orgId: project.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: { [EXTERNAL_SOURCE_MISSING_KEY]: now().toISOString() } },\n });\n summary.missing += 1;\n continue;\n }\n const issueId = options.issueId(item) ?? resolved.issueId;\n const issue = await options.intake.getIssue({ ...resolved, issueId });\n if (!issue) {\n await options.storage.syncCard({\n orgId: project.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: { [EXTERNAL_SOURCE_MISSING_KEY]: now().toISOString() } },\n });\n summary.missing += 1;\n continue;\n }\n\n const hadMissingMarker = typeof missingAt === 'string';\n const baseMetadata = withoutMissingMarker({ ...item.workItem.metadata, ...item.metadata });\n // Close detection for Linear: replay through rules ingress if closed\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !options.isTerminal(item) && options.onClosed) {\n const closedMetadata = withoutUndefined((await options.onClosed(item, issue, project, resolved)) ?? {});\n if (hadMissingMarker || !metadataMatches(baseMetadata, closedMetadata)) {\n await options.storage.syncCard({\n orgId: project.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: {\n ...baseMetadata,\n ...closedMetadata,\n ...(hadMissingMarker ? { [EXTERNAL_SOURCE_MISSING_KEY]: undefined } : {}),\n },\n },\n });\n summary.updated += 1;\n }\n summary.closed += 1;\n continue;\n }\n\n const metadata = withoutUndefined(await options.metadata(item, issue, resolved));\n if (!hadMissingMarker && metadataMatches(baseMetadata, metadata)) continue;\n await options.storage.syncCard({\n orgId: project.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: {\n ...baseMetadata,\n ...metadata,\n ...(hadMissingMarker ? { [EXTERNAL_SOURCE_MISSING_KEY]: undefined } : {}),\n },\n },\n });\n summary.updated += 1;\n } catch (error) {\n summary.failed += 1;\n summary.errors.push({\n projectId: project.id,\n workItemId: item.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n return summary;\n };\n\n return run as IssueReconciler<TScope>;\n}\n"],"mappings":";AAIA,MAAa,8BAA8B;AAC3C,MAAM,qBAAqB;AAuD3B,SAAS,UAAU,MAAe,OAAyB;CACzD,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,IAAI,CAAC,MAAM,QAAQ,IAAI,GAAG,OAAO,MAAM,WAAW;EAClD,MAAM,cAAc,KACjB,QA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B,GAAG,8BAA8B,KAAA,EAAU,IAAI,CAAC;MACzE,EACF;KACF,CAAC;KACD,QAAQ,WAAW;IACrB,SAAS,OAAO;KACd,QAAQ,UAAU;KAClB,QAAQ,OAAO,KAAK;MAClB,WAAW,QAAQ;MACnB,YAAY,KAAK;MACjB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;KAC9D,CAAC;IACH;GACF;EACF;EAEA,OAAO;CACT;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../src/integrations/issue-reconciler.ts"],"sourcesContent":["import type { Intake, IntakeIssue, ResolvedIntakeDispatch } from '../capabilities/intake.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { storageCards } from './kept-cards.js';\nimport type { CardSource } from './kept-cards.js';\n\nexport const EXTERNAL_SOURCE_MISSING_KEY = 'externalSourceMissingAt';\nconst MISSING_RECHECK_MS = 24 * 60 * 60_000;\n\nexport interface IssueReconcileSummary {\n projects: number;\n checked: number;\n updated: number;\n closed: number;\n missing: number;\n failed: number;\n errors: Array<{ projectId: string; workItemId?: string; error: string }>;\n}\n\n/**\n * Scope passed in by the caller. Providers that reconcile per-repository (like\n * GitHub, sharing target discovery with the PR reconciler) pass a target set\n * and a `matches(item, scope)` predicate. Providers with no repository concept\n * (Linear) pass no scope and every issue item is considered.\n */\nexport interface IssueReconcileScope<TScope> {\n scopes: TScope[];\n matches(item: Card, scope: TScope): boolean;\n}\n\nexport interface IssueReconcilerOptions<TScope = void> {\n integrationId: string;\n intake: Intake;\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n storage: WorkItemsStorage;\n /**\n * Every project's provider-backed cards, kept between sweeps. With it a sweep\n * that finds nothing to change reads nothing from storage. Without it every\n * sweep lists the projects and reads each board.\n */\n cards?: CardSource;\n externalSource?(item: Card): { type: string; externalId: string };\n issueId(item: Card): string | undefined;\n metadata(\n item: Card,\n issue: IntakeIssue,\n dispatch: ResolvedIntakeDispatch,\n ): Record<string, unknown> | Promise<Record<string, unknown>>;\n /**\n * Called when a closed issue (stateType 'completed' or 'canceled') is detected\n * on a non-terminal work item. Use this to replay the close event through\n * the provider's rules ingress.\n */\n onClosed?(\n item: Card,\n issue: IntakeIssue,\n project: FactoryProject,\n dispatch: ResolvedIntakeDispatch,\n ): Promise<Record<string, unknown> | void>;\n /** Whether the item already rests in a terminal phase of its board. Unknown phases are not terminal. */\n isTerminal(item: Card): boolean;\n now?: () => Date;\n}\n\nexport type IssueReconciler<TScope = void> = TScope extends void\n ? () => Promise<IssueReconcileSummary>\n : (scope: IssueReconcileScope<TScope>) => Promise<IssueReconcileSummary>;\n\nfunction sameValue(left: unknown, right: unknown): boolean {\n if (Array.isArray(right)) {\n if (!Array.isArray(left)) return right.length === 0;\n const leftStrings = left\n .filter((value): value is string => typeof value === 'string')\n .slice()\n .sort();\n const rightStrings = right\n .filter((value): value is string => typeof value === 'string')\n .slice()\n .sort();\n return (\n leftStrings.length === rightStrings.length && leftStrings.every((value, index) => value === rightStrings[index])\n );\n }\n if (right !== null && typeof right === 'object') {\n if (left === null || typeof left !== 'object' || Array.isArray(left)) return false;\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n return (\n leftKeys.length === rightKeys.length &&\n rightKeys.every(key => Object.hasOwn(leftRecord, key) && sameValue(leftRecord[key], rightRecord[key]))\n );\n }\n return left === right;\n}\n\nfunction metadataMatches(current: Record<string, unknown> | null, desired: Record<string, unknown>): boolean {\n return Object.entries(desired).every(([key, value]) => sameValue(current?.[key], value));\n}\n\n/**\n * Drop `undefined` entries so we never spread them into stored metadata. An\n * `undefined` field on the desired patch means \"no signal from the live issue\"\n * — we must preserve whatever was already stored, not clobber it.\n */\nfunction withoutUndefined(record: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n if (value !== undefined) out[key] = value;\n }\n return out;\n}\n\nfunction withoutMissingMarker(record: Record<string, unknown> | null): Record<string, unknown> {\n const { [EXTERNAL_SOURCE_MISSING_KEY]: _missingAt, ...metadata } = record ?? {};\n return metadata;\n}\n\nfunction issueItems(project: FactoryProject, items: readonly Card[], integrationId: string): Card[] {\n return items.filter(\n item =>\n item.factoryProjectId === project.id &&\n item.externalSource?.integrationId === integrationId &&\n item.externalSource.type === 'issue',\n );\n}\n\nfunction cardMetadata(item: Card): Record<string, unknown> {\n return withoutMissingMarker({ ...item.workItem.metadata, ...item.metadata });\n}\n\n/**\n * The metadata a write of `item` builds on. A kept card may be older than the\n * stored one, and writing its metadata back would undo what changed since, so\n * the card is read again. Null when the card is gone.\n */\nasync function storedCardMetadata<TScope>(\n options: IssueReconcilerOptions<TScope>,\n project: FactoryProject,\n item: Card,\n): Promise<Record<string, unknown> | null> {\n if (!options.cards) return cardMetadata(item);\n const stored = await options.storage.get({ orgId: project.orgId, id: item.id });\n return stored ? cardMetadata(stored) : null;\n}\n\nexport function createIssueReconciler<TScope = void>(options: IssueReconcilerOptions<TScope>): IssueReconciler<TScope> {\n const now = options.now ?? (() => new Date());\n const run = async (scope?: IssueReconcileScope<TScope>): Promise<IssueReconcileSummary> => {\n const summary: IssueReconcileSummary = {\n projects: 0,\n checked: 0,\n updated: 0,\n closed: 0,\n missing: 0,\n failed: 0,\n errors: [],\n };\n\n // A scoped sweep with zero targets is a no-op: the caller is telling us\n // there are no configured repositories to consider.\n if (scope && scope.scopes.length === 0) return summary;\n\n const cards = options.cards ?? storageCards({ projects: options.projects, workItems: options.storage });\n for (const project of await cards.projects()) {\n let all: readonly Card[];\n try {\n all = await cards.cards({ orgId: project.orgId, factoryProjectId: project.id });\n } catch (error) {\n // One project's unreadable cards must not end the sweep for every other project.\n summary.failed += 1;\n summary.errors.push({ projectId: project.id, error: error instanceof Error ? error.message : String(error) });\n continue;\n }\n const candidates = issueItems(project, all, options.integrationId);\n const items = scope\n ? candidates.filter(item => scope.scopes.some(target => scope.matches(item, target)))\n : candidates;\n if (items.length === 0) continue;\n summary.projects += 1;\n\n for (const item of items) {\n summary.checked += 1;\n try {\n const missingAt = item.workItem.metadata?.[EXTERNAL_SOURCE_MISSING_KEY];\n const missingTime = typeof missingAt === 'string' ? Date.parse(missingAt) : Number.NaN;\n const missingAge = now().getTime() - missingTime;\n if (Number.isFinite(missingTime) && missingAge >= 0 && missingAge < MISSING_RECHECK_MS) {\n summary.missing += 1;\n continue;\n }\n\n const resolved = await options.intake.resolveIntakeDispatch?.({\n orgId: project.orgId,\n externalSource: options.externalSource?.(item) ?? item.externalSource!,\n });\n if (!resolved) {\n await options.storage.syncCard({\n orgId: project.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: { [EXTERNAL_SOURCE_MISSING_KEY]: now().toISOString() } },\n });\n summary.missing += 1;\n continue;\n }\n const issueId = options.issueId(item) ?? resolved.issueId;\n const issue = await options.intake.getIssue({ ...resolved, issueId });\n if (!issue) {\n await options.storage.syncCard({\n orgId: project.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: { [EXTERNAL_SOURCE_MISSING_KEY]: now().toISOString() } },\n });\n summary.missing += 1;\n continue;\n }\n\n const hadMissingMarker = typeof missingAt === 'string';\n const baseMetadata = cardMetadata(item);\n // Close detection for Linear: replay through rules ingress if closed\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !options.isTerminal(item) && options.onClosed) {\n const closedMetadata = withoutUndefined((await options.onClosed(item, issue, project, resolved)) ?? {});\n if (hadMissingMarker || !metadataMatches(baseMetadata, closedMetadata)) {\n const storedMetadata = await storedCardMetadata(options, project, item);\n if (!storedMetadata) continue;\n await options.storage.syncCard({\n orgId: project.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: {\n ...storedMetadata,\n ...closedMetadata,\n ...(hadMissingMarker ? { [EXTERNAL_SOURCE_MISSING_KEY]: undefined } : {}),\n },\n },\n });\n summary.updated += 1;\n }\n summary.closed += 1;\n continue;\n }\n\n const metadata = withoutUndefined(await options.metadata(item, issue, resolved));\n if (!hadMissingMarker && metadataMatches(baseMetadata, metadata)) continue;\n const storedMetadata = await storedCardMetadata(options, project, item);\n if (!storedMetadata) continue;\n await options.storage.syncCard({\n orgId: project.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: {\n ...storedMetadata,\n ...metadata,\n ...(hadMissingMarker ? { [EXTERNAL_SOURCE_MISSING_KEY]: undefined } : {}),\n },\n },\n });\n summary.updated += 1;\n } catch (error) {\n summary.failed += 1;\n summary.errors.push({\n projectId: project.id,\n workItemId: item.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n return summary;\n };\n\n return run as IssueReconciler<TScope>;\n}\n"],"mappings":";;AAMA,MAAa,8BAA8B;AAC3C,MAAM,qBAAqB;AA6D3B,SAAS,UAAU,MAAe,OAAyB;CACzD,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,IAAI,CAAC,MAAM,QAAQ,IAAI,GAAG,OAAO,MAAM,WAAW;EAClD,MAAM,cAAc,KACjB,QAAQ,UAA2B,OAAO,UAAU,QAAQ,CAAC,CAC7D,MAAM,CAAC,CACP,KAAK;EACR,MAAM,eAAe,MAClB,QAAQ,UAA2B,OAAO,UAAU,QAAQ,CAAC,CAC7D,MAAM,CAAC,CACP,KAAK;EACR,OACE,YAAY,WAAW,aAAa,UAAU,YAAY,OAAO,OAAO,UAAU,UAAU,aAAa,MAAM;CAEnH;CACA,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAAG,OAAO;EAC7E,MAAM,aAAa;EACnB,MAAM,cAAc;EACpB,MAAM,WAAW,OAAO,KAAK,UAAU;EACvC,MAAM,YA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cAAc,QAAQ,GAAG;KAClE,MAAM,iBAAiB,MAAM,mBAAmB,SAAS,SAAS,IAAI;KACtE,IAAI,CAAC,gBAAgB;KACrB,MAAM,QAAQ,QAAQ,SAAS;MAC7B,OAAO,QAAQ;MACf,IAAI,KAAK;MACT,QAAQ;MACR,OAAO,EACL,UAAU;OACR,GAAG;OACH,GAAG;OACH,GAAI,mBAAmB,GAAG,8BAA8B,KAAA,EAAU,IAAI,CAAC;MACzE,EACF;KACF,CAAC;KACD,QAAQ,WAAW;IACrB,SAAS,OAAO;KACd,QAAQ,UAAU;KAClB,QAAQ,OAAO,KAAK;MAClB,WAAW,QAAQ;MACnB,YAAY,KAAK;MACjB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;KAC9D,CAAC;IACH;GACF;EACF;EAEA,OAAO;CACT;CAEA,OAAO;AACT"}
|
|
@@ -99,8 +99,9 @@ export declare class JiraIntegration implements FactoryIntegration {
|
|
|
99
99
|
routes(ctx: IntegrationContext): ApiRoute[];
|
|
100
100
|
/**
|
|
101
101
|
* Background reconciliation, matching the Platform integration: keeps filed
|
|
102
|
-
* Jira cards' metadata fresh
|
|
103
|
-
* ingress. Registered only when
|
|
102
|
+
* Jira cards' metadata fresh, replays close events through the rules
|
|
103
|
+
* ingress, and files the issues nobody has carded yet. Registered only when
|
|
104
|
+
* reconciliation is enabled.
|
|
104
105
|
*/
|
|
105
106
|
workers(ctx: IntegrationContext): MastraWorker[];
|
|
106
107
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../src/integrations/jira/integration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEx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E,EAC1B,MAAM,CAAC,EAAE,MAAM,EAAE,GAChB,OAAO,CAAC;QAAE,MAAM,EAAE,KAAK,CAAC,WAAW,GAAG;YAAE,QAAQ,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAc3F;IA6GD;;;;OAIG;IACH,MAAM,CAAC,GAAG,EAAE,kBAAkB,GAAG,QAAQ,EAAE,CAO1C;IAED;;;;;OAKG;IACH,OAAO,CAAC,GAAG,EAAE,kBAAkB,GAAG,YAAY,EAAE,CAW/C;IAED;;;;OAIG;IACG,UAAU,CAAC,IAAI,EAAE;QAAE,cAAc,EAAE,cAAc,CAAA;KAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAEpF;IAED,sEAAsE;IACtE,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMrC;CACF"}
|
|
@@ -5,9 +5,8 @@ import { JiraApiClient, JiraApiError } from "./api.js";
|
|
|
5
5
|
import { resolveJiraRules } from "./default-rules.js";
|
|
6
6
|
import { buildIntakeJql, unfilteredJiraScopes } from "./intake-jql.js";
|
|
7
7
|
import { attachJiraIssueReconciler } from "./issue-reconciler.js";
|
|
8
|
-
import {
|
|
8
|
+
import { jiraReconciliationInterval } from "./reconciliation-config.js";
|
|
9
9
|
import { buildJiraRoutes } from "./routes.js";
|
|
10
|
-
import { attachJiraRules } from "./rules.js";
|
|
11
10
|
// src/integrations/jira/integration.ts
|
|
12
11
|
/** Hard stop for comment pagination so a misbehaving `total` can't loop forever. */
|
|
13
12
|
const ISSUE_COMMENTS_MAX_PAGES = 20;
|
|
@@ -345,17 +344,16 @@ var JiraIntegration = class {
|
|
|
345
344
|
jira: this,
|
|
346
345
|
auth: ctx.auth,
|
|
347
346
|
intake: ctx.storage.intake,
|
|
348
|
-
workItems: ctx.runtime?.workItems
|
|
349
|
-
ingestFactoryIssues: attachJiraRules(this, ctx)
|
|
347
|
+
workItems: ctx.runtime?.workItems
|
|
350
348
|
});
|
|
351
349
|
}
|
|
352
350
|
/**
|
|
353
351
|
* Background reconciliation, matching the Platform integration: keeps filed
|
|
354
|
-
* Jira cards' metadata fresh
|
|
355
|
-
* ingress. Registered only when
|
|
352
|
+
* Jira cards' metadata fresh, replays close events through the rules
|
|
353
|
+
* ingress, and files the issues nobody has carded yet. Registered only when
|
|
354
|
+
* reconciliation is enabled.
|
|
356
355
|
*/
|
|
357
356
|
workers(ctx) {
|
|
358
|
-
if (!jiraReconciliationEnabled()) return [];
|
|
359
357
|
const reconcile = attachJiraIssueReconciler(this, ctx);
|
|
360
358
|
if (!reconcile) return [];
|
|
361
359
|
const intervalMs = jiraReconciliationInterval();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/jira/integration.ts"],"sourcesContent":["/**\n * `JiraIntegration` — the self-contained Jira Cloud integration.\n *\n * Implements the system-wide `FactoryIntegration` contract\n * (`../base.ts`): the deploy entry reads the `JIRA_*` env vars ONCE,\n * constructs an instance with explicit credentials, and passes it to\n * `MastraFactory`. Everything Jira-flavored the system does — project/issue\n * reads for Intake and the agent's issue tools — flows through this\n * instance. No other module reads `JIRA_*` env vars.\n *\n * Unlike Linear, credentials are **deployment-global** (Basic auth with\n * `email:apiToken` from the environment): there is no OAuth flow, no state\n * signer, and no per-org connection storage. The `IntegrationConnection`\n * arguments required by the `Intake` contract are accepted but not consulted\n * — the instance's own credentials authenticate every call.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\n\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n CreatedIntakeComment,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n IntakeItemPage,\n IntakeSource,\n ListIntakeIssuesInput,\n ListIntakeItemsInput,\n ResolveIntakeDispatchInput,\n ResolvedIntakeDispatch,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { adfToText } from './adf.js';\nimport { buildJiraAgentTools } from './agent-tools.js';\nimport type { JiraComment, JiraIssue, JiraTransition } from './api.js';\nimport { JiraApiClient, JiraApiError } from './api.js';\nimport type { JiraEventRules, JiraRuleOverrides } from './default-rules.js';\nimport { resolveJiraRules } from './default-rules.js';\nimport { buildIntakeJql, unfilteredJiraScopes } from './intake-jql.js';\nimport type { JiraIntakeScope } from './intake-jql.js';\nimport { attachJiraIssueReconciler } from './issue-reconciler.js';\nimport { jiraReconciliationEnabled, jiraReconciliationInterval } from './reconciliation-config.js';\nimport { buildJiraRoutes } from './routes.js';\nimport { attachJiraRules } from './rules.js';\n\n/** Deployment-global Jira Cloud credentials. All credential fields are required. */\nexport interface JiraIntegrationConfig {\n /** Site base URL, e.g. `https://acme.atlassian.net`, used for browser links. */\n baseUrl: string;\n /** API base URL for scoped tokens. Defaults to `baseUrl`. */\n apiBaseUrl?: string;\n /** Atlassian account email the API token belongs to. */\n email: string;\n /** API token from id.atlassian.com → Security → API tokens. */\n apiToken: string;\n /** Per-event replacements; omitted events retain defaults, null disables. */\n rules?: JiraRuleOverrides;\n}\n\n/** Hard stop for comment pagination so a misbehaving `total` can't loop forever. */\nconst ISSUE_COMMENTS_MAX_PAGES = 20;\n\n/** Hard stop for project pagination so a misbehaving `isLast` can't loop forever. */\nconst PROJECT_SEARCH_MAX_PAGES = 50;\n\n/**\n * The `Intake` contract requires a connection argument, but Jira credentials\n * live on the integration instance — this inert placeholder is accepted and\n * ignored everywhere, and keeps the real API token out of resolved dispatches\n * and agent-tool calls.\n */\nexport const DEPLOYMENT_CONNECTION: IntegrationConnection = { type: 'oauth', accessToken: 'deployment-global' };\n\n/** Jira issue keys look like `ENG-42`. */\nconst ISSUE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]*-\\d+$/;\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction normalizeSiteBaseUrl(baseUrl: string): string {\n let parsed: URL;\n try {\n parsed = new URL(baseUrl);\n } catch {\n throw new Error(`JiraIntegration baseUrl is not an absolute URL: \"${baseUrl}\".`);\n }\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {\n throw new Error(`JiraIntegration baseUrl must be an http(s) URL: \"${baseUrl}\".`);\n }\n return baseUrl.replace(/\\/+$/, '');\n}\n\n/**\n * Capability state types (`capabilities/intake.ts`) → Jira status-category\n * keys. `canceled` has no Jira category — it is resolved separately against\n * `done`-category transitions whose status name contains \"cancel\".\n */\nconst STATE_TYPE_TO_CATEGORY: Record<'unstarted' | 'started' | 'completed', string> = {\n unstarted: 'new',\n started: 'indeterminate',\n completed: 'done',\n};\n\n/** Jira status-category keys → capability state types. */\nfunction stateTypeFromCategory(key: string | undefined): string | null {\n switch (key) {\n case 'new':\n return 'unstarted';\n case 'indeterminate':\n return 'started';\n case 'done':\n return 'completed';\n default:\n return null;\n }\n}\n\nexport class JiraIntegration implements FactoryIntegration {\n /** Stable integration identifier (see `../base.ts`). */\n readonly id = 'jira';\n\n readonly #config: JiraIntegrationConfig;\n readonly #baseUrl: string;\n /** Typed REST client bound to the deployment credentials. */\n readonly api: JiraApiClient;\n\n /** Bound once by the factory via `initialize()` before any surface is used. */\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n readonly #orgIdByResourceId = new Map<string, string | null>();\n\n readonly #rules: JiraEventRules;\n\n get rules(): JiraEventRules {\n return this.#rules;\n }\n\n constructor(config: JiraIntegrationConfig) {\n this.#rules = resolveJiraRules(config.rules);\n this.#baseUrl = normalizeSiteBaseUrl(config.baseUrl);\n // JiraApiClient validates the credential group and normalizes the API URL.\n this.api = new JiraApiClient({ ...config, baseUrl: config.apiBaseUrl ?? config.baseUrl });\n this.#config = config;\n }\n\n /**\n * Bind the projects domain and the host auth seam. Jira has no per-org\n * connection rows, so the generic storage handle is unused — credentials\n * are deployment-global constructor config.\n */\n initialize({ projects, auth }: { projects: FactoryProjectsStorage; auth: RouteAuth }): void {\n this.#projects = projects;\n this.#auth = auth;\n }\n\n /** Factory projects domain — maps a session's resourceId to its owning org. */\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error('JiraIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#projects;\n }\n\n /**\n * Whether the host runs with web auth enabled. Intake selections are\n * org-owned, so every Jira surface is inert without a tenant auth seam.\n */\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n /**\n * Map a session's resourceId (the factory project id) to its owning org.\n * Same caching semantics as the Linear integration: definitive misses are\n * cached, transient database failures are not.\n */\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n // Non-UUID resource ids (local/dev resources) would make the uuid column\n // comparison throw — they're definitively \"not a project\", so cache that.\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n let orgId: string | null;\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n orgId = project?.orgId ?? null;\n } catch {\n // Transient database failure: skip the tools for this request but don't\n // cache the miss, so the next request retries the lookup.\n return null;\n }\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n }\n\n /** Test hook: clear the org cache between specs. */\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n }\n\n /** Normalized site base URL (no trailing slash) — `/browse/<key>` links hang off this. */\n get baseUrl(): string {\n return this.#baseUrl;\n }\n\n readonly intake: Intake = {\n bindingLabelFilters: true,\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: () => this.#listSources(),\n listItems: input => this.#listItems(input),\n listIssues: input => this.#listIssues(input),\n getIssue: input => this.#getIssue(input),\n createComment: input => this.#createComment(input),\n updateIssue: input => this.#updateIssue(input),\n };\n\n /**\n * Background-dispatch context. Credentials are deployment-global, so the\n * returned connection is a formality the Jira intake methods ignore; the\n * issue key is stored directly as the work item's `externalId` (mirroring\n * Linear, which stores the issue UUID).\n */\n async #resolveIntakeDispatch({ externalSource }: ResolveIntakeDispatchInput): Promise<ResolvedIntakeDispatch | null> {\n if (externalSource.type !== 'issue') return null;\n return {\n // Inert placeholder, never the real token: the Jira intake methods read\n // credentials from the client, and the resolved dispatch travels through\n // generic reconciler/dispatcher code that must stay secret-free.\n connection: DEPLOYMENT_CONNECTION,\n issueId: externalSource.externalId,\n };\n }\n\n /** All the site's projects (Settings intake-source picker), following `isLast` paging. */\n async #listSources(): Promise<IntakeSource[]> {\n const sources: IntakeSource[] = [];\n let startAt = 0;\n for (let pageCount = 0; pageCount < PROJECT_SEARCH_MAX_PAGES; pageCount++) {\n const page = await this.api.listProjects({ startAt });\n for (const project of page.values) {\n sources.push({\n id: project.id,\n name: project.name,\n type: 'project',\n metadata: { key: project.key },\n });\n }\n if (page.isLast || page.values.length === 0) break;\n startAt += page.values.length;\n }\n return sources;\n }\n\n async #listItems({ sourceIds, cursor }: ListIntakeItemsInput): Promise<IntakeItemPage> {\n if (sourceIds.length === 0) return { items: [], nextCursor: null };\n const page = await this.listActiveIssues(cursor, unfilteredJiraScopes(sourceIds));\n return {\n items: page.issues.map(issue => ({\n source: { type: 'issue', externalId: issue.identifier, url: issue.url },\n sourceId: issue.sourceId,\n title: `${issue.identifier}: ${issue.title}`,\n status: issue.state ?? undefined,\n labels: issue.labels,\n assignee: issue.assignee,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: {\n identifier: issue.identifier,\n issueRef: issue.identifier,\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 })),\n nextCursor: page.nextCursor,\n };\n }\n\n async #listIssues(input: ListIntakeIssuesInput): Promise<{ issues: IntakeIssue[]; nextCursor: string | null }> {\n const page = await this.listActiveIssues(\n input.cursor,\n input.sourceIds ? unfilteredJiraScopes(input.sourceIds) : undefined,\n input.labels,\n );\n return { issues: page.issues, nextCursor: page.nextCursor };\n }\n\n /**\n * One page of active issues (status category not Done), most recently\n * updated first, optionally narrowed to the given project scopes and labels.\n * The capability cursor is Jira's opaque `nextPageToken` passed through.\n */\n async listActiveIssues(\n cursor?: string,\n scopes?: JiraIntakeScope[],\n labels?: string[],\n ): Promise<{ issues: Array<IntakeIssue & { sourceId: string }>; nextCursor: string | null }> {\n const jql = buildIntakeJql(scopes, labels);\n if (jql === null) return { issues: [], nextCursor: null };\n const page = await this.api.searchIssues({\n jql,\n ...(cursor ? { nextPageToken: cursor } : {}),\n });\n return {\n issues: page.issues.map(issue => ({\n ...this.#toIntakeIssue(issue),\n sourceId: issue.fields.project?.id ?? '',\n })),\n nextCursor: page.nextPageToken ?? null,\n };\n }\n\n async #getIssue({ issueId }: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n let issue: JiraIssue;\n try {\n issue = await this.api.getIssue(issueId);\n } catch (err) {\n if (err instanceof JiraApiError && err.status === 404) return null;\n throw err;\n }\n const { comments, total } = await this.#listAllComments(issue.key);\n return {\n ...this.#toIntakeIssue(issue),\n commentCount: total,\n description: issue.fields.description ? adfToText(issue.fields.description) || null : null,\n comments: comments.map(comment => ({\n author: comment.author?.displayName ?? null,\n body: adfToText(comment.body),\n createdAt: comment.created,\n })),\n };\n }\n\n /** Every comment on the issue, oldest first, bounded by {@link ISSUE_COMMENTS_MAX_PAGES}. */\n async #listAllComments(keyOrId: string): Promise<{ comments: JiraComment[]; total: number }> {\n const comments: JiraComment[] = [];\n let total = 0;\n for (let page = 0; page < ISSUE_COMMENTS_MAX_PAGES; page++) {\n const result = await this.api.listComments(keyOrId, { startAt: comments.length });\n comments.push(...result.comments);\n total = result.total;\n if (result.comments.length === 0 || comments.length >= total) break;\n }\n return { comments, total };\n }\n\n async #createComment({ issueId, body }: CreateIntakeCommentInput): Promise<CreatedIntakeComment | null> {\n // The browse URL needs the issue key; resolve it when the caller passed a\n // numeric id instead.\n let key = issueId;\n if (!ISSUE_KEY_PATTERN.test(issueId)) {\n try {\n key = (await this.api.getIssue(issueId)).key;\n } catch (err) {\n if (err instanceof JiraApiError && err.status === 404) return null;\n throw err;\n }\n }\n let comment;\n try {\n comment = await this.api.createComment(key, body);\n } catch (err) {\n if (err instanceof JiraApiError && err.status === 404) return null;\n throw err;\n }\n return {\n id: comment.id,\n url: `${this.baseUrl}/browse/${key}?focusedCommentId=${comment.id}`,\n };\n }\n\n /**\n * Move an issue to a target state by applying a workflow transition. Jira\n * only exposes transitions that are currently legal, so a policy miss (no\n * transition reaches the target) returns `null` per the `Intake` contract —\n * infrastructure errors (network, auth) still throw.\n */\n async #updateIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n let issue: JiraIssue;\n try {\n issue = await this.api.getIssue(input.issueId);\n } catch (err) {\n if (err instanceof JiraApiError && err.status === 404) return null;\n throw err;\n }\n if (currentStatusMatches(issue, input.state)) {\n return this.#toIntakeIssue(issue);\n }\n const transitions = await this.api.listTransitions(issue.key);\n const transition = resolveTransition(transitions, input.state);\n if (!transition) return null;\n await this.api.applyTransition(issue.key, transition.id);\n const fresh = await this.api.getIssue(issue.key);\n return this.#toIntakeIssue(fresh);\n }\n\n #toIntakeIssue(issue: JiraIssue): IntakeIssue {\n const { fields } = issue;\n return {\n id: issue.id,\n identifier: issue.key,\n title: fields.summary ?? issue.key,\n url: `${this.baseUrl}/browse/${issue.key}`,\n author: fields.reporter?.displayName ?? null,\n state: fields.status?.name ?? null,\n stateType: stateTypeFromCategory(fields.status?.statusCategory?.key),\n priority: fields.priority?.name ?? null,\n assignee: fields.assignee?.displayName ?? null,\n source: fields.project?.key ?? null,\n sourceId: fields.project?.id ?? null,\n labels: fields.labels ?? [],\n commentCount: null,\n createdAt: fields.created ?? '',\n updatedAt: fields.updated ?? '',\n };\n }\n\n // ── FactoryIntegration surface ───────────────────────────────────────────\n\n /**\n * The integration's HTTP surface: `/web/jira/*` Mastra `apiRoutes` (status,\n * projects + issues for Intake). No OAuth routes — credentials are\n * deployment-global. Handlers operate on this instance.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n return buildJiraRoutes({\n jira: this,\n auth: ctx.auth,\n intake: ctx.storage.intake,\n workItems: ctx.runtime?.workItems,\n ingestFactoryIssues: attachJiraRules(this, ctx),\n });\n }\n\n /**\n * Background reconciliation, matching the Platform integration: keeps filed\n * Jira cards' metadata fresh and replays close events through the rules\n * ingress. Registered only when reconciliation is enabled.\n */\n workers(ctx: IntegrationContext): MastraWorker[] {\n if (!jiraReconciliationEnabled()) return [];\n const reconcile = attachJiraIssueReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = jiraReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * Org-scoped agent tools: the read-only issue-detail tool for sessions whose\n * resource is a factory project (Jira credentials are deployment-global,\n * so no per-org connection gates apply). v1 exposes no mutating Jira tools.\n */\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildJiraAgentTools({ requestContext: args.requestContext, jira: this });\n }\n\n /** Non-secret config snapshot for system diagnostics/startup logs. */\n diagnostics(): Record<string, unknown> {\n return {\n configured: true,\n site: new URL(this.baseUrl).host,\n email: maskEmail(this.#config.email),\n };\n }\n}\n\n/** `ops@acme.test` → `o***@acme.test` — enough to identify, never the value. */\nfunction maskEmail(email: string): string {\n const at = email.indexOf('@');\n if (at <= 0) return '***';\n return `${email[0]}***${email.slice(at)}`;\n}\n\n/** Whether the issue is already in the requested target state. */\nfunction currentStatusMatches(issue: JiraIssue, target: UpdateIntakeIssueInput['state']): boolean {\n const status = issue.fields.status;\n if (!status) return false;\n if (target.kind === 'byName') {\n return status.name.toLowerCase() === target.name.toLowerCase();\n }\n if (target.stateType === 'canceled') {\n return status.statusCategory?.key === 'done' && /cancel/i.test(status.name);\n }\n return status.statusCategory?.key === STATE_TYPE_TO_CATEGORY[target.stateType];\n}\n\n/** Resolve the target state against the issue's currently-legal transitions. */\nfunction resolveTransition(\n transitions: JiraTransition[],\n target: UpdateIntakeIssueInput['state'],\n): JiraTransition | null {\n if (target.kind === 'byName') {\n const wanted = target.name.toLowerCase();\n return transitions.find(transition => transition.to?.name.toLowerCase() === wanted) ?? null;\n }\n if (target.stateType === 'canceled') {\n return (\n transitions.find(\n transition => transition.to?.statusCategory?.key === 'done' && /cancel/i.test(transition.to.name),\n ) ?? null\n );\n }\n const category = STATE_TYPE_TO_CATEGORY[target.stateType];\n return transitions.find(transition => transition.to?.statusCategory?.key === category) ?? null;\n}\n"],"mappings":";;;;;;;;;;;;AAqEA,MAAM,2BAA2B;;AAGjC,MAAM,2BAA2B;;;;;;;AAQjC,MAAa,wBAA+C;CAAE,MAAM;CAAS,aAAa;AAAoB;;AAG9G,MAAM,oBAAoB;AAE1B,MAAM,eAAe;AAErB,SAAS,qBAAqB,SAAyB;CACrD,IAAI;CACJ,IAAI;EACF,SAAS,IAAI,IAAI,OAAO;CAC1B,QAAQ;EACN,MAAM,IAAI,MAAM,oDAAoD,QAAQ,GAAG;CACjF;CACA,IAAI,OAAO,aAAa,YAAY,OAAO,aAAa,SACtD,MAAM,IAAI,MAAM,oDAAoD,QAAQ,GAAG;CAEjF,OAAO,QAAQ,QAAQ,QAAQ,EAAE;AACnC;;;;;;AAOA,MAAM,yBAAgF;CACpF,WAAW;CACX,SAAS;CACT,WAAW;AACb;;AAGA,SAAS,sBAAsB,KAAwC;CACrE,QAAQ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,IAAI,gBAAgB,QAAQ,QAAQ,KAAK;AAC5F"}
|
|
1
|
+
{"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/jira/integration.ts"],"sourcesContent":["/**\n * `JiraIntegration` — the self-contained Jira Cloud integration.\n *\n * Implements the system-wide `FactoryIntegration` contract\n * (`../base.ts`): the deploy entry reads the `JIRA_*` env vars ONCE,\n * constructs an instance with explicit credentials, and passes it to\n * `MastraFactory`. Everything Jira-flavored the system does — project/issue\n * reads for Intake and the agent's issue tools — flows through this\n * instance. No other module reads `JIRA_*` env vars.\n *\n * Unlike Linear, credentials are **deployment-global** (Basic auth with\n * `email:apiToken` from the environment): there is no OAuth flow, no state\n * signer, and no per-org connection storage. The `IntegrationConnection`\n * arguments required by the `Intake` contract are accepted but not consulted\n * — the instance's own credentials authenticate every call.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\n\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n CreatedIntakeComment,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n IntakeItemPage,\n IntakeSource,\n ListIntakeIssuesInput,\n ListIntakeItemsInput,\n ResolveIntakeDispatchInput,\n ResolvedIntakeDispatch,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { adfToText } from './adf.js';\nimport { buildJiraAgentTools } from './agent-tools.js';\nimport type { JiraComment, JiraIssue, JiraTransition } from './api.js';\nimport { JiraApiClient, JiraApiError } from './api.js';\nimport type { JiraEventRules, JiraRuleOverrides } from './default-rules.js';\nimport { resolveJiraRules } from './default-rules.js';\nimport { buildIntakeJql, unfilteredJiraScopes } from './intake-jql.js';\nimport type { JiraIntakeScope } from './intake-jql.js';\nimport { attachJiraIssueReconciler } from './issue-reconciler.js';\nimport { jiraReconciliationInterval } from './reconciliation-config.js';\nimport { buildJiraRoutes } from './routes.js';\n\n/** Deployment-global Jira Cloud credentials. All credential fields are required. */\nexport interface JiraIntegrationConfig {\n /** Site base URL, e.g. `https://acme.atlassian.net`, used for browser links. */\n baseUrl: string;\n /** API base URL for scoped tokens. Defaults to `baseUrl`. */\n apiBaseUrl?: string;\n /** Atlassian account email the API token belongs to. */\n email: string;\n /** API token from id.atlassian.com → Security → API tokens. */\n apiToken: string;\n /** Per-event replacements; omitted events retain defaults, null disables. */\n rules?: JiraRuleOverrides;\n}\n\n/** Hard stop for comment pagination so a misbehaving `total` can't loop forever. */\nconst ISSUE_COMMENTS_MAX_PAGES = 20;\n\n/** Hard stop for project pagination so a misbehaving `isLast` can't loop forever. */\nconst PROJECT_SEARCH_MAX_PAGES = 50;\n\n/**\n * The `Intake` contract requires a connection argument, but Jira credentials\n * live on the integration instance — this inert placeholder is accepted and\n * ignored everywhere, and keeps the real API token out of resolved dispatches\n * and agent-tool calls.\n */\nexport const DEPLOYMENT_CONNECTION: IntegrationConnection = { type: 'oauth', accessToken: 'deployment-global' };\n\n/** Jira issue keys look like `ENG-42`. */\nconst ISSUE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]*-\\d+$/;\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction normalizeSiteBaseUrl(baseUrl: string): string {\n let parsed: URL;\n try {\n parsed = new URL(baseUrl);\n } catch {\n throw new Error(`JiraIntegration baseUrl is not an absolute URL: \"${baseUrl}\".`);\n }\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {\n throw new Error(`JiraIntegration baseUrl must be an http(s) URL: \"${baseUrl}\".`);\n }\n return baseUrl.replace(/\\/+$/, '');\n}\n\n/**\n * Capability state types (`capabilities/intake.ts`) → Jira status-category\n * keys. `canceled` has no Jira category — it is resolved separately against\n * `done`-category transitions whose status name contains \"cancel\".\n */\nconst STATE_TYPE_TO_CATEGORY: Record<'unstarted' | 'started' | 'completed', string> = {\n unstarted: 'new',\n started: 'indeterminate',\n completed: 'done',\n};\n\n/** Jira status-category keys → capability state types. */\nfunction stateTypeFromCategory(key: string | undefined): string | null {\n switch (key) {\n case 'new':\n return 'unstarted';\n case 'indeterminate':\n return 'started';\n case 'done':\n return 'completed';\n default:\n return null;\n }\n}\n\nexport class JiraIntegration implements FactoryIntegration {\n /** Stable integration identifier (see `../base.ts`). */\n readonly id = 'jira';\n\n readonly #config: JiraIntegrationConfig;\n readonly #baseUrl: string;\n /** Typed REST client bound to the deployment credentials. */\n readonly api: JiraApiClient;\n\n /** Bound once by the factory via `initialize()` before any surface is used. */\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n readonly #orgIdByResourceId = new Map<string, string | null>();\n\n readonly #rules: JiraEventRules;\n\n get rules(): JiraEventRules {\n return this.#rules;\n }\n\n constructor(config: JiraIntegrationConfig) {\n this.#rules = resolveJiraRules(config.rules);\n this.#baseUrl = normalizeSiteBaseUrl(config.baseUrl);\n // JiraApiClient validates the credential group and normalizes the API URL.\n this.api = new JiraApiClient({ ...config, baseUrl: config.apiBaseUrl ?? config.baseUrl });\n this.#config = config;\n }\n\n /**\n * Bind the projects domain and the host auth seam. Jira has no per-org\n * connection rows, so the generic storage handle is unused — credentials\n * are deployment-global constructor config.\n */\n initialize({ projects, auth }: { projects: FactoryProjectsStorage; auth: RouteAuth }): void {\n this.#projects = projects;\n this.#auth = auth;\n }\n\n /** Factory projects domain — maps a session's resourceId to its owning org. */\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error('JiraIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#projects;\n }\n\n /**\n * Whether the host runs with web auth enabled. Intake selections are\n * org-owned, so every Jira surface is inert without a tenant auth seam.\n */\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n /**\n * Map a session's resourceId (the factory project id) to its owning org.\n * Same caching semantics as the Linear integration: definitive misses are\n * cached, transient database failures are not.\n */\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n // Non-UUID resource ids (local/dev resources) would make the uuid column\n // comparison throw — they're definitively \"not a project\", so cache that.\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n let orgId: string | null;\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n orgId = project?.orgId ?? null;\n } catch {\n // Transient database failure: skip the tools for this request but don't\n // cache the miss, so the next request retries the lookup.\n return null;\n }\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n }\n\n /** Test hook: clear the org cache between specs. */\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n }\n\n /** Normalized site base URL (no trailing slash) — `/browse/<key>` links hang off this. */\n get baseUrl(): string {\n return this.#baseUrl;\n }\n\n readonly intake: Intake = {\n bindingLabelFilters: true,\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: () => this.#listSources(),\n listItems: input => this.#listItems(input),\n listIssues: input => this.#listIssues(input),\n getIssue: input => this.#getIssue(input),\n createComment: input => this.#createComment(input),\n updateIssue: input => this.#updateIssue(input),\n };\n\n /**\n * Background-dispatch context. Credentials are deployment-global, so the\n * returned connection is a formality the Jira intake methods ignore; the\n * issue key is stored directly as the work item's `externalId` (mirroring\n * Linear, which stores the issue UUID).\n */\n async #resolveIntakeDispatch({ externalSource }: ResolveIntakeDispatchInput): Promise<ResolvedIntakeDispatch | null> {\n if (externalSource.type !== 'issue') return null;\n return {\n // Inert placeholder, never the real token: the Jira intake methods read\n // credentials from the client, and the resolved dispatch travels through\n // generic reconciler/dispatcher code that must stay secret-free.\n connection: DEPLOYMENT_CONNECTION,\n issueId: externalSource.externalId,\n };\n }\n\n /** All the site's projects (Settings intake-source picker), following `isLast` paging. */\n async #listSources(): Promise<IntakeSource[]> {\n const sources: IntakeSource[] = [];\n let startAt = 0;\n for (let pageCount = 0; pageCount < PROJECT_SEARCH_MAX_PAGES; pageCount++) {\n const page = await this.api.listProjects({ startAt });\n for (const project of page.values) {\n sources.push({\n id: project.id,\n name: project.name,\n type: 'project',\n metadata: { key: project.key },\n });\n }\n if (page.isLast || page.values.length === 0) break;\n startAt += page.values.length;\n }\n return sources;\n }\n\n async #listItems({ sourceIds, cursor }: ListIntakeItemsInput): Promise<IntakeItemPage> {\n if (sourceIds.length === 0) return { items: [], nextCursor: null };\n const page = await this.listActiveIssues(cursor, unfilteredJiraScopes(sourceIds));\n return {\n items: page.issues.map(issue => ({\n source: { type: 'issue', externalId: issue.identifier, url: issue.url },\n sourceId: issue.sourceId,\n title: `${issue.identifier}: ${issue.title}`,\n status: issue.state ?? undefined,\n labels: issue.labels,\n assignee: issue.assignee,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: {\n identifier: issue.identifier,\n issueRef: issue.identifier,\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 })),\n nextCursor: page.nextCursor,\n };\n }\n\n async #listIssues(input: ListIntakeIssuesInput): Promise<{ issues: IntakeIssue[]; nextCursor: string | null }> {\n const page = await this.listActiveIssues(\n input.cursor,\n input.sourceIds ? unfilteredJiraScopes(input.sourceIds) : undefined,\n input.labels,\n );\n return { issues: page.issues, nextCursor: page.nextCursor };\n }\n\n /**\n * One page of active issues (status category not Done), most recently\n * updated first, optionally narrowed to the given project scopes and labels.\n * The capability cursor is Jira's opaque `nextPageToken` passed through.\n */\n async listActiveIssues(\n cursor?: string,\n scopes?: JiraIntakeScope[],\n labels?: string[],\n ): Promise<{ issues: Array<IntakeIssue & { sourceId: string }>; nextCursor: string | null }> {\n const jql = buildIntakeJql(scopes, labels);\n if (jql === null) return { issues: [], nextCursor: null };\n const page = await this.api.searchIssues({\n jql,\n ...(cursor ? { nextPageToken: cursor } : {}),\n });\n return {\n issues: page.issues.map(issue => ({\n ...this.#toIntakeIssue(issue),\n sourceId: issue.fields.project?.id ?? '',\n })),\n nextCursor: page.nextPageToken ?? null,\n };\n }\n\n async #getIssue({ issueId }: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n let issue: JiraIssue;\n try {\n issue = await this.api.getIssue(issueId);\n } catch (err) {\n if (err instanceof JiraApiError && err.status === 404) return null;\n throw err;\n }\n const { comments, total } = await this.#listAllComments(issue.key);\n return {\n ...this.#toIntakeIssue(issue),\n commentCount: total,\n description: issue.fields.description ? adfToText(issue.fields.description) || null : null,\n comments: comments.map(comment => ({\n author: comment.author?.displayName ?? null,\n body: adfToText(comment.body),\n createdAt: comment.created,\n })),\n };\n }\n\n /** Every comment on the issue, oldest first, bounded by {@link ISSUE_COMMENTS_MAX_PAGES}. */\n async #listAllComments(keyOrId: string): Promise<{ comments: JiraComment[]; total: number }> {\n const comments: JiraComment[] = [];\n let total = 0;\n for (let page = 0; page < ISSUE_COMMENTS_MAX_PAGES; page++) {\n const result = await this.api.listComments(keyOrId, { startAt: comments.length });\n comments.push(...result.comments);\n total = result.total;\n if (result.comments.length === 0 || comments.length >= total) break;\n }\n return { comments, total };\n }\n\n async #createComment({ issueId, body }: CreateIntakeCommentInput): Promise<CreatedIntakeComment | null> {\n // The browse URL needs the issue key; resolve it when the caller passed a\n // numeric id instead.\n let key = issueId;\n if (!ISSUE_KEY_PATTERN.test(issueId)) {\n try {\n key = (await this.api.getIssue(issueId)).key;\n } catch (err) {\n if (err instanceof JiraApiError && err.status === 404) return null;\n throw err;\n }\n }\n let comment;\n try {\n comment = await this.api.createComment(key, body);\n } catch (err) {\n if (err instanceof JiraApiError && err.status === 404) return null;\n throw err;\n }\n return {\n id: comment.id,\n url: `${this.baseUrl}/browse/${key}?focusedCommentId=${comment.id}`,\n };\n }\n\n /**\n * Move an issue to a target state by applying a workflow transition. Jira\n * only exposes transitions that are currently legal, so a policy miss (no\n * transition reaches the target) returns `null` per the `Intake` contract —\n * infrastructure errors (network, auth) still throw.\n */\n async #updateIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n let issue: JiraIssue;\n try {\n issue = await this.api.getIssue(input.issueId);\n } catch (err) {\n if (err instanceof JiraApiError && err.status === 404) return null;\n throw err;\n }\n if (currentStatusMatches(issue, input.state)) {\n return this.#toIntakeIssue(issue);\n }\n const transitions = await this.api.listTransitions(issue.key);\n const transition = resolveTransition(transitions, input.state);\n if (!transition) return null;\n await this.api.applyTransition(issue.key, transition.id);\n const fresh = await this.api.getIssue(issue.key);\n return this.#toIntakeIssue(fresh);\n }\n\n #toIntakeIssue(issue: JiraIssue): IntakeIssue {\n const { fields } = issue;\n return {\n id: issue.id,\n identifier: issue.key,\n title: fields.summary ?? issue.key,\n url: `${this.baseUrl}/browse/${issue.key}`,\n author: fields.reporter?.displayName ?? null,\n state: fields.status?.name ?? null,\n stateType: stateTypeFromCategory(fields.status?.statusCategory?.key),\n priority: fields.priority?.name ?? null,\n assignee: fields.assignee?.displayName ?? null,\n source: fields.project?.key ?? null,\n sourceId: fields.project?.id ?? null,\n labels: fields.labels ?? [],\n commentCount: null,\n createdAt: fields.created ?? '',\n updatedAt: fields.updated ?? '',\n };\n }\n\n // ── FactoryIntegration surface ───────────────────────────────────────────\n\n /**\n * The integration's HTTP surface: `/web/jira/*` Mastra `apiRoutes` (status,\n * projects + issues for Intake). No OAuth routes — credentials are\n * deployment-global. Handlers operate on this instance.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n return buildJiraRoutes({\n jira: this,\n auth: ctx.auth,\n intake: ctx.storage.intake,\n workItems: ctx.runtime?.workItems,\n });\n }\n\n /**\n * Background reconciliation, matching the Platform integration: keeps filed\n * Jira cards' metadata fresh, replays close events through the rules\n * ingress, and files the issues nobody has carded yet. Registered only when\n * reconciliation is enabled.\n */\n workers(ctx: IntegrationContext): MastraWorker[] {\n const reconcile = attachJiraIssueReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = jiraReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * Org-scoped agent tools: the read-only issue-detail tool for sessions whose\n * resource is a factory project (Jira credentials are deployment-global,\n * so no per-org connection gates apply). v1 exposes no mutating Jira tools.\n */\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildJiraAgentTools({ requestContext: args.requestContext, jira: this });\n }\n\n /** Non-secret config snapshot for system diagnostics/startup logs. */\n diagnostics(): Record<string, unknown> {\n return {\n configured: true,\n site: new URL(this.baseUrl).host,\n email: maskEmail(this.#config.email),\n };\n }\n}\n\n/** `ops@acme.test` → `o***@acme.test` — enough to identify, never the value. */\nfunction maskEmail(email: string): string {\n const at = email.indexOf('@');\n if (at <= 0) return '***';\n return `${email[0]}***${email.slice(at)}`;\n}\n\n/** Whether the issue is already in the requested target state. */\nfunction currentStatusMatches(issue: JiraIssue, target: UpdateIntakeIssueInput['state']): boolean {\n const status = issue.fields.status;\n if (!status) return false;\n if (target.kind === 'byName') {\n return status.name.toLowerCase() === target.name.toLowerCase();\n }\n if (target.stateType === 'canceled') {\n return status.statusCategory?.key === 'done' && /cancel/i.test(status.name);\n }\n return status.statusCategory?.key === STATE_TYPE_TO_CATEGORY[target.stateType];\n}\n\n/** Resolve the target state against the issue's currently-legal transitions. */\nfunction resolveTransition(\n transitions: JiraTransition[],\n target: UpdateIntakeIssueInput['state'],\n): JiraTransition | null {\n if (target.kind === 'byName') {\n const wanted = target.name.toLowerCase();\n return transitions.find(transition => transition.to?.name.toLowerCase() === wanted) ?? null;\n }\n if (target.stateType === 'canceled') {\n return (\n transitions.find(\n transition => transition.to?.statusCategory?.key === 'done' && /cancel/i.test(transition.to.name),\n ) ?? null\n );\n }\n const category = STATE_TYPE_TO_CATEGORY[target.stateType];\n return transitions.find(transition => transition.to?.statusCategory?.key === category) ?? null;\n}\n"],"mappings":";;;;;;;;;;;AAoEA,MAAM,2BAA2B;;AAGjC,MAAM,2BAA2B;;;;;;;AAQjC,MAAa,wBAA+C;CAAE,MAAM;CAAS,aAAa;AAAoB;;AAG9G,MAAM,oBAAoB;AAE1B,MAAM,eAAe;AAErB,SAAS,qBAAqB,SAAyB;CACrD,IAAI;CACJ,IAAI;EACF,SAAS,IAAI,IAAI,OAAO;CAC1B,QAAQ;EACN,MAAM,IAAI,MAAM,oDAAoD,QAAQ,GAAG;CACjF;CACA,IAAI,OAAO,aAAa,YAAY,OAAO,aAAa,SACtD,MAAM,IAAI,MAAM,oDAAoD,QAAQ,GAAG;CAEjF,OAAO,QAAQ,QAAQ,QAAQ,EAAE;AACnC;;;;;;AAOA,MAAM,yBAAgF;CACpF,WAAW;CACX,SAAS;CACT,WAAW;AACb;;AAGA,SAAS,sBAAsB,KAAwC;CACrE,QAAQ,KAAR;EACE,KAAK,OACH,OAAO;EACT,KAAK,iBACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,IAAa,kBAAb,MAA2D;;CAEzD,KAAc;CAEd;CACA;;CAEA;;CAGA;CACA;CACA,qCAA8B,IAAI,IAA2B;CAE7D;CAEA,IAAI,QAAwB;EAC1B,OAAO,KAAK;CACd;CAEA,YAAY,QAA+B;EACzC,KAAK,SAAS,iBAAiB,OAAO,KAAK;EAC3C,KAAK,WAAW,qBAAqB,OAAO,OAAO;EAEnD,KAAK,MAAM,IAAI,cAAc;GAAE,GAAG;GAAQ,SAAS,OAAO,cAAc,OAAO;EAAQ,CAAC;EACxF,KAAK,UAAU;CACjB;;;;;;CAOA,WAAW,EAAE,UAAU,QAAqE;EAC1F,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G,MAAM,SAAS,MAAM,OAAO;CAC5B,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,SAAS,UAClB,OAAO,OAAO,KAAK,YAAY,MAAM,OAAO,KAAK,YAAY;CAE/D,IAAI,OAAO,cAAc,YACvB,OAAO,OAAO,gBAAgB,QAAQ,UAAU,UAAU,KAAK,OAAO,IAAI;CAE5E,OAAO,OAAO,gBAAgB,QAAQ,uBAAuB,OAAO;AACtE;;AAGA,SAAS,kBACP,aACA,QACuB;CACvB,IAAI,OAAO,SAAS,UAAU;EAC5B,MAAM,SAAS,OAAO,KAAK,YAAY;EACvC,OAAO,YAAY,MAAK,eAAc,WAAW,IAAI,KAAK,YAAY,MAAM,MAAM,KAAK;CACzF;CACA,IAAI,OAAO,cAAc,YACvB,OACE,YAAY,MACV,eAAc,WAAW,IAAI,gBAAgB,QAAQ,UAAU,UAAU,KAAK,WAAW,GAAG,IAAI,CAClG,KAAK;CAGT,MAAM,WAAW,uBAAuB,OAAO;CAC/C,OAAO,YAAY,MAAK,eAAc,WAAW,IAAI,gBAAgB,QAAQ,QAAQ,KAAK;AAC5F"}
|
|
@@ -1,10 +1,26 @@
|
|
|
1
|
-
import type { Intake } from '../../capabilities/intake.js';
|
|
1
|
+
import type { Intake, IntakeIssue } from '../../capabilities/intake.js';
|
|
2
2
|
import type { IntegrationContext } from '../base.js';
|
|
3
3
|
import type { IssueReconciler } from '../issue-reconciler.js';
|
|
4
4
|
import type { JiraEventRules } from './default-rules.js';
|
|
5
|
+
import type { JiraIntakeScope } from './intake-jql.js';
|
|
5
6
|
export type JiraIssueReconciler = IssueReconciler;
|
|
7
|
+
/** One page of what a board lists; `externalId` and `site` are set by the Platform integration only. */
|
|
8
|
+
type ListActiveIssues = (cursor: string | undefined, scopes: JiraIntakeScope[]) => Promise<{
|
|
9
|
+
issues: Array<IntakeIssue & {
|
|
10
|
+
externalId?: string;
|
|
11
|
+
site?: string;
|
|
12
|
+
}>;
|
|
13
|
+
nextCursor: string | null;
|
|
14
|
+
}>;
|
|
15
|
+
/**
|
|
16
|
+
* One Jira sweep: refresh carded issues (metadata, closes), then list what
|
|
17
|
+
* every project's board shows so issues nobody has carded yet get their card.
|
|
18
|
+
* Jira sends Factory no events, so this is the only first-sight path.
|
|
19
|
+
*/
|
|
6
20
|
export declare function attachJiraIssueReconciler(jira: {
|
|
7
21
|
intake: Intake;
|
|
8
22
|
rules: JiraEventRules;
|
|
23
|
+
listActiveIssues: ListActiveIssues;
|
|
9
24
|
}, context: IntegrationContext): JiraIssueReconciler | undefined;
|
|
25
|
+
export {};
|
|
10
26
|
//# sourceMappingURL=issue-reconciler.d.ts.map
|
|
@@ -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,
|
|
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,WAAW,GAAG;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,CAAC;AAEjH;;;;GAIG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,cAAc,CAAC;IAAC,gBAAgB,EAAE,gBAAgB,CAAA;CAAE,EACnF,OAAO,EAAE,kBAAkB,GAC1B,mBAAmB,GAAG,SAAS,CAuEjC"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { workItemPhaseSemantics } from "../../boards/semantics.js";
|
|
2
2
|
import "../../boards/index.js";
|
|
3
3
|
import { toBoardSource } from "../../boards/project-boards.js";
|
|
4
|
+
import { withIntakeDiscovery } from "../intake-discovery.js";
|
|
4
5
|
import { createIssueReconciler } from "../issue-reconciler.js";
|
|
6
|
+
import { scopeJiraSourcesToProject } from "./binding-scope.js";
|
|
5
7
|
import { JiraRules } from "./rules.js";
|
|
6
8
|
// src/integrations/jira/issue-reconciler.ts
|
|
7
9
|
function issueToIngress(issueRef, issue) {
|
|
@@ -22,6 +24,11 @@ function issueToIngress(issueRef, issue) {
|
|
|
22
24
|
updatedAt: issue.updatedAt
|
|
23
25
|
};
|
|
24
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* One Jira sweep: refresh carded issues (metadata, closes), then list what
|
|
29
|
+
* every project's board shows so issues nobody has carded yet get their card.
|
|
30
|
+
* Jira sends Factory no events, so this is the only first-sight path.
|
|
31
|
+
*/
|
|
25
32
|
function attachJiraIssueReconciler(jira, context) {
|
|
26
33
|
if (!context.runtime || !jira.intake.resolveIntakeDispatch) return void 0;
|
|
27
34
|
const boards = context.runtime.boards;
|
|
@@ -32,11 +39,12 @@ function attachJiraIssueReconciler(jira, context) {
|
|
|
32
39
|
boards,
|
|
33
40
|
jiraRules: jira.rules
|
|
34
41
|
});
|
|
35
|
-
|
|
42
|
+
const reconcile = createIssueReconciler({
|
|
36
43
|
integrationId: "jira",
|
|
37
44
|
intake: jira.intake,
|
|
38
45
|
projects: context.storage.projects,
|
|
39
46
|
storage: context.runtime.workItems,
|
|
47
|
+
...context.runtime.keptCards ? { cards: context.runtime.keptCards } : {},
|
|
40
48
|
isTerminal: (item) => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === "terminal",
|
|
41
49
|
issueId: (item) => item.externalSource?.externalId,
|
|
42
50
|
metadata: (item, issue) => ({
|
|
@@ -64,6 +72,31 @@ function attachJiraIssueReconciler(jira, context) {
|
|
|
64
72
|
});
|
|
65
73
|
}
|
|
66
74
|
});
|
|
75
|
+
return withIntakeDiscovery(reconcile, {
|
|
76
|
+
integrationId: "jira",
|
|
77
|
+
intake: context.storage.intake,
|
|
78
|
+
projects: context.storage.projects,
|
|
79
|
+
open: async (project, selectedIds) => {
|
|
80
|
+
const { scopes } = await scopeJiraSourcesToProject({
|
|
81
|
+
intake: context.storage.intake,
|
|
82
|
+
orgId: project.orgId,
|
|
83
|
+
factoryProjectId: project.id,
|
|
84
|
+
selectedIds
|
|
85
|
+
});
|
|
86
|
+
return scopes.map((scope) => async (cursor) => {
|
|
87
|
+
const page = await jira.listActiveIssues(cursor, [scope]);
|
|
88
|
+
return {
|
|
89
|
+
issues: page.issues.map((issue) => ({
|
|
90
|
+
...issueToIngress(issue.externalId ?? issue.id, issue),
|
|
91
|
+
site: issue.site ?? null,
|
|
92
|
+
sourceId: issue.sourceId
|
|
93
|
+
})),
|
|
94
|
+
nextCursor: page.nextCursor
|
|
95
|
+
};
|
|
96
|
+
});
|
|
97
|
+
},
|
|
98
|
+
ingest: (input) => rules.ingest(input)
|
|
99
|
+
});
|
|
67
100
|
}
|
|
68
101
|
export { attachJiraIssueReconciler };
|
|
69
102
|
|
|
@@ -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 { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport type { JiraEventRules } from './default-rules.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\nexport function attachJiraIssueReconciler(\n jira: { intake: Intake; rules: JiraEventRules },\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
|
|
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(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,QAAQ,WAAW,CAAC,KAAK,OAAO,uBAAuB,OAAO,KAAA;CACnE,MAAM,SAAS,QAAQ,QAAQ;CAE/B,MAAM,QAAQ,IAAI,UAAU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B;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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reconciliation-config.d.ts","sourceRoot":"","sources":["../../../src/integrations/jira/reconciliation-config.ts"],"names":[],"mappings":"AAIA,wBAAgB,
|
|
1
|
+
{"version":3,"file":"reconciliation-config.d.ts","sourceRoot":"","sources":["../../../src/integrations/jira/reconciliation-config.ts"],"names":[],"mappings":"AAIA,wBAAgB,0BAA0B,IAAI,MAAM,GAAG,SAAS,CAQ/D"}
|