@giantswarm-io/pro 1.4.0 → 1.6.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,8 @@ 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
+ - **`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.
208
+
207
209
  ### Write Tools
208
210
 
209
211
  - **`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.
@@ -214,6 +216,10 @@ The `board` parameter defaults to `"roadmap"` on every board-scoped tool for bac
214
216
 
215
217
  - **`archive_item`** -- Archive a project item from the active board view.
216
218
 
219
+ - **`close_issue`** -- Close the GitHub issue underlying a single project item. Board-independent (queries by item ID). Accepts an optional `stateReason` (`"completed"` or `"not_planned"`, defaults to `"completed"`; any other value returns an error) and an optional `comment` posted before closing. Comments on issues in public repos require `confirmPublicSafe=true`. One item per call -- no bulk close. Closing the issue does not update the board's Status field; unless the board has GitHub's built-in "item closed -> set Status" workflow enabled, pair this with `update_issue_field` if the board Status should reflect the closure.
220
+
221
+ - **`reopen_issue`** -- Reopen the GitHub issue underlying a single project item. Board-independent (queries by item ID). Accepts an optional `comment` posted before reopening. Comments on issues in public repos require `confirmPublicSafe=true`. One item per call -- no bulk reopen. Reopening the issue does not update the board's Status field; unless the board has GitHub's built-in "item closed -> set Status" workflow enabled, pair this with `update_issue_field` if the board Status should reflect the reopening.
222
+
217
223
  - **`update_issue_labels`** -- Add and/or remove labels on the issue underlying a project item. Board-independent (queries by item ID). At least one of `addLabels`/`removeLabels` is required. Labels being added must already exist in the repository -- non-existent labels are rejected with a clear error instead of being auto-created. `added` and `removed` in the response both reflect effective changes only -- labels not already present pre-call for `added`, labels that were actually present pre-call for `removed` -- rather than echoing the requested sets.
218
224
 
219
225
  ## MCP Resources
@@ -232,7 +238,7 @@ Resources are provided per board. Read the schema resource before querying to un
232
238
  - `giantswarm/roadmap` is public. Use it only for sanitized, public-safe issue content.
233
239
  - `giantswarm/giantswarm` is internal/private. Use it for internal and customer-specific operational details.
234
240
  - Customer board issues live in private customer repositories (e.g. `giantswarm/<customer>`). The board itself is a public GitHub project, but issue content is only visible to users with repository access.
235
- - The server enforces an explicit confirmation (`confirmPublicSafe=true`) before creating issues in `giantswarm/roadmap`.
241
+ - The server enforces an explicit confirmation (`confirmPublicSafe=true`) before creating issues in `giantswarm/roadmap`, and before posting a comment via `close_issue`/`reopen_issue` on an issue in any public repository.
236
242
 
237
243
  ## Example Conversations
