@giantswarm-io/pro 1.5.0 → 1.7.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/README.md CHANGED
@@ -204,6 +204,10 @@ The `board` parameter defaults to `"roadmap"` on every board-scoped tool for bac
204
204
 
205
205
  - **`get_issue_details`** -- Get full details for a specific item: repository metadata, title, body text, comments with timestamps, assignees, labels, dates, and all field values. Board-independent (queries by item ID).
206
206
 
207
+ - **`list_issue_comments`** -- Fetch comments for multiple board items in a single call. Board-independent (queries by item ID). Resolves each item to its underlying issue and returns comment author/timestamps/body, with an optional `since` cutoff. Each comment includes `createdAt`, plus `updatedAt` when it differs from `createdAt` (i.e. the comment was edited). Bounded response: max 25 `itemIds` per call, newest 20 comments per issue by default (override with `maxPerIssue`), and long comment bodies are truncated with an explicit indicator. Without `since`, "newest" means newest by creation time, and per-issue REST pagination is capped (surfaced via a `truncatedPages` flag if more comments exist); with `since`, "newest" means newest by last-updated time, so a recently-edited older comment isn't dropped in favor of an untouched newer one, and its `updatedAt` shows why. The response's `itemCount` counts result items (including error entries), not comments.
208
+
209
+ - **`get_issue_timeline`** -- Get the compact activity timeline for a board item's underlying issue: label changes, assignments, milestones, renames, cross-references, and close reasons. Board-independent (queries by item ID). Optional `since`/`until`/`eventTypes` filters (applied client-side; malformed `since`/`until` values return an error). When more than 200 events qualify, only the most recent 200 are returned, with a `truncated` flag.
210
+
207
211
  ### Write Tools
208
212
 
209
213
  - **`update_issue_field`** -- Update a single-select field value. Provide human-readable field and option names; the server resolves them to GitHub node IDs. Specify `board` to target the correct board.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giantswarm-io/pro",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "Core library and MCP server for managing Giant Swarm's roadmap and customer project boards",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/src/index.js CHANGED
@@ -44,6 +44,13 @@ export {
44
44
  reprioritizeSubIssue
45
45
  } from './lib/sub-issues.js';
46
46
 
47
+ // Bulk issue comment fetching (board items -> underlying issue comments)
48
+ export {
49
+ listIssueCommentsForItems,
50
+ resolveItemIssueRefs,
51
+ fetchIssueComments
52
+ } from './lib/comments.js';
53
+
47
54
  // Low-level GitHub clients for anything not covered above
48
55
  export { graphQLWithAuth, fetchPaginated } from './lib/api.js';
