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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/* eslint-disable @typescript-eslint/no-explicit-any */
import axios from 'axios';

interface LinearActivityCreateParams {
  text: string;
  sourceURL: string;
}

interface LinearSettings {
  lastIssuesSync?: string;
  lastCommentsSync?: string;
  lastUserActionsSync?: string;
}

/**
 * Creates an activity message based on Linear data
 */
function createActivityMessage(params: LinearActivityCreateParams) {
  return {
    type: 'activity',
    data: {
      text: params.text,
      sourceURL: params.sourceURL,
    },
  };
}

/**
 * Fetches user information from Linear
 */
async function fetchUserInfo(apiKey: string) {
  try {
    const query = `
      query {
        viewer {
          id
          name
          email
        }
      }
    `;

    const response = await axios.post(
      'https://api.linear.app/graphql',
      { query },
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: apiKey,
        },
      },
    );

    return response.data.data.viewer;
  } catch (error) {
    throw error;
  }
}

/**
 * Fetches recent issues relevant to the user (created, assigned, or subscribed)
 */
async function fetchRecentIssues(apiKey: string, lastSyncTime: string) {
  try {
    const query = `
      query RecentIssues($lastSyncTime: DateTimeOrDuration) {
        issues(
          filter: {
            updatedAt: { gt: $lastSyncTime }
          },
          first: 50,
          orderBy: updatedAt
        ) {
          nodes {
            id
            identifier
            title
            url
            createdAt
            updatedAt
            state {
              id
              name
              type
            }
            team {
              id
              name
            }
            assignee {
              id
              name
              displayName
            }
            creator {
              id
              name
              displayName
            }
            subscribers {
              nodes {
                id
                name
                displayName
              }
            }
            priority
            history {
              nodes {
                id
                createdAt
                updatedAt
                fromStateId
                toStateId
                fromAssigneeId
                toAssigneeId
                fromPriority
                toPriority
              }
            }
          }
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    `;

    const response = await axios.post(
      'https://api.linear.app/graphql',
      {
        query,
        variables: {
          lastSyncTime,
        },
      },
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: apiKey,
        },
      },
    );

    return response.data.data.issues;
  } catch (error) {
    throw error;
  }
}

/**
 * Fetches recent comments on issues relevant to the user
 */
async function fetchRecentComments(apiKey: string, lastSyncTime: string) {
  try {
    const query = `
      query RecentComments($lastSyncTime: DateTimeOrDuration) {
        comments(
          filter: {
            updatedAt: { gt: $lastSyncTime }
          },
          first: 50,
          orderBy: updatedAt
        ) {
          nodes {
            id
            body
            createdAt
            updatedAt
            user {
              id
              name
              displayName
            }
            issue {
              id
              identifier
              title
              url
              creator {
                id
                name
                displayName
              }
              assignee {
                id
                name
                displayName
              }
              subscribers {
                nodes {
                  id
                  name
                  displayName
                }
              }
            }
          }
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    `;

    const response = await axios.post(
      'https://api.linear.app/graphql',
      {
        query,
        variables: {
          lastSyncTime,
        },
      },
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: apiKey,
        },
      },
    );

    return response.data.data.comments;
  } catch (error) {
    throw error;
  }
}

/**
 * Process issue activities and create appropriate activity records
 */
async function processIssueActivities(issues: any[], userId: string) {
  const activities = [];

  for (const issue of issues) {
    try {
      // Skip issues that don't involve the user
      const isAssignee = issue.assignee?.id === userId;
      const isCreatedByUser = issue.creator?.id === userId;

      // Check if user is subscribed to the issue
      const isSubscribed =
        issue.subscribers?.nodes?.some((subscriber: any) => subscriber.id === userId) || false;

      if (!isAssignee && !isCreatedByUser && !isSubscribed) {
        continue;
      }

      // Process history to determine what actually changed
      let activityCreated = false;

      // Process assignment changes first (highest priority)
      if (issue.history && issue.history.nodes) {
        for (const historyItem of issue.history.nodes) {
          if (historyItem.toAssigneeId && historyItem.fromAssigneeId !== historyItem.toAssigneeId) {
            if (historyItem.toAssigneeId === userId) {
              activities.push(
                createActivityMessage({
                  text: `${issue.identifier} (${issue.title}) Issue assigned to you`,
                  sourceURL: issue.url,
                }),
              );
              activityCreated = true;
              break;
            } else if (isCreatedByUser && historyItem.fromAssigneeId === userId) {
              activities.push(
                createActivityMessage({
                  text: `${issue.identifier} (${issue.title}) Issue unassigned from you`,
                  sourceURL: issue.url,
                }),
              );
              activityCreated = true;
              break;
            }
          }
        }
      }

      // If no assignment change, check for status changes
      if (!activityCreated && issue.history && issue.history.nodes) {
        for (const historyItem of issue.history.nodes) {
          if (historyItem.toStateId && historyItem.fromStateId !== historyItem.toStateId) {
            if (!isAssignee && !isCreatedByUser && !isSubscribed) {
              continue;
            }

            const stateType = issue.state?.type;
            let statusText = `moved to ${issue.state?.name || 'a new status'}`;

            if (stateType === 'completed') {
              statusText = 'completed';
            } else if (stateType === 'canceled') {
              statusText = 'canceled';
            }

            let title;
            if (isCreatedByUser || isAssignee) {
              title = `${issue.identifier} (${issue.title}) Issue ${statusText}`;
            } else {
              title = `${issue.identifier} (${issue.title}) Issue ${statusText}`;
            }

            activities.push(
              createActivityMessage({
                text: title,
                sourceURL: issue.url,
              }),
            );
            activityCreated = true;
            break;
          }
        }
      }

      // If no history changes, check if it's a new issue creation
      if (!activityCreated && isCreatedByUser) {
        // Only create activity if issue was created recently (within sync window)
        const createdAt = new Date(issue.createdAt);
        const updatedAt = new Date(issue.updatedAt);

        // If created and updated times are very close, it's likely a new issue
        if (Math.abs(createdAt.getTime() - updatedAt.getTime()) < 60000) {
          // within 1 minute
          activities.push(
            createActivityMessage({
              text: `${issue.identifier} (${issue.title}) Issue created`,
              sourceURL: issue.url,
            }),
          );
          activityCreated = true;
        }
      }
    } catch (error) {
      // Silently ignore errors to prevent stdout pollution
    }
  }

  return activities;
}

