@mastra/github-signals 0.0.0

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/dist/index.cjs ADDED
@@ -0,0 +1,1135 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var promises = require('fs/promises');
5
+ var os = require('os');
6
+ var path = require('path');
7
+ var util = require('util');
8
+ var signals = require('@mastra/core/signals');
9
+ var tools = require('@mastra/core/tools');
10
+ var z = require('zod');
11
+
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
+
14
+ var z__default = /*#__PURE__*/_interopDefault(z);
15
+
16
+ // src/index.ts
17
+ var _execFileAsync;
18
+ async function execFileAsync(file, args, options) {
19
+ if (!_execFileAsync) {
20
+ const cp = await import('child_process');
21
+ _execFileAsync = util.promisify(cp.execFile);
22
+ }
23
+ return _execFileAsync(file, args, options);
24
+ }
25
+ var GITHUB_SUBSCRIBE_PR_TAG = "github-subscribe-pr";
26
+ var GITHUB_UNSUBSCRIBE_PR_TAG = "github-unsubscribe-pr";
27
+ var GITHUB_SYNC_STATUS_TAG = "github-sync-status";
28
+ var GITHUB_SIGNALS_METADATA_KEY = "githubSignals";
29
+ var createGithubTool = tools.createTool;
30
+ function isPlainObject(value) {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value);
32
+ }
33
+ function readString(value) {
34
+ return typeof value === "string" && value.length > 0 ? value : void 0;
35
+ }
36
+ function readNumber(value) {
37
+ if (typeof value === "number" && Number.isInteger(value) && value > 0) return value;
38
+ if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);
39
+ return void 0;
40
+ }
41
+ function stableJson(value) {
42
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
43
+ if (isPlainObject(value)) {
44
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
45
+ }
46
+ return JSON.stringify(value);
47
+ }
48
+ function snapshotHash(value) {
49
+ return crypto.createHash("sha256").update(stableJson(value)).digest("hex");
50
+ }
51
+ function resolveHomePath(path$1) {
52
+ return path$1.startsWith("~/") ? path.join(os.homedir(), path$1.slice(2)) : path$1;
53
+ }
54
+ async function getGitcrawlDbPath() {
55
+ if (process.env.GITCRAWL_DB_PATH) return resolveHomePath(process.env.GITCRAWL_DB_PATH);
56
+ const configPath = process.env.GITCRAWL_CONFIG_PATH ?? path.join(os.homedir(), ".config", "gitcrawl", "config.toml");
57
+ try {
58
+ const config = await promises.readFile(resolveHomePath(configPath), "utf8");
59
+ const match = /^\s*db_path\s*=\s*['\"]([^'\"]+)['\"]/m.exec(config);
60
+ if (match?.[1]) return resolveHomePath(match[1]);
61
+ } catch {
62
+ }
63
+ return path.join(os.homedir(), ".config", "gitcrawl", "gitcrawl.db");
64
+ }
65
+ async function queryGitcrawlDb(sql) {
66
+ const dbPath = await getGitcrawlDbPath();
67
+ const { stdout } = await execFileAsync("sqlite3", ["-json", dbPath, sql], { maxBuffer: 10 * 1024 * 1024 });
68
+ return JSON.parse(stdout || "[]");
69
+ }
70
+ function sqlString(value) {
71
+ return `'${value.replaceAll("'", "''")}'`;
72
+ }
73
+ function getSignalMetadata(message) {
74
+ if (message.role !== "signal") return void 0;
75
+ const signal = message.content.metadata?.signal;
76
+ return isPlainObject(signal) ? signal : void 0;
77
+ }
78
+ function getGithubMetadata(threadMetadata) {
79
+ const mastra = isPlainObject(threadMetadata?.mastra) ? threadMetadata.mastra : {};
80
+ const githubSignals = isPlainObject(mastra[GITHUB_SIGNALS_METADATA_KEY]) ? mastra[GITHUB_SIGNALS_METADATA_KEY] : {};
81
+ const rawSubscriptions = Array.isArray(githubSignals.subscriptions) ? githubSignals.subscriptions : [];
82
+ const subscriptions = [];
83
+ for (const rawSubscription of rawSubscriptions) {
84
+ if (!isPlainObject(rawSubscription)) continue;
85
+ const owner = readString(rawSubscription.owner);
86
+ const repo = readString(rawSubscription.repo);
87
+ const number = readNumber(rawSubscription.number);
88
+ const subscribedAt = readString(rawSubscription.subscribedAt);
89
+ const updatedAt = readString(rawSubscription.updatedAt);
90
+ const lastSubscribeSignalId = readString(rawSubscription.lastSubscribeSignalId);
91
+ if (!owner || !repo || !number || !subscribedAt || !updatedAt || !lastSubscribeSignalId) continue;
92
+ subscriptions.push({
93
+ owner,
94
+ repo,
95
+ number,
96
+ subscribedAt,
97
+ updatedAt,
98
+ lastSubscribeSignalId,
99
+ ...readString(rawSubscription.lastSyncAt) ? { lastSyncAt: readString(rawSubscription.lastSyncAt) } : {},
100
+ ...rawSubscription.lastSyncStatus === "success" || rawSubscription.lastSyncStatus === "error" || rawSubscription.lastSyncStatus === "skipped" ? { lastSyncStatus: rawSubscription.lastSyncStatus } : {},
101
+ ...readString(rawSubscription.lastSyncError) ? { lastSyncError: readString(rawSubscription.lastSyncError) } : {},
102
+ ...readString(rawSubscription.lastObservedGithubUpdatedAt) ? { lastObservedGithubUpdatedAt: readString(rawSubscription.lastObservedGithubUpdatedAt) } : {},
103
+ ...readString(rawSubscription.lastObservedContentHash) ? { lastObservedContentHash: readString(rawSubscription.lastObservedContentHash) } : {},
104
+ ...readString(rawSubscription.lastObservedThreadContentHash) ? { lastObservedThreadContentHash: readString(rawSubscription.lastObservedThreadContentHash) } : {},
105
+ ...readString(rawSubscription.lastObservedHeadSha) ? { lastObservedHeadSha: readString(rawSubscription.lastObservedHeadSha) } : {},
106
+ ...readString(rawSubscription.lastObservedState) ? { lastObservedState: readString(rawSubscription.lastObservedState) } : {},
107
+ ...readString(rawSubscription.lastObservedMergeableState) ? { lastObservedMergeableState: readString(rawSubscription.lastObservedMergeableState) } : {},
108
+ ...readString(rawSubscription.lastObservedCiState) ? { lastObservedCiState: readString(rawSubscription.lastObservedCiState) } : {},
109
+ ...readString(rawSubscription.lastObservedReviewStateHash) ? { lastObservedReviewStateHash: readString(rawSubscription.lastObservedReviewStateHash) } : {},
110
+ ...readString(rawSubscription.lastNotificationAt) ? { lastNotificationAt: readString(rawSubscription.lastNotificationAt) } : {},
111
+ ...readString(rawSubscription.lastNotificationKind) ? { lastNotificationKind: readString(rawSubscription.lastNotificationKind) } : {},
112
+ ...rawSubscription.lastNotificationPriority === "medium" || rawSubscription.lastNotificationPriority === "high" ? { lastNotificationPriority: rawSubscription.lastNotificationPriority } : {},
113
+ ...readString(rawSubscription.lastNotificationSummary) ? { lastNotificationSummary: readString(rawSubscription.lastNotificationSummary) } : {}
114
+ });
115
+ }
116
+ return {
117
+ subscriptions,
118
+ ...githubSignals.subscriptionHintShown === true ? { subscriptionHintShown: true } : {}
119
+ };
120
+ }
121
+ function setGithubMetadata(threadMetadata, githubSignals) {
122
+ const existing = threadMetadata ?? {};
123
+ const mastra = isPlainObject(existing.mastra) ? existing.mastra : {};
124
+ const existingGithubSignals = isPlainObject(mastra[GITHUB_SIGNALS_METADATA_KEY]) ? mastra[GITHUB_SIGNALS_METADATA_KEY] : {};
125
+ return {
126
+ ...existing,
127
+ mastra: {
128
+ ...mastra,
129
+ [GITHUB_SIGNALS_METADATA_KEY]: {
130
+ ...existingGithubSignals,
131
+ ...githubSignals
132
+ }
133
+ }
134
+ };
135
+ }
136
+ function getFailingChecks(snapshot) {
137
+ return (snapshot.checks ?? []).filter((check) => check.conclusion === "failure" || check.conclusion === "timed_out");
138
+ }
139
+ function getPendingChecks(snapshot) {
140
+ return (snapshot.checks ?? []).filter((check) => check.status && check.status !== "completed");
141
+ }
142
+ function getPrLabel(subscription, snapshot) {
143
+ const pr = `${subscription.owner}/${subscription.repo}#${subscription.number}`;
144
+ return snapshot?.title ? `${pr}: ${snapshot.title}` : pr;
145
+ }
146
+ function getMergedNotificationSummary(label) {
147
+ return `${label} was merged. This thread has been automatically unsubscribed from this PR. Resubscribe if you still need updates.`;
148
+ }
149
+ function getCheckUpdatedTime(check) {
150
+ const value = check.updatedAt ? Date.parse(check.updatedAt) : Number.NaN;
151
+ return Number.isFinite(value) ? value : 0;
152
+ }
153
+ function getCheckKey(check) {
154
+ return `${check.name || "check"}:${check.detailsUrl || check.workflowName || ""}`;
155
+ }
156
+ function normalizeGithubChecksForSnapshot(input) {
157
+ const latestCheckUpdatedAt = input.checkRows.reduce(
158
+ (latest, check) => Math.max(latest, getCheckUpdatedTime(check)),
159
+ 0
160
+ );
161
+ const rows = [
162
+ ...input.checkRows,
163
+ ...input.workflowRows.filter(
164
+ (workflow) => input.checkRows.length === 0 || getCheckUpdatedTime(workflow) >= latestCheckUpdatedAt
165
+ )
166
+ ];
167
+ const byKey = /* @__PURE__ */ new Map();
168
+ for (const row of rows) {
169
+ const key = getCheckKey(row);
170
+ const existing = byKey.get(key);
171
+ if (!existing) {
172
+ byKey.set(key, row);
173
+ continue;
174
+ }
175
+ const rowTime = getCheckUpdatedTime(row);
176
+ const existingTime = getCheckUpdatedTime(existing);
177
+ if (rowTime > existingTime || rowTime === existingTime && existing.source === "workflow" && row.source === "check") {
178
+ byKey.set(key, row);
179
+ }
180
+ }
181
+ return [...byKey.values()].map(({ source: _source, ...check }) => check).sort((a, b) => `${a.name}:${a.detailsUrl ?? ""}`.localeCompare(`${b.name}:${b.detailsUrl ?? ""}`));
182
+ }
183
+ function isBotOnlyActivity(snapshot) {
184
+ return snapshot.latestCommentIsBot === true && (!snapshot.ciState || snapshot.ciState === "unknown");
185
+ }
186
+ function stringifyEvidence(value) {
187
+ if (typeof value === "string") return value;
188
+ try {
189
+ return JSON.stringify(value);
190
+ } catch {
191
+ return "";
192
+ }
193
+ }
194
+ function detectPrWorkEvidence(input) {
195
+ const evidence = [
196
+ input.text ?? "",
197
+ ...(input.toolCalls ?? []).map((toolCall) => `${toolCall.toolName} ${stringifyEvidence(toolCall.args)}`)
198
+ ].join("\n");
199
+ if (!evidence.trim()) return void 0;
200
+ const url = /github\.com\/([^\s/#]+)\/([^\s/#]+)\/pull\/(\d+)/i.exec(evidence);
201
+ if (url?.[1] && url[2] && url[3]) return { owner: url[1], repo: url[2], number: Number(url[3]) };
202
+ const repoRef = /\b([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(\d+)\b/.exec(evidence);
203
+ if (repoRef?.[1] && repoRef[2] && repoRef[3])
204
+ return { owner: repoRef[1], repo: repoRef[2], number: Number(repoRef[3]) };
205
+ const ghCommand = /\bgh\s+(?:pr\s+(?:view|checks|status|comment|diff|checkout)|run\s+(?:rerun|view))\b/i.test(
206
+ evidence
207
+ );
208
+ if (!ghCommand) return void 0;
209
+ const numberMatch = /(?:^|\s)#?(\d{2,})(?:\s|$)/.exec(evidence);
210
+ return numberMatch?.[1] ? { number: Number(numberMatch[1]) } : void 0;
211
+ }
212
+ function classifyGithubActivityNotification(input) {
213
+ const pr = `${input.subscription.owner}/${input.subscription.repo}#${input.subscription.number}`;
214
+ const label = getPrLabel(input.subscription, input.snapshot);
215
+ if (input.snapshot.state && input.subscription.lastObservedState !== input.snapshot.state) {
216
+ if (input.snapshot.state === "merged")
217
+ return {
218
+ kind: "pull-request-merged",
219
+ priority: "high",
220
+ summary: getMergedNotificationSummary(label)
221
+ };
222
+ if (input.snapshot.state === "closed")
223
+ return { kind: "pull-request-closed", priority: "high", summary: `${label} was closed` };
224
+ if (input.subscription.lastObservedState && input.snapshot.state === "open")
225
+ return { kind: "pull-request-reopened", priority: "medium", summary: `${label} was reopened` };
226
+ }
227
+ const failingChecks = getFailingChecks(input.snapshot);
228
+ if (input.snapshot.ciState === "failure" && input.subscription.lastObservedCiState !== "failure") {
229
+ const names = failingChecks.slice(0, 3).map((check) => check.name).join(", ");
230
+ return {
231
+ kind: "pull-request-ci-failure",
232
+ priority: "high",
233
+ summary: `${pr} has failing CI${names ? `: ${names}` : ""}`
234
+ };
235
+ }
236
+ if (input.snapshot.mergeableState === "dirty" && input.subscription.lastObservedMergeableState !== "dirty") {
237
+ return {
238
+ kind: "pull-request-conflict",
239
+ priority: "high",
240
+ summary: `${pr} has merge conflicts${input.snapshot.title ? `: ${input.snapshot.title}` : ""}`
241
+ };
242
+ }
243
+ if (input.snapshot.mergeableState && input.subscription.lastObservedMergeableState === "dirty" && input.snapshot.mergeableState !== "dirty") {
244
+ return {
245
+ kind: "pull-request-conflict-resolved",
246
+ priority: "medium",
247
+ summary: `${pr} merge conflicts were resolved`
248
+ };
249
+ }
250
+ if (input.snapshot.mergeableState === "dirty") return void 0;
251
+ if (input.snapshot.ciState === "success" && input.subscription.lastObservedCiState && input.subscription.lastObservedCiState !== "success") {
252
+ return { kind: "pull-request-ci-recovered", priority: "medium", summary: `${pr} CI recovered` };
253
+ }
254
+ if (input.snapshot.reviewStateHash && input.subscription.lastObservedReviewStateHash && input.snapshot.reviewStateHash !== input.subscription.lastObservedReviewStateHash && (input.snapshot.unresolvedReviewThreads ?? 0) > 0) {
255
+ return {
256
+ kind: "pull-request-review-activity",
257
+ priority: "medium",
258
+ summary: `${pr} has ${input.snapshot.unresolvedReviewThreads} unresolved review thread${input.snapshot.unresolvedReviewThreads === 1 ? "" : "s"}`
259
+ };
260
+ }
261
+ const pendingChecks = getPendingChecks(input.snapshot);
262
+ if (input.snapshot.ciState === "pending" && input.subscription.lastObservedCiState !== "pending" && pendingChecks.length > 0) {
263
+ const names = pendingChecks.slice(0, 3).map((check) => check.name).join(", ");
264
+ return {
265
+ kind: "pull-request-ci-pending",
266
+ priority: "medium",
267
+ summary: `${pr} has CI still running${names ? `: ${names}` : ""}`
268
+ };
269
+ }
270
+ if (input.snapshot.ciState === "pending" && input.subscription.lastObservedCiState === "pending") return void 0;
271
+ if (isBotOnlyActivity(input.snapshot)) return void 0;
272
+ return {
273
+ kind: "pull-request-activity",
274
+ priority: "medium",
275
+ summary: `${pr} has new activity${input.snapshot.title ? `: ${input.snapshot.title}` : ""}`
276
+ };
277
+ }
278
+ function classifyGithubBaselineNotification(input) {
279
+ const pr = `${input.subscription.owner}/${input.subscription.repo}#${input.subscription.number}`;
280
+ const failingChecks = getFailingChecks(input.snapshot);
281
+ const reviewCount = input.snapshot.unresolvedReviewThreads ?? 0;
282
+ const high = input.snapshot.ciState === "failure" || input.snapshot.mergeableState === "dirty";
283
+ const details = [
284
+ input.snapshot.state ? `state: ${input.snapshot.state}` : void 0,
285
+ input.snapshot.ciState && input.snapshot.ciState !== "unknown" ? `CI: ${input.snapshot.ciState}` : void 0,
286
+ input.snapshot.mergeableState ? `mergeability: ${input.snapshot.mergeableState}` : void 0,
287
+ reviewCount > 0 ? `${reviewCount} unresolved review thread${reviewCount === 1 ? "" : "s"}` : void 0,
288
+ failingChecks.length > 0 ? `failing: ${failingChecks.slice(0, 3).map((check) => check.name).join(", ")}` : void 0
289
+ ].filter(Boolean);
290
+ return {
291
+ kind: "pull-request-baseline",
292
+ priority: high ? "high" : "medium",
293
+ summary: `${pr} subscribed${input.snapshot.title ? `: ${input.snapshot.title}` : ""}${details.length ? ` (${details.join("; ")})` : ""}`
294
+ };
295
+ }
296
+ function applySnapshotCursor(subscription, snapshot) {
297
+ if (snapshot.githubUpdatedAt) subscription.lastObservedGithubUpdatedAt = snapshot.githubUpdatedAt;
298
+ if (snapshot.contentHash) subscription.lastObservedContentHash = snapshot.contentHash;
299
+ if (snapshot.threadContentHash) subscription.lastObservedThreadContentHash = snapshot.threadContentHash;
300
+ if (snapshot.headSha) subscription.lastObservedHeadSha = snapshot.headSha;
301
+ if (snapshot.state) subscription.lastObservedState = snapshot.state;
302
+ if (snapshot.mergeableState) subscription.lastObservedMergeableState = snapshot.mergeableState;
303
+ if (snapshot.ciState) subscription.lastObservedCiState = snapshot.ciState;
304
+ if (snapshot.reviewStateHash) subscription.lastObservedReviewStateHash = snapshot.reviewStateHash;
305
+ }
306
+ function parseGitHubRemoteUrl(remoteUrl) {
307
+ const trimmed = remoteUrl.trim().replace(/\.git$/, "");
308
+ const httpsMatch = /^https:\/\/github\.com\/([^/]+)\/([^/]+)$/.exec(trimmed);
309
+ if (httpsMatch?.[1] && httpsMatch[2]) return { owner: httpsMatch[1], repo: httpsMatch[2] };
310
+ const sshMatch = /^git@github\.com:([^/]+)\/([^/]+)$/.exec(trimmed);
311
+ if (sshMatch?.[1] && sshMatch[2]) return { owner: sshMatch[1], repo: sshMatch[2] };
312
+ return void 0;
313
+ }
314
+ var GitRemoteRepositoryResolver = class {
315
+ async resolveRepository(input) {
316
+ try {
317
+ const { stdout } = await execFileAsync("git", ["remote", "get-url", "origin"], {
318
+ cwd: input.cwd,
319
+ signal: input.abortSignal
320
+ });
321
+ return parseGitHubRemoteUrl(stdout);
322
+ } catch {
323
+ return void 0;
324
+ }
325
+ }
326
+ };
327
+ var GitcrawlSyncClient = class {
328
+ #command;
329
+ constructor(options = {}) {
330
+ this.#command = options.command ?? "gitcrawl";
331
+ }
332
+ async syncPullRequest(input) {
333
+ try {
334
+ const args = [
335
+ "sync",
336
+ `${input.owner}/${input.repo}`,
337
+ "--numbers",
338
+ String(input.number),
339
+ ...input.includeComments === false ? [] : ["--include-comments"],
340
+ "--with",
341
+ "pr-details",
342
+ "--json"
343
+ ];
344
+ const { stdout, stderr } = await execFileAsync(this.#command, args, {
345
+ cwd: input.cwd,
346
+ signal: input.abortSignal,
347
+ maxBuffer: 10 * 1024 * 1024
348
+ });
349
+ return { ok: true, stdout, stderr };
350
+ } catch (error) {
351
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
352
+ }
353
+ }
354
+ async getPullRequestSnapshot(input) {
355
+ try {
356
+ const { stdout } = await execFileAsync(
357
+ this.#command,
358
+ ["threads", `${input.owner}/${input.repo}`, "--numbers", String(input.number), "--json"],
359
+ {
360
+ cwd: input.cwd,
361
+ signal: input.abortSignal,
362
+ maxBuffer: 10 * 1024 * 1024
363
+ }
364
+ );
365
+ const parsed = JSON.parse(stdout);
366
+ const thread = parsed.threads?.find((item) => readNumber(item.number) === input.number);
367
+ if (!thread) return void 0;
368
+ const owner = sqlString(input.owner);
369
+ const repo = sqlString(input.repo);
370
+ const number = input.number;
371
+ const [threadDetails] = await queryGitcrawlDb(`select t.state, t.closed_at_gh, t.merged_at_gh
372
+ from threads t
373
+ join repositories r on r.id=t.repo_id
374
+ where r.owner=${owner} and r.name=${repo} and t.number=${number}
375
+ limit 1`);
376
+ const [details] = await queryGitcrawlDb(`select d.head_sha, d.head_ref, d.mergeable_state,
377
+ json_extract(d.raw_json, '$.merged_at') as merged_at
378
+ from pull_request_details d
379
+ join threads t on t.id=d.thread_id
380
+ join repositories r on r.id=t.repo_id
381
+ where r.owner=${owner} and r.name=${repo} and t.number=${number}
382
+ limit 1`);
383
+ const headSha = readString(details?.head_sha);
384
+ const checkRows = await queryGitcrawlDb(`select c.name, c.status, c.conclusion, c.workflow_name, c.details_url,
385
+ coalesce(c.completed_at, c.started_at, c.fetched_at) as updated_at
386
+ from pull_request_checks c
387
+ join threads t on t.id=c.thread_id
388
+ join repositories r on r.id=t.repo_id
389
+ where r.owner=${owner} and r.name=${repo} and t.number=${number}${headSha ? ` and json_extract(c.raw_json, '$.head_sha')=${sqlString(headSha)}` : ""}`);
390
+ const workflowRows = details?.head_sha ? await queryGitcrawlDb(`select workflow_name, status, conclusion, html_url, updated_at_gh
391
+ from github_workflow_runs w
392
+ join repositories r on r.id=w.repo_id
393
+ where r.owner=${owner} and r.name=${repo} and w.head_sha=${sqlString(details.head_sha)}`) : [];
394
+ const [reviewState] = await queryGitcrawlDb(`select count(*) as unresolved_count,
395
+ max(coalesce(first_comment_updated_at, first_comment_created_at, fetched_at)) as latest_review_thread_at
396
+ from pull_request_review_threads rt
397
+ join threads t on t.id=rt.thread_id
398
+ join repositories r on r.id=t.repo_id
399
+ where r.owner=${owner} and r.name=${repo} and t.number=${number} and rt.is_resolved=0`);
400
+ const [latestComment] = await queryGitcrawlDb(`select c.author_login, c.author_type, c.is_bot
401
+ from comments c
402
+ join threads t on t.id=c.thread_id
403
+ join repositories r on r.id=t.repo_id
404
+ where r.owner=${owner} and r.name=${repo} and t.number=${number}
405
+ order by coalesce(c.updated_at_gh, c.created_at_gh) desc
406
+ limit 1`);
407
+ const checks = normalizeGithubChecksForSnapshot({
408
+ checkRows: checkRows.map((row) => ({
409
+ source: "check",
410
+ name: readString(row.name) ?? "check",
411
+ status: readString(row.status),
412
+ conclusion: readString(row.conclusion),
413
+ workflowName: readString(row.workflow_name),
414
+ detailsUrl: readString(row.details_url),
415
+ updatedAt: readString(row.updated_at)
416
+ })),
417
+ workflowRows: workflowRows.map((row) => ({
418
+ source: "workflow",
419
+ name: readString(row.workflow_name) ?? "workflow",
420
+ status: readString(row.status),
421
+ conclusion: readString(row.conclusion),
422
+ workflowName: readString(row.workflow_name),
423
+ detailsUrl: readString(row.html_url),
424
+ updatedAt: readString(row.updated_at_gh)
425
+ }))
426
+ });
427
+ const ciState = checks.some((check) => check.conclusion === "failure" || check.conclusion === "timed_out") ? "failure" : checks.some((check) => check.status && check.status !== "completed") ? "pending" : checks.length > 0 ? "success" : "unknown";
428
+ const threadContentHash = readString(thread.content_hash);
429
+ const unresolvedReviewThreads = Number(reviewState?.unresolved_count ?? 0);
430
+ const reviewStateHash = snapshotHash({
431
+ unresolvedReviewThreads,
432
+ latestReviewThreadAt: reviewState?.latest_review_thread_at
433
+ });
434
+ const contentHash = snapshotHash({
435
+ threadContentHash,
436
+ state: thread.state,
437
+ headSha: details?.head_sha,
438
+ mergeableState: details?.mergeable_state,
439
+ ciState,
440
+ reviewStateHash,
441
+ checks: checks.map((check) => ({
442
+ name: check.name,
443
+ status: check.status,
444
+ conclusion: check.conclusion,
445
+ detailsUrl: check.detailsUrl,
446
+ updatedAt: check.updatedAt
447
+ }))
448
+ });
449
+ return {
450
+ title: readString(thread.title),
451
+ state: readString(details?.merged_at) || readString(threadDetails?.merged_at_gh) ? "merged" : readString(threadDetails?.state) ?? readString(thread.state),
452
+ htmlUrl: readString(thread.html_url),
453
+ githubUpdatedAt: readString(thread.updated_at_gh),
454
+ closedAt: readString(threadDetails?.closed_at_gh),
455
+ mergedAt: readString(details?.merged_at) ?? readString(threadDetails?.merged_at_gh),
456
+ threadContentHash,
457
+ contentHash,
458
+ headSha: readString(details?.head_sha),
459
+ headRef: readString(details?.head_ref),
460
+ mergeableState: readString(details?.mergeable_state),
461
+ checks,
462
+ ciState,
463
+ unresolvedReviewThreads,
464
+ reviewStateHash,
465
+ latestReviewThreadAt: readString(reviewState?.latest_review_thread_at),
466
+ latestCommentAuthor: readString(latestComment?.author_login),
467
+ latestCommentAuthorType: readString(latestComment?.author_type),
468
+ latestCommentIsBot: latestComment?.is_bot === 1
469
+ };
470
+ } catch {
471
+ return void 0;
472
+ }
473
+ }
474
+ };
475
+ var GithubSignals = class extends signals.SignalProvider {
476
+ id = "github-signals";
477
+ name = "GitHub Signals";
478
+ #ghMastra;
479
+ static signals = {
480
+ subscribeToPR(input) {
481
+ const normalized = typeof input === "number" ? { number: input } : input;
482
+ return {
483
+ type: "reactive",
484
+ tagName: GITHUB_SUBSCRIBE_PR_TAG,
485
+ contents: `Subscribe to GitHub PR #${normalized.number}`,
486
+ attributes: {
487
+ ...normalized.owner ? { owner: normalized.owner } : {},
488
+ ...normalized.repo ? { repo: normalized.repo } : {},
489
+ number: normalized.number
490
+ },
491
+ metadata: {
492
+ github: {
493
+ action: "subscribeToPR",
494
+ ...normalized
495
+ }
496
+ }
497
+ };
498
+ },
499
+ unsubscribeFromPR(input) {
500
+ const normalized = typeof input === "number" ? { number: input } : input;
501
+ return {
502
+ type: "reactive",
503
+ tagName: GITHUB_UNSUBSCRIBE_PR_TAG,
504
+ contents: `Unsubscribe from GitHub PR #${normalized.number}`,
505
+ attributes: {
506
+ ...normalized.owner ? { owner: normalized.owner } : {},
507
+ ...normalized.repo ? { repo: normalized.repo } : {},
508
+ number: normalized.number
509
+ },
510
+ metadata: {
511
+ github: {
512
+ action: "unsubscribeFromPR",
513
+ ...normalized
514
+ }
515
+ }
516
+ };
517
+ }
518
+ };
519
+ #options;
520
+ #syncClient;
521
+ #repositoryResolver;
522
+ #polling = /* @__PURE__ */ new Map();
523
+ #agent;
524
+ #agentOptions = {};
525
+ #subscriptionsChangedHandler;
526
+ constructor(options = {}) {
527
+ super();
528
+ this.#options = options;
529
+ this.#syncClient = options.syncClient ?? new GitcrawlSyncClient({ command: options.gitcrawlCommand });
530
+ this.#repositoryResolver = options.repositoryResolver ?? new GitRemoteRepositoryResolver();
531
+ if (options.getNotificationStreamOptions) {
532
+ this.#agentOptions = { getNotificationStreamOptions: options.getNotificationStreamOptions };
533
+ }
534
+ }
535
+ /**
536
+ * @deprecated Use `Agent({ signals: [githubSignals] })` instead.
537
+ * Kept for backward compatibility.
538
+ */
539
+ addAgent(agent, options = {}) {
540
+ this.#agent = agent;
541
+ this.#agentOptions = options;
542
+ }
543
+ /**
544
+ * Called by the Agent constructor when this provider is passed via `signals: [...]`.
545
+ * Sets the bidirectional link so the provider can send signals back to the agent.
546
+ */
547
+ connect(agent) {
548
+ super.connect(agent);
549
+ this.#agent = agent;
550
+ }
551
+ getInputProcessors() {
552
+ return [this];
553
+ }
554
+ getOutputProcessors() {
555
+ return [this];
556
+ }
557
+ onSubscriptionsChanged(handler) {
558
+ this.#subscriptionsChangedHandler = handler;
559
+ }
560
+ __registerMastra(mastra) {
561
+ super.__registerMastra(mastra);
562
+ this.#ghMastra = mastra;
563
+ }
564
+ async syncThreadNow(input) {
565
+ return this.#pollThread(input, { includeComments: true });
566
+ }
567
+ async subscribeThreadToPR(input) {
568
+ const pr = typeof input.pr === "number" ? { number: input.pr } : input.pr;
569
+ return this.#subscribe({
570
+ id: `github-command-subscribe-${crypto.randomUUID()}`,
571
+ ...pr,
572
+ threadId: input.threadId,
573
+ resourceId: input.resourceId
574
+ });
575
+ }
576
+ async unsubscribeThreadFromPR(input) {
577
+ const pr = typeof input.pr === "number" ? { number: input.pr } : input.pr;
578
+ return this.#unsubscribe({
579
+ id: `github-command-unsubscribe-${crypto.randomUUID()}`,
580
+ ...pr,
581
+ threadId: input.threadId,
582
+ resourceId: input.resourceId
583
+ });
584
+ }
585
+ async startPollingForThread(input, options = {}) {
586
+ const subscriptions = await this.#getThreadSubscriptions(input);
587
+ if (subscriptions.length === 0) {
588
+ this.stopPollingForThread(input);
589
+ return false;
590
+ }
591
+ const key = this.#pollingKey(input);
592
+ for (const [pollingKey, state] of this.#polling.entries()) {
593
+ if (pollingKey === key) continue;
594
+ clearInterval(state.timer);
595
+ this.#polling.delete(pollingKey);
596
+ }
597
+ if (this.#polling.has(key)) return true;
598
+ let scheduledPollCount = options.pollImmediately ? 1 : 0;
599
+ const runPoll = (pollOptions = {}) => {
600
+ void this.#pollThread(input, pollOptions).catch((error) => {
601
+ console.warn("GitHub PR polling failed:", error);
602
+ });
603
+ };
604
+ const timer = setInterval(() => {
605
+ scheduledPollCount += 1;
606
+ runPoll({ includeComments: scheduledPollCount % 2 === 1 });
607
+ }, this.#options.pollIntervalMs ?? 3e5);
608
+ if (options.pollImmediately) runPoll({ includeComments: true });
609
+ timer.unref?.();
610
+ this.#polling.set(key, { ...input, timer, running: false });
611
+ return true;
612
+ }
613
+ stopPollingForThread(input) {
614
+ const key = this.#pollingKey(input);
615
+ const state = this.#polling.get(key);
616
+ if (!state) return;
617
+ clearInterval(state.timer);
618
+ this.#polling.delete(key);
619
+ }
620
+ isPollingThread(input) {
621
+ return this.#polling.has(this.#pollingKey(input));
622
+ }
623
+ getPollIntervalMs() {
624
+ return this.#options.pollIntervalMs ?? 3e5;
625
+ }
626
+ stopAllPolling() {
627
+ for (const state of this.#polling.values()) clearInterval(state.timer);
628
+ this.#polling.clear();
629
+ }
630
+ async pollThreadNow(input) {
631
+ return this.#pollThread(input, { includeComments: true });
632
+ }
633
+ async processInputStep(args) {
634
+ const tools = this.#createTools(args);
635
+ if (args.stepNumber !== 0) return { tools };
636
+ const signal = this.#findLatestGithubSignal(args.messages);
637
+ if (!signal) return { tools };
638
+ const threadContext = this.#getThreadContext(args);
639
+ if (signal.tagName === GITHUB_UNSUBSCRIBE_PR_TAG) {
640
+ const result2 = await this.#unsubscribe({ ...signal, ...threadContext, abortSignal: args.abortSignal });
641
+ await this.#sendStatus(args, result2, {
642
+ status: result2.removed ? "unsubscribed" : "not_subscribed",
643
+ action: "unsubscribeFromPR",
644
+ message: result2.removed ? `Unsubscribed from ${result2.owner}/${result2.repo}#${result2.number}.` : `No GitHub subscription found for ${result2.owner}/${result2.repo}#${result2.number}.`
645
+ });
646
+ return { tools };
647
+ }
648
+ const result = await this.#subscribe({ ...signal, ...threadContext, abortSignal: args.abortSignal });
649
+ if (result.alreadyProcessed) return { tools };
650
+ await this.#sendStatus(args, result, {
651
+ status: result.syncResult?.ok === false ? "sync_error" : "subscribed",
652
+ action: "subscribeToPR",
653
+ message: result.syncResult?.ok === false ? `Subscribed to ${result.owner}/${result.repo}#${result.number}, but gitcrawl sync failed: ${result.syncResult.error}` : `Subscribed to ${result.owner}/${result.repo}#${result.number}.`
654
+ });
655
+ return { tools };
656
+ }
657
+ async processOutputStep(args) {
658
+ const evidence = detectPrWorkEvidence({ text: args.text, toolCalls: args.toolCalls });
659
+ if (!evidence) return args.messages;
660
+ const threadContext = this.#getThreadContext(args);
661
+ if (!threadContext.threadId || !threadContext.resourceId) return args.messages;
662
+ const { threadStore, loadedThread } = await this.#loadThread(threadContext);
663
+ const githubMetadata = getGithubMetadata(loadedThread.metadata);
664
+ if (githubMetadata.subscriptionHintShown || githubMetadata.subscriptions.length > 0) return args.messages;
665
+ let repository;
666
+ try {
667
+ repository = await this.#resolveRepository({
668
+ id: "github-subscription-hint",
669
+ owner: evidence.owner,
670
+ repo: evidence.repo,
671
+ number: evidence.number
672
+ });
673
+ } catch {
674
+ return args.messages;
675
+ }
676
+ await threadStore.saveThread({
677
+ thread: {
678
+ ...loadedThread,
679
+ id: threadContext.threadId,
680
+ resourceId: threadContext.resourceId,
681
+ createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
682
+ updatedAt: /* @__PURE__ */ new Date(),
683
+ metadata: setGithubMetadata(loadedThread.metadata, { ...githubMetadata, subscriptionHintShown: true })
684
+ }
685
+ });
686
+ await args.sendSignal?.({
687
+ type: "reactive",
688
+ tagName: "system-reminder",
689
+ contents: `Looks like you're working with ${repository.owner}/${repository.repo}#${evidence.number}. Use /github subscribe ${evidence.number} or the github_subscribe_pr tool to follow updates.`,
690
+ attributes: { type: "github-subscription-hint" },
691
+ metadata: {
692
+ github: {
693
+ action: "subscriptionHint",
694
+ owner: repository.owner,
695
+ repo: repository.repo,
696
+ number: evidence.number
697
+ }
698
+ }
699
+ });
700
+ return args.messages;
701
+ }
702
+ async #resolveThreadStore() {
703
+ if (this.#options.threadStore) return this.#options.threadStore;
704
+ const storage = this.#ghMastra?.getStorage?.();
705
+ const memoryStore = storage?.getStore ? await storage.getStore("memory") : void 0;
706
+ return memoryStore;
707
+ }
708
+ #getThreadContext(args) {
709
+ const memoryContext = args.requestContext?.get("MastraMemory");
710
+ return { threadId: memoryContext?.thread?.id, resourceId: memoryContext?.resourceId };
711
+ }
712
+ #createTools(args) {
713
+ const threadContext = this.#getThreadContext(args);
714
+ return {
715
+ ...args.tools,
716
+ github_subscribe_pr: createGithubTool({
717
+ id: "github_subscribe_pr",
718
+ description: "Subscribe this thread to a GitHub pull request. Syncs only the requested PR with gitcrawl and stores the subscription on the thread.",
719
+ inputSchema: z__default.default.object({
720
+ number: z__default.default.number().int().positive(),
721
+ owner: z__default.default.string().optional(),
722
+ repo: z__default.default.string().optional()
723
+ }),
724
+ execute: async (input) => {
725
+ const result = await this.#subscribe({
726
+ id: `github-tool-subscribe-${crypto.randomUUID()}`,
727
+ owner: input.owner,
728
+ repo: input.repo,
729
+ number: input.number,
730
+ threadId: threadContext.threadId,
731
+ resourceId: threadContext.resourceId
732
+ });
733
+ return {
734
+ subscribed: true,
735
+ owner: result.owner,
736
+ repo: result.repo,
737
+ number: result.number,
738
+ syncStatus: result.syncResult?.ok === false ? "error" : result.syncResult ? "success" : void 0,
739
+ message: result.syncResult?.ok === false ? `Subscribed to ${result.owner}/${result.repo}#${result.number}, but gitcrawl sync failed: ${result.syncResult.error}` : `Subscribed to ${result.owner}/${result.repo}#${result.number}.`
740
+ };
741
+ }
742
+ }),
743
+ github_unsubscribe_pr: createGithubTool({
744
+ id: "github_unsubscribe_pr",
745
+ description: "Unsubscribe this thread from a GitHub pull request.",
746
+ inputSchema: z__default.default.object({
747
+ number: z__default.default.number().int().positive(),
748
+ owner: z__default.default.string().optional(),
749
+ repo: z__default.default.string().optional()
750
+ }),
751
+ execute: async (input) => {
752
+ const result = await this.#unsubscribe({
753
+ id: `github-tool-unsubscribe-${crypto.randomUUID()}`,
754
+ owner: input.owner,
755
+ repo: input.repo,
756
+ number: input.number,
757
+ threadId: threadContext.threadId,
758
+ resourceId: threadContext.resourceId
759
+ });
760
+ return {
761
+ unsubscribed: result.removed ?? false,
762
+ owner: result.owner,
763
+ repo: result.repo,
764
+ number: result.number,
765
+ remainingSubscriptions: result.remainingSubscriptions,
766
+ message: result.removed ? `Unsubscribed from ${result.owner}/${result.repo}#${result.number}.` : `No GitHub subscription found for ${result.owner}/${result.repo}#${result.number}.`
767
+ };
768
+ }
769
+ })
770
+ };
771
+ }
772
+ async #resolveRepository(input) {
773
+ const resolvedRepository = input.owner && input.repo ? { owner: input.owner, repo: input.repo } : this.#options.owner && this.#options.repo ? { owner: this.#options.owner, repo: this.#options.repo } : await this.#repositoryResolver.resolveRepository({
774
+ cwd: this.#options.cwd,
775
+ abortSignal: input.abortSignal
776
+ });
777
+ if (!resolvedRepository?.owner || !resolvedRepository.repo) {
778
+ throw new Error(
779
+ "GitHub PR subscription requires owner and repo. Run inside a GitHub repo or pass owner and repo."
780
+ );
781
+ }
782
+ return resolvedRepository;
783
+ }
784
+ async #loadThread(input) {
785
+ const threadStore = await this.#resolveThreadStore();
786
+ if (!threadStore) throw new Error("GitHub PR subscription requires memory-backed thread storage.");
787
+ if (!input.threadId || !input.resourceId)
788
+ throw new Error("GitHub PR subscription requires threadId and resourceId.");
789
+ const loadedThread = await threadStore.getThreadById({ threadId: input.threadId, resourceId: input.resourceId }) ?? void 0;
790
+ if (!loadedThread) throw new Error(`Could not load thread ${input.threadId}.`);
791
+ return { threadStore, loadedThread };
792
+ }
793
+ #pollingKey(input) {
794
+ return `${input.resourceId}:${input.threadId}`;
795
+ }
796
+ #getNotificationAgent(_input) {
797
+ if (this.#agent) return this.#agent;
798
+ const agentId = _input?.agentId ?? this.#options.agentId;
799
+ return agentId ? this.#ghMastra?.getAgentById?.(agentId) : void 0;
800
+ }
801
+ async #getThreadSubscriptions(input) {
802
+ const { loadedThread } = await this.#loadThread(input);
803
+ return getGithubMetadata(loadedThread.metadata).subscriptions;
804
+ }
805
+ #notifySubscriptionsChanged(input) {
806
+ this.#subscriptionsChangedHandler?.(input);
807
+ }
808
+ async #pollThread(input, options = {}) {
809
+ const key = this.#pollingKey(input);
810
+ const state = this.#polling.get(key);
811
+ if (state?.running) {
812
+ return 0;
813
+ }
814
+ if (state) state.running = true;
815
+ try {
816
+ const { threadStore, loadedThread } = await this.#loadThread(input);
817
+ const githubMetadata = getGithubMetadata(loadedThread.metadata);
818
+ if (githubMetadata.subscriptions.length === 0) {
819
+ this.stopPollingForThread(input);
820
+ return 0;
821
+ }
822
+ const now = (/* @__PURE__ */ new Date()).toISOString();
823
+ const subscriptions = [];
824
+ for (const subscription of githubMetadata.subscriptions) {
825
+ const syncInput = {
826
+ owner: subscription.owner,
827
+ repo: subscription.repo,
828
+ number: subscription.number,
829
+ cwd: this.#options.cwd,
830
+ includeComments: options.includeComments
831
+ };
832
+ const syncResult = await this.#syncClient.syncPullRequest(syncInput);
833
+ const snapshot = syncResult.ok ? await this.#syncClient.getPullRequestSnapshot?.(syncInput) : void 0;
834
+ const nextSubscription = {
835
+ ...subscription,
836
+ updatedAt: now,
837
+ lastSyncAt: now,
838
+ lastSyncStatus: syncResult.ok ? "success" : "error"
839
+ };
840
+ if (syncResult.error) nextSubscription.lastSyncError = syncResult.error;
841
+ else delete nextSubscription.lastSyncError;
842
+ const previousGithubUpdatedAt = subscription.lastObservedGithubUpdatedAt;
843
+ const previousContentHash = subscription.lastObservedContentHash;
844
+ const previousThreadContentHash = subscription.lastObservedThreadContentHash;
845
+ const previousHeadSha = subscription.lastObservedHeadSha;
846
+ if (snapshot) applySnapshotCursor(nextSubscription, snapshot);
847
+ const isFirstObservation = syncResult.ok && snapshot && !previousGithubUpdatedAt && !previousContentHash;
848
+ const legacyAggregateChanged = previousContentHash && snapshot?.contentHash && previousContentHash !== snapshot.contentHash && !previousThreadContentHash && !previousHeadSha;
849
+ const changed = isFirstObservation || syncResult.ok && snapshot && (legacyAggregateChanged || previousThreadContentHash && snapshot.threadContentHash && previousThreadContentHash !== snapshot.threadContentHash || previousHeadSha && snapshot.headSha && previousHeadSha !== snapshot.headSha || subscription.lastObservedState && snapshot.state && subscription.lastObservedState !== snapshot.state || subscription.lastObservedMergeableState && snapshot.mergeableState && subscription.lastObservedMergeableState !== snapshot.mergeableState || subscription.lastObservedCiState && snapshot.ciState && subscription.lastObservedCiState !== snapshot.ciState || subscription.lastObservedReviewStateHash && snapshot.reviewStateHash && subscription.lastObservedReviewStateHash !== snapshot.reviewStateHash);
850
+ let shouldKeepSubscription = true;
851
+ if (changed) {
852
+ const notification = await this.#sendActivityNotification({
853
+ polling: input,
854
+ subscription,
855
+ snapshot,
856
+ previousGithubUpdatedAt,
857
+ previousContentHash
858
+ });
859
+ if (notification) {
860
+ nextSubscription.lastNotificationAt = now;
861
+ nextSubscription.lastNotificationKind = notification.kind;
862
+ nextSubscription.lastNotificationPriority = notification.priority;
863
+ nextSubscription.lastNotificationSummary = notification.summary;
864
+ shouldKeepSubscription = notification.kind !== "pull-request-merged";
865
+ }
866
+ }
867
+ if (shouldKeepSubscription) subscriptions.push(nextSubscription);
868
+ }
869
+ await threadStore.saveThread({
870
+ thread: {
871
+ ...loadedThread,
872
+ id: input.threadId,
873
+ resourceId: input.resourceId,
874
+ createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
875
+ updatedAt: /* @__PURE__ */ new Date(),
876
+ metadata: setGithubMetadata(loadedThread.metadata, { subscriptions })
877
+ }
878
+ });
879
+ this.#notifySubscriptionsChanged({ threadId: input.threadId, resourceId: input.resourceId, subscriptions });
880
+ if (subscriptions.length === 0) this.stopPollingForThread(input);
881
+ return subscriptions.length;
882
+ } catch (error) {
883
+ throw error;
884
+ } finally {
885
+ const latestState = this.#polling.get(key);
886
+ if (latestState) latestState.running = false;
887
+ }
888
+ }
889
+ async #sendGithubNotification(input) {
890
+ const failingChecks = getFailingChecks(input.snapshot);
891
+ const pendingChecks = getPendingChecks(input.snapshot);
892
+ const notificationInput = {
893
+ source: "github",
894
+ kind: input.notification.kind,
895
+ priority: input.notification.priority,
896
+ summary: input.notification.summary,
897
+ dedupeKey: `github:${input.subscription.owner}/${input.subscription.repo}#${input.subscription.number}:${input.dedupeSuffix}`,
898
+ coalesceKey: `github:${input.subscription.owner}/${input.subscription.repo}#${input.subscription.number}:${input.notification.kind}`,
899
+ attributes: {
900
+ owner: input.subscription.owner,
901
+ repo: input.subscription.repo,
902
+ number: input.subscription.number,
903
+ ...input.snapshot.title ? { title: input.snapshot.title } : {},
904
+ ...input.snapshot.state ? { state: input.snapshot.state } : {},
905
+ ...input.snapshot.htmlUrl ? { url: input.snapshot.htmlUrl } : {},
906
+ ...input.snapshot.githubUpdatedAt ? { githubUpdatedAt: input.snapshot.githubUpdatedAt } : {},
907
+ ...input.previousGithubUpdatedAt ? { previousGithubUpdatedAt: input.previousGithubUpdatedAt } : {},
908
+ ...input.snapshot.mergeableState ? { mergeableState: input.snapshot.mergeableState } : {},
909
+ ...input.snapshot.ciState ? { ciState: input.snapshot.ciState } : {},
910
+ ...input.snapshot.unresolvedReviewThreads !== void 0 ? { unresolvedReviewThreads: input.snapshot.unresolvedReviewThreads } : {},
911
+ ...failingChecks.length > 0 ? { failingChecks: failingChecks.map((check) => check.name).join(", ") } : {},
912
+ ...pendingChecks.length > 0 ? { pendingChecks: pendingChecks.map((check) => check.name).join(", ") } : {}
913
+ },
914
+ metadata: {
915
+ github: {
916
+ owner: input.subscription.owner,
917
+ repo: input.subscription.repo,
918
+ number: input.subscription.number,
919
+ title: input.snapshot.title,
920
+ state: input.snapshot.state,
921
+ htmlUrl: input.snapshot.htmlUrl,
922
+ githubUpdatedAt: input.snapshot.githubUpdatedAt,
923
+ previousGithubUpdatedAt: input.previousGithubUpdatedAt,
924
+ contentHash: input.snapshot.contentHash,
925
+ previousContentHash: input.previousContentHash,
926
+ threadContentHash: input.snapshot.threadContentHash,
927
+ headSha: input.snapshot.headSha,
928
+ headRef: input.snapshot.headRef,
929
+ mergeableState: input.snapshot.mergeableState,
930
+ ciState: input.snapshot.ciState,
931
+ closedAt: input.snapshot.closedAt,
932
+ mergedAt: input.snapshot.mergedAt,
933
+ unresolvedReviewThreads: input.snapshot.unresolvedReviewThreads,
934
+ reviewStateHash: input.snapshot.reviewStateHash,
935
+ latestReviewThreadAt: input.snapshot.latestReviewThreadAt,
936
+ latestCommentAuthor: input.snapshot.latestCommentAuthor,
937
+ latestCommentAuthorType: input.snapshot.latestCommentAuthorType,
938
+ latestCommentIsBot: input.snapshot.latestCommentIsBot,
939
+ failingChecks,
940
+ pendingChecks
941
+ }
942
+ }
943
+ };
944
+ const streamOptions = await this.#agentOptions.getNotificationStreamOptions?.(input.target);
945
+ await input.agent?.sendNotificationSignal?.(
946
+ notificationInput,
947
+ streamOptions ? { ...input.target, ifIdle: { streamOptions } } : input.target
948
+ );
949
+ }
950
+ async #sendBaselineNotification(input) {
951
+ const agent = this.#getNotificationAgent({});
952
+ if (!agent?.sendNotificationSignal) return;
953
+ await this.#sendGithubNotification({
954
+ agent,
955
+ subscription: input.subscription,
956
+ snapshot: input.snapshot,
957
+ notification: classifyGithubBaselineNotification({ subscription: input.subscription, snapshot: input.snapshot }),
958
+ target: { resourceId: input.resourceId, threadId: input.threadId },
959
+ dedupeSuffix: `baseline:${input.subscription.lastSubscribeSignalId}`
960
+ });
961
+ }
962
+ async #sendActivityNotification(input) {
963
+ const agent = this.#getNotificationAgent(input.polling);
964
+ if (!agent?.sendNotificationSignal) return void 0;
965
+ const notification = classifyGithubActivityNotification({
966
+ subscription: input.subscription,
967
+ snapshot: input.snapshot
968
+ });
969
+ if (!notification) return void 0;
970
+ await this.#sendGithubNotification({
971
+ agent,
972
+ subscription: input.subscription,
973
+ snapshot: input.snapshot,
974
+ notification,
975
+ target: { resourceId: input.polling.resourceId, threadId: input.polling.threadId },
976
+ dedupeSuffix: input.snapshot.contentHash ?? input.snapshot.githubUpdatedAt ?? String(Date.now()),
977
+ previousGithubUpdatedAt: input.previousGithubUpdatedAt,
978
+ previousContentHash: input.previousContentHash
979
+ });
980
+ return notification;
981
+ }
982
+ async #subscribe(input) {
983
+ const { owner, repo } = await this.#resolveRepository(input);
984
+ const { threadStore, loadedThread } = await this.#loadThread(input);
985
+ const githubMetadata = getGithubMetadata(loadedThread.metadata);
986
+ const existingIndex = githubMetadata.subscriptions.findIndex(
987
+ (subscription2) => subscription2.owner === owner && subscription2.repo === repo && subscription2.number === input.number
988
+ );
989
+ const existing = existingIndex >= 0 ? githubMetadata.subscriptions[existingIndex] : void 0;
990
+ if (existing?.lastSubscribeSignalId === input.id) {
991
+ return { owner, repo, number: input.number, subscription: existing, alreadyProcessed: true };
992
+ }
993
+ const now = (/* @__PURE__ */ new Date()).toISOString();
994
+ const subscription = {
995
+ owner,
996
+ repo,
997
+ number: input.number,
998
+ subscribedAt: existing?.subscribedAt ?? now,
999
+ updatedAt: now,
1000
+ lastSubscribeSignalId: input.id,
1001
+ ...existing?.lastSyncAt ? { lastSyncAt: existing.lastSyncAt } : {},
1002
+ ...existing?.lastSyncStatus ? { lastSyncStatus: existing.lastSyncStatus } : {},
1003
+ ...existing?.lastSyncError ? { lastSyncError: existing.lastSyncError } : {},
1004
+ ...existing?.lastObservedGithubUpdatedAt ? { lastObservedGithubUpdatedAt: existing.lastObservedGithubUpdatedAt } : {},
1005
+ ...existing?.lastObservedContentHash ? { lastObservedContentHash: existing.lastObservedContentHash } : {},
1006
+ ...existing?.lastObservedThreadContentHash ? { lastObservedThreadContentHash: existing.lastObservedThreadContentHash } : {},
1007
+ ...existing?.lastObservedHeadSha ? { lastObservedHeadSha: existing.lastObservedHeadSha } : {},
1008
+ ...existing?.lastObservedState ? { lastObservedState: existing.lastObservedState } : {},
1009
+ ...existing?.lastObservedMergeableState ? { lastObservedMergeableState: existing.lastObservedMergeableState } : {},
1010
+ ...existing?.lastObservedCiState ? { lastObservedCiState: existing.lastObservedCiState } : {},
1011
+ ...existing?.lastObservedReviewStateHash ? { lastObservedReviewStateHash: existing.lastObservedReviewStateHash } : {}
1012
+ };
1013
+ let syncResult;
1014
+ let baselineSnapshot;
1015
+ if (this.#options.syncOnSubscribe !== false) {
1016
+ const syncInput = {
1017
+ owner,
1018
+ repo,
1019
+ number: input.number,
1020
+ cwd: this.#options.cwd,
1021
+ abortSignal: input.abortSignal
1022
+ };
1023
+ syncResult = await this.#syncClient.syncPullRequest(syncInput);
1024
+ subscription.lastSyncAt = (/* @__PURE__ */ new Date()).toISOString();
1025
+ subscription.lastSyncStatus = syncResult.ok ? "success" : "error";
1026
+ if (syncResult.error) subscription.lastSyncError = syncResult.error;
1027
+ else delete subscription.lastSyncError;
1028
+ const snapshot = syncResult.ok ? await this.#syncClient.getPullRequestSnapshot?.(syncInput) : void 0;
1029
+ baselineSnapshot = snapshot;
1030
+ if (snapshot) applySnapshotCursor(subscription, snapshot);
1031
+ } else {
1032
+ subscription.lastSyncStatus = "skipped";
1033
+ }
1034
+ const subscriptions = [subscription];
1035
+ await threadStore.saveThread({
1036
+ thread: {
1037
+ ...loadedThread,
1038
+ id: input.threadId,
1039
+ resourceId: input.resourceId,
1040
+ createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
1041
+ updatedAt: /* @__PURE__ */ new Date(),
1042
+ metadata: setGithubMetadata(loadedThread.metadata, { subscriptions })
1043
+ }
1044
+ });
1045
+ this.#notifySubscriptionsChanged({ threadId: input.threadId, resourceId: input.resourceId, subscriptions });
1046
+ if (baselineSnapshot) {
1047
+ await this.#sendBaselineNotification({
1048
+ threadId: input.threadId,
1049
+ resourceId: input.resourceId,
1050
+ subscription,
1051
+ snapshot: baselineSnapshot
1052
+ });
1053
+ }
1054
+ await this.startPollingForThread({ threadId: input.threadId, resourceId: input.resourceId });
1055
+ return { owner, repo, number: input.number, subscription, syncResult };
1056
+ }
1057
+ async #unsubscribe(input) {
1058
+ const { owner, repo } = await this.#resolveRepository(input);
1059
+ const { threadStore, loadedThread } = await this.#loadThread(input);
1060
+ const githubMetadata = getGithubMetadata(loadedThread.metadata);
1061
+ const subscriptions = githubMetadata.subscriptions.filter(
1062
+ (subscription) => !(subscription.owner === owner && subscription.repo === repo && subscription.number === input.number)
1063
+ );
1064
+ const removed = subscriptions.length !== githubMetadata.subscriptions.length;
1065
+ if (removed) {
1066
+ await threadStore.saveThread({
1067
+ thread: {
1068
+ ...loadedThread,
1069
+ id: input.threadId,
1070
+ resourceId: input.resourceId,
1071
+ createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
1072
+ updatedAt: /* @__PURE__ */ new Date(),
1073
+ metadata: setGithubMetadata(loadedThread.metadata, { subscriptions })
1074
+ }
1075
+ });
1076
+ this.#notifySubscriptionsChanged({ threadId: input.threadId, resourceId: input.resourceId, subscriptions });
1077
+ if (subscriptions.length === 0)
1078
+ this.stopPollingForThread({ threadId: input.threadId, resourceId: input.resourceId });
1079
+ }
1080
+ return { owner, repo, number: input.number, removed, remainingSubscriptions: subscriptions.length };
1081
+ }
1082
+ #findLatestGithubSignal(messages) {
1083
+ const message = messages.at(-1);
1084
+ if (!message) return void 0;
1085
+ const signal = getSignalMetadata(message);
1086
+ if (!signal || signal.tagName !== GITHUB_SUBSCRIBE_PR_TAG && signal.tagName !== GITHUB_UNSUBSCRIBE_PR_TAG) {
1087
+ return void 0;
1088
+ }
1089
+ const attributes = isPlainObject(signal.attributes) ? signal.attributes : {};
1090
+ const metadata = isPlainObject(signal.metadata) ? signal.metadata : {};
1091
+ const github = isPlainObject(metadata.github) ? metadata.github : {};
1092
+ const number = readNumber(attributes.number) ?? readNumber(github.number);
1093
+ if (!number) return void 0;
1094
+ return {
1095
+ tagName: String(signal.tagName),
1096
+ id: readString(signal.id) ?? message.id,
1097
+ owner: readString(attributes.owner) ?? readString(github.owner),
1098
+ repo: readString(attributes.repo) ?? readString(github.repo),
1099
+ number
1100
+ };
1101
+ }
1102
+ async #sendStatus(args, signal, status) {
1103
+ await args.sendSignal?.({
1104
+ type: "reactive",
1105
+ tagName: GITHUB_SYNC_STATUS_TAG,
1106
+ contents: status.message,
1107
+ attributes: {
1108
+ status: status.status,
1109
+ owner: signal.owner,
1110
+ repo: signal.repo,
1111
+ number: signal.number
1112
+ },
1113
+ metadata: {
1114
+ github: {
1115
+ action: status.action,
1116
+ status: status.status,
1117
+ owner: signal.owner,
1118
+ repo: signal.repo,
1119
+ number: signal.number
1120
+ }
1121
+ }
1122
+ });
1123
+ }
1124
+ };
1125
+
1126
+ exports.GITHUB_SIGNALS_METADATA_KEY = GITHUB_SIGNALS_METADATA_KEY;
1127
+ exports.GITHUB_SUBSCRIBE_PR_TAG = GITHUB_SUBSCRIBE_PR_TAG;
1128
+ exports.GITHUB_SYNC_STATUS_TAG = GITHUB_SYNC_STATUS_TAG;
1129
+ exports.GITHUB_UNSUBSCRIBE_PR_TAG = GITHUB_UNSUBSCRIBE_PR_TAG;
1130
+ exports.GitRemoteRepositoryResolver = GitRemoteRepositoryResolver;
1131
+ exports.GitcrawlSyncClient = GitcrawlSyncClient;
1132
+ exports.GithubSignals = GithubSignals;
1133
+ exports.normalizeGithubChecksForSnapshot = normalizeGithubChecksForSnapshot;
1134
+ //# sourceMappingURL=index.cjs.map
1135
+ //# sourceMappingURL=index.cjs.map