238
244
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giantswarm-io/pro",
3
- "version": "1.4.0",
3
+ "version": "1.6.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/lib/items.js CHANGED
@@ -151,6 +151,8 @@ function resolveRepositoryName(repository) {
151
151
  * @param {string} [options.state] - Filter by issue state: "open" or "closed"
152
152
  * @param {string} [options.keyword] - Free text search matching titles and text fields
153
153
  * @param {string} [options.updated] - Filter by last-updated date (e.g. ">@today-7d")
154
+ * @param {string} [options.created] - Filter by creation date (e.g. ">@today-90d")
155
+ * @param {string} [options.closed] - Filter by closed date (e.g. ">@today-30d")
154
156
  * @param {string} [options.reason] - Filter by close reason: "completed", "not planned", or "reopened"
155
157
  * @param {string} [options.token] - Optional per-request GitHub token
156
158
  * @returns {Promise<Object>} - Result with status and data
@@ -161,7 +163,7 @@ export async function listItems(options) {
161
163
  const {
162
164
  boardId, repository = null, filters = {}, emptyFields = [],
163
165
  assignee = null, label = null, state = null, keyword = null,
164
- updated = null, reason = null, token
166
+ updated = null, created = null, closed = null, reason = null, token
165
167
  } = options;
166
168
 
167
169
  if (!boardId) {
@@ -222,6 +224,24 @@ export async function listItems(options) {
222
224
  }
223
225
  }
224
226
 
227
+ // Created date filter — same GitHub Projects query syntax as `updated`.
228
+ // Examples: ">@today-90d", "<@today-30d", "@today", ">2025-01-01"
229
+ if (created) {
230
+ const trimmed = created.trim();
231
+ if (trimmed) {
232
+ queryTerms.push(`created:${trimmed}`);
233
+ }
234
+ }
235
+
236
+ // Closed date filter — same GitHub Projects query syntax as `updated`.
237
+ // Examples: ">@today-30d", "<@today-7d", "@today", ">2025-01-01"
238
+ if (closed) {
239
+ const trimmed = closed.trim();
240
+ if (trimmed) {
241
+ queryTerms.push(`closed:${trimmed}`);
242
+ }
243
+ }
244
+
225
245
  // Close reason filter
226
246
  if (reason) {
227
247
  const trimmed = reason.trim();
@@ -387,10 +407,14 @@ export async function listItems(options) {
387
407
  url: item.content?.url,
388
408
  repo: item.content?.repository?.nameWithOwner || null,
389
409
  private: item.content?.repository?.isPrivate ?? null,
410
+ state: item.content?.state || null,
411
+ createdAt: item.content?.createdAt || null,
412
+ updatedAt: item.content?.updatedAt || null,
390
413
  fields
391
414
  };
392
415
 
393
- // Only include assignees and labels when non-empty to keep output compact
416
+ // Only include closedAt, assignees, and labels when non-empty to keep output compact
417
+ if (item.content?.closedAt) entry.closedAt = item.content.closedAt;
394
418
  if (assignees.length > 0) entry.assignees = assignees;
395
419
  if (labels.length > 0) entry.labels = labels;
396
420
 
@@ -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,13 +1,15 @@
1
1
  /**
2
2
  * MCP Tools Implementation
3
3
  *
4
- * Exposes 7 tools for managing Giant Swarm project boards:
4
+ * Exposes 9 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
8
8
  * - create_issue_in_project: Create a new issue and add to a board
9
9
  * - add_existing_issue: Add an existing issue to a board
10
10
  * - archive_item: Archive a project item
11
+ * - close_issue: Close the issue underlying a project item
12
+ * - reopen_issue: Reopen the issue underlying a project item
11
13
  * - update_issue_labels: Add and/or remove labels on an issue
12
14
  */
13
15
 
@@ -25,10 +27,15 @@ import {
25
27
  ARCHIVE_ITEM_MUTATION,
26
28
  ISSUE_NODE_ID_QUERY,
27
29
  UPDATE_ITEM_FIELD_MUTATION,
28
- USER_ID_QUERY
30
+ USER_ID_QUERY,
31
+ ITEM_ISSUE_ID_QUERY,
32
+ CLOSE_ISSUE_MUTATION,
33
+ REOPEN_ISSUE_MUTATION,
34
+ ADD_COMMENT_MUTATION
29
35
  } from '../project.js';
30
36
  import { logger } from '../logger.js';
31
37
  import { subIssueTools, subIssueToolHandlers } from './sub-issues.js';
38
+ import { timelineTools, timelineToolHandlers } from './timeline.js';
32
39
 
33
40
  const BOARD_NAMES = Object.keys(BOARDS);
34
41
 
@@ -42,13 +49,29 @@ function extractToken(extra) {
42
49
  return extra?.authInfo?.token;
43
50
  }
44
51
 
52
+ /**
53
+ * Resolve a project item ID to its underlying GitHub issue (id, number, state, url,
54
+ * and repository visibility).
55
+ * @param {string} itemId - The project item ID
56
+ * @param {string} [token] - Optional per-request GitHub token
57
+ * @returns {Promise<{id: string, number: number, state: string, url: string, repository: {isPrivate: boolean, nameWithOwner: string}}>}
58
+ */
59
+ async function resolveItemIssueId(itemId, token) {
60
+ const result = await graphQLWithAuth(ITEM_ISSUE_ID_QUERY, { itemId }, token);
61
+ const issue = result?.node?.content;
62
+ if (!issue?.id) {
63
+ throw new Error(`Could not resolve an underlying issue for item '${itemId}'`);
64
+ }
65
+ return issue;
66
+ }
67
+
45
68
  // ---------------------------------------------------------------------------
46
69
  // Tool: list_issues
47
70
  // ---------------------------------------------------------------------------
48
71
 
49
72
  export const listIssuesTool = {
50
73
  name: 'list_issues',
51
- description: 'List and filter issues from a project board (roadmap or customer). Uses generic field filters -- read the board\'s schema resource first (e.g. roadmap://schema or customer://schema) to discover available fields and valid option values. Returns compact items with `repo` (nameWithOwner), `private` flag, and a `fields` map (only non-empty values). The repo URL is always https://github.com/{repo}.',
74
+ description: 'List and filter issues from a project board (roadmap or customer). Uses generic field filters -- read the board\'s schema resource first (e.g. roadmap://schema or customer://schema) to discover available fields and valid option values. Returns compact items with `repo` (nameWithOwner), `private` flag, `state` (OPEN/CLOSED), `createdAt`/`updatedAt` timestamps, `closedAt` (only present when the item is closed), and a `fields` map (only non-empty values). The repo URL is always https://github.com/{repo}.',
52
75
  inputSchema: {
53
76
  type: 'object',
54
77
  properties: {
@@ -92,6 +115,14 @@ export const listIssuesTool = {
92
115
  type: 'string',
93
116
  description: 'Filter by last-updated date using GitHub Projects syntax. Examples: ">@today-7d" (updated in last 7 days), "<@today-30d" (not updated in last 30 days), "@today" (updated today), ">2025-01-01" (updated after a specific date).'
94
117
  },
118
+ created: {
119
+ type: 'string',
120
+ description: 'Filter by creation date using GitHub Projects syntax. Examples: ">@today-90d" (created in last 90 days), "<@today-365d" (created more than a year ago), ">2025-01-01" (created after a specific date).'
121
+ },
122
+ closed: {
123
+ type: 'string',
124
+ description: 'Filter by closed date using GitHub Projects syntax. Only applies to closed items. Examples: ">@today-30d" (closed in last 30 days), "@today" (closed today), ">2025-01-01" (closed after a specific date).'
125
+ },
95
126
  reason: {
96
127
  type: 'string',
97
128
  enum: ['completed', 'not planned', 'reopened'],
@@ -101,9 +132,9 @@ export const listIssuesTool = {
101
132
  }
102
133
  };
103
134
 
104
- const KNOWN_LIST_PARAMS = new Set([
135
+ export const KNOWN_LIST_PARAMS = new Set([
105
136
  'board', 'project', 'repository', 'filters', 'emptyFields',
106
- 'assignee', 'label', 'state', 'keyword', 'updated', 'reason'
137
+ 'assignee', 'label', 'state', 'keyword', 'updated', 'created', 'closed', 'reason'
107
138
  ]);
108
139
 
109
140
  // Board field names are single words (Team, Kind, Status), so simple
@@ -130,7 +161,8 @@ export async function handleListIssues(args, extra) {
130
161
  board, repository: args.repository, filters,
131
162
  emptyFields: args.emptyFields, assignee: args.assignee,
132
163
  label: args.label, state: args.state, keyword: args.keyword,
133
- updated: args.updated, reason: args.reason
164
+ updated: args.updated, created: args.created, closed: args.closed,
165
+ reason: args.reason
134
166
  });
135
167
 
136
168
  const result = await listItems({
@@ -143,6 +175,8 @@ export async function handleListIssues(args, extra) {
143
175
  state: args.state || null,
144
176
  keyword: args.keyword || null,
145
177
  updated: args.updated || null,
178
+ created: args.created || null,
179
+ closed: args.closed || null,
146
180
  reason: args.reason || null,
147
181
  token
148
182
  });
@@ -621,6 +655,153 @@ export async function handleArchiveItem(args, extra) {
621
655
  }
622
656
  }
623
657
 
658
+ // ---------------------------------------------------------------------------
659
+ // Tool: close_issue
660
+ // ---------------------------------------------------------------------------
661
+
662
+ export const closeIssueTool = {
663
+ name: 'close_issue',
664
+ description: 'Close the GitHub issue underlying a single project board item. Board-independent (queries by item ID). Optionally posts a comment before closing. Operates on exactly one item per call -- there is no bulk close. Comments on issues in public repos require confirmPublicSafe=true. This does not change the board\'s Status field -- unless the board has GitHub\'s built-in "item closed -> set Status" workflow enabled, pair this call with update_issue_field if the board Status should reflect the closure.',
665
+ inputSchema: {
666
+ type: 'object',
667
+ properties: {
668
+ itemId: {
669
+ type: 'string',
670
+ description: 'The project item ID whose underlying issue should be closed'
671
+ },
672
+ stateReason: {
673
+ type: 'string',
674
+ enum: ['completed', 'not_planned'],
675
+ description: 'Why the issue is being closed. Defaults to "completed".'
676
+ },
677
+ comment: {
678
+ type: 'string',
679
+ description: 'Optional comment to post on the issue before closing it'
680
+ },
681
+ confirmPublicSafe: {
682
+ type: 'boolean',
683
+ description: 'Required when comment is provided and the underlying issue is in a public repository. Must be true to confirm the comment is sanitized and safe for public visibility.'
684
+ }
685
+ },
686
+ required: ['itemId']
687
+ }
688
+ };
689
+
690
+ export async function handleCloseIssue(args, extra) {
691
+ try {
692
+ const token = extractToken(extra);
693
+ logger.info('MCP: Closing issue', { itemId: args.itemId, stateReason: args.stateReason });
694
+
695
+ // Validate stateReason before any network calls -- an invalid value must not
696
+ // have side effects (e.g. posting a comment) before the error is returned.
697
+ let stateReason;
698
+ if (!args.stateReason) {
699
+ stateReason = 'COMPLETED';
700
+ } else if (args.stateReason === 'completed') {
701
+ stateReason = 'COMPLETED';
702
+ } else if (args.stateReason === 'not_planned') {
703
+ stateReason = 'NOT_PLANNED';
704
+ } else {
705
+ return { error: `Invalid stateReason '${args.stateReason}'. Must be "completed" or "not_planned".` };
706
+ }
707
+
708
+ const issue = await resolveItemIssueId(args.itemId, token);
709
+
710
+ if (args.comment) {
711
+ if (issue.repository?.isPrivate === false && args.confirmPublicSafe !== true) {
712
+ return {
713
+ error: `Posting a comment to ${issue.repository.nameWithOwner} (public) requires confirmPublicSafe=true to reduce accidental disclosure of internal or customer-specific information.`
714
+ };
715
+ }
716
+ await graphQLWithAuth(ADD_COMMENT_MUTATION, { subjectId: issue.id, body: args.comment }, token);
717
+ }
718
+
719
+ const result = await graphQLWithAuth(CLOSE_ISSUE_MUTATION, { issueId: issue.id, stateReason }, token);
720
+ const closed = result.closeIssue.issue;
721
+
722
+ return {
723
+ content: [{
724
+ type: 'text',
725
+ text: JSON.stringify({
726
+ success: true,
727
+ itemId: args.itemId,
728
+ issueUrl: closed.url,
729
+ state: closed.state,
730
+ stateReason: closed.stateReason,
731
+ commentPosted: Boolean(args.comment)
732
+ })
733
+ }]
734
+ };
735
+ } catch (error) {
736
+ logger.error('MCP: Error closing issue', { error: error.message });
737
+ return { error: error.message };
738
+ }
739
+ }
740
+
741
+ // ---------------------------------------------------------------------------
742
+ // Tool: reopen_issue
743
+ // ---------------------------------------------------------------------------
744
+
745
+ export const reopenIssueTool = {
746
+ name: 'reopen_issue',
747
+ description: 'Reopen the GitHub issue underlying a single project board item. Board-independent (queries by item ID). Optionally posts a comment before reopening. Operates on exactly one item per call -- there is no bulk reopen. Comments on issues in public repos require confirmPublicSafe=true. This does not change the board\'s Status field -- unless the board has GitHub\'s built-in "item closed -> set Status" workflow enabled, pair this call with update_issue_field if the board Status should reflect the reopening.',
748
+ inputSchema: {
749
+ type: 'object',
750
+ properties: {
751
+ itemId: {
752
+ type: 'string',
753
+ description: 'The project item ID whose underlying issue should be reopened'
754
+ },
755
+ comment: {
756
+ type: 'string',
757
+ description: 'Optional comment to post on the issue before reopening it'
758
+ },
759
+ confirmPublicSafe: {
760
+ type: 'boolean',
761
+ description: 'Required when comment is provided and the underlying issue is in a public repository. Must be true to confirm the comment is sanitized and safe for public visibility.'
762
+ }
763
+ },
764
+ required: ['itemId']
765
+ }
766
+ };
767
+
768
+ export async function handleReopenIssue(args, extra) {
769
+ try {
770
+ const token = extractToken(extra);
771
+ logger.info('MCP: Reopening issue', { itemId: args.itemId });
772
+
773
+ const issue = await resolveItemIssueId(args.itemId, token);
774
+
775
+ if (args.comment) {
776
+ if (issue.repository?.isPrivate === false && args.confirmPublicSafe !== true) {
777
+ return {
778
+ error: `Posting a comment to ${issue.repository.nameWithOwner} (public) requires confirmPublicSafe=true to reduce accidental disclosure of internal or customer-specific information.`
779
+ };
780
+ }
781
+ await graphQLWithAuth(ADD_COMMENT_MUTATION, { subjectId: issue.id, body: args.comment }, token);
782
+ }
783
+
784
+ const result = await graphQLWithAuth(REOPEN_ISSUE_MUTATION, { issueId: issue.id }, token);
785
+ const reopened = result.reopenIssue.issue;
786
+
787
+ return {
788
+ content: [{
789
+ type: 'text',
790
+ text: JSON.stringify({
791
+ success: true,
792
+ itemId: args.itemId,
793
+ issueUrl: reopened.url,
794
+ state: reopened.state,
795
+ commentPosted: Boolean(args.comment)
796
+ })
797
+ }]
798
+ };
799
+ } catch (error) {
800
+ logger.error('MCP: Error reopening issue', { error: error.message });
801
+ return { error: error.message };
802
+ }
803
+ }
804
+
624
805
  // ---------------------------------------------------------------------------
625
806
  // Tool: update_issue_labels
626
807
  // ---------------------------------------------------------------------------
@@ -737,8 +918,11 @@ export const tools = [
737
918
  createIssueInProjectTool,
738
919
  addExistingIssueTool,
739
920
  archiveItemTool,
921
+ closeIssueTool,
922
+ reopenIssueTool,
740
923
  updateIssueLabelsTool,
741
- ...subIssueTools
924
+ ...subIssueTools,
925
+ ...timelineTools
742
926
  ];
743
927
 
744
928
  export const toolHandlers = {
@@ -748,6 +932,9 @@ export const toolHandlers = {
748
932
  create_issue_in_project: handleCreateIssueInProject,
749
933
  add_existing_issue: handleAddExistingIssue,
750
934
  archive_item: handleArchiveItem,
935
+ close_issue: handleCloseIssue,
936
+ reopen_issue: handleReopenIssue,
751
937
  update_issue_labels: handleUpdateIssueLabels,
752
- ...subIssueToolHandlers
938
+ ...subIssueToolHandlers,
939
+ ...timelineToolHandlers
753
940
  };
@@ -171,6 +171,10 @@ const LIST_ITEMS_QUERY = `
171
171
  title
172
172
  number
173
173
  url
174
+ state
175
+ createdAt
176
+ updatedAt
177
+ closedAt
174
178
  repository {
175
179
  nameWithOwner
176
180
  isPrivate
@@ -391,6 +395,74 @@ const USER_ID_QUERY = `
391
395
  }
392
396
  `;
393
397
 
398
+ // Query to resolve the underlying issue node ID for a project item, including
399
+ // the repository's visibility so callers can gate free-text writes (e.g. comments)
400
+ // to public repos behind an explicit confirmation.
401
+ const ITEM_ISSUE_ID_QUERY = `
402
+ query GetItemIssueId($itemId: ID!) {
403
+ node(id: $itemId) {
404
+ ... on ProjectV2Item {
405
+ content {
406
+ ... on Issue {
407
+ id
408
+ number
409
+ state
410
+ url
411
+ repository {
412
+ isPrivate
413
+ nameWithOwner
414
+ }
415
+ }
416
+ }
417
+ }
418
+ }
419
+ }
420
+ `;
421
+
422
+ // Mutation to close an issue
423
+ const CLOSE_ISSUE_MUTATION = `
424
+ mutation CloseIssue($issueId: ID!, $stateReason: IssueClosedStateReason) {
425
+ closeIssue(input: { issueId: $issueId, stateReason: $stateReason }) {
426
+ issue {
427
+ id
428
+ number
429
+ state
430
+ stateReason
431
+ url
432
+ }
433
+ }
434
+ }
435
+ `;
436
+
437
+ // Mutation to reopen an issue
438
+ const REOPEN_ISSUE_MUTATION = `
439
+ mutation ReopenIssue($issueId: ID!) {
440
+ reopenIssue(input: { issueId: $issueId }) {
441
+ issue {
442
+ id
443
+ number
444
+ state
445
+ url
446
+ }
447
+ }
448
+ }
449
+ `;
450
+
451
+ // Mutation to add a comment to an issue (used to post a comment before
452
+ // closing/reopening when the caller supplies one)
453
+ const ADD_COMMENT_MUTATION = `
454
+ mutation AddComment($subjectId: ID!, $body: String!) {
455
+ addComment(input: { subjectId: $subjectId, body: $body }) {
456
+ commentEdge {
457
+ node {
458
+ id
459
+ url
460
+ }
461
+ }
462
+ }
463
+ }
464
+ `;
465
+
394
466
  export {
395
467
  REPO_ID_QUERY,
396
468
  LIST_ITEMS_QUERY,
@@ -402,5 +474,9 @@ export {
402
474
  ADD_ITEM_TO_PROJECT_MUTATION,
403
475
  ARCHIVE_ITEM_MUTATION,
404
476
  ISSUE_NODE_ID_QUERY,
405
- USER_ID_QUERY
477
+ USER_ID_QUERY,
478
+ ITEM_ISSUE_ID_QUERY,
479
+ CLOSE_ISSUE_MUTATION,
480
+ REOPEN_ISSUE_MUTATION,
481
+ ADD_COMMENT_MUTATION
406
482
  };
@@ -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
+ }