49
56
  export { getOctokit, parseIssueRef, resolveIssueId } from './lib/rest-api.js';
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Bulk Issue Comments Module
3
+ *
4
+ * Resolves GitHub Projects V2 items to their underlying issues (via a single
5
+ * batched GraphQL `nodes(ids:)` lookup) and fetches each issue's comments via
6
+ * the REST API, which supports `since` filtering natively. Bounds response
7
+ * size by capping the number of items per call, the number of REST pages
8
+ * fetched per issue (when `since` is absent), the number of comments kept
9
+ * per issue, and truncating long comment bodies.
10
+ *
11
+ * Ordering semantics for the kept comments differ by mode:
12
+ * - Without `since`: newest by creation order (the REST endpoint's natural
13
+ * oldest-first order, sliced from the end).
14
+ * - With `since`: newest by `updated_at`, so a recently-edited older
15
+ * comment is kept over an untouched newer-created one.
16
+ *
17
+ * Each comment always exposes `createdAt`; `updatedAt` is included only when
18
+ * it differs from `createdAt` (i.e. the comment was edited), so the `since`
19
+ * mode's updated_at-driven retention is observable without bloating the
20
+ * common (unedited) case.
21
+ */
22
+
23
+ import { graphQLWithAuth } from './api.js';
24
+ import { getOctokit } from './rest-api.js';
25
+ import { ITEM_ISSUE_REFS_QUERY } from './project.js';
26
+ import { logger } from './logger.js';
27
+
28
+ /** Maximum number of itemIds accepted in a single list_issue_comments call. */
29
+ export const MAX_ITEMS_PER_CALL = 25;
30
+
31
+ /** Default number of newest comments kept per issue when maxPerIssue isn't given. */
32
+ export const DEFAULT_MAX_PER_ISSUE = 20;
33
+
34
+ /** Comment bodies longer than this are truncated with an explicit indicator. */
35
+ export const MAX_COMMENT_BODY_LENGTH = 2000;
36
+
37
+ /**
38
+ * Hard cap on REST pages fetched per issue when `since` is absent. Bounds a
39
+ * single list_issue_comments call to at most MAX_PAGES * 100 REST requests'
40
+ * worth of comments per issue, rather than fetching every page unconditionally.
41
+ * When `since` is supplied this cap does not apply (see fetchIssueComments).
42
+ */
43
+ export const MAX_PAGES = 5;
44
+
45
+ /**
46
+ * Truncate an overly long comment body, appending an explicit indicator of
47
+ * how much was cut so callers can tell the body isn't complete.
48
+ * @param {string} body
49
+ * @returns {string}
50
+ */
51
+ function truncateBody(body) {
52
+ if (typeof body !== 'string') return '';
53
+ if (body.length <= MAX_COMMENT_BODY_LENGTH) return body;
54
+ const cut = body.length - MAX_COMMENT_BODY_LENGTH;
55
+ return `${body.slice(0, MAX_COMMENT_BODY_LENGTH)}\n\n[... truncated ${cut} characters ...]`;
56
+ }
57
+
58
+ /**
59
+ * Resolve a batch of project item IDs to their underlying issue's
60
+ * owner/repo/number in a single batched GraphQL request.
61
+ * @param {string[]} itemIds - Project item (PVTI) IDs
62
+ * @param {string} [token] - Optional per-request GitHub token
63
+ * @returns {Promise<Map<string, {owner: string, repo: string, number: number}|null>>}
64
+ * Map from itemId to its issue ref, or null when the item doesn't resolve
65
+ * to an accessible Issue.
66
+ */
67
+ export async function resolveItemIssueRefs(itemIds, token) {
68
+ const result = await graphQLWithAuth(ITEM_ISSUE_REFS_QUERY, { ids: itemIds }, token);
69
+ const nodes = result?.nodes || [];
70
+ const refs = new Map();
71
+
72
+ itemIds.forEach((itemId, i) => {
73
+ const node = nodes[i];
74
+ const nameWithOwner = node?.content?.repository?.nameWithOwner;
75
+ const number = node?.content?.number;
76
+ if (!node || !nameWithOwner || !number) {
77
+ refs.set(itemId, null);
78
+ return;
79
+ }
80
+ const [owner, repo] = nameWithOwner.split('/');
81
+ refs.set(itemId, { owner, repo, number });
82
+ });
83
+
84
+ return refs;
85
+ }
86
+
87
+ /**
88
+ * Fetch comments for a single issue via REST. `since` is applied server-side
89
+ * (native GitHub support). The per-issue comments endpoint only returns
90
+ * results oldest-first with no server-side reverse option.
91
+ *
92
+ * When `since` is absent, page fan-out is bounded by MAX_PAGES -- an issue
93
+ * with far more comments than maxPerIssue would otherwise fetch every page
94
+ * just to keep the newest few. When stopping short, `truncatedPages: true`
95
+ * is returned so callers know more comments exist beyond what was fetched.
96
+ * When `since` is supplied, all matching pages are fetched (uncapped, same
97
+ * as before) and the newest-by-`updated_at` comments are kept, so a
98
+ * recently-edited older comment isn't dropped in favor of an untouched
99
+ * newer-created one.
100
+ * @param {{owner: string, repo: string, number: number}} ref
101
+ * @param {{since?: string, maxPerIssue: number, token?: string}} options
102
+ * @returns {Promise<{comments: Array<{author: string, createdAt: string, updatedAt?: string, body: string}>, totalFetched: number, truncatedPages: boolean}>}
103
+ */
104
+ export async function fetchIssueComments({ owner, repo, number }, { since, maxPerIssue, token }) {
105
+ const client = getOctokit(token);
106
+ const params = { owner, repo, issue_number: number, per_page: 100 };
107
+ if (since) params.since = since;
108
+
109
+ let all = [];
110
+ let truncatedPages = false;
111
+
112
+ if (since) {
113
+ all = await client.paginate(
114
+ 'GET /repos/{owner}/{repo}/issues/{issue_number}/comments',
115
+ params
116
+ );
117
+ } else {
118
+ let pages = 0;
119
+ const iterator = client.paginate.iterator(
120
+ 'GET /repos/{owner}/{repo}/issues/{issue_number}/comments',
121
+ params
122
+ );
123
+ for await (const { data } of iterator) {
124
+ all.push(...data);
125
+ pages += 1;
126
+ if (pages >= MAX_PAGES) {
127
+ truncatedPages = true;
128
+ break;
129
+ }
130
+ }
131
+ }
132
+
133
+ let kept = all;
134
+ if (maxPerIssue > 0) {
135
+ kept = since
136
+ ? [...all].sort((a, b) => (a.updated_at || '').localeCompare(b.updated_at || '')).slice(-maxPerIssue)
137
+ : all.slice(-maxPerIssue);
138
+ }
139
+
140
+ return {
141
+ comments: kept.map(c => {
142
+ const comment = {
143
+ author: c.user?.login || '',
144
+ createdAt: c.created_at,
145
+ body: truncateBody(c.body || '')
146
+ };
147
+ // Only surface updatedAt when it differs from createdAt (i.e. the
148
+ // comment was edited) -- keeps the common unedited case compact while
149
+ // making the since-mode retention semantics (governed by updated_at)
150
+ // observable when they actually diverge from createdAt.
151
+ if (c.updated_at && c.updated_at !== c.created_at) {
152
+ comment.updatedAt = c.updated_at;
153
+ }
154
+ return comment;
155
+ }),
156
+ totalFetched: all.length,
157
+ truncatedPages
158
+ };
159
+ }
160
+
161
+ /**
162
+ * List comments across multiple board items in one call. Without `since`,
163
+ * kept comments are the newest by creation; with `since`, the newest by
164
+ * `updated_at` (see fetchIssueComments).
165
+ * @param {Object} options
166
+ * @param {string[]} options.itemIds - Project item (PVTI) IDs, max MAX_ITEMS_PER_CALL
167
+ * @param {string} [options.since] - ISO 8601 timestamp; only comments at/after this time
168
+ * @param {number} [options.maxPerIssue] - Newest comments to keep per issue (default DEFAULT_MAX_PER_ISSUE)
169
+ * @param {string} [options.token] - Optional per-request GitHub token
170
+ * @returns {Promise<Array>} - One entry per itemId, in input order
171
+ */
172
+ export async function listIssueCommentsForItems({ itemIds, since, maxPerIssue, token } = {}) {
173
+ if (!Array.isArray(itemIds) || itemIds.length === 0) {
174
+ throw new Error('itemIds must be a non-empty array of project item IDs.');
175
+ }
176
+ if (itemIds.length > MAX_ITEMS_PER_CALL) {
177
+ throw new Error(
178
+ `Too many itemIds (${itemIds.length}). Max ${MAX_ITEMS_PER_CALL} per call -- split into multiple calls.`
179
+ );
180
+ }
181
+
182
+ const effectiveMaxPerIssue = Number.isFinite(maxPerIssue) && maxPerIssue > 0
183
+ ? Math.floor(maxPerIssue)
184
+ : DEFAULT_MAX_PER_ISSUE;
185
+
186
+ const refs = await resolveItemIssueRefs(itemIds, token);
187
+
188
+ const results = [];
189
+ for (const itemId of itemIds) {
190
+ const ref = refs.get(itemId);
191
+ if (!ref) {
192
+ results.push({ itemId, error: 'Item not found or is not an issue' });
193
+ continue;
194
+ }
195
+
196
+ try {
197
+ const { comments, totalFetched, truncatedPages } = await fetchIssueComments(ref, {
198
+ since,
199
+ maxPerIssue: effectiveMaxPerIssue,
200
+ token
201
+ });
202
+ results.push({
203
+ itemId,
204
+ repository: `${ref.owner}/${ref.repo}`,
205
+ issueNumber: ref.number,
206
+ commentCount: comments.length,
207
+ totalCommentsFetched: totalFetched,
208
+ truncatedPages,
209
+ comments
210
+ });
211
+ } catch (err) {
212
+ logger.error('Error fetching comments for issue', { itemId, error: err.message });
213
+ results.push({ itemId, error: err.message });
214
+ }
215
+ }
216
+
217
+ return results;
218
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * MCP Issue Timeline Tool
3
+ *
4
+ * Exposes 1 tool for reading an issue's activity timeline:
5
+ * - get_issue_timeline: List label/assignment/milestone/rename/cross-reference
6
+ * events for the issue underlying a project board item.
7
+ */
8
+
9
+ import { getItemByID } from '../items.js';
10
+ import { getIssueTimeline, MAX_TIMELINE_EVENTS } from '../timeline.js';
11
+ import { logger } from '../logger.js';
12
+
13
+ /**
14
+ * Extract the GitHub token from MCP request extra context.
15
+ * @param {Object} [extra] - MCP request extra context
16
+ * @returns {string|undefined}
17
+ */
18
+ function extractToken(extra) {
19
+ return extra?.authInfo?.token;
20
+ }
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Tool: get_issue_timeline
24
+ // ---------------------------------------------------------------------------
25
+
26
+ export const getIssueTimelineTool = {
27
+ name: 'get_issue_timeline',
28
+ description: `Get the activity timeline for a project board item's underlying issue: label changes, assignments, milestones, renames, cross-references, and close reasons. Returns compact events ordered chronologically (oldest first); when more than ${MAX_TIMELINE_EVENTS} events qualify, only the most recent ${MAX_TIMELINE_EVENTS} are returned (see \`truncated\` in the response). No server-side date/type filters exist on this endpoint, so \`since\`/\`until\`/\`eventTypes\` are applied client-side -- pass full ISO 8601 timestamps (not just a date) for precise since/until cutoffs.`,
29
+ inputSchema: {
30
+ type: 'object',
31
+ properties: {
32
+ itemId: {
33
+ type: 'string',
34
+ description: 'The ID of the project item to retrieve the timeline for. Board-independent (queries by item ID).'
35
+ },
36
+ since: {
37
+ type: 'string',
38
+ description: 'Only include events at or after this ISO 8601 date/time (e.g. "2026-01-01T00:00:00Z").'
39
+ },
40
+ until: {
41
+ type: 'string',
42
+ description: 'Only include events at or before this ISO 8601 date/time.'
43
+ },
44
+ eventTypes: {
45
+ type: 'array',
46
+ items: { type: 'string' },
47
+ description: 'Only include events of these raw timeline types (e.g. ["labeled", "closed", "cross-referenced", "assigned", "renamed", "referenced"]). Omit to include all types.'
48
+ }
49
+ },
50
+ required: ['itemId']
51
+ }
52
+ };
53
+
54
+ export async function handleGetIssueTimeline(args, extra) {
55
+ try {
56
+ const token = extractToken(extra);
57
+ logger.info('MCP: Getting issue timeline', {
58
+ itemId: args.itemId, since: args.since, until: args.until, eventTypes: args.eventTypes
59
+ });
60
+
61
+ const item = await getItemByID(args.itemId, token);
62
+ if (!item.repository?.nameWithOwner || !item.number) {
63
+ return { error: `Could not resolve item '${args.itemId}' to an underlying issue.` };
64
+ }
65
+ const [owner, repo] = item.repository.nameWithOwner.split('/');
66
+
67
+ const result = await getIssueTimeline(
68
+ {
69
+ owner,
70
+ repo,
71
+ issue_number: item.number,
72
+ since: args.since || null,
73
+ until: args.until || null,
74
+ eventTypes: args.eventTypes || null
75
+ },
76
+ token
77
+ );
78
+
79
+ if (result.error) {
80
+ return { error: result.error };
81
+ }
82
+ const { events, truncated } = result;
83
+
84
+ return {
85
+ content: [{
86
+ type: 'text',
87
+ text: JSON.stringify({
88
+ count: events.length,
89
+ truncated,
90
+ events
91
+ })
92
+ }]
93
+ };
94
+ } catch (error) {
95
+ logger.error('MCP: Error getting issue timeline', { error: error.message });
96
+ return { error: error.message };
97
+ }
98
+ }
99
+
100
+ // ---------------------------------------------------------------------------
101
+ // Exports
102
+ // ---------------------------------------------------------------------------
103
+
104
+ export const timelineTools = [
105
+ getIssueTimelineTool
106
+ ];
107
+
108
+ export const timelineToolHandlers = {
109
+ get_issue_timeline: handleGetIssueTimeline
110
+ };
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * MCP Tools Implementation
3
3
  *
4
- * Exposes 9 tools for managing Giant Swarm project boards:
4
+ * Exposes 10 tools for managing Giant Swarm project boards:
5
5
  * - list_issues: Filter and list project items with generic field filters
6
6
  * - get_issue_details: Get full details for a specific item
7
7
  * - update_issue_field: Update a single-select field value
@@ -11,6 +11,7 @@
11
11
  * - close_issue: Close the issue underlying a project item
12
12
  * - reopen_issue: Reopen the issue underlying a project item
13
13
  * - update_issue_labels: Add and/or remove labels on an issue
14
+ * - list_issue_comments: Fetch comments across multiple board items in one call
14
15
  */
15
16
 
16
17
  import { listItems, getItemByID, updateItemField } from '../items.js';
@@ -35,6 +36,12 @@ import {
35
36
  } from '../project.js';
36
37
  import { logger } from '../logger.js';
37
38
  import { subIssueTools, subIssueToolHandlers } from './sub-issues.js';
39
+ import { timelineTools, timelineToolHandlers } from './timeline.js';
40
+ import {
41
+ listIssueCommentsForItems,
42
+ MAX_ITEMS_PER_CALL,
43
+ DEFAULT_MAX_PER_ISSUE
44
+ } from '../comments.js';
38
45
 
39
46
  const BOARD_NAMES = Object.keys(BOARDS);
40
47
 
@@ -906,6 +913,67 @@ export async function handleUpdateIssueLabels(args, extra) {
906
913
  }
907
914
  }
