@mastra/factory 0.6.0-alpha.1 → 0.6.0-alpha.3
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/CHANGELOG.md +117 -0
- package/dist/capabilities/version-control.d.ts +1 -0
- package/dist/capabilities/version-control.d.ts.map +1 -1
- package/dist/factory.d.ts +10 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +13 -1
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/integration.d.ts +13 -1
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +50 -2
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/issue-reconciler.d.ts +24 -0
- package/dist/integrations/github/issue-reconciler.d.ts.map +1 -0
- package/dist/integrations/github/issue-reconciler.js +104 -0
- package/dist/integrations/github/issue-reconciler.js.map +1 -0
- package/dist/integrations/github/reconcile-worker.d.ts +8 -0
- package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +38 -1
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +45 -6
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +33 -2
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +89 -11
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +74 -8
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.d.ts +19 -0
- package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -0
- package/dist/integrations/issue-reconcile-worker.js +98 -0
- package/dist/integrations/issue-reconcile-worker.js.map +1 -0
- package/dist/integrations/issue-reconciler.d.ts +47 -0
- package/dist/integrations/issue-reconciler.d.ts.map +1 -0
- package/dist/integrations/issue-reconciler.js +104 -0
- package/dist/integrations/issue-reconciler.js.map +1 -0
- package/dist/integrations/linear/integration.d.ts +2 -0
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +14 -1
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/issue-reconciler.d.ts +6 -0
- package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -0
- package/dist/integrations/linear/issue-reconciler.js +64 -0
- package/dist/integrations/linear/issue-reconciler.js.map +1 -0
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +5 -2
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.d.ts +7 -0
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +24 -0
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +13 -3
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +35 -1
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts +105 -0
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -0
- package/dist/integrations/platform/linear/event-worker.js +380 -0
- package/dist/integrations/platform/linear/event-worker.js.map +1 -0
- package/dist/integrations/platform/linear/integration.d.ts +9 -0
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +37 -1
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/routes/config.d.ts +25 -0
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +63 -1
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/fs.d.ts +16 -2
- package/dist/routes/fs.d.ts.map +1 -1
- package/dist/routes/fs.js +47 -5
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/surface.d.ts +2 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +2 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/binding-context.d.ts +28 -1
- package/dist/rules/binding-context.d.ts.map +1 -1
- package/dist/rules/binding-context.js +66 -1
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/defaults.d.ts.map +1 -1
- package/dist/rules/defaults.js +37 -2
- package/dist/rules/defaults.js.map +1 -1
- package/dist/rules/tools.d.ts +2 -0
- package/dist/rules/tools.d.ts.map +1 -1
- package/dist/rules/tools.js +15 -6
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/types.d.ts +7 -2
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +2 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/session/filesystem-capture.d.ts +26 -0
- package/dist/session/filesystem-capture.d.ts.map +1 -0
- package/dist/session/filesystem-capture.js +75 -0
- package/dist/session/filesystem-capture.js.map +1 -0
- package/dist/storage/domains/filesystem/base.d.ts +26 -0
- package/dist/storage/domains/filesystem/base.d.ts.map +1 -0
- package/dist/storage/domains/filesystem/base.js +74 -0
- package/dist/storage/domains/filesystem/base.js.map +1 -0
- package/dist/storage/domains/projects/base.d.ts +1 -0
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +3 -0
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +2 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +6 -0
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +3 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +11 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +17 -0
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/factory-skills/factory-triage/SKILL.md +45 -12
- package/package.json +5 -5
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { PlatformApiError } from "../api-client.js";
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
3
|
+
import { NoopLeaseProvider, isLeaseProvider } from "@mastra/core/events";
|
|
4
|
+
import { MastraWorker } from "@mastra/core/worker";
|
|
5
|
+
//#region src/integrations/platform/linear/event-worker.ts
|
|
6
|
+
const API_PREFIX = "/v1/server/linear";
|
|
7
|
+
const DEFAULT_POLL_INTERVAL_MS = 2e4;
|
|
8
|
+
const DEFAULT_RECONCILE_INTERVAL_MS = 5 * 6e4;
|
|
9
|
+
const EVENT_PAGE_SIZE = 500;
|
|
10
|
+
const MIN_LEASE_TTL_MS = 3e4;
|
|
11
|
+
const CURSOR_ORG_ID = "__platform_linear_event_worker__";
|
|
12
|
+
const CURSOR_USER_ID = "worker";
|
|
13
|
+
const LEASE_KEY = "platform-linear-events:linear";
|
|
14
|
+
/**
|
|
15
|
+
* Tails the Platform Linear event stream (Redis-backed, per workspace) and
|
|
16
|
+
* runs the same folded issue-reconcile sweep pattern as
|
|
17
|
+
* `PlatformGithubEventWorker`. Issue events are translated into a normal
|
|
18
|
+
* `LinearRulesIngress` so downstream rule dispatch is identical to the
|
|
19
|
+
* polling path.
|
|
20
|
+
*
|
|
21
|
+
* Cursor state is persisted per workspace via the integration's generic
|
|
22
|
+
* settings surface, keyed by a well-known worker identity. Cold start uses
|
|
23
|
+
* `afterTimestamp: now - 1` to avoid replaying the 14-day stream backlog.
|
|
24
|
+
*
|
|
25
|
+
* ## Delivery semantics
|
|
26
|
+
*
|
|
27
|
+
* **At-most-once** per event. The cursor advances to the last event ID in a
|
|
28
|
+
* page after all dispatch attempts on that page complete, regardless of
|
|
29
|
+
* whether individual ingest calls threw. Ingest failures are logged, the
|
|
30
|
+
* offending event is not retried, and drift is caught by the folded
|
|
31
|
+
* `LinearIssueReconciler` sweep on its own cadence (default 5 minutes). This
|
|
32
|
+
* matches `PlatformGithubEventWorker` and avoids poison-pill events blocking
|
|
33
|
+
* the whole stream. Any consumer that needs exactly-once must idempotently
|
|
34
|
+
* handle the same issue arriving via both the event path and the reconcile
|
|
35
|
+
* path.
|
|
36
|
+
*/
|
|
37
|
+
var PlatformLinearEventWorker = class extends MastraWorker {
|
|
38
|
+
name = "platform-linear-events";
|
|
39
|
+
#client;
|
|
40
|
+
#linear;
|
|
41
|
+
#storage;
|
|
42
|
+
#projects;
|
|
43
|
+
#workItems;
|
|
44
|
+
#ingestFactoryIssue;
|
|
45
|
+
#reconcileFactoryState;
|
|
46
|
+
#pollEventsEnabled;
|
|
47
|
+
#intervalMs;
|
|
48
|
+
#reconcileIntervalMs;
|
|
49
|
+
#now;
|
|
50
|
+
#leaseOwner = randomUUID();
|
|
51
|
+
#running = false;
|
|
52
|
+
#timer;
|
|
53
|
+
#leaseRenewalTimer;
|
|
54
|
+
#inFlight;
|
|
55
|
+
#leaseProvider = NoopLeaseProvider;
|
|
56
|
+
#leaseTtlMs;
|
|
57
|
+
#hasLease = false;
|
|
58
|
+
#startedAt = 0;
|
|
59
|
+
#lastReconcileAt = 0;
|
|
60
|
+
#settings = {
|
|
61
|
+
version: 1,
|
|
62
|
+
workspaces: {}
|
|
63
|
+
};
|
|
64
|
+
constructor(config) {
|
|
65
|
+
super();
|
|
66
|
+
this.#client = config.client;
|
|
67
|
+
this.#linear = config.linear;
|
|
68
|
+
this.#storage = config.storage;
|
|
69
|
+
this.#projects = config.projects;
|
|
70
|
+
this.#workItems = config.workItems;
|
|
71
|
+
this.#ingestFactoryIssue = config.ingestFactoryIssue;
|
|
72
|
+
this.#reconcileFactoryState = config.reconcileFactoryState;
|
|
73
|
+
this.#pollEventsEnabled = config.pollEventsEnabled ?? true;
|
|
74
|
+
this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
75
|
+
this.#reconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;
|
|
76
|
+
if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) throw new Error("Platform Linear event polling interval must be a positive number.");
|
|
77
|
+
if (!Number.isFinite(this.#reconcileIntervalMs) || this.#reconcileIntervalMs <= 0) throw new Error("Platform Linear reconcile interval must be a positive number.");
|
|
78
|
+
this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);
|
|
79
|
+
this.#now = config.now ?? Date.now;
|
|
80
|
+
}
|
|
81
|
+
async init(deps) {
|
|
82
|
+
await super.init(deps);
|
|
83
|
+
this.#leaseProvider = getLeaseProvider(deps.pubsub);
|
|
84
|
+
}
|
|
85
|
+
async start() {
|
|
86
|
+
if (this.#running) return;
|
|
87
|
+
if (!this.deps) throw new Error("PlatformLinearEventWorker: call init() before start()");
|
|
88
|
+
this.#startedAt = this.#now() - 1;
|
|
89
|
+
this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));
|
|
90
|
+
this.#running = true;
|
|
91
|
+
this.deps.logger.info("Platform Linear event polling started", {
|
|
92
|
+
intervalMs: this.#intervalMs,
|
|
93
|
+
leaseTtlMs: this.#leaseTtlMs
|
|
94
|
+
});
|
|
95
|
+
this.#schedule(0);
|
|
96
|
+
}
|
|
97
|
+
async stop() {
|
|
98
|
+
if (!this.#running) return;
|
|
99
|
+
this.#running = false;
|
|
100
|
+
if (this.#timer) clearTimeout(this.#timer);
|
|
101
|
+
this.#timer = void 0;
|
|
102
|
+
this.#stopLeaseRenewal();
|
|
103
|
+
await this.#inFlight;
|
|
104
|
+
if (this.#hasLease) {
|
|
105
|
+
await this.#leaseProvider.releaseLease(LEASE_KEY, this.#leaseOwner).catch(() => void 0);
|
|
106
|
+
this.#hasLease = false;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
get isRunning() {
|
|
110
|
+
return this.#running;
|
|
111
|
+
}
|
|
112
|
+
#schedule(delayMs) {
|
|
113
|
+
if (!this.#running) return;
|
|
114
|
+
this.#timer = setTimeout(() => {
|
|
115
|
+
this.#timer = void 0;
|
|
116
|
+
const run = this.#tick();
|
|
117
|
+
this.#inFlight = run;
|
|
118
|
+
run.finally(() => {
|
|
119
|
+
if (this.#inFlight === run) this.#inFlight = void 0;
|
|
120
|
+
});
|
|
121
|
+
}, delayMs);
|
|
122
|
+
this.#timer.unref?.();
|
|
123
|
+
}
|
|
124
|
+
async #tick() {
|
|
125
|
+
let nextDelay = this.#intervalMs;
|
|
126
|
+
try {
|
|
127
|
+
if (!await this.#ensureLease()) return;
|
|
128
|
+
nextDelay = await this.#poll();
|
|
129
|
+
} catch (error) {
|
|
130
|
+
nextDelay = retryDelay(error, this.#intervalMs);
|
|
131
|
+
this.deps?.logger.error("Platform Linear event polling cycle failed", {
|
|
132
|
+
error: error instanceof Error ? error.message : String(error),
|
|
133
|
+
retryInMs: nextDelay
|
|
134
|
+
});
|
|
135
|
+
} finally {
|
|
136
|
+
this.#schedule(nextDelay);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
async #ensureLease() {
|
|
140
|
+
if (this.#hasLease) return true;
|
|
141
|
+
const result = await this.#leaseProvider.acquireLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs);
|
|
142
|
+
this.#hasLease = result.acquired;
|
|
143
|
+
if (this.#hasLease) this.#startLeaseRenewal();
|
|
144
|
+
return this.#hasLease;
|
|
145
|
+
}
|
|
146
|
+
#startLeaseRenewal() {
|
|
147
|
+
if (this.#leaseRenewalTimer) return;
|
|
148
|
+
this.#leaseRenewalTimer = setInterval(() => {
|
|
149
|
+
this.#leaseProvider.renewLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs).then((renewed) => {
|
|
150
|
+
if (!renewed) {
|
|
151
|
+
this.#hasLease = false;
|
|
152
|
+
this.#stopLeaseRenewal();
|
|
153
|
+
}
|
|
154
|
+
}).catch((error) => {
|
|
155
|
+
this.#hasLease = false;
|
|
156
|
+
this.#stopLeaseRenewal();
|
|
157
|
+
this.deps?.logger.warn("Platform Linear event polling lease renewal failed", { error: error instanceof Error ? error.message : String(error) });
|
|
158
|
+
});
|
|
159
|
+
}, Math.floor(this.#leaseTtlMs / 3));
|
|
160
|
+
this.#leaseRenewalTimer.unref?.();
|
|
161
|
+
}
|
|
162
|
+
#stopLeaseRenewal() {
|
|
163
|
+
if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);
|
|
164
|
+
this.#leaseRenewalTimer = void 0;
|
|
165
|
+
}
|
|
166
|
+
async #poll() {
|
|
167
|
+
let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileIntervalMs;
|
|
168
|
+
if (this.#pollEventsEnabled) {
|
|
169
|
+
let workspaces = [];
|
|
170
|
+
try {
|
|
171
|
+
workspaces = await this.#linear.listWorkspaces();
|
|
172
|
+
} catch (error) {
|
|
173
|
+
const delay = retryDelay(error, this.#intervalMs);
|
|
174
|
+
retryInMs = Math.max(retryInMs, delay);
|
|
175
|
+
this.deps?.logger.error("Platform Linear workspace listing failed", {
|
|
176
|
+
error: error instanceof Error ? error.message : String(error),
|
|
177
|
+
retryInMs: delay
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
for (const workspace of workspaces) {
|
|
181
|
+
if (!this.#running || !this.#hasLease) break;
|
|
182
|
+
try {
|
|
183
|
+
await this.#pollWorkspace(workspace.linearWorkspaceId);
|
|
184
|
+
} catch (error) {
|
|
185
|
+
const delay = retryDelay(error, this.#intervalMs);
|
|
186
|
+
retryInMs = Math.max(retryInMs, delay);
|
|
187
|
+
this.deps?.logger.error("Platform Linear workspace event polling failed", {
|
|
188
|
+
linearWorkspaceId: workspace.linearWorkspaceId,
|
|
189
|
+
error: error instanceof Error ? error.message : String(error),
|
|
190
|
+
retryInMs: delay
|
|
191
|
+
});
|
|
192
|
+
if (error instanceof PlatformApiError && error.status === 429) break;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
await this.#maybeReconcile();
|
|
197
|
+
return retryInMs;
|
|
198
|
+
}
|
|
199
|
+
async #maybeReconcile() {
|
|
200
|
+
if (!this.#reconcileFactoryState || !this.#running || !this.#hasLease) return;
|
|
201
|
+
const now = this.#now();
|
|
202
|
+
if (now - this.#lastReconcileAt < this.#reconcileIntervalMs) return;
|
|
203
|
+
this.#lastReconcileAt = now;
|
|
204
|
+
const startedAt = Date.now();
|
|
205
|
+
try {
|
|
206
|
+
const { errors, ...counts } = await this.#reconcileFactoryState();
|
|
207
|
+
const context = {
|
|
208
|
+
...counts,
|
|
209
|
+
durationMs: Date.now() - startedAt
|
|
210
|
+
};
|
|
211
|
+
if (counts.failed > 0) this.deps?.logger.warn("Platform Linear issue reconcile sweep completed with failures", {
|
|
212
|
+
...context,
|
|
213
|
+
errors
|
|
214
|
+
});
|
|
215
|
+
else if (counts.updated > 0) this.deps?.logger.info("Platform Linear issue reconcile patched stale metadata", context);
|
|
216
|
+
else this.deps?.logger.debug("Platform Linear issue reconcile sweep completed", context);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
this.deps?.logger.error("Platform Linear issue reconcile failed", {
|
|
219
|
+
durationMs: Date.now() - startedAt,
|
|
220
|
+
error: error instanceof Error ? error.message : String(error)
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
async #pollWorkspace(linearWorkspaceId) {
|
|
225
|
+
if (!this.#settings.workspaces[linearWorkspaceId]) {
|
|
226
|
+
this.#settings.workspaces[linearWorkspaceId] = { afterTimestamp: this.#startedAt };
|
|
227
|
+
await this.#saveSettings();
|
|
228
|
+
}
|
|
229
|
+
while (this.#running && this.#hasLease) {
|
|
230
|
+
const cursor = this.#settings.workspaces[linearWorkspaceId];
|
|
231
|
+
const query = new URLSearchParams({
|
|
232
|
+
limit: String(EVENT_PAGE_SIZE),
|
|
233
|
+
type: "Issue"
|
|
234
|
+
});
|
|
235
|
+
if ("afterEventId" in cursor) query.set("afterEventId", cursor.afterEventId);
|
|
236
|
+
else query.set("after", String(cursor.afterTimestamp));
|
|
237
|
+
const pollStartedAt = performance.now();
|
|
238
|
+
const page = await this.#client.request("GET", `${API_PREFIX}/workspaces/${encodeURIComponent(linearWorkspaceId)}/events?${query}`);
|
|
239
|
+
this.deps?.logger.debug("Platform Linear workspace event poll completed", {
|
|
240
|
+
linearWorkspaceId,
|
|
241
|
+
eventCount: page.events.length,
|
|
242
|
+
latencyMs: Math.round(performance.now() - pollStartedAt)
|
|
243
|
+
});
|
|
244
|
+
if (page.events.length === 0) return;
|
|
245
|
+
const lastId = page.events[page.events.length - 1].id;
|
|
246
|
+
const projects = await this.#projects.listAll();
|
|
247
|
+
for (const event of page.events) {
|
|
248
|
+
if (!this.#running || !this.#hasLease) return;
|
|
249
|
+
await this.#dispatchEvent(linearWorkspaceId, event, projects);
|
|
250
|
+
}
|
|
251
|
+
if ("afterEventId" in cursor && cursor.afterEventId === lastId) return;
|
|
252
|
+
this.#settings.workspaces[linearWorkspaceId] = { afterEventId: lastId };
|
|
253
|
+
await this.#saveSettings();
|
|
254
|
+
if (page.events.length < EVENT_PAGE_SIZE) return;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
async #dispatchEvent(linearWorkspaceId, event, projects) {
|
|
258
|
+
if (event.envelope.type !== "Issue") return;
|
|
259
|
+
if (!this.#ingestFactoryIssue) return;
|
|
260
|
+
const issue = parseIssueEnvelope(event.envelope);
|
|
261
|
+
if (!issue) {
|
|
262
|
+
this.deps?.logger.warn("Platform Linear event log returned an unusable Issue payload", {
|
|
263
|
+
linearWorkspaceId,
|
|
264
|
+
eventId: event.id
|
|
265
|
+
});
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const sourceKey = `linear:${issue.identifier}`;
|
|
269
|
+
let dispatched = 0;
|
|
270
|
+
for (const project of projects) {
|
|
271
|
+
let items;
|
|
272
|
+
try {
|
|
273
|
+
items = await this.#workItems.list({
|
|
274
|
+
orgId: project.orgId,
|
|
275
|
+
factoryProjectId: project.id
|
|
276
|
+
});
|
|
277
|
+
} catch (error) {
|
|
278
|
+
this.deps?.logger.error("Platform Linear work-item lookup failed", {
|
|
279
|
+
linearWorkspaceId,
|
|
280
|
+
eventId: event.id,
|
|
281
|
+
projectId: project.id,
|
|
282
|
+
error: error instanceof Error ? error.message : String(error)
|
|
283
|
+
});
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
if (!items.some((item) => item.externalSource?.integrationId === "linear" && item.externalSource.type === "issue" && item.externalSource.externalId === sourceKey)) continue;
|
|
287
|
+
try {
|
|
288
|
+
await this.#ingestFactoryIssue({
|
|
289
|
+
orgId: project.orgId,
|
|
290
|
+
userId: "platform-linear-event-worker",
|
|
291
|
+
factoryProjectId: project.id,
|
|
292
|
+
issues: [issue]
|
|
293
|
+
});
|
|
294
|
+
dispatched += 1;
|
|
295
|
+
} catch (error) {
|
|
296
|
+
this.deps?.logger.error("Platform Linear issue ingest failed", {
|
|
297
|
+
linearWorkspaceId,
|
|
298
|
+
eventId: event.id,
|
|
299
|
+
projectId: project.id,
|
|
300
|
+
error: error instanceof Error ? error.message : String(error)
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
if (dispatched === 0) this.deps?.logger.debug("Platform Linear Issue event had no linked work items to update", {
|
|
305
|
+
linearWorkspaceId,
|
|
306
|
+
eventId: event.id,
|
|
307
|
+
sourceKey
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
async #saveSettings() {
|
|
311
|
+
await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
function getLeaseProvider(pubsub) {
|
|
315
|
+
const getProvider = pubsub.getLeaseProvider;
|
|
316
|
+
if (typeof getProvider === "function") return getProvider.call(pubsub) ?? NoopLeaseProvider;
|
|
317
|
+
return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;
|
|
318
|
+
}
|
|
319
|
+
function normalizeSettings(value) {
|
|
320
|
+
if (!value || value.version !== 1 || !value.workspaces || typeof value.workspaces !== "object") return {
|
|
321
|
+
version: 1,
|
|
322
|
+
workspaces: {}
|
|
323
|
+
};
|
|
324
|
+
return {
|
|
325
|
+
version: 1,
|
|
326
|
+
workspaces: { ...value.workspaces }
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
function retryDelay(error, fallbackMs) {
|
|
330
|
+
if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) return Math.max(fallbackMs, error.retryAfterSeconds * 1e3);
|
|
331
|
+
return fallbackMs;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Translate an Issue webhook envelope into the rules-ingress shape.
|
|
335
|
+
* Returns undefined when the payload lacks the identifiers we need to
|
|
336
|
+
* match a work item.
|
|
337
|
+
*/
|
|
338
|
+
function parseIssueEnvelope(envelope) {
|
|
339
|
+
const data = envelope.data;
|
|
340
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return void 0;
|
|
341
|
+
const raw = data;
|
|
342
|
+
const id = typeof raw.id === "string" ? raw.id : void 0;
|
|
343
|
+
const identifier = typeof raw.identifier === "string" ? raw.identifier : void 0;
|
|
344
|
+
const title = typeof raw.title === "string" ? raw.title : void 0;
|
|
345
|
+
const url = typeof raw.url === "string" ? raw.url : envelope.url ?? void 0;
|
|
346
|
+
if (!id || !identifier || !title || !url) return void 0;
|
|
347
|
+
const state = optionalObject(raw.state);
|
|
348
|
+
const team = optionalObject(raw.team);
|
|
349
|
+
const assignee = optionalObject(raw.assignee);
|
|
350
|
+
const creator = optionalObject(raw.user) ?? optionalObject(raw.creator);
|
|
351
|
+
const labels = Array.isArray(raw.labels) ? raw.labels.flatMap((label) => {
|
|
352
|
+
const obj = optionalObject(label);
|
|
353
|
+
return obj && typeof obj.name === "string" ? [obj.name] : [];
|
|
354
|
+
}) : [];
|
|
355
|
+
const createdAt = typeof raw.createdAt === "string" ? raw.createdAt : envelope.createdAt ?? "";
|
|
356
|
+
const updatedAt = typeof raw.updatedAt === "string" ? raw.updatedAt : createdAt;
|
|
357
|
+
return {
|
|
358
|
+
id,
|
|
359
|
+
identifier,
|
|
360
|
+
title,
|
|
361
|
+
url,
|
|
362
|
+
state: (state && typeof state.name === "string" ? state.name : null) ?? "",
|
|
363
|
+
stateType: (state && typeof state.type === "string" ? state.type : null) ?? "",
|
|
364
|
+
priorityLabel: typeof raw.priorityLabel === "string" ? raw.priorityLabel : "",
|
|
365
|
+
assignee: assignee && typeof assignee.name === "string" ? assignee.name : null,
|
|
366
|
+
creator: creator && typeof creator.name === "string" ? creator.name : null,
|
|
367
|
+
team: team && typeof team.name === "string" ? team.name : null,
|
|
368
|
+
labels,
|
|
369
|
+
createdAt,
|
|
370
|
+
updatedAt
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
function optionalObject(value) {
|
|
374
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
375
|
+
return value;
|
|
376
|
+
}
|
|
377
|
+
//#endregion
|
|
378
|
+
export { PlatformLinearEventWorker };
|
|
379
|
+
|
|
380
|
+
//# sourceMappingURL=event-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-worker.js","names":["#client","#linear","#storage","#projects","#workItems","#ingestFactoryIssue","#reconcileFactoryState","#pollEventsEnabled","#intervalMs","#reconcileIntervalMs","#now","#leaseOwner","#leaseTtlMs","#leaseProvider","#running","#startedAt","#settings","#schedule","#timer","#stopLeaseRenewal","#inFlight","#hasLease","#tick","#ensureLease","#poll","#startLeaseRenewal","#leaseRenewalTimer","#pollWorkspace","#maybeReconcile","#lastReconcileAt","#saveSettings","#dispatchEvent"],"sources":["../../../../src/integrations/platform/linear/event-worker.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { 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 { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../../../storage/domains/work-items/base.js';\nimport type { IssueReconciler } from '../../issue-reconciler.js';\nimport type { LinearIssueIngress, LinearRulesIngress } from '../../linear/rules.js';\nimport { PlatformApiClient, PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/linear';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\nconst DEFAULT_RECONCILE_INTERVAL_MS = 5 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_linear_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst LEASE_KEY = 'platform-linear-events:linear';\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformLinearEventWorkerSettings = {\n version: 1;\n workspaces: Record<string, EventCursor>;\n};\n\nexport type PlatformLinearEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformLinearEventWorkerSettings,\n Record<string, unknown>\n>;\n\n/**\n * Minimal envelope shape mirrored from `@platform/linear`. Kept opaque\n * (`data: unknown`) — every consumer demuxes by `type`.\n */\nexport interface LinearWebhookEnvelope {\n type: string;\n action: string | null;\n createdAt: string | null;\n webhookTimestamp: number | null;\n linearOrganizationId: string | null;\n oauthClientId: string | null;\n url: string | null;\n data: unknown;\n}\n\nexport interface LinearEventLogEntry {\n id: string;\n timestamp: number;\n envelope: LinearWebhookEnvelope;\n}\n\nexport interface PlatformLinearWorkspace {\n linearWorkspaceId: string;\n linearWorkspaceName?: string;\n}\n\n/**\n * Everything the worker needs to drive ingest + reconciliation without\n * pulling in the full `PlatformLinearIntegration` type (circular).\n */\nexport interface PlatformLinearEventDispatchIntegration {\n listWorkspaces(): Promise<PlatformLinearWorkspace[]>;\n}\n\nexport interface PlatformLinearEventWorkerConfig {\n client: PlatformApiClient;\n linear: PlatformLinearEventDispatchIntegration;\n storage: PlatformLinearEventStorage;\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n /**\n * Used to scope event dispatch to `(orgId, factoryProjectId)` pairs that\n * already have a work item linked to the incoming Linear issue. Without\n * this scoping, a workspace-scoped event would fan out to every project in\n * every org and materialize a triage card in each — a cross-tenant leak.\n * First-observation of a Linear issue happens through the user-authenticated\n * `/web/linear/issues?factoryProjectId=...` intake path instead.\n */\n workItems: Pick<WorkItemsStorage, 'list'>;\n /** Called with a single-issue rules ingress derived from an `Issue` webhook. */\n ingestFactoryIssue?: (input: LinearRulesIngress) => Promise<unknown>;\n reconcileFactoryState?: IssueReconciler;\n /** When false the worker skips event tailing and only runs the reconcile sweep. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n reconcileIntervalMs?: number;\n now?: () => number;\n}\n\n/**\n * Tails the Platform Linear event stream (Redis-backed, per workspace) and\n * runs the same folded issue-reconcile sweep pattern as\n * `PlatformGithubEventWorker`. Issue events are translated into a normal\n * `LinearRulesIngress` so downstream rule dispatch is identical to the\n * polling path.\n *\n * Cursor state is persisted per workspace via the integration's generic\n * settings surface, keyed by a well-known worker identity. Cold start uses\n * `afterTimestamp: now - 1` to avoid replaying the 14-day stream backlog.\n *\n * ## Delivery semantics\n *\n * **At-most-once** per event. The cursor advances to the last event ID in a\n * page after all dispatch attempts on that page complete, regardless of\n * whether individual ingest calls threw. Ingest failures are logged, the\n * offending event is not retried, and drift is caught by the folded\n * `LinearIssueReconciler` sweep on its own cadence (default 5 minutes). This\n * matches `PlatformGithubEventWorker` and avoids poison-pill events blocking\n * the whole stream. Any consumer that needs exactly-once must idempotently\n * handle the same issue arriving via both the event path and the reconcile\n * path.\n */\nexport class PlatformLinearEventWorker extends MastraWorker {\n readonly name = 'platform-linear-events';\n\n readonly #client: PlatformApiClient;\n readonly #linear: PlatformLinearEventDispatchIntegration;\n readonly #storage: PlatformLinearEventStorage;\n readonly #projects: Pick<FactoryProjectsStorage, 'listAll'>;\n readonly #workItems: Pick<WorkItemsStorage, 'list'>;\n readonly #ingestFactoryIssue: ((input: LinearRulesIngress) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: IssueReconciler | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #intervalMs: number;\n readonly #reconcileIntervalMs: number;\n readonly #now: () => number;\n readonly #leaseOwner = randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n #lastReconcileAt = 0;\n #settings: PlatformLinearEventWorkerSettings = { version: 1, workspaces: {} };\n\n constructor(config: PlatformLinearEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#linear = config.linear;\n this.#storage = config.storage;\n this.#projects = config.projects;\n this.#workItems = config.workItems;\n this.#ingestFactoryIssue = config.ingestFactoryIssue;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.#reconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform Linear event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#reconcileIntervalMs) || this.#reconcileIntervalMs <= 0) {\n throw new Error('Platform Linear reconcile interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n this.#now = config.now ?? Date.now;\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('PlatformLinearEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform Linear event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\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 this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(LEASE_KEY, this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\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();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform Linear event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform Linear event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n // Reconcile-only mode has no event tail to keep fresh, so tick on the\n // slower reconcile cadence instead of the polling interval.\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileIntervalMs;\n\n if (this.#pollEventsEnabled) {\n // Only list workspaces when actually tailing events: reconciliation\n // does not need the workspace list, and folding this call into\n // reconcile-only mode would let one workspace-listing outage take\n // down the reconcile sweep as well.\n let workspaces: PlatformLinearWorkspace[] = [];\n try {\n workspaces = await this.#linear.listWorkspaces();\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace listing failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n }\n\n for (const workspace of workspaces) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollWorkspace(workspace.linearWorkspaceId);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace event polling failed', {\n linearWorkspaceId: workspace.linearWorkspaceId,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile();\n\n return retryInMs;\n }\n\n async #maybeReconcile(): Promise<void> {\n if (!this.#reconcileFactoryState || !this.#running || !this.#hasLease) return;\n const now = this.#now();\n if (now - this.#lastReconcileAt < this.#reconcileIntervalMs) return;\n // Advance the clock before sweeping so a persistently failing sweep stays\n // on cadence instead of retrying every poll tick.\n this.#lastReconcileAt = now;\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState();\n const context = { ...counts, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform Linear issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform Linear issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform Linear issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue reconcile failed', {\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n async #pollWorkspace(linearWorkspaceId: string): Promise<void> {\n if (!this.#settings.workspaces[linearWorkspaceId]) {\n this.#settings.workspaces[linearWorkspaceId] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.workspaces[linearWorkspaceId]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE), type: 'Issue' });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('after', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: LinearEventLogEntry[] }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(linearWorkspaceId)}/events?${query}`,\n );\n this.deps?.logger.debug('Platform Linear workspace event poll completed', {\n linearWorkspaceId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0) return;\n\n const lastId = page.events[page.events.length - 1]!.id;\n\n // Resolve the project set once per page instead of once per event.\n // The event stream can return up to EVENT_PAGE_SIZE (500) events; the\n // project list rarely changes within the second or two it takes to\n // dispatch a single page, and #dispatchEvent still consults storage\n // per-project to check for a linked work item.\n const projects = await this.#projects.listAll();\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n await this.#dispatchEvent(linearWorkspaceId, event, projects);\n }\n\n if ('afterEventId' in cursor && cursor.afterEventId === lastId) return;\n this.#settings.workspaces[linearWorkspaceId] = { afterEventId: lastId };\n await this.#saveSettings();\n\n // Short pages mean we've caught up; wait for the next tick.\n if (page.events.length < EVENT_PAGE_SIZE) return;\n }\n }\n\n async #dispatchEvent(\n linearWorkspaceId: string,\n event: LinearEventLogEntry,\n projects: readonly { id: string; orgId: string }[],\n ): Promise<void> {\n if (event.envelope.type !== 'Issue') return;\n if (!this.#ingestFactoryIssue) return;\n const issue = parseIssueEnvelope(event.envelope);\n if (!issue) {\n this.deps?.logger.warn('Platform Linear event log returned an unusable Issue payload', {\n linearWorkspaceId,\n eventId: event.id,\n });\n return;\n }\n\n // The event stream is workspace-scoped and Platform Linear has no\n // workspace→org mapping we can trust. To avoid cross-tenant fan-out (an\n // Issue from org A materializing a triage card in org B via the default\n // `linearIssueObserved` rule), only dispatch to `(orgId, factoryProjectId)`\n // pairs that already have a persisted work item for this Linear issue.\n // First-observation of a Linear issue happens through the\n // user-authenticated `/web/linear/issues?factoryProjectId=...` intake path.\n const sourceKey = `linear:${issue.identifier}`;\n let dispatched = 0;\n for (const project of projects) {\n let items;\n try {\n items = await this.#workItems.list({ orgId: project.orgId, factoryProjectId: project.id });\n } catch (error) {\n this.deps?.logger.error('Platform Linear work-item lookup failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const linked = items.some(\n item =>\n item.externalSource?.integrationId === 'linear' &&\n item.externalSource.type === 'issue' &&\n item.externalSource.externalId === sourceKey,\n );\n if (!linked) continue;\n try {\n await this.#ingestFactoryIssue({\n orgId: project.orgId,\n userId: 'platform-linear-event-worker',\n factoryProjectId: project.id,\n issues: [issue],\n });\n dispatched += 1;\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue ingest failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (dispatched === 0) {\n this.deps?.logger.debug('Platform Linear Issue event had no linked work items to update', {\n linearWorkspaceId,\n eventId: event.id,\n sourceKey,\n });\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\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 : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformLinearEventWorkerSettings | null): PlatformLinearEventWorkerSettings {\n if (!value || value.version !== 1 || !value.workspaces || typeof value.workspaces !== 'object') {\n return { version: 1, workspaces: {} };\n }\n return { version: 1, workspaces: { ...value.workspaces } };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n\n/**\n * Translate an Issue webhook envelope into the rules-ingress shape.\n * Returns undefined when the payload lacks the identifiers we need to\n * match a work item.\n */\nfunction parseIssueEnvelope(envelope: LinearWebhookEnvelope): LinearIssueIngress | undefined {\n const data = envelope.data;\n if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;\n const raw = data as Record<string, unknown>;\n const id = typeof raw.id === 'string' ? raw.id : undefined;\n const identifier = typeof raw.identifier === 'string' ? raw.identifier : undefined;\n const title = typeof raw.title === 'string' ? raw.title : undefined;\n const url = typeof raw.url === 'string' ? raw.url : envelope.url ?? undefined;\n if (!id || !identifier || !title || !url) return undefined;\n\n const state = optionalObject(raw.state);\n const team = optionalObject(raw.team);\n const assignee = optionalObject(raw.assignee);\n const creator = optionalObject(raw.user) ?? optionalObject(raw.creator);\n const labels = Array.isArray(raw.labels)\n ? raw.labels.flatMap(label => {\n const obj = optionalObject(label);\n return obj && typeof obj.name === 'string' ? [obj.name] : [];\n })\n : [];\n\n const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : envelope.createdAt ?? '';\n const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt;\n\n return {\n id,\n identifier,\n title,\n url,\n state: (state && typeof state.name === 'string' ? state.name : null) ?? '',\n stateType: (state && typeof state.type === 'string' ? state.type : null) ?? '',\n priorityLabel: typeof raw.priorityLabel === 'string' ? raw.priorityLabel : '',\n assignee: assignee && typeof assignee.name === 'string' ? assignee.name : null,\n creator: creator && typeof creator.name === 'string' ? creator.name : null,\n team: team && typeof team.name === 'string' ? team.name : null,\n labels,\n createdAt,\n updatedAt,\n };\n}\n\nfunction optionalObject(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n"],"mappings":";;;;;AAcA,MAAM,aAAa;AACnB,MAAM,2BAA2B;AACjC,MAAM,gCAAgC,IAAI;AAC1C,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;AA+FlB,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW;CAElC,WAAW;CACX;CACA;CACA;CACA,iBAAgC;CAChC;CACA,YAAY;CACZ,aAAa;CACb,mBAAmB;CACnB,YAA+C;EAAE,SAAS;EAAG,YAAY,CAAC;CAAE;CAE5E,YAAY,QAAyC;EACnD,MAAM;EACN,KAAKA,UAAU,OAAO;EACtB,KAAKC,UAAU,OAAO;EACtB,KAAKC,WAAW,OAAO;EACvB,KAAKC,YAAY,OAAO;EACxB,KAAKC,aAAa,OAAO;EACzB,KAAKC,sBAAsB,OAAO;EACl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S,WAAW,KAAK,OAAO;EAC1D;EACA;EACA;CACF;AACF;AAEA,SAAS,eAAe,OAAqD;CAC3E,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO,KAAA;CACxE,OAAO;AACT"}
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import type { RequestContext } from '@mastra/core/request-context';
|
|
2
2
|
import type { ApiRoute } from '@mastra/core/server';
|
|
3
|
+
import type { MastraWorker } from '@mastra/core/worker';
|
|
3
4
|
import type { Intake } from '../../../capabilities/intake.js';
|
|
4
5
|
import type { RouteAuth } from '../../../routes/route.js';
|
|
5
6
|
import type { FactoryProjectsStorage } from '../../../storage/domains/projects/base.js';
|
|
6
7
|
import type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../../base.js';
|
|
7
8
|
import type { LinearConnectionCheck } from '../../linear/integration.js';
|
|
8
9
|
import type { LinearConnectionRow, LinearStorageHandle } from '../../linear/storage.js';
|
|
10
|
+
type LinearWorkspace = {
|
|
11
|
+
linearWorkspaceId: string;
|
|
12
|
+
linearWorkspaceName: string;
|
|
13
|
+
urlKey: string | null;
|
|
14
|
+
connected: boolean;
|
|
15
|
+
};
|
|
9
16
|
type LinearProject = {
|
|
10
17
|
id: string;
|
|
11
18
|
name: string;
|
|
@@ -33,6 +40,7 @@ export declare class PlatformLinearIntegration implements FactoryIntegration {
|
|
|
33
40
|
getFreshAccessToken(_connection: LinearConnectionRow): Promise<string>;
|
|
34
41
|
canPostComments(connection: LinearConnectionRow): boolean;
|
|
35
42
|
checkConnection(orgId: string): Promise<LinearConnectionCheck>;
|
|
43
|
+
workers(ctx: IntegrationContext): MastraWorker[];
|
|
36
44
|
routes(ctx: IntegrationContext): ApiRoute[];
|
|
37
45
|
agentTools({ requestContext }: {
|
|
38
46
|
requestContext: RequestContext;
|
|
@@ -41,6 +49,7 @@ export declare class PlatformLinearIntegration implements FactoryIntegration {
|
|
|
41
49
|
listProjects(): Promise<Array<LinearProject & {
|
|
42
50
|
workspaceId: string;
|
|
43
51
|
}>>;
|
|
52
|
+
listWorkspaces(): Promise<LinearWorkspace[]>;
|
|
44
53
|
}
|
|
45
54
|
export {};
|
|
46
55
|
//# sourceMappingURL=integration.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/linear/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/linear/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAIxD,OAAO,KAAK,EAAE,MAAM,EAA0D,MAAM,iCAAiC,CAAC;AACtH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,2CAA2C,CAAC;AACxF,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAE9F,OAAO,KAAK,EAAE,qBAAqB,EAAqB,MAAM,6BAA6B,CAAC;AAI5F,OAAO,KAAK,EAAwB,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AA+C9G,KAAK,eAAe,GAAG;IACrB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,SAAS,EAAE,OAAO,CAAC;CACpB,CAAC;AACF,KAA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,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIhC,YAAY,IAAI,OAAO,CAAC,KAAK,CAAC,aAAa,GAAG;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IA+BvE,cAAc,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;CAuInD"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { PlatformApiClient, PlatformApiError, logPlatformInfo, logPlatformWarn, platformApiClientConfigFromEnv } from "../api-client.js";
|
|
2
|
-
import { buildLinearRoutes } from "../../linear/routes.js";
|
|
3
2
|
import { attachLinearRules } from "../../linear/rules.js";
|
|
3
|
+
import { attachLinearIssueReconciler } from "../../linear/issue-reconciler.js";
|
|
4
|
+
import { buildLinearRoutes } from "../../linear/routes.js";
|
|
4
5
|
import { buildLinearAgentTools } from "../../linear/agent-tools.js";
|
|
6
|
+
import { PlatformLinearEventWorker } from "./event-worker.js";
|
|
5
7
|
import { registerApiRoute } from "@mastra/core/server";
|
|
6
8
|
//#region src/integrations/platform/linear/integration.ts
|
|
7
9
|
const API_PREFIX = "/v1/server/linear";
|
|
@@ -241,6 +243,30 @@ var PlatformLinearIntegration = class {
|
|
|
241
243
|
checkedAt: Date.now()
|
|
242
244
|
};
|
|
243
245
|
}
|
|
246
|
+
workers(ctx) {
|
|
247
|
+
const pollingEnabled = process.env.MASTRACODE_PLATFORM_LINEAR_POLLING_ENABLED?.trim().toLowerCase() !== "false";
|
|
248
|
+
const reconcileEnabled = process.env.MASTRACODE_LINEAR_RECONCILE_ENABLED?.trim().toLowerCase() !== "false";
|
|
249
|
+
if (!pollingEnabled && !reconcileEnabled) return [];
|
|
250
|
+
const ingest = attachLinearRules(ctx);
|
|
251
|
+
const reconcile = reconcileEnabled ? attachLinearIssueReconciler(this, ctx) : void 0;
|
|
252
|
+
const workItems = ctx.rules?.workItems;
|
|
253
|
+
if (!workItems) return [];
|
|
254
|
+
if (!ingest && !reconcile) return [];
|
|
255
|
+
const pollIntervalMs = optionalPositiveIntegerEnv("MASTRACODE_PLATFORM_LINEAR_POLLING_INTERVAL_MS");
|
|
256
|
+
const reconcileIntervalMs = optionalPositiveIntegerEnv("MASTRACODE_LINEAR_RECONCILE_INTERVAL_MS");
|
|
257
|
+
return [new PlatformLinearEventWorker({
|
|
258
|
+
client: this.#client,
|
|
259
|
+
linear: { listWorkspaces: () => this.listWorkspaces() },
|
|
260
|
+
storage: ctx.storage.generic,
|
|
261
|
+
projects: ctx.storage.projects,
|
|
262
|
+
workItems,
|
|
263
|
+
...ingest ? { ingestFactoryIssue: ingest } : {},
|
|
264
|
+
...reconcile ? { reconcileFactoryState: reconcile } : {},
|
|
265
|
+
pollEventsEnabled: pollingEnabled,
|
|
266
|
+
...pollIntervalMs !== void 0 ? { intervalMs: pollIntervalMs } : {},
|
|
267
|
+
...reconcileIntervalMs !== void 0 ? { reconcileIntervalMs } : {}
|
|
268
|
+
})];
|
|
269
|
+
}
|
|
244
270
|
routes(ctx) {
|
|
245
271
|
return [this.#connectRoute(ctx), ...buildLinearRoutes({
|
|
246
272
|
auth: ctx.auth,
|
|
@@ -313,6 +339,9 @@ var PlatformLinearIntegration = class {
|
|
|
313
339
|
}));
|
|
314
340
|
}))).flat();
|
|
315
341
|
}
|
|
342
|
+
async listWorkspaces() {
|
|
343
|
+
return this.#listWorkspaces();
|
|
344
|
+
}
|
|
316
345
|
async #listWorkspaces() {
|
|
317
346
|
return (await this.#client.request("GET", `${API_PREFIX}/workspaces`)).workspaces.filter((workspace) => workspace.connected);
|
|
318
347
|
}
|
|
@@ -477,6 +506,13 @@ function requireLinearConnection(connection) {
|
|
|
477
506
|
function isNotFound(error) {
|
|
478
507
|
return error instanceof PlatformApiError && error.status === 404;
|
|
479
508
|
}
|
|
509
|
+
function optionalPositiveIntegerEnv(name) {
|
|
510
|
+
const value = process.env[name]?.trim();
|
|
511
|
+
if (!value) return void 0;
|
|
512
|
+
const parsed = Number(value);
|
|
513
|
+
if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new Error(`${name} must be a positive integer.`);
|
|
514
|
+
return parsed;
|
|
515
|
+
}
|
|
480
516
|
//#endregion
|
|
481
517
|
export { PlatformLinearIntegration };
|
|
482
518
|
|