Repository navigation
Expand file tree
/
Copy pathworker.ts
More file actions
1880 lines (1724 loc) · 62.8 KB
/
Copy pathworker.ts
File metadata and controls
1880 lines (1724 loc) · 62.8 KB
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Linear plugin worker entrypoint.
*
* Lifecycle:
* - `setup` — read config, instantiate the Linear client, wire all event/job/
* data/action/tool/webhook handlers in synchronous registration order.
* - `onConfigChanged` — rebuild the Linear client without restarting.
* - `onValidateConfig` — used by the "Test Connection" button in settings.
* - `onWebhook` — verifies the Linear HMAC signature and routes payloads.
* - `onHealth` — surfaces last-sync / last-webhook timestamps.
*/
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
import {
definePlugin,
runWorker,
type PluginContext,
type PluginEvent,
type PluginHealthDiagnostics,
type PluginJobContext,
type PluginWebhookInput,
type ToolResult,
type ToolRunContext,
} from "@paperclipai/plugin-sdk";
import type { Issue } from "@paperclipai/plugin-sdk";
import {
ACTION_KEYS,
ACTIVITY_BUFFER_MAX,
DATA_KEYS,
DEFAULTS,
ENTITY_TYPES,
JOB_KEYS,
STATE_KEYS,
STATE_NAMESPACE,
TOOL_NAMES,
WEBHOOK_KEYS,
} from "./constants.js";
import { LinearApiError, LinearClient } from "./linear-client.js";
import {
DEFAULT_CONFIG,
type LinearIssue,
type LinearIssueLink,
type LinearLabel,
type LinearPluginConfig,
type LinearProject,
type LinearProjectLink,
type LinearTeam,
type LinearWebhookIssueData,
type LinearWebhookPayload,
type LinearWorkflowState,
type LinearWorkflowStateType,
type RecentActivityEntry,
} from "./types.js";
// ---------------------------------------------------------------------------
// Module-level mutable state — recreated on every worker restart, by design.
// ---------------------------------------------------------------------------
let currentContext: PluginContext | null = null;
let currentClient: LinearClient | null = null;
let currentConfig: LinearPluginConfig | null = null;
let cachedImportLabel: LinearLabel | null = null;
const recentActivity: RecentActivityEntry[] = [];
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function activity(entry: Omit<RecentActivityEntry, "id" | "createdAt">): RecentActivityEntry {
const next: RecentActivityEntry = {
id: randomUUID(),
createdAt: new Date().toISOString(),
...entry,
};
recentActivity.unshift(next);
if (recentActivity.length > ACTIVITY_BUFFER_MAX) {
recentActivity.length = ACTIVITY_BUFFER_MAX;
}
return next;
}
function summarizeError(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
}
/** Coerce a typed Linear API object into the `Record<string, unknown>` that the entities API wants. */
function asRecord(value: object): Record<string, unknown> {
return value as unknown as Record<string, unknown>;
}
async function loadConfig(ctx: PluginContext): Promise<LinearPluginConfig> {
const raw = (await ctx.config.get()) as Partial<LinearPluginConfig>;
return {
...DEFAULT_CONFIG,
...raw,
};
}
async function resolveApiKey(
ctx: PluginContext,
config: LinearPluginConfig,
): Promise<string | null> {
if (config.apiKeyRef) {
try {
return await ctx.secrets.resolve(config.apiKeyRef);
} catch (error) {
ctx.logger.warn("Failed to resolve apiKeyRef, falling back to apiKey", {
error: summarizeError(error),
});
}
}
if (config.apiKey && config.apiKey.length > 0) return config.apiKey;
return null;
}
async function resolveWebhookSecret(
ctx: PluginContext,
config: LinearPluginConfig,
): Promise<string | null> {
if (config.webhookSecretRef) {
try {
return await ctx.secrets.resolve(config.webhookSecretRef);
} catch {
// fall through to raw
}
}
return config.webhookSecret ?? null;
}
async function buildClient(
ctx: PluginContext,
config: LinearPluginConfig,
): Promise<LinearClient | null> {
const apiKey = await resolveApiKey(ctx, config);
if (!apiKey) return null;
return new LinearClient({
apiUrl: config.apiUrl ?? DEFAULTS.apiUrl,
apiKey,
http: ctx.http,
logger: ctx.logger,
});
}
function requireClient(): LinearClient {
if (!currentClient) {
throw new Error(
"Linear client not initialized — paste an API key in plugin settings",
);
}
return currentClient;
}
function requireConfig(): LinearPluginConfig {
if (!currentConfig) throw new Error("Linear plugin config not loaded yet");
return currentConfig;
}
function requireCtx(): PluginContext {
if (!currentContext) throw new Error("Plugin context not initialized");
return currentContext;
}
// ---------------------------------------------------------------------------
// Project link state
// ---------------------------------------------------------------------------
async function getProjectLink(
ctx: PluginContext,
paperclipProjectId: string,
): Promise<LinearProjectLink | null> {
const value = await ctx.state.get({
scopeKind: "project",
scopeId: paperclipProjectId,
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.projectLink,
});
return (value as LinearProjectLink | null) ?? null;
}
async function setProjectLink(
ctx: PluginContext,
paperclipProjectId: string,
link: LinearProjectLink,
): Promise<void> {
await ctx.state.set(
{
scopeKind: "project",
scopeId: paperclipProjectId,
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.projectLink,
},
link,
);
// Maintain a reverse-index so webhook handlers can find the Paperclip
// project from the Linear project ID without scanning every project.
if (link.linearProjectId) {
await ctx.state.set(
{
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: `${STATE_KEYS.reverseProjectLink}:${link.linearProjectId}`,
},
paperclipProjectId,
);
}
}
async function deleteProjectLink(ctx: PluginContext, paperclipProjectId: string): Promise<void> {
const existing = await getProjectLink(ctx, paperclipProjectId);
await ctx.state.delete({
scopeKind: "project",
scopeId: paperclipProjectId,
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.projectLink,
});
if (existing?.linearProjectId) {
await ctx.state.delete({
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: `${STATE_KEYS.reverseProjectLink}:${existing.linearProjectId}`,
});
}
}
async function findPaperclipProjectByLinearProject(
ctx: PluginContext,
linearProjectId: string,
): Promise<string | null> {
const value = await ctx.state.get({
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: `${STATE_KEYS.reverseProjectLink}:${linearProjectId}`,
});
return typeof value === "string" ? value : null;
}
// ---------------------------------------------------------------------------
// Issue link state
// ---------------------------------------------------------------------------
async function getIssueLink(
ctx: PluginContext,
paperclipIssueId: string,
): Promise<LinearIssueLink | null> {
const value = await ctx.state.get({
scopeKind: "issue",
scopeId: paperclipIssueId,
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.linearLink,
});
return (value as LinearIssueLink | null) ?? null;
}
async function setIssueLink(
ctx: PluginContext,
paperclipIssueId: string,
link: LinearIssueLink,
): Promise<void> {
await ctx.state.set(
{
scopeKind: "issue",
scopeId: paperclipIssueId,
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.linearLink,
},
link,
);
}
async function deleteIssueLink(ctx: PluginContext, paperclipIssueId: string): Promise<void> {
await ctx.state.delete({
scopeKind: "issue",
scopeId: paperclipIssueId,
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.linearLink,
});
}
// ---------------------------------------------------------------------------
// Linear cache helpers
// ---------------------------------------------------------------------------
async function refreshLinearCache(ctx: PluginContext): Promise<{
teams: LinearTeam[];
projects: LinearProject[];
}> {
const client = requireClient();
const [teams, projects] = await Promise.all([client.listTeams(), client.listProjects()]);
await ctx.state.set(
{
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.cachedLinearTeams,
},
teams,
);
await ctx.state.set(
{
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.cachedLinearProjects,
},
projects,
);
return { teams, projects };
}
async function ensureImportLabel(): Promise<LinearLabel | null> {
const config = requireConfig();
const labelName = config.importLabelName ?? DEFAULT_CONFIG.importLabelName;
if (!labelName) return null;
if (cachedImportLabel && cachedImportLabel.name === labelName) return cachedImportLabel;
const label = await requireClient().ensureWorkspaceLabel(labelName);
cachedImportLabel = label;
return label;
}
function issueHasLabel(data: LinearWebhookIssueData, labelName: string): boolean {
if (Array.isArray(data.labels)) {
return data.labels.some((l) => l.name === labelName);
}
return false;
}
function issueHasLabelOnObject(issue: LinearIssue, labelName: string): boolean {
return (issue.labels?.nodes ?? []).some((l) => l.name === labelName);
}
/**
* Look up the Linear issue ID we should pass as `parentId` when mirroring a
* Paperclip issue. Returns `null` when the Paperclip issue has no parent or
* when the parent has not been linked to Linear yet — the caller leaves
* `parentId` unset in that case so Linear creates a top-level issue, and the
* relationship gets stitched up in the second backfill pass.
*/
async function resolveParentLinearId(
ctx: PluginContext,
issue: Issue,
): Promise<string | null> {
if (!issue.parentId) return null;
const parentLink = await getIssueLink(ctx, issue.parentId);
return parentLink?.linearIssueId ?? null;
}
// ---------------------------------------------------------------------------
// Workflow state mapping (Paperclip status ↔ Linear workflow state)
// ---------------------------------------------------------------------------
/**
* Maps a Paperclip `IssueStatus` to a Linear workflow-state `type`. Linear's
* `type` column is the only stable cross-team semantic — names are custom per
* team. We pick the closest type, then resolve to a concrete `stateId` per
* team via the cached workflow states.
*
* Paperclip statuses come from `ISSUE_STATUSES` in @paperclipai/shared.
*/
function paperclipStatusToLinearType(status: Issue["status"]): LinearWorkflowStateType {
switch (status) {
case "backlog":
return "backlog";
case "todo":
return "unstarted";
case "in_progress":
case "in_review":
case "blocked":
return "started";
case "done":
return "completed";
case "cancelled":
return "canceled";
default:
return "unstarted";
}
}
/**
* Returns the Linear workflow state that best matches the Paperclip status for
* the given team. Prefers a name match (e.g. "In Review" ⇄ "in_review") then
* falls back to the type match. Caches per team in plugin state for the life
* of the worker (and persists across restarts). Returns `null` when the team
* has no states cached and we can't fetch (no client) — caller should leave
* `stateId` unset and let Linear pick its team default.
*/
async function getStateIdForStatus(
ctx: PluginContext,
teamId: string,
status: Issue["status"],
): Promise<string | null> {
const states = await getOrFetchWorkflowStates(ctx, teamId);
if (states.length === 0) return null;
const wantedType = paperclipStatusToLinearType(status);
const normalized = (s: string) => s.replace(/[\s_-]+/g, "").toLowerCase();
const wantedName = normalized(status);
// 1) Name match — let teams with custom names like "In Review" win over a
// generic "started" state.
const byName = states.find((s) => normalized(s.name) === wantedName);
if (byName) return byName.id;
// 2) Type match — pick the lowest-position state of the wanted type so we
// target the canonical entry point (e.g. "Backlog" not "Triage > Backlog").
const byType = states
.filter((s) => s.type === wantedType)
.sort((a, b) => a.position - b.position)[0];
return byType?.id ?? null;
}
async function getOrFetchWorkflowStates(
ctx: PluginContext,
teamId: string,
): Promise<LinearWorkflowState[]> {
const stateKey = `${STATE_KEYS.workflowStatesByTeam}:${teamId}`;
const cached = (await ctx.state.get({
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey,
})) as LinearWorkflowState[] | null;
if (cached && cached.length > 0) return cached;
if (!currentClient) return [];
try {
const fresh = await currentClient.listWorkflowStates(teamId);
await ctx.state.set(
{ scopeKind: "instance", namespace: STATE_NAMESPACE, stateKey },
fresh,
);
return fresh;
} catch (error) {
ctx.logger.warn("Failed to fetch Linear workflow states", {
teamId,
error: summarizeError(error),
});
return [];
}
}
// ---------------------------------------------------------------------------
// Event handlers — Paperclip → Linear
// ---------------------------------------------------------------------------
async function handlePaperclipIssueCreated(event: PluginEvent): Promise<void> {
const config = requireConfig();
if (!config.pushPaperclipIssues) return;
const ctx = requireCtx();
const issueId = event.entityId;
if (!issueId) return;
const existing = await getIssueLink(ctx, issueId);
if (existing) return; // already linked
const issue = await ctx.issues.get(issueId, event.companyId);
if (!issue?.projectId) return;
const projectLink = await getProjectLink(ctx, issue.projectId);
if (!projectLink) {
// Project not linked → nothing to do (silent, not an error).
return;
}
try {
const stateId = await getStateIdForStatus(
ctx,
projectLink.linearTeamId,
issue.status,
);
const parentLinearId = await resolveParentLinearId(ctx, issue);
const linearIssue = await requireClient().createIssue({
teamId: projectLink.linearTeamId,
title: issue.title,
...(issue.description ? { description: issue.description } : {}),
...(projectLink.linearProjectId ? { projectId: projectLink.linearProjectId } : {}),
...(stateId ? { stateId } : {}),
...(parentLinearId ? { parentId: parentLinearId } : {}),
});
const link: LinearIssueLink = {
linearIssueId: linearIssue.id,
linearIdentifier: linearIssue.identifier,
linearUrl: linearIssue.url,
linearTeamId: linearIssue.team.id,
linearProjectId: linearIssue.project?.id ?? null,
pushedAt: new Date().toISOString(),
lastSyncedAt: new Date().toISOString(),
};
await setIssueLink(ctx, issueId, link);
await ctx.entities.upsert({
entityType: ENTITY_TYPES.linearIssue,
scopeKind: "issue",
scopeId: issueId,
externalId: linearIssue.id,
title: linearIssue.title,
status: linearIssue.state.name,
data: { ...asRecord(linearIssue), paperclipIssueId: issueId },
});
await ctx.activity.log({
companyId: event.companyId,
message: `Pushed issue to Linear: ${linearIssue.identifier}`,
entityType: "issue",
entityId: issueId,
metadata: { linearIssueId: linearIssue.id, linearUrl: linearIssue.url },
});
activity({
level: "info",
source: "event",
message: `Pushed ${issue.title} → ${linearIssue.identifier} (${projectLink.linearProjectName ?? projectLink.linearTeamName})`,
});
} catch (error) {
ctx.logger.error("Failed to push issue to Linear", { issueId, error: summarizeError(error) });
activity({
level: "error",
source: "event",
message: `Push failed for ${issue.title}: ${summarizeError(error)}`,
});
}
}
async function handlePaperclipIssueUpdated(event: PluginEvent): Promise<void> {
const config = requireConfig();
if (!config.pushPaperclipIssues) return;
const ctx = requireCtx();
const issueId = event.entityId;
if (!issueId) return;
const link = await getIssueLink(ctx, issueId);
if (!link) return;
const issue = await ctx.issues.get(issueId, event.companyId);
if (!issue) return;
try {
const stateId = await getStateIdForStatus(ctx, link.linearTeamId, issue.status);
const parentLinearId = await resolveParentLinearId(ctx, issue);
await requireClient().updateIssue(link.linearIssueId, {
title: issue.title,
...(issue.description ? { description: issue.description } : {}),
...(stateId ? { stateId } : {}),
// Pass parent change-or-clear: Linear's `parentId` semantics let us
// overwrite, so include the resolved value (which may be the same).
...(parentLinearId ? { parentId: parentLinearId } : {}),
});
await setIssueLink(ctx, issueId, { ...link, lastSyncedAt: new Date().toISOString() });
activity({
level: "info",
source: "event",
message: `Updated Linear issue ${link.linearIdentifier} (status ${issue.status})`,
});
} catch (error) {
ctx.logger.error("Failed to update Linear issue", { issueId, error: summarizeError(error) });
}
}
async function handlePaperclipCommentCreated(event: PluginEvent): Promise<void> {
const ctx = requireCtx();
const payload = event.payload as { commentId?: string; issueId?: string; body?: string };
if (!payload.issueId || !payload.body) return;
const link = await getIssueLink(ctx, payload.issueId);
if (!link) return;
try {
await requireClient().createComment(link.linearIssueId, payload.body);
activity({
level: "info",
source: "event",
message: `Mirrored comment to ${link.linearIdentifier}`,
});
} catch (error) {
ctx.logger.error("Failed to mirror comment", {
issueId: payload.issueId,
error: summarizeError(error),
});
}
}
// ---------------------------------------------------------------------------
// Webhook handler — Linear → Paperclip
// ---------------------------------------------------------------------------
function verifyLinearSignature(
rawBody: string,
signatureHeader: string | string[] | undefined,
secret: string,
): boolean {
const headerVal = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
if (!headerVal) return false;
const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
const expectedBuf = Buffer.from(expected, "hex");
const providedBuf = Buffer.from(headerVal, "hex");
if (expectedBuf.length !== providedBuf.length) return false;
return timingSafeEqual(expectedBuf, providedBuf);
}
async function handleLinearWebhook(input: PluginWebhookInput): Promise<void> {
const ctx = requireCtx();
const config = requireConfig();
const secret = await resolveWebhookSecret(ctx, config);
if (secret) {
const sigHeader =
input.headers[DEFAULTS.webhookSignatureHeader] ??
input.headers["x-linear-signature"] ??
input.headers["linear-signature"];
if (!verifyLinearSignature(input.rawBody, sigHeader, secret)) {
ctx.logger.warn("Rejected Linear webhook with bad signature", {
requestId: input.requestId,
});
throw new Error("Invalid Linear webhook signature");
}
}
const payload = input.parsedBody as LinearWebhookPayload | undefined;
if (!payload || typeof payload !== "object") {
ctx.logger.warn("Linear webhook missing parsedBody", { requestId: input.requestId });
return;
}
await ctx.state.set(
{ scopeKind: "instance", namespace: STATE_NAMESPACE, stateKey: STATE_KEYS.lastWebhookAt },
new Date().toISOString(),
);
if (payload.type === "Issue") {
await handleLinearIssueWebhook(ctx, config, payload);
} else {
activity({
level: "info",
source: "webhook",
message: `Linear ${payload.type} ${payload.action} ignored`,
});
}
}
async function handleLinearIssueWebhook(
ctx: PluginContext,
config: LinearPluginConfig,
payload: LinearWebhookPayload,
): Promise<void> {
const data = payload.data;
const linearIssueId = data.id;
if (!linearIssueId) return;
const linked = await ctx.entities.list({
entityType: ENTITY_TYPES.linearIssue,
externalId: linearIssueId,
limit: 1,
});
const existing = linked[0];
if (payload.action === "remove") {
if (existing?.scopeId) {
await deleteIssueLink(ctx, existing.scopeId);
activity({
level: "info",
source: "webhook",
message: `Linear issue ${linearIssueId} removed; link cleared`,
});
}
return;
}
// Update existing linked issue: refresh metadata only.
if (existing?.scopeId) {
const issueLink = await getIssueLink(ctx, existing.scopeId);
if (issueLink) {
await setIssueLink(ctx, existing.scopeId, {
...issueLink,
lastSyncedAt: new Date().toISOString(),
});
}
const refreshedTitle =
typeof data.title === "string" ? data.title : existing.title ?? undefined;
const refreshedStatus = data.state?.name;
await ctx.entities.upsert({
entityType: ENTITY_TYPES.linearIssue,
scopeKind: "issue",
scopeId: existing.scopeId,
externalId: linearIssueId,
...(refreshedTitle !== undefined ? { title: refreshedTitle } : {}),
...(refreshedStatus !== undefined ? { status: refreshedStatus } : {}),
data: asRecord(data),
});
return;
}
// Create side: import only when import is enabled, the issue carries the
// configured label, and the Linear project maps to a Paperclip project.
if (!config.importLinearIssues) return;
const labelName = config.importLabelName ?? DEFAULT_CONFIG.importLabelName;
if (!labelName || !issueHasLabel(data, labelName)) {
activity({
level: "info",
source: "webhook",
message: `Linear ${data.identifier ?? linearIssueId} ignored — missing "${labelName}" label`,
});
return;
}
const linearProjectId = data.project?.id;
if (!linearProjectId) {
activity({
level: "warning",
source: "webhook",
message: `Linear ${data.identifier ?? linearIssueId} has the import label but no Linear project — skipping`,
});
return;
}
const paperclipProjectId = await findPaperclipProjectByLinearProject(ctx, linearProjectId);
if (!paperclipProjectId) {
activity({
level: "warning",
source: "webhook",
message: `Linear project ${data.project?.name ?? linearProjectId} is not linked to a Paperclip project`,
});
return;
}
const projectLink = await getProjectLink(ctx, paperclipProjectId);
if (!projectLink) return;
const title = data.title ?? `Linear ${data.identifier ?? linearIssueId}`;
const description = typeof data.description === "string" ? data.description : undefined;
try {
// The host derives originKind="plugin:paperclip.linear" from the installed plugin.
const created = await ctx.issues.create({
companyId: projectLink.companyId,
projectId: paperclipProjectId,
title,
...(description !== undefined ? { description } : {}),
originId: linearIssueId,
});
const link: LinearIssueLink = {
linearIssueId,
linearIdentifier: data.identifier ?? linearIssueId,
linearUrl: typeof data.url === "string" ? data.url : (payload.url ?? ""),
linearTeamId: data.team?.id ?? projectLink.linearTeamId,
linearProjectId,
pushedAt: new Date().toISOString(),
lastSyncedAt: new Date().toISOString(),
};
await setIssueLink(ctx, created.id, link);
const importedStatus = data.state?.name;
await ctx.entities.upsert({
entityType: ENTITY_TYPES.linearIssue,
scopeKind: "issue",
scopeId: created.id,
externalId: linearIssueId,
title,
...(importedStatus !== undefined ? { status: importedStatus } : {}),
data: asRecord(data),
});
activity({
level: "info",
source: "webhook",
message: `Imported Linear ${link.linearIdentifier} → Paperclip ${created.id}`,
});
} catch (error) {
ctx.logger.error("Failed to import Linear issue", {
linearIssueId,
error: summarizeError(error),
});
}
}
// ---------------------------------------------------------------------------
// Job handlers
// ---------------------------------------------------------------------------
async function runFullSync(_job: PluginJobContext): Promise<void> {
const ctx = requireCtx();
if (!currentClient) {
ctx.logger.warn("Skipping full sync — Linear not configured");
return;
}
ctx.logger.info("Starting Linear full sync");
const { teams, projects } = await refreshLinearCache(ctx);
for (const team of teams) {
await ctx.entities.upsert({
entityType: ENTITY_TYPES.linearTeam,
scopeKind: "instance",
externalId: team.id,
title: `${team.key} – ${team.name}`,
data: asRecord(team),
});
}
for (const project of projects) {
await ctx.entities.upsert({
entityType: ENTITY_TYPES.linearProject,
scopeKind: "instance",
externalId: project.id,
title: project.name,
data: asRecord(project),
});
}
await ensureImportLabel();
await ctx.state.set(
{ scopeKind: "instance", namespace: STATE_NAMESPACE, stateKey: STATE_KEYS.lastFullSyncAt },
new Date().toISOString(),
);
activity({
level: "info",
source: "job",
message: `Full sync — ${teams.length} teams, ${projects.length} projects`,
});
}
async function runIncrementalSync(_job: PluginJobContext): Promise<void> {
const ctx = requireCtx();
const config = requireConfig();
if (!currentClient) return;
const labelName = config.importLabelName ?? DEFAULT_CONFIG.importLabelName;
// Find every linked Paperclip project and pull labelled Linear issues for each
// mapped Linear project. ctx.entities listing is a workable proxy for "iterate
// over all project links" since we upsert one per linked project elsewhere.
// We keep a fallback wide-net query for unrelated linked issues that may have
// already been imported.
const cursor =
((await ctx.state.get({
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.syncCursor,
})) as string | null) ?? new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
const issues = await requireClient().issuesUpdatedSince(cursor, {
labelName,
limit: 100,
});
let newest = cursor;
for (const issue of issues) {
if (issue.updatedAt > newest) newest = issue.updatedAt;
if (!issueHasLabelOnObject(issue, labelName)) continue;
// Refresh existing link if we already track this Linear issue.
const linked = await ctx.entities.list({
entityType: ENTITY_TYPES.linearIssue,
externalId: issue.id,
limit: 1,
});
if (linked[0]?.scopeId) {
await ctx.entities.upsert({
entityType: ENTITY_TYPES.linearIssue,
scopeKind: "issue",
scopeId: linked[0].scopeId,
externalId: issue.id,
title: issue.title,
status: issue.state.name,
data: asRecord(issue),
});
continue;
}
// Otherwise import if it lives under a mapped Linear project.
if (!config.importLinearIssues) continue;
const linearProjectId = issue.project?.id;
if (!linearProjectId) continue;
const paperclipProjectId = await findPaperclipProjectByLinearProject(ctx, linearProjectId);
if (!paperclipProjectId) continue;
const projectLink = await getProjectLink(ctx, paperclipProjectId);
if (!projectLink) continue;
try {
const description = issue.description ?? undefined;
const created = await ctx.issues.create({
companyId: projectLink.companyId,
projectId: paperclipProjectId,
title: issue.title,
...(description !== undefined ? { description } : {}),
originId: issue.id,
});
const link: LinearIssueLink = {
linearIssueId: issue.id,
linearIdentifier: issue.identifier,
linearUrl: issue.url,
linearTeamId: issue.team.id,
linearProjectId,
pushedAt: new Date().toISOString(),
lastSyncedAt: new Date().toISOString(),
};
await setIssueLink(ctx, created.id, link);
await ctx.entities.upsert({
entityType: ENTITY_TYPES.linearIssue,
scopeKind: "issue",
scopeId: created.id,
externalId: issue.id,
title: issue.title,
status: issue.state.name,
data: asRecord(issue),
});
activity({
level: "info",
source: "job",
message: `Imported ${issue.identifier} via incremental sync`,
});
} catch (error) {
ctx.logger.error("Incremental import failed", {
issueId: issue.id,
error: summarizeError(error),
});
}
}
await ctx.state.set(
{ scopeKind: "instance", namespace: STATE_NAMESPACE, stateKey: STATE_KEYS.syncCursor },
newest,
);
await ctx.state.set(
{
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.lastIncrementalSyncAt,
},
new Date().toISOString(),
);
activity({
level: "info",
source: "job",
message: `Incremental sync — ${issues.length} labelled Linear updates`,
});
}
// ---------------------------------------------------------------------------
// UI data + action handlers
// ---------------------------------------------------------------------------
function registerDataHandlers(ctx: PluginContext): void {
ctx.data.register(DATA_KEYS.syncHealth, async () => {
const [lastFull, lastInc, lastHook] = await Promise.all([
ctx.state.get({
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.lastFullSyncAt,
}),
ctx.state.get({
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.lastIncrementalSyncAt,
}),
ctx.state.get({
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.lastWebhookAt,
}),
]);
const links = await ctx.entities.list({
entityType: ENTITY_TYPES.linearIssue,
scopeKind: "issue",
limit: 1000,
});
return {
configured: Boolean(currentClient),
lastFullSyncAt: lastFull as string | null,
lastIncrementalSyncAt: lastInc as string | null,
lastWebhookAt: lastHook as string | null,
linkedIssueCount: links.length,
importLabelName:
currentConfig?.importLabelName ?? DEFAULT_CONFIG.importLabelName,
};
});
ctx.data.register(DATA_KEYS.recentActivity, async () => ({
entries: recentActivity.slice(0, 25),
}));
ctx.data.register(DATA_KEYS.linearTeams, async () => {
const cached =
((await ctx.state.get({
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.cachedLinearTeams,
})) as LinearTeam[] | null) ?? [];
return { teams: cached };
});
ctx.data.register(DATA_KEYS.linearProjects, async () => {
const cached =
((await ctx.state.get({
scopeKind: "instance",
namespace: STATE_NAMESPACE,
stateKey: STATE_KEYS.cachedLinearProjects,
})) as LinearProject[] | null) ?? [];
return { projects: cached };
});
ctx.data.register(DATA_KEYS.paperclipCompanies, async () => {
const companies = await ctx.companies.list({ limit: 100 });
return { companies };
});