908
915
 
916
+ // ---------------------------------------------------------------------------
917
+ // Tool: list_issue_comments
918
+ // ---------------------------------------------------------------------------
919
+
920
+ export const listIssueCommentsTool = {
921
+ name: 'list_issue_comments',
922
+ description: `Fetch comments for multiple board items in a single call. Board-independent (queries by item ID). Resolves each item to its underlying GitHub issue and returns the comment author, timestamps, and body for each. Bounded response: max ${MAX_ITEMS_PER_CALL} itemIds per call, and only the newest ${DEFAULT_MAX_PER_ISSUE} comments per issue by default (override with maxPerIssue); long comment bodies are truncated with an explicit truncation indicator. Each comment includes \`createdAt\`, plus \`updatedAt\` when it differs from \`createdAt\` (i.e. the comment was edited). Ordering differs by mode: without \`since\`, the newest comments by creation time are kept; with \`since\`, the newest comments by last-updated time are kept (so a recently-edited older comment survives ahead of an untouched newer one, and its \`updatedAt\` shows why). The response's \`itemCount\` counts result items (including error entries), not comments.`,
923
+ inputSchema: {
924
+ type: 'object',
925
+ properties: {
926
+ itemIds: {
927
+ type: 'array',
928
+ items: { type: 'string' },
929
+ description: `The project item IDs to fetch comments for. Max ${MAX_ITEMS_PER_CALL} per call.`
930
+ },
931
+ since: {
932
+ type: 'string',
933
+ description: 'Only return comments created/updated at or after this ISO 8601 timestamp (e.g. "2026-06-01T00:00:00Z"). Changes which comments are kept when maxPerIssue trims the results -- see the tool description.'
934
+ },
935
+ maxPerIssue: {
936
+ type: 'number',
937
+ description: `Maximum number of comments to return per issue, keeping the newest ones. Defaults to ${DEFAULT_MAX_PER_ISSUE}.`
938
+ }
939
+ },
940
+ required: ['itemIds']
941
+ }
942
+ };
943
+
944
+ export async function handleListIssueComments(args, extra) {
945
+ try {
946
+ const token = extractToken(extra);
947
+ const itemIds = args.itemIds;
948
+
949
+ logger.info('MCP: Listing issue comments', {
950
+ itemCount: Array.isArray(itemIds) ? itemIds.length : 0,
951
+ since: args.since,
952
+ maxPerIssue: args.maxPerIssue
953
+ });
954
+
955
+ const results = await listIssueCommentsForItems({
956
+ itemIds,
957
+ since: args.since || null,
958
+ maxPerIssue: args.maxPerIssue,
959
+ token
960
+ });
961
+
962
+ return {
963
+ content: [{
964
+ type: 'text',
965
+ text: JSON.stringify({
966
+ itemCount: results.length,
967
+ items: results
968
+ })
969
+ }]
970
+ };
971
+ } catch (error) {
972
+ logger.error('MCP: Error listing issue comments', { error: error.message });
973
+ return { error: error.message };
974
+ }
975
+ }
976
+
909
977
  // ---------------------------------------------------------------------------