/**
 * Process comment activities and create appropriate activity records
 */
async function processCommentActivities(comments: any[], userId: string, userInfo: any) {
  const activities = [];

  for (const comment of comments) {
    try {
      const isCommenter = comment.user?.id === userId;
      const isIssueCreator = comment.issue?.creator?.id === userId;
      const isAssignee = comment.issue?.assignee?.id === userId;

      // Check if user is subscribed to the issue
      const isSubscribed =
        comment.issue?.subscribers?.nodes?.some((subscriber: any) => subscriber.id === userId) ||
        false;

      // Check for mentions in the comment body
      const isMentioned = checkForUserMentions(comment.body, userInfo);

      // Skip if not relevant to user
      if (!isCommenter && !isIssueCreator && !isAssignee && !isSubscribed && !isMentioned) {
        continue;
      }

      let title;

      if (isCommenter) {
        // Comment created by the user
        title = `You commented on issue ${comment.issue.identifier}: ${truncateText(comment.body, 100)}`;
      } else if (isMentioned) {
        // User was mentioned in the comment
        title = `${comment.user?.name || 'Someone'} mentioned you in issue ${comment.issue.identifier}: ${truncateText(comment.body, 100)}`;
      } else if (isAssignee || isIssueCreator || isSubscribed) {
        // Comment on issue where user is assignee, creator, or subscriber
        let relation = 'an issue';
        if (isAssignee) {
          relation = 'your assigned issue';
        } else if (isIssueCreator) {
          relation = 'your issue';
        } else if (isSubscribed) {
          relation = "an issue you're subscribed to";
        }
        title = `${comment.user?.name || 'Someone'} commented on ${relation} ${comment.issue.identifier}: ${truncateText(comment.body, 100)}`;
      }

      if (title) {
        activities.push(
          createActivityMessage({
            text: title,
            sourceURL: `${comment.issue.url}#comment-${comment.id}`,
          }),
        );
      }
    } catch (error) {
      // Silently ignore errors to prevent stdout pollution
    }
  }

  return activities;
}

/**
 * Helper function to check for user mentions in text
 */
function checkForUserMentions(text: string, userInfo: any): boolean {
  if (!text || !userInfo) return false;

  const lowerText = text.toLowerCase();

  // Check for @username, @display name, or @email mentions
  const mentionPatterns = [
    userInfo.name && `@${userInfo.name.toLowerCase()}`,
    userInfo.displayName && `@${userInfo.displayName.toLowerCase()}`,
    userInfo.email && `@${userInfo.email.toLowerCase()}`,
  ].filter(Boolean);

  return mentionPatterns.some((pattern) => lowerText.includes(pattern));
}

/**
 * Helper function to truncate text with ellipsis
 */
function truncateText(text: string, maxLength: number): string {
  if (!text) return '';
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
}

/**
 * Helper function to get default sync time (24 hours ago)
 */
function getDefaultSyncTime(): string {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  return yesterday.toISOString();
}

/**
 * Main function to handle scheduled sync for Linear integration
 */
export async function handleSchedule(config: any, state: any) {
  try {
    const integrationConfiguration = config;

    // Check if we have a valid access token
    if (!integrationConfiguration?.apiKey) {
      return [];
    }

    // Get settings or initialize if not present
    let settings = (state || {}) as LinearSettings;

    // Default to 24 hours ago if no last sync times
    const lastIssuesSync = settings.lastIssuesSync || getDefaultSyncTime();
    const lastCommentsSync = settings.lastCommentsSync || getDefaultSyncTime();

    // Fetch user info to identify activities relevant to them
    let user;
    try {
      user = await fetchUserInfo(integrationConfiguration.apiKey);
    } catch (error) {
      return [];
    }

    if (!user || !user.id) {
      return [];
    }

    // Collect all messages
    const messages = [];

    // Process all issue activities (created, assigned, updated, etc.)
    try {
      const issues = await fetchRecentIssues(integrationConfiguration.apiKey, lastIssuesSync);
      if (issues && issues.nodes) {
        const issueActivities = await processIssueActivities(issues.nodes, user.id);
        messages.push(...issueActivities);
      }
    } catch (error) {
      // Silently ignore errors to prevent stdout pollution
    }

    // Process all comment activities
    try {
      const comments = await fetchRecentComments(integrationConfiguration.apiKey, lastCommentsSync);
      if (comments && comments.nodes) {
        const commentActivities = await processCommentActivities(comments.nodes, user.id, user);
        messages.push(...commentActivities);
      }
    } catch (error) {
      // Silently ignore errors to prevent stdout pollution
    }

    // Update last sync times
    const newSyncTime = new Date().toISOString();

    // Add state message for saving settings
    messages.push({
      type: 'state',
      data: {
        ...settings,
        lastIssuesSync: newSyncTime,
        lastCommentsSync: newSyncTime,
      },
    });

    return messages;
  } catch (error) {
    return [];
  }
}

/**
 * The main handler for the scheduled sync event
 */
export async function scheduleHandler(config: any, state: any) {
  return handleSchedule(config, state);
}