@mastra/factory 0.16.0-alpha.6 → 0.16.0-alpha.7
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 +2 -1
- package/dist/boards/work.d.ts.map +1 -1
- package/dist/boards/work.js +20 -3
- package/dist/boards/work.js.map +1 -1
- package/dist/factory.d.ts +5 -3
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +13 -5
- package/dist/factory.js.map +1 -1
- package/dist/integrations/jira/adf.d.ts +26 -0
- package/dist/integrations/jira/adf.d.ts.map +1 -0
- package/dist/integrations/jira/adf.js +73 -0
- package/dist/integrations/jira/adf.js.map +1 -0
- package/dist/integrations/jira/agent-tools.d.ts +45 -0
- package/dist/integrations/jira/agent-tools.d.ts.map +1 -0
- package/dist/integrations/jira/agent-tools.js +87 -0
- package/dist/integrations/jira/agent-tools.js.map +1 -0
- package/dist/integrations/jira/api.d.ts +157 -0
- package/dist/integrations/jira/api.d.ts.map +1 -0
- package/dist/integrations/jira/api.js +141 -0
- package/dist/integrations/jira/api.js.map +1 -0
- package/dist/integrations/jira/claim.d.ts +9 -0
- package/dist/integrations/jira/claim.d.ts.map +1 -0
- package/dist/integrations/jira/claim.js +15 -0
- package/dist/integrations/jira/claim.js.map +1 -0
- package/dist/integrations/jira/default-rules.d.ts +47 -0
- package/dist/integrations/jira/default-rules.d.ts.map +1 -0
- package/dist/integrations/jira/default-rules.js +67 -0
- package/dist/integrations/jira/default-rules.js.map +1 -0
- package/dist/integrations/jira/integration.d.ts +114 -0
- package/dist/integrations/jira/integration.d.ts.map +1 -0
- package/dist/integrations/jira/integration.js +401 -0
- package/dist/integrations/jira/integration.js.map +1 -0
- package/dist/integrations/jira/issue-reconciler.d.ts +10 -0
- package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -0
- package/dist/integrations/jira/issue-reconciler.js +70 -0
- package/dist/integrations/jira/issue-reconciler.js.map +1 -0
- package/dist/integrations/jira/reconciliation-config.d.ts +3 -0
- package/dist/integrations/jira/reconciliation-config.d.ts.map +1 -0
- package/dist/integrations/jira/reconciliation-config.js +17 -0
- package/dist/integrations/jira/reconciliation-config.js.map +1 -0
- package/dist/integrations/jira/routes.d.ts +54 -0
- package/dist/integrations/jira/routes.d.ts.map +1 -0
- package/dist/integrations/jira/routes.js +260 -0
- package/dist/integrations/jira/routes.js.map +1 -0
- package/dist/integrations/jira/rules.d.ts +57 -0
- package/dist/integrations/jira/rules.d.ts.map +1 -0
- package/dist/integrations/jira/rules.js +175 -0
- package/dist/integrations/jira/rules.js.map +1 -0
- package/dist/integrations/platform/connect/routes.d.ts +39 -0
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -0
- package/dist/integrations/platform/connect/routes.js +123 -0
- package/dist/integrations/platform/connect/routes.js.map +1 -0
- package/dist/integrations/platform/github/event-worker.js +1 -1
- package/dist/integrations/platform/github/integration.js +1 -1
- package/dist/integrations/platform/jira/agent-tools.d.ts +36 -0
- package/dist/integrations/platform/jira/agent-tools.d.ts.map +1 -0
- package/dist/integrations/platform/jira/agent-tools.js +85 -0
- package/dist/integrations/platform/jira/agent-tools.js.map +1 -0
- package/dist/integrations/platform/jira/integration.d.ts +65 -0
- package/dist/integrations/platform/jira/integration.d.ts.map +1 -0
- package/dist/integrations/platform/jira/integration.js +540 -0
- package/dist/integrations/platform/jira/integration.js.map +1 -0
- package/dist/integrations/platform/jira/routes.d.ts +55 -0
- package/dist/integrations/platform/jira/routes.d.ts.map +1 -0
- package/dist/integrations/platform/jira/routes.js +274 -0
- package/dist/integrations/platform/jira/routes.js.map +1 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +24 -4
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +1 -1
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/index.d.ts +2 -2
- package/dist/rules/index.d.ts.map +1 -1
- package/dist/rules/index.js +2 -2
- package/dist/rules/types.d.ts +30 -3
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +5 -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/work-item-branch.d.ts +1 -1
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +3 -2
- package/dist/work-item-branch.js.map +1 -1
- package/package.json +8 -8
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `JiraIntegration` — the self-contained Jira Cloud integration.
|
|
3
|
+
*
|
|
4
|
+
* Implements the system-wide `FactoryIntegration` contract
|
|
5
|
+
* (`../base.ts`): the deploy entry reads the `JIRA_*` env vars ONCE,
|
|
6
|
+
* constructs an instance with explicit credentials, and passes it to
|
|
7
|
+
* `MastraFactory`. Everything Jira-flavored the system does — project/issue
|
|
8
|
+
* reads for Intake and the agent's issue tools — flows through this
|
|
9
|
+
* instance. No other module reads `JIRA_*` env vars.
|
|
10
|
+
*
|
|
11
|
+
* Unlike Linear, credentials are **deployment-global** (Basic auth with
|
|
12
|
+
* `email:apiToken` from the environment): there is no OAuth flow, no state
|
|
13
|
+
* signer, and no per-org connection storage. The `IntegrationConnection`
|
|
14
|
+
* arguments required by the `Intake` contract are accepted but not consulted
|
|
15
|
+
* — the instance's own credentials authenticate every call.
|
|
16
|
+
*/
|
|
17
|
+
import type { RequestContext } from '@mastra/core/request-context';
|
|
18
|
+
import type { ApiRoute } from '@mastra/core/server';
|
|
19
|
+
import type { MastraWorker } from '@mastra/core/worker';
|
|
20
|
+
import type { IntegrationConnection } from '../../capabilities/connection.js';
|
|
21
|
+
import type { Intake, IntakeIssue } from '../../capabilities/intake.js';
|
|
22
|
+
import type { RouteAuth } from '../../routes/route.js';
|
|
23
|
+
import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
|
|
24
|
+
import type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';
|
|
25
|
+
import { JiraApiClient } from './api.js';
|
|
26
|
+
import type { JiraEventRules, JiraRuleOverrides } from './default-rules.js';
|
|
27
|
+
/** Deployment-global Jira Cloud credentials. All credential fields are required. */
|
|
28
|
+
export interface JiraIntegrationConfig {
|
|
29
|
+
/** Site base URL, e.g. `https://acme.atlassian.net`. */
|
|
30
|
+
baseUrl: string;
|
|
31
|
+
/** Atlassian account email the API token belongs to. */
|
|
32
|
+
email: string;
|
|
33
|
+
/** API token from id.atlassian.com → Security → API tokens. */
|
|
34
|
+
apiToken: string;
|
|
35
|
+
/** Per-event replacements; omitted events retain defaults, null disables. */
|
|
36
|
+
rules?: JiraRuleOverrides;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The `Intake` contract requires a connection argument, but Jira credentials
|
|
40
|
+
* live on the integration instance — this inert placeholder is accepted and
|
|
41
|
+
* ignored everywhere, and keeps the real API token out of resolved dispatches
|
|
42
|
+
* and agent-tool calls.
|
|
43
|
+
*/
|
|
44
|
+
export declare const DEPLOYMENT_CONNECTION: IntegrationConnection;
|
|
45
|
+
export declare class JiraIntegration implements FactoryIntegration {
|
|
46
|
+
#private;
|
|
47
|
+
/** Stable integration identifier (see `../base.ts`). */
|
|
48
|
+
readonly id = "jira";
|
|
49
|
+
/** Typed REST client bound to the deployment credentials. */
|
|
50
|
+
readonly api: JiraApiClient;
|
|
51
|
+
get rules(): JiraEventRules;
|
|
52
|
+
constructor(config: JiraIntegrationConfig);
|
|
53
|
+
/**
|
|
54
|
+
* Bind the projects domain and the host auth seam. Jira has no per-org
|
|
55
|
+
* connection rows, so the generic storage handle is unused — credentials
|
|
56
|
+
* are deployment-global constructor config.
|
|
57
|
+
*/
|
|
58
|
+
initialize({ projects, auth }: {
|
|
59
|
+
projects: FactoryProjectsStorage;
|
|
60
|
+
auth: RouteAuth;
|
|
61
|
+
}): void;
|
|
62
|
+
/** Factory projects domain — maps a session's resourceId to its owning org. */
|
|
63
|
+
get projects(): FactoryProjectsStorage;
|
|
64
|
+
/**
|
|
65
|
+
* Whether the host runs with web auth enabled. Intake selections are
|
|
66
|
+
* org-owned, so every Jira surface is inert without a tenant auth seam.
|
|
67
|
+
*/
|
|
68
|
+
get authEnabled(): boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Map a session's resourceId (the factory project id) to its owning org.
|
|
71
|
+
* Same caching semantics as the Linear integration: definitive misses are
|
|
72
|
+
* cached, transient database failures are not.
|
|
73
|
+
*/
|
|
74
|
+
resolveOrgId(resourceId: string): Promise<string | null>;
|
|
75
|
+
/** Test hook: clear the org cache between specs. */
|
|
76
|
+
clearCaches(): void;
|
|
77
|
+
/** Normalized site base URL (no trailing slash) — `/browse/<key>` links hang off this. */
|
|
78
|
+
get baseUrl(): string;
|
|
79
|
+
readonly intake: Intake;
|
|
80
|
+
/**
|
|
81
|
+
* One page of active issues (status category not Done), most recently
|
|
82
|
+
* updated first, optionally filtered to projects and labels. The
|
|
83
|
+
* capability cursor is Jira's opaque `nextPageToken` passed through.
|
|
84
|
+
*/
|
|
85
|
+
listActiveIssues(cursor?: string, projectIds?: string[], labels?: string[]): Promise<{
|
|
86
|
+
issues: Array<IntakeIssue & {
|
|
87
|
+
sourceId: string;
|
|
88
|
+
}>;
|
|
89
|
+
nextCursor: string | null;
|
|
90
|
+
}>;
|
|
91
|
+
/**
|
|
92
|
+
* The integration's HTTP surface: `/web/jira/*` Mastra `apiRoutes` (status,
|
|
93
|
+
* projects + issues for Intake). No OAuth routes — credentials are
|
|
94
|
+
* deployment-global. Handlers operate on this instance.
|
|
95
|
+
*/
|
|
96
|
+
routes(ctx: IntegrationContext): ApiRoute[];
|
|
97
|
+
/**
|
|
98
|
+
* Background reconciliation, matching the Platform integration: keeps filed
|
|
99
|
+
* Jira cards' metadata fresh and replays close events through the rules
|
|
100
|
+
* ingress. Registered only when reconciliation is enabled.
|
|
101
|
+
*/
|
|
102
|
+
workers(ctx: IntegrationContext): MastraWorker[];
|
|
103
|
+
/**
|
|
104
|
+
* Org-scoped agent tools: the read-only issue-detail tool for sessions whose
|
|
105
|
+
* resource is a factory project (Jira credentials are deployment-global,
|
|
106
|
+
* so no per-org connection gates apply). v1 exposes no mutating Jira tools.
|
|
107
|
+
*/
|
|
108
|
+
agentTools(args: {
|
|
109
|
+
requestContext: RequestContext;
|
|
110
|
+
}): Promise<IntegrationTools>;
|
|
111
|
+
/** Non-secret config snapshot for system diagnostics/startup logs. */
|
|
112
|
+
diagnostics(): Record<string, unknown>;
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=integration.d.ts.map
|
|
@@ -0,0 +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;AAExD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,KAAK,EAIV,MAAM,EACN,WAAW,EASZ,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAK3F,OAAO,EAAE,aAAa,EAAgB,MAAM,UAAU,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAO5E,oFAAoF;AACpF,MAAM,WAAW,qBAAqB;IACpC,wDAAwD;IACxD,OAAO,EAAE,MAAM,CAAC;IAChB,wDAAwD;IACxD,KAAK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AkB,GAAG,QAAQ,EAAE;IAS3C;;;;OAIG;IACH,OAAO,CAAC,GAAG,EAAE,kBAAkB,GAAG,YAAY,EAAE;IAchD;;;;OAIG;IACG,UAAU,CAAC,IAAI,EAAE;QAAE,cAAc,EAAE,cAAc,CAAA;KAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAIrF,sEAAsE;IACtE,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;CAOvC"}
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { IssueReconcileWorker } from "../issue-reconcile-worker.js";
|
|
2
|
+
import { adfToText } from "./adf.js";
|
|
3
|
+
import { JiraApiClient, JiraApiError } from "./api.js";
|
|
4
|
+
import { resolveJiraRules } from "./default-rules.js";
|
|
5
|
+
import { attachJiraRules } from "./rules.js";
|
|
6
|
+
import { attachJiraIssueReconciler } from "./issue-reconciler.js";
|
|
7
|
+
import { jiraReconciliationEnabled, jiraReconciliationInterval } from "./reconciliation-config.js";
|
|
8
|
+
import { buildJiraRoutes } from "./routes.js";
|
|
9
|
+
import { buildJiraAgentTools } from "./agent-tools.js";
|
|
10
|
+
//#region src/integrations/jira/integration.ts
|
|
11
|
+
/** Hard stop for comment pagination so a misbehaving `total` can't loop forever. */
|
|
12
|
+
const ISSUE_COMMENTS_MAX_PAGES = 20;
|
|
13
|
+
/** Hard stop for project pagination so a misbehaving `isLast` can't loop forever. */
|
|
14
|
+
const PROJECT_SEARCH_MAX_PAGES = 50;
|
|
15
|
+
/**
|
|
16
|
+
* The `Intake` contract requires a connection argument, but Jira credentials
|
|
17
|
+
* live on the integration instance — this inert placeholder is accepted and
|
|
18
|
+
* ignored everywhere, and keeps the real API token out of resolved dispatches
|
|
19
|
+
* and agent-tool calls.
|
|
20
|
+
*/
|
|
21
|
+
const DEPLOYMENT_CONNECTION = {
|
|
22
|
+
type: "oauth",
|
|
23
|
+
accessToken: "deployment-global"
|
|
24
|
+
};
|
|
25
|
+
/** Jira issue keys look like `ENG-42`. */
|
|
26
|
+
const ISSUE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]*-\d+$/;
|
|
27
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
28
|
+
/**
|
|
29
|
+
* Capability state types (`capabilities/intake.ts`) → Jira status-category
|
|
30
|
+
* keys. `canceled` has no Jira category — it is resolved separately against
|
|
31
|
+
* `done`-category transitions whose status name contains "cancel".
|
|
32
|
+
*/
|
|
33
|
+
const STATE_TYPE_TO_CATEGORY = {
|
|
34
|
+
unstarted: "new",
|
|
35
|
+
started: "indeterminate",
|
|
36
|
+
completed: "done"
|
|
37
|
+
};
|
|
38
|
+
/** Jira status-category keys → capability state types. */
|
|
39
|
+
function stateTypeFromCategory(key) {
|
|
40
|
+
switch (key) {
|
|
41
|
+
case "new": return "unstarted";
|
|
42
|
+
case "indeterminate": return "started";
|
|
43
|
+
case "done": return "completed";
|
|
44
|
+
default: return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
var JiraIntegration = class {
|
|
48
|
+
/** Stable integration identifier (see `../base.ts`). */
|
|
49
|
+
id = "jira";
|
|
50
|
+
#config;
|
|
51
|
+
/** Typed REST client bound to the deployment credentials. */
|
|
52
|
+
api;
|
|
53
|
+
/** Bound once by the factory via `initialize()` before any surface is used. */
|
|
54
|
+
#projects;
|
|
55
|
+
#auth;
|
|
56
|
+
#orgIdByResourceId = /* @__PURE__ */ new Map();
|
|
57
|
+
#rules;
|
|
58
|
+
get rules() {
|
|
59
|
+
return this.#rules;
|
|
60
|
+
}
|
|
61
|
+
constructor(config) {
|
|
62
|
+
this.#rules = resolveJiraRules(config.rules);
|
|
63
|
+
this.api = new JiraApiClient(config);
|
|
64
|
+
this.#config = config;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Bind the projects domain and the host auth seam. Jira has no per-org
|
|
68
|
+
* connection rows, so the generic storage handle is unused — credentials
|
|
69
|
+
* are deployment-global constructor config.
|
|
70
|
+
*/
|
|
71
|
+
initialize({ projects, auth }) {
|
|
72
|
+
this.#projects = projects;
|
|
73
|
+
this.#auth = auth;
|
|
74
|
+
}
|
|
75
|
+
/** Factory projects domain — maps a session's resourceId to its owning org. */
|
|
76
|
+
get projects() {
|
|
77
|
+
if (!this.#projects) throw new Error("JiraIntegration is not initialized — the factory binds storage during prepare().");
|
|
78
|
+
return this.#projects;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Whether the host runs with web auth enabled. Intake selections are
|
|
82
|
+
* org-owned, so every Jira surface is inert without a tenant auth seam.
|
|
83
|
+
*/
|
|
84
|
+
get authEnabled() {
|
|
85
|
+
return this.#auth?.enabled() ?? false;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Map a session's resourceId (the factory project id) to its owning org.
|
|
89
|
+
* Same caching semantics as the Linear integration: definitive misses are
|
|
90
|
+
* cached, transient database failures are not.
|
|
91
|
+
*/
|
|
92
|
+
async resolveOrgId(resourceId) {
|
|
93
|
+
const cached = this.#orgIdByResourceId.get(resourceId);
|
|
94
|
+
if (cached !== void 0) return cached;
|
|
95
|
+
if (!UUID_PATTERN.test(resourceId)) {
|
|
96
|
+
this.#orgIdByResourceId.set(resourceId, null);
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
let orgId;
|
|
100
|
+
try {
|
|
101
|
+
await this.projects.ensureReady();
|
|
102
|
+
orgId = (await this.projects.getById({ id: resourceId }))?.orgId ?? null;
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
this.#orgIdByResourceId.set(resourceId, orgId);
|
|
107
|
+
return orgId;
|
|
108
|
+
}
|
|
109
|
+
/** Test hook: clear the org cache between specs. */
|
|
110
|
+
clearCaches() {
|
|
111
|
+
this.#orgIdByResourceId.clear();
|
|
112
|
+
}
|
|
113
|
+
/** Normalized site base URL (no trailing slash) — `/browse/<key>` links hang off this. */
|
|
114
|
+
get baseUrl() {
|
|
115
|
+
return this.api.baseUrl;
|
|
116
|
+
}
|
|
117
|
+
intake = {
|
|
118
|
+
resolveIntakeDispatch: (input) => this.#resolveIntakeDispatch(input),
|
|
119
|
+
listSources: () => this.#listSources(),
|
|
120
|
+
listItems: (input) => this.#listItems(input),
|
|
121
|
+
listIssues: (input) => this.#listIssues(input),
|
|
122
|
+
getIssue: (input) => this.#getIssue(input),
|
|
123
|
+
createComment: (input) => this.#createComment(input),
|
|
124
|
+
updateIssue: (input) => this.#updateIssue(input)
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Background-dispatch context. Credentials are deployment-global, so the
|
|
128
|
+
* returned connection is a formality the Jira intake methods ignore; the
|
|
129
|
+
* issue key is stored directly as the work item's `externalId` (mirroring
|
|
130
|
+
* Linear, which stores the issue UUID).
|
|
131
|
+
*/
|
|
132
|
+
async #resolveIntakeDispatch({ externalSource }) {
|
|
133
|
+
if (externalSource.type !== "issue") return null;
|
|
134
|
+
return {
|
|
135
|
+
connection: DEPLOYMENT_CONNECTION,
|
|
136
|
+
issueId: externalSource.externalId
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/** All the site's projects (Settings intake-source picker), following `isLast` paging. */
|
|
140
|
+
async #listSources() {
|
|
141
|
+
const sources = [];
|
|
142
|
+
let startAt = 0;
|
|
143
|
+
for (let pageCount = 0; pageCount < PROJECT_SEARCH_MAX_PAGES; pageCount++) {
|
|
144
|
+
const page = await this.api.listProjects({ startAt });
|
|
145
|
+
for (const project of page.values) sources.push({
|
|
146
|
+
id: project.id,
|
|
147
|
+
name: project.name,
|
|
148
|
+
type: "project",
|
|
149
|
+
metadata: { key: project.key }
|
|
150
|
+
});
|
|
151
|
+
if (page.isLast || page.values.length === 0) break;
|
|
152
|
+
startAt += page.values.length;
|
|
153
|
+
}
|
|
154
|
+
return sources;
|
|
155
|
+
}
|
|
156
|
+
async #listItems({ sourceIds, cursor }) {
|
|
157
|
+
if (sourceIds.length === 0) return {
|
|
158
|
+
items: [],
|
|
159
|
+
nextCursor: null
|
|
160
|
+
};
|
|
161
|
+
const page = await this.listActiveIssues(cursor, sourceIds);
|
|
162
|
+
return {
|
|
163
|
+
items: page.issues.map((issue) => ({
|
|
164
|
+
source: {
|
|
165
|
+
type: "issue",
|
|
166
|
+
externalId: issue.identifier,
|
|
167
|
+
url: issue.url
|
|
168
|
+
},
|
|
169
|
+
sourceId: issue.sourceId,
|
|
170
|
+
title: `${issue.identifier}: ${issue.title}`,
|
|
171
|
+
status: issue.state ?? void 0,
|
|
172
|
+
labels: issue.labels,
|
|
173
|
+
assignee: issue.assignee,
|
|
174
|
+
createdAt: issue.createdAt,
|
|
175
|
+
updatedAt: issue.updatedAt,
|
|
176
|
+
metadata: {
|
|
177
|
+
identifier: issue.identifier,
|
|
178
|
+
issueRef: issue.identifier,
|
|
179
|
+
state: issue.state,
|
|
180
|
+
stateType: issue.stateType,
|
|
181
|
+
priority: issue.priority,
|
|
182
|
+
project: issue.source,
|
|
183
|
+
assignee: issue.assignee,
|
|
184
|
+
assignees: issue.assignees ?? [],
|
|
185
|
+
creator: issue.author,
|
|
186
|
+
author: issue.author,
|
|
187
|
+
labels: issue.labels,
|
|
188
|
+
createdAt: issue.createdAt,
|
|
189
|
+
updatedAt: issue.updatedAt
|
|
190
|
+
}
|
|
191
|
+
})),
|
|
192
|
+
nextCursor: page.nextCursor
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
async #listIssues(input) {
|
|
196
|
+
const page = await this.listActiveIssues(input.cursor, input.sourceIds, input.labels);
|
|
197
|
+
return {
|
|
198
|
+
issues: page.issues,
|
|
199
|
+
nextCursor: page.nextCursor
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* One page of active issues (status category not Done), most recently
|
|
204
|
+
* updated first, optionally filtered to projects and labels. The
|
|
205
|
+
* capability cursor is Jira's opaque `nextPageToken` passed through.
|
|
206
|
+
*/
|
|
207
|
+
async listActiveIssues(cursor, projectIds, labels) {
|
|
208
|
+
const page = await this.api.searchIssues({
|
|
209
|
+
jql: buildIntakeJql(projectIds, labels),
|
|
210
|
+
...cursor ? { nextPageToken: cursor } : {}
|
|
211
|
+
});
|
|
212
|
+
return {
|
|
213
|
+
issues: page.issues.map((issue) => ({
|
|
214
|
+
...this.#toIntakeIssue(issue),
|
|
215
|
+
sourceId: issue.fields.project?.id ?? ""
|
|
216
|
+
})),
|
|
217
|
+
nextCursor: page.nextPageToken ?? null
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
async #getIssue({ issueId }) {
|
|
221
|
+
let issue;
|
|
222
|
+
try {
|
|
223
|
+
issue = await this.api.getIssue(issueId);
|
|
224
|
+
} catch (err) {
|
|
225
|
+
if (err instanceof JiraApiError && err.status === 404) return null;
|
|
226
|
+
throw err;
|
|
227
|
+
}
|
|
228
|
+
const { comments, total } = await this.#listAllComments(issue.key);
|
|
229
|
+
return {
|
|
230
|
+
...this.#toIntakeIssue(issue),
|
|
231
|
+
commentCount: total,
|
|
232
|
+
description: issue.fields.description ? adfToText(issue.fields.description) || null : null,
|
|
233
|
+
comments: comments.map((comment) => ({
|
|
234
|
+
author: comment.author?.displayName ?? null,
|
|
235
|
+
body: adfToText(comment.body),
|
|
236
|
+
createdAt: comment.created
|
|
237
|
+
}))
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
/** Every comment on the issue, oldest first, bounded by {@link ISSUE_COMMENTS_MAX_PAGES}. */
|
|
241
|
+
async #listAllComments(keyOrId) {
|
|
242
|
+
const comments = [];
|
|
243
|
+
let total = 0;
|
|
244
|
+
for (let page = 0; page < ISSUE_COMMENTS_MAX_PAGES; page++) {
|
|
245
|
+
const result = await this.api.listComments(keyOrId, { startAt: comments.length });
|
|
246
|
+
comments.push(...result.comments);
|
|
247
|
+
total = result.total;
|
|
248
|
+
if (result.comments.length === 0 || comments.length >= total) break;
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
comments,
|
|
252
|
+
total
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
async #createComment({ issueId, body }) {
|
|
256
|
+
let key = issueId;
|
|
257
|
+
if (!ISSUE_KEY_PATTERN.test(issueId)) try {
|
|
258
|
+
key = (await this.api.getIssue(issueId)).key;
|
|
259
|
+
} catch (err) {
|
|
260
|
+
if (err instanceof JiraApiError && err.status === 404) return null;
|
|
261
|
+
throw err;
|
|
262
|
+
}
|
|
263
|
+
const comment = await this.api.createComment(key, body);
|
|
264
|
+
return {
|
|
265
|
+
id: comment.id,
|
|
266
|
+
url: `${this.baseUrl}/browse/${key}?focusedCommentId=${comment.id}`
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Move an issue to a target state by applying a workflow transition. Jira
|
|
271
|
+
* only exposes transitions that are currently legal, so a policy miss (no
|
|
272
|
+
* transition reaches the target) returns `null` per the `Intake` contract —
|
|
273
|
+
* infrastructure errors (network, auth) still throw.
|
|
274
|
+
*/
|
|
275
|
+
async #updateIssue(input) {
|
|
276
|
+
let issue;
|
|
277
|
+
try {
|
|
278
|
+
issue = await this.api.getIssue(input.issueId);
|
|
279
|
+
} catch (err) {
|
|
280
|
+
if (err instanceof JiraApiError && err.status === 404) return null;
|
|
281
|
+
throw err;
|
|
282
|
+
}
|
|
283
|
+
if (currentStatusMatches(issue, input.state)) return this.#toIntakeIssue(issue);
|
|
284
|
+
const transition = resolveTransition(await this.api.listTransitions(issue.key), input.state);
|
|
285
|
+
if (!transition) return null;
|
|
286
|
+
await this.api.applyTransition(issue.key, transition.id);
|
|
287
|
+
const fresh = await this.api.getIssue(issue.key);
|
|
288
|
+
return this.#toIntakeIssue(fresh);
|
|
289
|
+
}
|
|
290
|
+
#toIntakeIssue(issue) {
|
|
291
|
+
const { fields } = issue;
|
|
292
|
+
return {
|
|
293
|
+
id: issue.id,
|
|
294
|
+
identifier: issue.key,
|
|
295
|
+
title: fields.summary ?? issue.key,
|
|
296
|
+
url: `${this.baseUrl}/browse/${issue.key}`,
|
|
297
|
+
author: fields.reporter?.displayName ?? null,
|
|
298
|
+
state: fields.status?.name ?? null,
|
|
299
|
+
stateType: stateTypeFromCategory(fields.status?.statusCategory?.key),
|
|
300
|
+
priority: fields.priority?.name ?? null,
|
|
301
|
+
assignee: fields.assignee?.displayName ?? null,
|
|
302
|
+
source: fields.project?.key ?? null,
|
|
303
|
+
sourceId: fields.project?.id ?? null,
|
|
304
|
+
labels: fields.labels ?? [],
|
|
305
|
+
commentCount: null,
|
|
306
|
+
createdAt: fields.created ?? "",
|
|
307
|
+
updatedAt: fields.updated ?? ""
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* The integration's HTTP surface: `/web/jira/*` Mastra `apiRoutes` (status,
|
|
312
|
+
* projects + issues for Intake). No OAuth routes — credentials are
|
|
313
|
+
* deployment-global. Handlers operate on this instance.
|
|
314
|
+
*/
|
|
315
|
+
routes(ctx) {
|
|
316
|
+
return buildJiraRoutes({
|
|
317
|
+
jira: this,
|
|
318
|
+
auth: ctx.auth,
|
|
319
|
+
intake: ctx.storage.intake,
|
|
320
|
+
ingestFactoryIssues: attachJiraRules(this, ctx)
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Background reconciliation, matching the Platform integration: keeps filed
|
|
325
|
+
* Jira cards' metadata fresh and replays close events through the rules
|
|
326
|
+
* ingress. Registered only when reconciliation is enabled.
|
|
327
|
+
*/
|
|
328
|
+
workers(ctx) {
|
|
329
|
+
if (!jiraReconciliationEnabled()) return [];
|
|
330
|
+
const reconcile = attachJiraIssueReconciler(this, ctx);
|
|
331
|
+
if (!reconcile) return [];
|
|
332
|
+
const intervalMs = jiraReconciliationInterval();
|
|
333
|
+
return [new IssueReconcileWorker({
|
|
334
|
+
integrationId: this.id,
|
|
335
|
+
reconcile,
|
|
336
|
+
...intervalMs ? { intervalMs } : {}
|
|
337
|
+
})];
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Org-scoped agent tools: the read-only issue-detail tool for sessions whose
|
|
341
|
+
* resource is a factory project (Jira credentials are deployment-global,
|
|
342
|
+
* so no per-org connection gates apply). v1 exposes no mutating Jira tools.
|
|
343
|
+
*/
|
|
344
|
+
async agentTools(args) {
|
|
345
|
+
return buildJiraAgentTools({
|
|
346
|
+
requestContext: args.requestContext,
|
|
347
|
+
jira: this
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
/** Non-secret config snapshot for system diagnostics/startup logs. */
|
|
351
|
+
diagnostics() {
|
|
352
|
+
return {
|
|
353
|
+
configured: true,
|
|
354
|
+
site: new URL(this.baseUrl).host,
|
|
355
|
+
email: maskEmail(this.#config.email)
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
/** `ops@acme.test` → `o***@acme.test` — enough to identify, never the value. */
|
|
360
|
+
function maskEmail(email) {
|
|
361
|
+
const at = email.indexOf("@");
|
|
362
|
+
if (at <= 0) return "***";
|
|
363
|
+
return `${email[0]}***${email.slice(at)}`;
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Build the intake JQL. Source ids and labels come from stored org config /
|
|
367
|
+
* request input, so both are sanitized before interpolation: numeric project
|
|
368
|
+
* ids pass through bare, project keys are restricted to a safe charset, and
|
|
369
|
+
* label quotes/backslashes are stripped.
|
|
370
|
+
*/
|
|
371
|
+
function buildIntakeJql(projectIds, labels) {
|
|
372
|
+
const clauses = [];
|
|
373
|
+
const safeProjects = (projectIds ?? []).map((id) => id.trim()).filter((id) => /^[A-Za-z0-9_]+$/.test(id)).map((id) => /^\d+$/.test(id) ? id : `"${id}"`);
|
|
374
|
+
if (safeProjects.length > 0) clauses.push(`project IN (${safeProjects.join(", ")})`);
|
|
375
|
+
clauses.push("statusCategory != Done");
|
|
376
|
+
const safeLabels = [...new Set((labels ?? []).map((label) => label.trim().replace(/["\\]/g, "")).filter(Boolean))];
|
|
377
|
+
if (safeLabels.length > 0) clauses.push(`labels IN (${safeLabels.map((label) => `"${label}"`).join(", ")})`);
|
|
378
|
+
return `${clauses.join(" AND ")} ORDER BY updated DESC`;
|
|
379
|
+
}
|
|
380
|
+
/** Whether the issue is already in the requested target state. */
|
|
381
|
+
function currentStatusMatches(issue, target) {
|
|
382
|
+
const status = issue.fields.status;
|
|
383
|
+
if (!status) return false;
|
|
384
|
+
if (target.kind === "byName") return status.name.toLowerCase() === target.name.toLowerCase();
|
|
385
|
+
if (target.stateType === "canceled") return status.statusCategory?.key === "done" && /cancel/i.test(status.name);
|
|
386
|
+
return status.statusCategory?.key === STATE_TYPE_TO_CATEGORY[target.stateType];
|
|
387
|
+
}
|
|
388
|
+
/** Resolve the target state against the issue's currently-legal transitions. */
|
|
389
|
+
function resolveTransition(transitions, target) {
|
|
390
|
+
if (target.kind === "byName") {
|
|
391
|
+
const wanted = target.name.toLowerCase();
|
|
392
|
+
return transitions.find((transition) => transition.to?.name.toLowerCase() === wanted) ?? null;
|
|
393
|
+
}
|
|
394
|
+
if (target.stateType === "canceled") return transitions.find((transition) => transition.to?.statusCategory?.key === "done" && /cancel/i.test(transition.to.name)) ?? null;
|
|
395
|
+
const category = STATE_TYPE_TO_CATEGORY[target.stateType];
|
|
396
|
+
return transitions.find((transition) => transition.to?.statusCategory?.key === category) ?? null;
|
|
397
|
+
}
|
|
398
|
+
//#endregion
|
|
399
|
+
export { DEPLOYMENT_CONNECTION, JiraIntegration };
|
|
400
|
+
|
|
401
|
+
//# sourceMappingURL=integration.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"integration.js","names":["#config","#orgIdByResourceId","#rules","#projects","#auth","#resolveIntakeDispatch","#listSources","#listItems","#listIssues","#getIssue","#createComment","#updateIssue","#toIntakeIssue","#listAllComments"],"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 { 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`. */\n baseUrl: 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\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 /** 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 // JiraApiClient validates the credential group and normalizes the URL.\n this.api = new JiraApiClient(config);\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.api.baseUrl;\n }\n\n readonly intake: Intake = {\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, 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(input.cursor, input.sourceIds, input.labels);\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 filtered to projects and labels. The\n * capability cursor is Jira's opaque `nextPageToken` passed through.\n */\n async listActiveIssues(\n cursor?: string,\n projectIds?: string[],\n labels?: string[],\n ): Promise<{ issues: Array<IntakeIssue & { sourceId: string }>; nextCursor: string | null }> {\n const page = await this.api.searchIssues({\n jql: buildIntakeJql(projectIds, labels),\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 const comment = await this.api.createComment(key, body);\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 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/**\n * Build the intake JQL. Source ids and labels come from stored org config /\n * request input, so both are sanitized before interpolation: numeric project\n * ids pass through bare, project keys are restricted to a safe charset, and\n * label quotes/backslashes are stripped.\n */\nfunction buildIntakeJql(projectIds?: string[], labels?: string[]): string {\n const clauses: string[] = [];\n const safeProjects = (projectIds ?? [])\n .map(id => id.trim())\n .filter(id => /^[A-Za-z0-9_]+$/.test(id))\n .map(id => (/^\\d+$/.test(id) ? id : `\"${id}\"`));\n if (safeProjects.length > 0) {\n clauses.push(`project IN (${safeProjects.join(', ')})`);\n }\n clauses.push('statusCategory != Done');\n const safeLabels = [...new Set((labels ?? []).map(label => label.trim().replace(/[\"\\\\]/g, '')).filter(Boolean))];\n if (safeLabels.length > 0) {\n clauses.push(`labels IN (${safeLabels.map(label => `\"${label}\"`).join(', ')})`);\n }\n return `${clauses.join(' AND ')} ORDER BY updated DESC`;\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":";;;;;;;;;;;AAiEA,MAAM,2BAA2B;;AAGjC,MAAM,2BAA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AAQ,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"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Intake } from '../../capabilities/intake.js';
|
|
2
|
+
import type { IntegrationContext } from '../base.js';
|
|
3
|
+
import type { IssueReconciler } from '../issue-reconciler.js';
|
|
4
|
+
import type { JiraEventRules } from './default-rules.js';
|
|
5
|
+
export type JiraIssueReconciler = IssueReconciler;
|
|
6
|
+
export declare function attachJiraIssueReconciler(jira: {
|
|
7
|
+
intake: Intake;
|
|
8
|
+
rules: JiraEventRules;
|
|
9
|
+
}, context: IntegrationContext): JiraIssueReconciler | undefined;
|
|
10
|
+
//# sourceMappingURL=issue-reconciler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"issue-reconciler.d.ts","sourceRoot":"","sources":["../../../src/integrations/jira/issue-reconciler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAe,MAAM,8BAA8B,CAAC;AACxE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAIzD,MAAM,MAAM,mBAAmB,GAAG,eAAe,CAAC;AAqBlD,wBAAgB,yBAAyB,CACvC,IAAI,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,cAAc,CAAA;CAAE,EAC/C,OAAO,EAAE,kBAAkB,GAC1B,mBAAmB,GAAG,SAAS,CA4CjC"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { workItemPhaseSemantics } from "../../boards/semantics.js";
|
|
2
|
+
import "../../boards/index.js";
|
|
3
|
+
import { createIssueReconciler } from "../issue-reconciler.js";
|
|
4
|
+
import { JiraRules } from "./rules.js";
|
|
5
|
+
//#region src/integrations/jira/issue-reconciler.ts
|
|
6
|
+
function issueToIngress(issueRef, issue) {
|
|
7
|
+
return {
|
|
8
|
+
id: issueRef,
|
|
9
|
+
identifier: issue.identifier,
|
|
10
|
+
title: issue.title,
|
|
11
|
+
url: issue.url,
|
|
12
|
+
state: issue.state ?? "",
|
|
13
|
+
stateType: issue.stateType ?? "",
|
|
14
|
+
priorityLabel: issue.priority ?? "",
|
|
15
|
+
assignee: issue.assignee ?? null,
|
|
16
|
+
author: issue.author ?? null,
|
|
17
|
+
project: issue.source ?? null,
|
|
18
|
+
site: null,
|
|
19
|
+
labels: [...issue.labels ?? []],
|
|
20
|
+
createdAt: issue.createdAt,
|
|
21
|
+
updatedAt: issue.updatedAt
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function attachJiraIssueReconciler(jira, context) {
|
|
25
|
+
if (!context.runtime || !jira.intake.resolveIntakeDispatch) return void 0;
|
|
26
|
+
const boards = context.runtime.boards;
|
|
27
|
+
const rules = new JiraRules({
|
|
28
|
+
projects: context.storage.projects,
|
|
29
|
+
storage: context.runtime.workItems,
|
|
30
|
+
configVersion: context.runtime.configVersion,
|
|
31
|
+
boards,
|
|
32
|
+
jiraRules: jira.rules
|
|
33
|
+
});
|
|
34
|
+
return createIssueReconciler({
|
|
35
|
+
integrationId: "jira",
|
|
36
|
+
intake: jira.intake,
|
|
37
|
+
projects: context.storage.projects,
|
|
38
|
+
storage: context.runtime.workItems,
|
|
39
|
+
isTerminal: (item) => workItemPhaseSemantics(boards, item)?.kind === "terminal",
|
|
40
|
+
issueId: (item) => item.externalSource?.externalId,
|
|
41
|
+
metadata: (item, issue) => ({
|
|
42
|
+
identifier: issue.identifier,
|
|
43
|
+
issueRef: item.externalSource?.externalId ?? issue.id,
|
|
44
|
+
autoStartCandidate: issue.stateType === "unstarted" || issue.stateType === "started",
|
|
45
|
+
state: issue.state,
|
|
46
|
+
stateType: issue.stateType,
|
|
47
|
+
priority: issue.priority,
|
|
48
|
+
project: issue.source,
|
|
49
|
+
assignee: issue.assignee,
|
|
50
|
+
assignees: issue.assignees ?? [],
|
|
51
|
+
creator: issue.author,
|
|
52
|
+
author: issue.author,
|
|
53
|
+
labels: issue.labels ?? [],
|
|
54
|
+
createdAt: issue.createdAt,
|
|
55
|
+
updatedAt: issue.updatedAt
|
|
56
|
+
}),
|
|
57
|
+
onClosed: async (item, issue, project) => {
|
|
58
|
+
await rules.ingest({
|
|
59
|
+
orgId: project.orgId,
|
|
60
|
+
userId: "factory-rule-dispatcher",
|
|
61
|
+
factoryProjectId: project.id,
|
|
62
|
+
issues: [issueToIngress(item.externalSource?.externalId ?? issue.id, issue)]
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
//#endregion
|
|
68
|
+
export { attachJiraIssueReconciler };
|
|
69
|
+
|
|
70
|
+
//# sourceMappingURL=issue-reconciler.js.map
|