910
978
  // Exports
911
979
  // ---------------------------------------------------------------------------
@@ -920,7 +988,9 @@ export const tools = [
920
988
  closeIssueTool,
921
989
  reopenIssueTool,
922
990
  updateIssueLabelsTool,
923
- ...subIssueTools
991
+ listIssueCommentsTool,
992
+ ...subIssueTools,
993
+ ...timelineTools
924
994
  ];
925
995
 
926
996
  export const toolHandlers = {
@@ -933,5 +1003,7 @@ export const toolHandlers = {
933
1003
  close_issue: handleCloseIssue,
934
1004
  reopen_issue: handleReopenIssue,
935
1005
  update_issue_labels: handleUpdateIssueLabels,
936
- ...subIssueToolHandlers
1006
+ list_issue_comments: handleListIssueComments,
1007
+ ...subIssueToolHandlers,
1008
+ ...timelineToolHandlers
937
1009
  };
@@ -395,6 +395,29 @@ const USER_ID_QUERY = `
395
395
  }
396
396
  `;
397
397
 
398
+ // Batched lookup: resolve a list of ProjectV2Item IDs to their underlying
399
+ // issue's repository + number in a single round trip, using GitHub's
400
+ // root-level `nodes(ids:)` query. The response array is in the same order
401
+ // as the requested `ids` (entries are null for items that don't resolve to
402
+ // an Issue, e.g. deleted or inaccessible content).
403
+ const ITEM_ISSUE_REFS_QUERY = `
404
+ query GetItemIssueRefs($ids: [ID!]!) {
405
+ nodes(ids: $ids) {
406
+ ... on ProjectV2Item {
407
+ id
408
+ content {
409
+ ... on Issue {
410
+ number
411
+ repository {
412
+ nameWithOwner
413
+ }
414
+ }
415
+ }
416
+ }
417
+ }
418
+ }
419
+ `;
420
+
398
421
  // Query to resolve the underlying issue node ID for a project item, including
399
422
  // the repository's visibility so callers can gate free-text writes (e.g. comments)
400
423
  // to public repos behind an explicit confirmation.
@@ -475,6 +498,7 @@ export {
475
498
  ARCHIVE_ITEM_MUTATION,
476
499
  ISSUE_NODE_ID_QUERY,
477
500
  USER_ID_QUERY,
501
+ ITEM_ISSUE_REFS_QUERY,
478
502
  ITEM_ISSUE_ID_QUERY,
479
503
  CLOSE_ISSUE_MUTATION,
480
504
  REOPEN_ISSUE_MUTATION,
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Issue Timeline Module
3
+ *
4
+ * Provides access to the GitHub Issue Timeline REST API (not available via
5
+ * GraphQL, same reasoning as sub-issues.js). Maps raw timeline events to a
6
+ * compact shape and supports client-side since/until/eventTypes filtering,
7
+ * with an early pagination stop once `until` is exceeded, since the timeline
8
+ * is returned in chronological (oldest-first) order. When more than
9
+ * MAX_TIMELINE_EVENTS qualifying events exist, the most recent ones are kept
10
+ * and `truncated: true` is set.
11
+ */
12
+
13
+ import { getOctokit } from './rest-api.js';
14
+ import { logger } from './logger.js';
15
+
16
+ const DEFAULT_PAGE_SIZE = 100;
17
+
18
+ /**
19
+ * Maximum number of (post-filter) events returned by getIssueTimeline.
20
+ * When more qualifying events exist, the result is truncated and
21
+ * `truncated: true` is set on the return value.
22
+ */
23
+ export const MAX_TIMELINE_EVENTS = 200;
24
+
25
+ /**
26
+ * Extract a GitHub login (or best-effort name) from an actor-like object.
27
+ * @param {Object} [obj]
28
+ * @returns {string|undefined}
29
+ */
30
+ function actorLogin(obj) {
31
+ return obj?.login || obj?.name || undefined;
32
+ }
33
+
34
+ /**
35
+ * Best-effort timestamp for a raw timeline event, used both for since/until
36
+ * filtering and as the compact event's createdAt.
37
+ * @param {Object} event
38
+ * @returns {string|null}
39
+ */
40
+ function eventTimestamp(event) {
41
+ return event.created_at || event.submitted_at || event.author?.date || event.committer?.date || null;
42
+ }
43
+
44
+ /**
45
+ * Map a single raw timeline event to a compact { type, actor, createdAt, detail } shape.
46
+ * `detail` is only populated for event types where it carries meaningful signal;
47
+ * all other payload fields (bodies, diffs, node IDs, etc.) are dropped.
48
+ * @param {Object} event - Raw event from GET /repos/{owner}/{repo}/issues/{issue_number}/timeline
49
+ * @returns {{ type: string, actor?: string, createdAt: string|null, detail?: Object }|null}
50
+ */
51
+ export function compactTimelineEvent(event) {
52
+ const type = event?.event;
53
+ if (!type) return null;
54
+
55
+ const base = {
56
+ type,
57
+ actor: actorLogin(event.actor) || actorLogin(event.user) || actorLogin(event.author),
58
+ createdAt: eventTimestamp(event)
59
+ };
60
+
61
+ switch (type) {
62
+ case 'labeled':
63
+ case 'unlabeled':
64
+ return { ...base, detail: { label: event.label?.name } };
65
+
66
+ case 'closed':
67
+ return event.state_reason
68
+ ? { ...base, detail: { stateReason: event.state_reason } }
69
+ : base;
70
+
71
+ case 'cross-referenced': {
72
+ const src = event.source?.issue;
73
+ return {
74
+ ...base,
75
+ actor: actorLogin(event.actor) || actorLogin(src?.user),
76
+ createdAt: event.created_at || src?.created_at || base.createdAt,
77
+ detail: src
78
+ ? {
79
+ ref: `${src.repository?.full_name || ''}#${src.number}`,
80
+ title: src.title,
81
+ isPullRequest: Boolean(src.pull_request)
82
+ }
83
+ : undefined
84
+ };
85
+ }
86
+
87
+ case 'assigned':
88
+ case 'unassigned':
89
+ return { ...base, detail: { assignee: actorLogin(event.assignee) } };
90
+
91
+ case 'milestoned':
92
+ case 'demilestoned':
93
+ return { ...base, detail: { milestone: event.milestone?.title } };
94
+
95
+ case 'renamed':
96
+ return { ...base, detail: { from: event.rename?.from, to: event.rename?.to } };
97
+
98
+ case 'referenced':
99
+ return { ...base, detail: { commit: event.commit_id } };
100
+
101
+ default:
102
+ return base;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Fetch and compact the activity timeline for a GitHub issue, paginating
108
+ * via Octokit and filtering client-side (the timeline endpoint has no
109
+ * server-side date/type filters). Stops paginating early once `until` is
110
+ * exceeded, since events are returned in chronological (oldest-first) order.
111
+ * When more than MAX_TIMELINE_EVENTS qualifying events are found, only the
112
+ * most recent MAX_TIMELINE_EVENTS are kept (oldest-first order preserved
113
+ * within that tail) and `truncated: true` is set.
114
+ *
115
+ * @param {Object} params
116
+ * @param {string} params.owner
117
+ * @param {string} params.repo
118
+ * @param {number} params.issue_number
119
+ * @param {string} [params.since] - ISO 8601 date/time; only include events at or after this instant
120
+ * @param {string} [params.until] - ISO 8601 date/time; only include events at or before this instant
121
+ * @param {string[]} [params.eventTypes] - Only include events whose raw `type` is in this list
122
+ * @param {string} [token] - Optional per-request GitHub token
123
+ * @returns {Promise<{ events: Array, truncated: boolean } | { error: string }>}
124
+ */
125
+ export async function getIssueTimeline({ owner, repo, issue_number, since, until, eventTypes }, token) {
126
+ const sinceDate = since ? new Date(since) : null;
127
+ const untilDate = until ? new Date(until) : null;
128
+
129
+ if (sinceDate && Number.isNaN(sinceDate.getTime())) {
130
+ return { error: `Invalid 'since' date/time: '${since}'` };
131
+ }
132
+ if (untilDate && Number.isNaN(untilDate.getTime())) {
133
+ return { error: `Invalid 'until' date/time: '${until}'` };
134
+ }
135
+
136
+ const client = getOctokit(token);
137
+ const typeFilter = Array.isArray(eventTypes) && eventTypes.length > 0 ? new Set(eventTypes) : null;
138
+
139
+ logger.debug('Fetching issue timeline', { owner, repo, issue_number, since, until, eventTypes });
140
+
141
+ const events = [];
142
+ let page = 1;
143
+
144
+ outer:
145
+ while (true) {
146
+ const { data } = await client.request(
147
+ 'GET /repos/{owner}/{repo}/issues/{issue_number}/timeline',
148
+ { owner, repo, issue_number, per_page: DEFAULT_PAGE_SIZE, page }
149
+ );
150
+
151
+ if (!Array.isArray(data) || data.length === 0) break;
152
+
153
+ for (const raw of data) {
154
+ const ts = eventTimestamp(raw);
155
+ const tsDate = ts ? new Date(ts) : null;
156
+
157
+ // Chronological (oldest-first) order means once we're past `until`,
158
+ // nothing later in the timeline can be in range either.
159
+ if (untilDate && tsDate && tsDate > untilDate) {
160
+ break outer;
161
+ }
162
+ if (sinceDate && tsDate && tsDate < sinceDate) {
163
+ continue;
164
+ }
165
+
166
+ const compact = compactTimelineEvent(raw);
167
+ if (!compact) continue;
168
+ if (typeFilter && !typeFilter.has(compact.type)) continue;
169
+
170
+ events.push(compact);
171
+ }
172
+
173
+ if (data.length < DEFAULT_PAGE_SIZE) break;
174
+ page += 1;
175
+ }
176
+
177
+ const truncated = events.length > MAX_TIMELINE_EVENTS;
178
+ const kept = truncated ? events.slice(events.length - MAX_TIMELINE_EVENTS) : events;
179
+
180
+ return { events: kept, truncated };
181
+ }