maxsimcli 4.5.0 → 4.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.
Files changed (221) hide show
  1. package/dist/assets/CHANGELOG.md +38 -0
  2. package/dist/backend-server.cjs +2739 -41
  3. package/dist/backend-server.cjs.map +1 -1
  4. package/dist/cli.cjs +3 -3
  5. package/dist/{lifecycle-DxCru7rk.cjs → lifecycle-D8mcsEjy.cjs} +2 -2
  6. package/dist/{lifecycle-DxCru7rk.cjs.map → lifecycle-D8mcsEjy.cjs.map} +1 -1
  7. package/dist/mcp-server.cjs +2715 -16
  8. package/dist/mcp-server.cjs.map +1 -1
  9. package/dist/{server-By0TN-nC.cjs → server-BAHfh_vw.cjs} +2716 -17
  10. package/dist/server-BAHfh_vw.cjs.map +1 -0
  11. package/package.json +1 -1
  12. package/dist/.tsbuildinfo +0 -1
  13. package/dist/backend/index.d.ts +0 -4
  14. package/dist/backend/index.d.ts.map +0 -1
  15. package/dist/backend/index.js +0 -12
  16. package/dist/backend/index.js.map +0 -1
  17. package/dist/backend/lifecycle.d.ts +0 -13
  18. package/dist/backend/lifecycle.d.ts.map +0 -1
  19. package/dist/backend/lifecycle.js +0 -168
  20. package/dist/backend/lifecycle.js.map +0 -1
  21. package/dist/backend/server.d.ts +0 -13
  22. package/dist/backend/server.d.ts.map +0 -1
  23. package/dist/backend/server.js +0 -1013
  24. package/dist/backend/server.js.map +0 -1
  25. package/dist/backend/terminal.d.ts +0 -49
  26. package/dist/backend/terminal.d.ts.map +0 -1
  27. package/dist/backend/terminal.js +0 -209
  28. package/dist/backend/terminal.js.map +0 -1
  29. package/dist/backend/types.d.ts +0 -77
  30. package/dist/backend/types.d.ts.map +0 -1
  31. package/dist/backend/types.js +0 -6
  32. package/dist/backend/types.js.map +0 -1
  33. package/dist/backend-server.d.cts +0 -2
  34. package/dist/backend-server.d.ts +0 -11
  35. package/dist/backend-server.d.ts.map +0 -1
  36. package/dist/backend-server.js +0 -43
  37. package/dist/backend-server.js.map +0 -1
  38. package/dist/cli.d.cts +0 -2
  39. package/dist/cli.d.ts +0 -7
  40. package/dist/cli.d.ts.map +0 -1
  41. package/dist/cli.js +0 -510
  42. package/dist/cli.js.map +0 -1
  43. package/dist/core/artefakte.d.ts +0 -12
  44. package/dist/core/artefakte.d.ts.map +0 -1
  45. package/dist/core/artefakte.js +0 -152
  46. package/dist/core/artefakte.js.map +0 -1
  47. package/dist/core/commands.d.ts +0 -26
  48. package/dist/core/commands.d.ts.map +0 -1
  49. package/dist/core/commands.js +0 -550
  50. package/dist/core/commands.js.map +0 -1
  51. package/dist/core/config.d.ts +0 -10
  52. package/dist/core/config.d.ts.map +0 -1
  53. package/dist/core/config.js +0 -143
  54. package/dist/core/config.js.map +0 -1
  55. package/dist/core/context-loader.d.ts +0 -21
  56. package/dist/core/context-loader.d.ts.map +0 -1
  57. package/dist/core/context-loader.js +0 -212
  58. package/dist/core/context-loader.js.map +0 -1
  59. package/dist/core/core.d.ts +0 -91
  60. package/dist/core/core.d.ts.map +0 -1
  61. package/dist/core/core.js +0 -823
  62. package/dist/core/core.js.map +0 -1
  63. package/dist/core/dashboard-launcher.d.ts +0 -56
  64. package/dist/core/dashboard-launcher.d.ts.map +0 -1
  65. package/dist/core/dashboard-launcher.js +0 -246
  66. package/dist/core/dashboard-launcher.js.map +0 -1
  67. package/dist/core/drift.d.ts +0 -37
  68. package/dist/core/drift.d.ts.map +0 -1
  69. package/dist/core/drift.js +0 -213
  70. package/dist/core/drift.js.map +0 -1
  71. package/dist/core/frontmatter.d.ts +0 -33
  72. package/dist/core/frontmatter.d.ts.map +0 -1
  73. package/dist/core/frontmatter.js +0 -193
  74. package/dist/core/frontmatter.js.map +0 -1
  75. package/dist/core/index.d.ts +0 -28
  76. package/dist/core/index.d.ts.map +0 -1
  77. package/dist/core/index.js +0 -189
  78. package/dist/core/index.js.map +0 -1
  79. package/dist/core/init.d.ts +0 -287
  80. package/dist/core/init.d.ts.map +0 -1
  81. package/dist/core/init.js +0 -816
  82. package/dist/core/init.js.map +0 -1
  83. package/dist/core/milestone.d.ts +0 -9
  84. package/dist/core/milestone.d.ts.map +0 -1
  85. package/dist/core/milestone.js +0 -230
  86. package/dist/core/milestone.js.map +0 -1
  87. package/dist/core/phase.d.ts +0 -53
  88. package/dist/core/phase.d.ts.map +0 -1
  89. package/dist/core/phase.js +0 -891
  90. package/dist/core/phase.js.map +0 -1
  91. package/dist/core/roadmap.d.ts +0 -10
  92. package/dist/core/roadmap.d.ts.map +0 -1
  93. package/dist/core/roadmap.js +0 -165
  94. package/dist/core/roadmap.js.map +0 -1
  95. package/dist/core/skills.d.ts +0 -20
  96. package/dist/core/skills.d.ts.map +0 -1
  97. package/dist/core/skills.js +0 -144
  98. package/dist/core/skills.js.map +0 -1
  99. package/dist/core/start.d.ts +0 -15
  100. package/dist/core/start.d.ts.map +0 -1
  101. package/dist/core/start.js +0 -80
  102. package/dist/core/start.js.map +0 -1
  103. package/dist/core/state.d.ts +0 -32
  104. package/dist/core/state.d.ts.map +0 -1
  105. package/dist/core/state.js +0 -582
  106. package/dist/core/state.js.map +0 -1
  107. package/dist/core/template.d.ts +0 -30
  108. package/dist/core/template.d.ts.map +0 -1
  109. package/dist/core/template.js +0 -223
  110. package/dist/core/template.js.map +0 -1
  111. package/dist/core/types.d.ts +0 -519
  112. package/dist/core/types.d.ts.map +0 -1
  113. package/dist/core/types.js +0 -60
  114. package/dist/core/types.js.map +0 -1
  115. package/dist/core/verify.d.ts +0 -128
  116. package/dist/core/verify.d.ts.map +0 -1
  117. package/dist/core/verify.js +0 -754
  118. package/dist/core/verify.js.map +0 -1
  119. package/dist/hooks/index.d.ts +0 -11
  120. package/dist/hooks/index.d.ts.map +0 -1
  121. package/dist/hooks/index.js +0 -18
  122. package/dist/hooks/index.js.map +0 -1
  123. package/dist/hooks/maxsim-check-update.d.ts +0 -17
  124. package/dist/hooks/maxsim-check-update.d.ts.map +0 -1
  125. package/dist/hooks/maxsim-check-update.js +0 -101
  126. package/dist/hooks/maxsim-check-update.js.map +0 -1
  127. package/dist/hooks/maxsim-context-monitor.d.ts +0 -21
  128. package/dist/hooks/maxsim-context-monitor.d.ts.map +0 -1
  129. package/dist/hooks/maxsim-context-monitor.js +0 -131
  130. package/dist/hooks/maxsim-context-monitor.js.map +0 -1
  131. package/dist/hooks/maxsim-statusline.d.ts +0 -19
  132. package/dist/hooks/maxsim-statusline.d.ts.map +0 -1
  133. package/dist/hooks/maxsim-statusline.js +0 -146
  134. package/dist/hooks/maxsim-statusline.js.map +0 -1
  135. package/dist/hooks/shared.d.ts +0 -11
  136. package/dist/hooks/shared.d.ts.map +0 -1
  137. package/dist/hooks/shared.js +0 -29
  138. package/dist/hooks/shared.js.map +0 -1
  139. package/dist/index.d.ts +0 -2
  140. package/dist/index.d.ts.map +0 -1
  141. package/dist/index.js +0 -3
  142. package/dist/index.js.map +0 -1
  143. package/dist/install/adapters.d.ts +0 -6
  144. package/dist/install/adapters.d.ts.map +0 -1
  145. package/dist/install/adapters.js +0 -65
  146. package/dist/install/adapters.js.map +0 -1
  147. package/dist/install/copy.d.ts +0 -6
  148. package/dist/install/copy.d.ts.map +0 -1
  149. package/dist/install/copy.js +0 -71
  150. package/dist/install/copy.js.map +0 -1
  151. package/dist/install/dashboard.d.ts +0 -16
  152. package/dist/install/dashboard.d.ts.map +0 -1
  153. package/dist/install/dashboard.js +0 -273
  154. package/dist/install/dashboard.js.map +0 -1
  155. package/dist/install/hooks.d.ts +0 -31
  156. package/dist/install/hooks.d.ts.map +0 -1
  157. package/dist/install/hooks.js +0 -260
  158. package/dist/install/hooks.js.map +0 -1
  159. package/dist/install/index.d.ts +0 -2
  160. package/dist/install/index.d.ts.map +0 -1
  161. package/dist/install/index.js +0 -534
  162. package/dist/install/index.js.map +0 -1
  163. package/dist/install/manifest.d.ts +0 -23
  164. package/dist/install/manifest.d.ts.map +0 -1
  165. package/dist/install/manifest.js +0 -133
  166. package/dist/install/manifest.js.map +0 -1
  167. package/dist/install/patches.d.ts +0 -10
  168. package/dist/install/patches.d.ts.map +0 -1
  169. package/dist/install/patches.js +0 -124
  170. package/dist/install/patches.js.map +0 -1
  171. package/dist/install/shared.d.ts +0 -56
  172. package/dist/install/shared.d.ts.map +0 -1
  173. package/dist/install/shared.js +0 -181
  174. package/dist/install/shared.js.map +0 -1
  175. package/dist/install/uninstall.d.ts +0 -5
  176. package/dist/install/uninstall.d.ts.map +0 -1
  177. package/dist/install/uninstall.js +0 -222
  178. package/dist/install/uninstall.js.map +0 -1
  179. package/dist/install/utils.d.ts +0 -27
  180. package/dist/install/utils.d.ts.map +0 -1
  181. package/dist/install/utils.js +0 -99
  182. package/dist/install/utils.js.map +0 -1
  183. package/dist/install.d.cts +0 -2
  184. package/dist/mcp/config-tools.d.ts +0 -13
  185. package/dist/mcp/config-tools.d.ts.map +0 -1
  186. package/dist/mcp/config-tools.js +0 -66
  187. package/dist/mcp/config-tools.js.map +0 -1
  188. package/dist/mcp/context-tools.d.ts +0 -13
  189. package/dist/mcp/context-tools.d.ts.map +0 -1
  190. package/dist/mcp/context-tools.js +0 -176
  191. package/dist/mcp/context-tools.js.map +0 -1
  192. package/dist/mcp/index.d.ts +0 -11
  193. package/dist/mcp/index.d.ts.map +0 -1
  194. package/dist/mcp/index.js +0 -26
  195. package/dist/mcp/index.js.map +0 -1
  196. package/dist/mcp/phase-tools.d.ts +0 -13
  197. package/dist/mcp/phase-tools.d.ts.map +0 -1
  198. package/dist/mcp/phase-tools.js +0 -177
  199. package/dist/mcp/phase-tools.js.map +0 -1
  200. package/dist/mcp/roadmap-tools.d.ts +0 -13
  201. package/dist/mcp/roadmap-tools.d.ts.map +0 -1
  202. package/dist/mcp/roadmap-tools.js +0 -79
  203. package/dist/mcp/roadmap-tools.js.map +0 -1
  204. package/dist/mcp/state-tools.d.ts +0 -13
  205. package/dist/mcp/state-tools.d.ts.map +0 -1
  206. package/dist/mcp/state-tools.js +0 -185
  207. package/dist/mcp/state-tools.js.map +0 -1
  208. package/dist/mcp/todo-tools.d.ts +0 -13
  209. package/dist/mcp/todo-tools.d.ts.map +0 -1
  210. package/dist/mcp/todo-tools.js +0 -143
  211. package/dist/mcp/todo-tools.js.map +0 -1
  212. package/dist/mcp/utils.d.ts +0 -27
  213. package/dist/mcp/utils.d.ts.map +0 -1
  214. package/dist/mcp/utils.js +0 -82
  215. package/dist/mcp/utils.js.map +0 -1
  216. package/dist/mcp-server.d.cts +0 -2
  217. package/dist/mcp-server.d.ts +0 -12
  218. package/dist/mcp-server.d.ts.map +0 -1
  219. package/dist/mcp-server.js +0 -31
  220. package/dist/mcp-server.js.map +0 -1
  221. package/dist/server-By0TN-nC.cjs.map +0 -1
@@ -4,6 +4,7 @@ let node_fs = require("node:fs");
4
4
  node_fs = require_cli.__toESM(node_fs);
5
5
  let node_path = require("node:path");
6
6
  node_path = require_cli.__toESM(node_path);
7
+ let node_child_process = require("node:child_process");
7
8
  let node_os = require("node:os");
8
9
  node_os = require_cli.__toESM(node_os);
9
10
  let node_http = require("node:http");
@@ -15,7 +16,1464 @@ let _modelcontextprotocol_sdk_server_streamableHttp_js = require("@modelcontextp
15
16
  let detect_port = require("detect-port");
16
17
  detect_port = require_cli.__toESM(detect_port);
17
18
  let zod = require("zod");
19
+ let node_util = require("node:util");
18
20
 
21
+ //#region src/github/gh.ts
22
+ /**
23
+ * GitHub CLI Wrapper — Core gh CLI interaction layer
24
+ *
25
+ * Wraps the `gh` CLI using `child_process.execFile` (never `exec`) for security.
26
+ * Provides typed results via GhResult<T> discriminated union.
27
+ * Supports graceful degradation: detectGitHubMode() returns 'local-only'
28
+ * when gh is not installed or not authenticated with required scopes.
29
+ *
30
+ * CRITICAL: Never import octokit or any npm GitHub SDK.
31
+ * CRITICAL: Never call process.exit() — return GhResult instead.
32
+ */
33
+ const execFileAsync = (0, node_util.promisify)(node_child_process.execFile);
34
+ /**
35
+ * Check if the `gh` CLI is installed and authenticated with required scopes.
36
+ *
37
+ * Parses the output of `gh auth status` (which writes to stderr, not stdout).
38
+ * Returns structured AuthStatus with scope detection for 'project' scope.
39
+ * Timeout: 10 seconds.
40
+ */
41
+ async function checkGhAuth() {
42
+ try {
43
+ const { stdout, stderr } = await execFileAsync("gh", ["auth", "status"], { timeout: 1e4 });
44
+ const output = stderr || stdout;
45
+ const authenticated = !output.includes("not logged in");
46
+ const scopeMatch = output.match(/Token scopes?:\s*'([^']+(?:',\s*'[^']+)*)'/);
47
+ const scopes = [];
48
+ if (scopeMatch) {
49
+ const allScopes = scopeMatch[0].matchAll(/'([^']+)'/g);
50
+ for (const m of allScopes) scopes.push(m[1]);
51
+ }
52
+ const userMatch = output.match(/Logged in to [^\s]+ as ([^\s(]+)/);
53
+ return {
54
+ installed: true,
55
+ authenticated,
56
+ scopes,
57
+ hasProjectScope: scopes.includes("project") || scopes.includes("read:project"),
58
+ username: userMatch ? userMatch[1] : null
59
+ };
60
+ } catch (e) {
61
+ const error = e;
62
+ if (error.code === "ENOENT") return {
63
+ installed: false,
64
+ authenticated: false,
65
+ scopes: [],
66
+ hasProjectScope: false,
67
+ username: null
68
+ };
69
+ error.stderr || error.message;
70
+ return {
71
+ installed: true,
72
+ authenticated: false,
73
+ scopes: [],
74
+ hasProjectScope: false,
75
+ username: null
76
+ };
77
+ }
78
+ }
79
+ /**
80
+ * Detect the GitHub integration mode based on auth status.
81
+ *
82
+ * Returns 'full' only when gh is installed, authenticated, and has the
83
+ * 'project' scope. Otherwise returns 'local-only' for graceful degradation.
84
+ */
85
+ async function detectGitHubMode() {
86
+ const auth = await checkGhAuth();
87
+ if (!auth.installed) return "local-only";
88
+ if (!auth.authenticated) return "local-only";
89
+ if (!auth.hasProjectScope) {
90
+ console.error("[maxsim] GitHub Projects requires 'project' scope. Run: gh auth refresh -s project");
91
+ return "local-only";
92
+ }
93
+ return "full";
94
+ }
95
+ /**
96
+ * Execute a `gh` CLI command and return a typed GhResult.
97
+ *
98
+ * - Uses `execFile` (not `exec`) for security
99
+ * - Default timeout: 30 seconds
100
+ * - Auto-detects JSON output when args contain `--json` or `--format`
101
+ * - Maps exit codes and stderr patterns to GhErrorCode
102
+ * - For `gh issue create`: does NOT try to parse JSON (it returns a URL string)
103
+ * - Always includes raw stderr in error messages for AI consumption
104
+ */
105
+ async function ghExec(args, options) {
106
+ const timeout = options?.timeout ?? 3e4;
107
+ const isIssueCreate = args[0] === "issue" && args[1] === "create";
108
+ const hasJsonFlag = args.includes("--json") || args.some((a) => a.startsWith("--format"));
109
+ const shouldParseJson = options?.parseJson ?? (hasJsonFlag && !isIssueCreate);
110
+ try {
111
+ const { stdout, stderr } = await execFileAsync("gh", args, {
112
+ cwd: options?.cwd,
113
+ timeout,
114
+ maxBuffer: 10 * 1024 * 1024
115
+ });
116
+ if (shouldParseJson) try {
117
+ return {
118
+ ok: true,
119
+ data: JSON.parse(stdout)
120
+ };
121
+ } catch {
122
+ return {
123
+ ok: false,
124
+ error: `Failed to parse gh output as JSON: ${stdout.slice(0, 500)}`,
125
+ code: "UNKNOWN"
126
+ };
127
+ }
128
+ return {
129
+ ok: true,
130
+ data: stdout.trim()
131
+ };
132
+ } catch (e) {
133
+ return mapExecError(e);
134
+ }
135
+ }
136
+ /**
137
+ * Execute a GraphQL query via `gh api graphql`.
138
+ *
139
+ * - String variables use `-f key=value`
140
+ * - Non-string variables (numbers, booleans) use `-F key=value`
141
+ * - Parses JSON response and checks for GraphQL `errors` array
142
+ */
143
+ async function ghGraphQL(query, variables) {
144
+ const args = [
145
+ "api",
146
+ "graphql",
147
+ "-f",
148
+ `query=${query}`
149
+ ];
150
+ if (variables) for (const [key, value] of Object.entries(variables)) if (typeof value === "string") args.push("-f", `${key}=${value}`);
151
+ else args.push("-F", `${key}=${String(value)}`);
152
+ const result = await ghExec(args, { parseJson: true });
153
+ if (!result.ok) return result;
154
+ if (result.data.errors && result.data.errors.length > 0) {
155
+ const messages = result.data.errors.map((e) => e.message).join("; ");
156
+ const code = mapGraphQLErrorCode(messages);
157
+ return {
158
+ ok: false,
159
+ error: `GraphQL error: ${messages}`,
160
+ code
161
+ };
162
+ }
163
+ if (result.data.data === void 0) return {
164
+ ok: false,
165
+ error: "GraphQL response missing data field",
166
+ code: "UNKNOWN"
167
+ };
168
+ return {
169
+ ok: true,
170
+ data: result.data.data
171
+ };
172
+ }
173
+ /**
174
+ * Map an execFile error to a GhResult with appropriate GhErrorCode.
175
+ */
176
+ function mapExecError(e) {
177
+ const error = e;
178
+ if (error.code === "ENOENT") return {
179
+ ok: false,
180
+ error: "gh CLI is not installed. Install from https://cli.github.com/",
181
+ code: "NOT_INSTALLED"
182
+ };
183
+ const stderr = error.stderr || error.message || "";
184
+ if (error.status === 4) return {
185
+ ok: false,
186
+ error: `Not found: ${stderr}`,
187
+ code: "NOT_FOUND"
188
+ };
189
+ if (stderr.includes("not logged in") || stderr.includes("authentication") || stderr.includes("auth login") || stderr.includes("401")) return {
190
+ ok: false,
191
+ error: `Authentication required: ${stderr}`,
192
+ code: "NOT_AUTHENTICATED"
193
+ };
194
+ if (stderr.includes("403") || stderr.includes("permission") || stderr.includes("denied")) return {
195
+ ok: false,
196
+ error: `Permission denied: ${stderr}`,
197
+ code: "PERMISSION_DENIED"
198
+ };
199
+ if (stderr.includes("rate limit") || stderr.includes("429") || stderr.includes("API rate")) return {
200
+ ok: false,
201
+ error: `Rate limited: ${stderr}`,
202
+ code: "RATE_LIMITED"
203
+ };
204
+ if (stderr.includes("scope") || stderr.includes("insufficient")) return {
205
+ ok: false,
206
+ error: `Missing scope: ${stderr}`,
207
+ code: "SCOPE_MISSING"
208
+ };
209
+ if (stderr.includes("not found") || stderr.includes("404") || stderr.includes("Could not resolve")) return {
210
+ ok: false,
211
+ error: `Not found: ${stderr}`,
212
+ code: "NOT_FOUND"
213
+ };
214
+ return {
215
+ ok: false,
216
+ error: `gh command failed: ${stderr}`,
217
+ code: "UNKNOWN"
218
+ };
219
+ }
220
+ /**
221
+ * Map GraphQL error messages to GhErrorCode.
222
+ */
223
+ function mapGraphQLErrorCode(message) {
224
+ const lower = message.toLowerCase();
225
+ if (lower.includes("not found") || lower.includes("could not resolve")) return "NOT_FOUND";
226
+ if (lower.includes("insufficient") || lower.includes("scope")) return "SCOPE_MISSING";
227
+ if (lower.includes("forbidden") || lower.includes("permission")) return "PERMISSION_DENIED";
228
+ if (lower.includes("rate") || lower.includes("throttl")) return "RATE_LIMITED";
229
+ return "UNKNOWN";
230
+ }
231
+
232
+ //#endregion
233
+ //#region src/github/mapping.ts
234
+ /**
235
+ * GitHub Issues Mapping — Persistence layer for github-issues.json
236
+ *
237
+ * Manages the `.planning/github-issues.json` file that maps MAXSIM tasks/todos
238
+ * to their corresponding GitHub issue numbers, node IDs, and project item IDs.
239
+ *
240
+ * All file operations use synchronous fs (matching the pattern in existing core modules).
241
+ * Uses planningPath() from core to construct file paths.
242
+ *
243
+ * CRITICAL: Never call process.exit() — throw or return null instead.
244
+ */
245
+ const MAPPING_FILENAME = "github-issues.json";
246
+ /**
247
+ * Get the absolute path to `.planning/github-issues.json` for a given cwd.
248
+ */
249
+ function mappingFilePath(cwd) {
250
+ return require_cli.planningPath(cwd, MAPPING_FILENAME);
251
+ }
252
+ /**
253
+ * Load and parse the mapping file.
254
+ *
255
+ * Returns null if the file does not exist.
256
+ * Throws on malformed JSON or invalid structure (missing required fields).
257
+ */
258
+ function loadMapping(cwd) {
259
+ const filePath = mappingFilePath(cwd);
260
+ try {
261
+ node_fs.default.statSync(filePath);
262
+ } catch {
263
+ return null;
264
+ }
265
+ const raw = node_fs.default.readFileSync(filePath, "utf-8");
266
+ const parsed = JSON.parse(raw);
267
+ if (typeof parsed.project_number !== "number" || typeof parsed.repo !== "string") throw new Error(`Invalid github-issues.json: missing required fields 'project_number' (number) and 'repo' (string)`);
268
+ return parsed;
269
+ }
270
+ /**
271
+ * Write the mapping file to `.planning/github-issues.json`.
272
+ *
273
+ * Creates the `.planning/` directory if it does not exist.
274
+ * Writes with 2-space indent for readability and diff-friendliness.
275
+ */
276
+ function saveMapping(cwd, mapping) {
277
+ const filePath = mappingFilePath(cwd);
278
+ const dir = node_path.default.dirname(filePath);
279
+ node_fs.default.mkdirSync(dir, { recursive: true });
280
+ node_fs.default.writeFileSync(filePath, JSON.stringify(mapping, null, 2) + "\n", "utf-8");
281
+ }
282
+ /**
283
+ * Update a specific task's issue mapping within a phase.
284
+ *
285
+ * Load-modify-save pattern. Creates phase entry if it does not exist.
286
+ * Merges partial data with existing entry (if any).
287
+ *
288
+ * @throws If mapping file does not exist (must be initialized first via saveMapping)
289
+ */
290
+ function updateTaskMapping(cwd, phaseNum, taskId, data) {
291
+ const mapping = loadMapping(cwd);
292
+ if (!mapping) throw new Error("github-issues.json does not exist. Run project setup first.");
293
+ if (!mapping.phases[phaseNum]) mapping.phases[phaseNum] = {
294
+ tracking_issue: {
295
+ number: 0,
296
+ node_id: "",
297
+ item_id: "",
298
+ status: "To Do"
299
+ },
300
+ plan: "",
301
+ tasks: {}
302
+ };
303
+ const existing = mapping.phases[phaseNum].tasks[taskId];
304
+ const defaults = {
305
+ number: 0,
306
+ node_id: "",
307
+ item_id: "",
308
+ status: "To Do"
309
+ };
310
+ mapping.phases[phaseNum].tasks[taskId] = Object.assign(defaults, existing, data);
311
+ saveMapping(cwd, mapping);
312
+ }
313
+ /**
314
+ * Update a specific todo's issue mapping.
315
+ *
316
+ * Load-modify-save pattern. Creates `todos` section if missing.
317
+ * Merges partial data with existing entry (if any).
318
+ *
319
+ * @throws If mapping file does not exist (must be initialized first via saveMapping)
320
+ */
321
+ function updateTodoMapping(cwd, todoId, data) {
322
+ const mapping = loadMapping(cwd);
323
+ if (!mapping) throw new Error("github-issues.json does not exist. Run project setup first.");
324
+ if (!mapping.todos) mapping.todos = {};
325
+ const existing = mapping.todos[todoId];
326
+ const defaults = {
327
+ number: 0,
328
+ node_id: "",
329
+ item_id: "",
330
+ status: "To Do"
331
+ };
332
+ mapping.todos[todoId] = Object.assign(defaults, existing, data);
333
+ saveMapping(cwd, mapping);
334
+ }
335
+ /**
336
+ * Create a properly typed empty mapping object with sensible defaults.
337
+ *
338
+ * Used during initial project setup to create the mapping file.
339
+ */
340
+ function createEmptyMapping(repo) {
341
+ return {
342
+ project_number: 0,
343
+ project_id: "",
344
+ repo,
345
+ status_field_id: "",
346
+ status_options: {},
347
+ estimate_field_id: "",
348
+ milestone_id: 0,
349
+ milestone_title: "",
350
+ labels: {},
351
+ phases: {},
352
+ todos: {}
353
+ };
354
+ }
355
+
356
+ //#endregion
357
+ //#region src/github/issues.ts
358
+ /**
359
+ * Parse an issue number from a `gh issue create` stdout URL.
360
+ *
361
+ * `gh issue create` outputs a URL like:
362
+ * https://github.com/owner/repo/issues/42\n
363
+ *
364
+ * We trim whitespace and extract the last path segment as the issue number.
365
+ */
366
+ function parseIssueNumberFromUrl(stdout) {
367
+ const lastSegment = stdout.trim().split("/").pop();
368
+ if (!lastSegment) return null;
369
+ const num = parseInt(lastSegment, 10);
370
+ return Number.isNaN(num) ? null : num;
371
+ }
372
+ /**
373
+ * After creating an issue (parsed number from URL), fetch its node_id
374
+ * via `gh issue view {number} --json nodeId,number,url`.
375
+ */
376
+ async function fetchIssueDetails(issueNumber) {
377
+ const result = await ghExec([
378
+ "issue",
379
+ "view",
380
+ String(issueNumber),
381
+ "--json",
382
+ "nodeId,number,url"
383
+ ], { parseJson: true });
384
+ if (!result.ok) return {
385
+ ok: false,
386
+ error: result.error,
387
+ code: result.code
388
+ };
389
+ return {
390
+ ok: true,
391
+ data: {
392
+ number: result.data.number,
393
+ url: result.data.url,
394
+ node_id: result.data.nodeId
395
+ }
396
+ };
397
+ }
398
+ /**
399
+ * Create a task issue with full specification body in collapsible details section.
400
+ *
401
+ * Title format: `[P{phaseNum}] {title}`
402
+ * Body includes summary, actions, acceptance criteria, dependencies in `<details>`.
403
+ * Labels: maxsim, phase-task.
404
+ *
405
+ * Returns the issue number, URL, and node_id.
406
+ */
407
+ async function createTaskIssue(opts) {
408
+ const issueTitle = `[P${opts.phaseNum}] ${opts.title}`;
409
+ const depsSection = opts.dependencies && opts.dependencies.length > 0 ? `\n### Dependencies\nDepends on: ${opts.dependencies.map((d) => `#${d}`).join(", ")}\n` : "";
410
+ const estimateSection = opts.estimate !== void 0 ? `\n### Estimate\n${opts.estimate} points\n` : "";
411
+ const args = [
412
+ "issue",
413
+ "create",
414
+ "--title",
415
+ issueTitle,
416
+ "--body",
417
+ `## Summary
418
+ ${opts.summary}
419
+
420
+ <details>
421
+ <summary>Full Specification</summary>
422
+
423
+ ### Actions
424
+ ${opts.actions.map((a) => `- ${a}`).join("\n")}
425
+
426
+ ### Acceptance Criteria
427
+ ${opts.acceptanceCriteria.map((c) => `- [ ] ${c}`).join("\n")}
428
+ ${depsSection}${estimateSection}
429
+ </details>
430
+
431
+ ---
432
+ *Phase: ${opts.phaseNum} | Plan: ${opts.planNum} | Task: ${opts.taskId}*
433
+ *Generated by MAXSIM*`
434
+ ];
435
+ args.push("--label", "maxsim");
436
+ args.push("--label", "phase-task");
437
+ if (opts.labels) for (const label of opts.labels) args.push("--label", label);
438
+ if (opts.milestone) args.push("--milestone", opts.milestone);
439
+ if (opts.projectTitle) args.push("--project", opts.projectTitle);
440
+ const createResult = await ghExec(args);
441
+ if (!createResult.ok) return {
442
+ ok: false,
443
+ error: createResult.error,
444
+ code: createResult.code
445
+ };
446
+ const issueNumber = parseIssueNumberFromUrl(createResult.data);
447
+ if (issueNumber === null) return {
448
+ ok: false,
449
+ error: `Failed to parse issue number from gh output: ${createResult.data}`,
450
+ code: "UNKNOWN"
451
+ };
452
+ return fetchIssueDetails(issueNumber);
453
+ }
454
+ /**
455
+ * Create a parent tracking issue for a phase with a live checkbox task list.
456
+ *
457
+ * Title format: `[Phase {phaseNum}] {phaseName}`
458
+ * Body includes task list with checkbox links: `- [ ] #{childNumber}`
459
+ * Labels: maxsim, phase-task.
460
+ */
461
+ async function createParentTrackingIssue(opts) {
462
+ const issueTitle = `[Phase ${opts.phaseNum}] ${opts.phaseName}`;
463
+ const taskList = opts.childIssueNumbers.map((n) => `- [ ] #${n}`).join("\n");
464
+ const args = [
465
+ "issue",
466
+ "create",
467
+ "--title",
468
+ issueTitle,
469
+ "--body",
470
+ `## Phase ${opts.phaseNum}: ${opts.phaseName}
471
+
472
+ ### Tasks
473
+ ${taskList}
474
+
475
+ ---
476
+ *Phase tracking issue -- Generated by MAXSIM*`
477
+ ];
478
+ args.push("--label", "maxsim");
479
+ args.push("--label", "phase-task");
480
+ if (opts.milestone) args.push("--milestone", opts.milestone);
481
+ if (opts.projectTitle) args.push("--project", opts.projectTitle);
482
+ const createResult = await ghExec(args);
483
+ if (!createResult.ok) return {
484
+ ok: false,
485
+ error: createResult.error,
486
+ code: createResult.code
487
+ };
488
+ const issueNumber = parseIssueNumberFromUrl(createResult.data);
489
+ if (issueNumber === null) return {
490
+ ok: false,
491
+ error: `Failed to parse issue number from gh output: ${createResult.data}`,
492
+ code: "UNKNOWN"
493
+ };
494
+ return fetchIssueDetails(issueNumber);
495
+ }
496
+ /**
497
+ * Create a todo issue with a lighter body (no collapsible details section).
498
+ *
499
+ * Labels: maxsim, todo.
500
+ */
501
+ async function createTodoIssue(opts) {
502
+ let body = "";
503
+ if (opts.description) body += `${opts.description}\n`;
504
+ if (opts.acceptanceCriteria && opts.acceptanceCriteria.length > 0) {
505
+ body += `\n### Acceptance Criteria\n`;
506
+ body += opts.acceptanceCriteria.map((c) => `- [ ] ${c}`).join("\n");
507
+ body += "\n";
508
+ }
509
+ body += `\n---\n*Generated by MAXSIM*`;
510
+ const args = [
511
+ "issue",
512
+ "create",
513
+ "--title",
514
+ opts.title,
515
+ "--body",
516
+ body
517
+ ];
518
+ args.push("--label", "maxsim");
519
+ args.push("--label", "todo");
520
+ if (opts.milestone) args.push("--milestone", opts.milestone);
521
+ if (opts.projectTitle) args.push("--project", opts.projectTitle);
522
+ const createResult = await ghExec(args);
523
+ if (!createResult.ok) return {
524
+ ok: false,
525
+ error: createResult.error,
526
+ code: createResult.code
527
+ };
528
+ const issueNumber = parseIssueNumberFromUrl(createResult.data);
529
+ if (issueNumber === null) return {
530
+ ok: false,
531
+ error: `Failed to parse issue number from gh output: ${createResult.data}`,
532
+ code: "UNKNOWN"
533
+ };
534
+ return fetchIssueDetails(issueNumber);
535
+ }
536
+ /**
537
+ * Build a PR description body with `Closes #{N}` lines for auto-close on merge (AC-08).
538
+ *
539
+ * This function is called by `mcp_create_pr` in Plan 04's github-tools.ts.
540
+ */
541
+ function buildPrBody(closesIssues, additionalContent) {
542
+ return `${closesIssues.map((n) => `Closes #${n}`).join("\n")}${additionalContent ? `\n\n${additionalContent}` : ""}`;
543
+ }
544
+ /**
545
+ * Close an issue with an optional reason.
546
+ *
547
+ * Reason defaults to 'completed' if not specified.
548
+ */
549
+ async function closeIssue(issueNumber, reason) {
550
+ const args = [
551
+ "issue",
552
+ "close",
553
+ String(issueNumber)
554
+ ];
555
+ if (reason) args.push("--reason", reason);
556
+ const result = await ghExec(args);
557
+ if (!result.ok) return {
558
+ ok: false,
559
+ error: result.error,
560
+ code: result.code
561
+ };
562
+ return {
563
+ ok: true,
564
+ data: void 0
565
+ };
566
+ }
567
+ /**
568
+ * Close an issue as superseded by a newer issue.
569
+ *
570
+ * 1. Posts "Superseded by #{newIssueNumber}" comment on old issue
571
+ * 2. Adds 'superseded' label to old issue
572
+ * 3. Closes old issue as completed
573
+ * 4. Posts "Replaces #{oldIssueNumber}" comment on new issue
574
+ *
575
+ * Creates bidirectional cross-references.
576
+ */
577
+ async function closeIssueAsSuperseded(oldIssueNumber, newIssueNumber) {
578
+ const commentResult = await postComment(oldIssueNumber, `Superseded by #${newIssueNumber}`);
579
+ if (!commentResult.ok) return {
580
+ ok: false,
581
+ error: commentResult.error,
582
+ code: commentResult.code
583
+ };
584
+ const labelResult = await ghExec([
585
+ "issue",
586
+ "edit",
587
+ String(oldIssueNumber),
588
+ "--add-label",
589
+ "superseded"
590
+ ]);
591
+ if (!labelResult.ok) return {
592
+ ok: false,
593
+ error: labelResult.error,
594
+ code: labelResult.code
595
+ };
596
+ const closeResult = await closeIssue(oldIssueNumber, "completed");
597
+ if (!closeResult.ok) return closeResult;
598
+ const replaceCommentResult = await postComment(newIssueNumber, `Replaces #${oldIssueNumber}`);
599
+ if (!replaceCommentResult.ok) return {
600
+ ok: false,
601
+ error: replaceCommentResult.error,
602
+ code: replaceCommentResult.code
603
+ };
604
+ return {
605
+ ok: true,
606
+ data: void 0
607
+ };
608
+ }
609
+ /**
610
+ * Post a comment on an issue.
611
+ */
612
+ async function postComment(issueNumber, body) {
613
+ const result = await ghExec([
614
+ "issue",
615
+ "comment",
616
+ String(issueNumber),
617
+ "--body",
618
+ body
619
+ ]);
620
+ if (!result.ok) return {
621
+ ok: false,
622
+ error: result.error,
623
+ code: result.code
624
+ };
625
+ return {
626
+ ok: true,
627
+ data: void 0
628
+ };
629
+ }
630
+ /**
631
+ * Import an existing external GitHub issue into MAXSIM tracking.
632
+ *
633
+ * Reads the issue details and adds 'maxsim' and 'imported' labels.
634
+ * Returns the issue details for the AI to decide placement.
635
+ */
636
+ async function importExternalIssue(issueNumber) {
637
+ const viewResult = await ghExec([
638
+ "issue",
639
+ "view",
640
+ String(issueNumber),
641
+ "--json",
642
+ "title,labels,body,state"
643
+ ], { parseJson: true });
644
+ if (!viewResult.ok) return {
645
+ ok: false,
646
+ error: viewResult.error,
647
+ code: viewResult.code
648
+ };
649
+ const labelResult = await ghExec([
650
+ "issue",
651
+ "edit",
652
+ String(issueNumber),
653
+ "--add-label",
654
+ "maxsim,imported"
655
+ ]);
656
+ if (!labelResult.ok) return {
657
+ ok: false,
658
+ error: labelResult.error,
659
+ code: labelResult.code
660
+ };
661
+ const existingLabels = viewResult.data.labels.map((l) => l.name);
662
+ const allLabels = Array.from(new Set([
663
+ ...existingLabels,
664
+ "maxsim",
665
+ "imported"
666
+ ]));
667
+ return {
668
+ ok: true,
669
+ data: {
670
+ number: issueNumber,
671
+ title: viewResult.data.title,
672
+ labels: allLabels
673
+ }
674
+ };
675
+ }
676
+ /**
677
+ * Update the parent tracking issue's task list checkbox.
678
+ *
679
+ * Reads the parent issue body, finds `- [ ] #{childNumber}` or `- [x] #{childNumber}`,
680
+ * toggles the checkbox, and updates the issue body via `gh issue edit`.
681
+ */
682
+ async function updateParentTaskList(parentIssueNumber, childIssueNumber, checked) {
683
+ const viewResult = await ghExec([
684
+ "issue",
685
+ "view",
686
+ String(parentIssueNumber),
687
+ "--json",
688
+ "body"
689
+ ], { parseJson: true });
690
+ if (!viewResult.ok) return {
691
+ ok: false,
692
+ error: viewResult.error,
693
+ code: viewResult.code
694
+ };
695
+ const currentBody = viewResult.data.body;
696
+ const checkboxPattern = new RegExp(`- \\[([ x])\\] #${childIssueNumber}\\b`, "g");
697
+ const newCheckState = checked ? "x" : " ";
698
+ const updatedBody = currentBody.replace(checkboxPattern, `- [${newCheckState}] #${childIssueNumber}`);
699
+ if (updatedBody === currentBody) return {
700
+ ok: true,
701
+ data: void 0
702
+ };
703
+ const editResult = await ghExec([
704
+ "issue",
705
+ "edit",
706
+ String(parentIssueNumber),
707
+ "--body",
708
+ updatedBody
709
+ ]);
710
+ if (!editResult.ok) return {
711
+ ok: false,
712
+ error: editResult.error,
713
+ code: editResult.code
714
+ };
715
+ return {
716
+ ok: true,
717
+ data: void 0
718
+ };
719
+ }
720
+ /**
721
+ * Create all issues for a plan at once (eager creation on plan finalization).
722
+ *
723
+ * 1. Creates all task issues with concurrency limit of 5 (rate limit safety).
724
+ * 2. After all task issues created, creates parent tracking issue.
725
+ * 3. Updates mapping file for all created issues.
726
+ * 4. Returns parent issue number and all task issue numbers.
727
+ *
728
+ * Handles partial failures: continues batch, reports which failed.
729
+ */
730
+ async function createAllPlanIssues(opts) {
731
+ const BATCH_SIZE = 5;
732
+ const results = [];
733
+ const failures = [];
734
+ for (let i = 0; i < opts.tasks.length; i += BATCH_SIZE) {
735
+ const batchPromises = opts.tasks.slice(i, i + BATCH_SIZE).map(async (task) => {
736
+ let depIssueNumbers;
737
+ if (task.dependencies && task.dependencies.length > 0) depIssueNumbers = task.dependencies.map((depId) => {
738
+ const found = results.find((r) => r.taskId === depId);
739
+ return found ? found.issueNumber : 0;
740
+ }).filter((n) => n > 0);
741
+ const result = await createTaskIssue({
742
+ title: task.title,
743
+ phaseNum: opts.phaseNum,
744
+ planNum: opts.planNum,
745
+ taskId: task.taskId,
746
+ summary: task.summary,
747
+ actions: task.actions,
748
+ acceptanceCriteria: task.acceptanceCriteria,
749
+ dependencies: depIssueNumbers,
750
+ milestone: opts.milestone,
751
+ projectTitle: opts.projectTitle,
752
+ estimate: task.estimate
753
+ });
754
+ return {
755
+ taskId: task.taskId,
756
+ result
757
+ };
758
+ });
759
+ const batchResults = await Promise.all(batchPromises);
760
+ for (const { taskId, result } of batchResults) if (result.ok) results.push({
761
+ taskId,
762
+ issueNumber: result.data.number,
763
+ nodeId: result.data.node_id
764
+ });
765
+ else failures.push({
766
+ taskId,
767
+ error: result.error
768
+ });
769
+ }
770
+ if (results.length === 0) return {
771
+ ok: false,
772
+ error: `All task issue creations failed: ${failures.map((f) => `${f.taskId}: ${f.error}`).join("; ")}`,
773
+ code: "UNKNOWN"
774
+ };
775
+ const childNumbers = results.map((r) => r.issueNumber);
776
+ const parentResult = await createParentTrackingIssue({
777
+ phaseNum: opts.phaseNum,
778
+ phaseName: opts.phaseName,
779
+ childIssueNumbers: childNumbers,
780
+ milestone: opts.milestone,
781
+ projectTitle: opts.projectTitle
782
+ });
783
+ if (!parentResult.ok) return {
784
+ ok: false,
785
+ error: `Task issues created but parent tracking issue failed: ${parentResult.error}`,
786
+ code: parentResult.code
787
+ };
788
+ const mapping = loadMapping(opts.cwd);
789
+ if (mapping) {
790
+ if (!mapping.phases[opts.phaseNum]) mapping.phases[opts.phaseNum] = {
791
+ tracking_issue: {
792
+ number: 0,
793
+ node_id: "",
794
+ item_id: "",
795
+ status: "To Do"
796
+ },
797
+ plan: "",
798
+ tasks: {}
799
+ };
800
+ mapping.phases[opts.phaseNum].tracking_issue = {
801
+ number: parentResult.data.number,
802
+ node_id: parentResult.data.node_id,
803
+ item_id: "",
804
+ status: "To Do"
805
+ };
806
+ mapping.phases[opts.phaseNum].plan = `${opts.phaseNum}-${opts.planNum}`;
807
+ for (const r of results) mapping.phases[opts.phaseNum].tasks[r.taskId] = {
808
+ number: r.issueNumber,
809
+ node_id: r.nodeId,
810
+ item_id: "",
811
+ status: "To Do"
812
+ };
813
+ saveMapping(opts.cwd, mapping);
814
+ }
815
+ const taskIssues = results.map((r) => ({
816
+ taskId: r.taskId,
817
+ issueNumber: r.issueNumber
818
+ }));
819
+ return {
820
+ ok: true,
821
+ data: {
822
+ parentIssue: parentResult.data.number,
823
+ taskIssues
824
+ }
825
+ };
826
+ }
827
+ /**
828
+ * Supersede old plan's issues when a plan is re-planned (fresh issues per plan).
829
+ *
830
+ * 1. Load mapping to find old plan's issue numbers.
831
+ * 2. For each old issue, close as superseded with cross-reference to new issue.
832
+ * 3. Close old parent tracking issue as superseded.
833
+ * 4. Update mapping: mark old entries, add new entries.
834
+ */
835
+ async function supersedePlanIssues(opts) {
836
+ const mapping = loadMapping(opts.cwd);
837
+ if (!mapping) return {
838
+ ok: false,
839
+ error: "github-issues.json does not exist. Run project setup first.",
840
+ code: "NOT_FOUND"
841
+ };
842
+ const phase = mapping.phases[opts.phaseNum];
843
+ if (!phase) return {
844
+ ok: false,
845
+ error: `No phase ${opts.phaseNum} found in mapping file`,
846
+ code: "NOT_FOUND"
847
+ };
848
+ const currentPlan = phase.plan;
849
+ const expectedOldPlan = `${opts.phaseNum}-${opts.oldPlanNum}`;
850
+ if (currentPlan !== expectedOldPlan) return {
851
+ ok: false,
852
+ error: `Phase ${opts.phaseNum} is on plan '${currentPlan}', expected '${expectedOldPlan}'`,
853
+ code: "UNKNOWN"
854
+ };
855
+ const failures = [];
856
+ const oldTasks = Object.entries(phase.tasks);
857
+ for (const [taskId, oldTask] of oldTasks) {
858
+ const newIssue = opts.newIssueNumbers.find((n) => n.taskId === taskId);
859
+ if (!newIssue) {
860
+ const closeResult = await closeIssue(oldTask.number, "completed");
861
+ if (!closeResult.ok) failures.push(`close task ${taskId} (#${oldTask.number}): ${closeResult.error}`);
862
+ continue;
863
+ }
864
+ const supersedeResult = await closeIssueAsSuperseded(oldTask.number, newIssue.issueNumber);
865
+ if (!supersedeResult.ok) failures.push(`supersede task ${taskId} (#${oldTask.number} -> #${newIssue.issueNumber}): ${supersedeResult.error}`);
866
+ }
867
+ if (phase.tracking_issue.number > 0) {
868
+ const closeResult = await closeIssue(phase.tracking_issue.number, "completed");
869
+ if (!closeResult.ok) failures.push(`close parent tracking issue #${phase.tracking_issue.number}: ${closeResult.error}`);
870
+ }
871
+ phase.plan = `${opts.phaseNum}-${opts.newPlanNum}`;
872
+ phase.tasks = {};
873
+ for (const newIssue of opts.newIssueNumbers) phase.tasks[newIssue.taskId] = {
874
+ number: newIssue.issueNumber,
875
+ node_id: "",
876
+ item_id: "",
877
+ status: "To Do"
878
+ };
879
+ saveMapping(opts.cwd, mapping);
880
+ if (failures.length > 0) return {
881
+ ok: false,
882
+ error: `Partial failure during supersession: ${failures.join("; ")}`,
883
+ code: "UNKNOWN"
884
+ };
885
+ return {
886
+ ok: true,
887
+ data: void 0
888
+ };
889
+ }
890
+
891
+ //#endregion
892
+ //#region src/github/projects.ts
893
+ /**
894
+ * Extract error info from a failed GhResult and re-wrap it for a different
895
+ * generic type. This avoids TypeScript narrowing issues with discriminated
896
+ * union property access.
897
+ */
898
+ function fail$2(result) {
899
+ return {
900
+ ok: false,
901
+ error: result.error,
902
+ code: result.code
903
+ };
904
+ }
905
+ /**
906
+ * Create a new GitHub Projects v2 board.
907
+ *
908
+ * Runs `gh project create --owner @me --title "{title}" --format json`.
909
+ * Returns the project number and node ID.
910
+ */
911
+ async function createProjectBoard(title) {
912
+ const result = await ghExec([
913
+ "project",
914
+ "create",
915
+ "--owner",
916
+ "@me",
917
+ "--title",
918
+ title,
919
+ "--format",
920
+ "json"
921
+ ], { parseJson: true });
922
+ if (!result.ok) return result;
923
+ return {
924
+ ok: true,
925
+ data: {
926
+ number: result.data.number,
927
+ id: result.data.id
928
+ }
929
+ };
930
+ }
931
+ /**
932
+ * Ensure a project board exists, creating it if needed.
933
+ *
934
+ * Checks the mapping file for an existing project. If found, verifies it
935
+ * still exists via `gh project view`. If not found, creates a new board
936
+ * and sets up fields and status options.
937
+ *
938
+ * Returns the project number, ID, and whether it was newly created.
939
+ */
940
+ async function ensureProjectBoard(title, cwd) {
941
+ const mapping = loadMapping(cwd);
942
+ if (mapping && mapping.project_number > 0 && mapping.project_id) {
943
+ if ((await ghExec([
944
+ "project",
945
+ "view",
946
+ String(mapping.project_number),
947
+ "--owner",
948
+ "@me",
949
+ "--format",
950
+ "json"
951
+ ], { parseJson: true })).ok) return {
952
+ ok: true,
953
+ data: {
954
+ number: mapping.project_number,
955
+ id: mapping.project_id,
956
+ created: false
957
+ }
958
+ };
959
+ }
960
+ const createResult = await createProjectBoard(title);
961
+ if (!createResult.ok) return fail$2(createResult);
962
+ const { number, id } = createResult.data;
963
+ const setupResult = await setupProjectFields(number, id, cwd);
964
+ if (!setupResult.ok) return fail$2(setupResult);
965
+ return {
966
+ ok: true,
967
+ data: {
968
+ number,
969
+ id,
970
+ created: true
971
+ }
972
+ };
973
+ }
974
+ /**
975
+ * Get all fields for a project board.
976
+ *
977
+ * Runs `gh project field-list {num} --owner @me --format json`.
978
+ * Returns field list with IDs, names, types, and options (for single-select).
979
+ */
980
+ async function getProjectFields(projectNum) {
981
+ const result = await ghExec([
982
+ "project",
983
+ "field-list",
984
+ String(projectNum),
985
+ "--owner",
986
+ "@me",
987
+ "--format",
988
+ "json"
989
+ ], { parseJson: true });
990
+ if (!result.ok) return fail$2(result);
991
+ return {
992
+ ok: true,
993
+ data: result.data.fields ?? result.data
994
+ };
995
+ }
996
+ /**
997
+ * Add a new single-select option to a project field via GraphQL.
998
+ *
999
+ * The `updateProjectV2Field` mutation REPLACES all options, so all existing
1000
+ * options must be included alongside the new one.
1001
+ *
1002
+ * Returns the new option's ID.
1003
+ */
1004
+ async function addStatusOption(projectId, statusFieldId, optionName, existingOptions) {
1005
+ const result = await ghGraphQL(`
1006
+ mutation {
1007
+ updateProjectV2Field(input: {
1008
+ projectId: "${projectId}"
1009
+ fieldId: "${statusFieldId}"
1010
+ singleSelectOptions: [${[...existingOptions.map((o) => `{name: "${o.name}", description: "", color: GRAY}`), `{name: "${optionName}", description: "", color: BLUE}`].join(", ")}]
1011
+ }) {
1012
+ projectV2Field {
1013
+ ... on ProjectV2SingleSelectField {
1014
+ options { id name }
1015
+ }
1016
+ }
1017
+ }
1018
+ }
1019
+ `);
1020
+ if (!result.ok) return fail$2(result);
1021
+ const newOption = result.data.updateProjectV2Field.projectV2Field.options.find((o) => o.name === optionName);
1022
+ if (!newOption) return {
1023
+ ok: false,
1024
+ error: `Option "${optionName}" was not found after mutation — it may have been renamed or rejected`,
1025
+ code: "UNKNOWN"
1026
+ };
1027
+ return {
1028
+ ok: true,
1029
+ data: newOption.id
1030
+ };
1031
+ }
1032
+ /**
1033
+ * Set up project fields: Status options and Estimate number field.
1034
+ *
1035
+ * Orchestrates the full field setup:
1036
+ * (a) Get existing fields
1037
+ * (b) Find Status field, verify "In Review" option exists or add it
1038
+ * (c) Create Estimate NUMBER field via `gh project field-create`
1039
+ * (d) Store all field/option IDs in the mapping file
1040
+ */
1041
+ async function setupProjectFields(projectNum, projectId, cwd) {
1042
+ const fieldsResult = await getProjectFields(projectNum);
1043
+ if (!fieldsResult.ok) return fail$2(fieldsResult);
1044
+ const fields = fieldsResult.data;
1045
+ const statusField = fields.find((f) => f.name === "Status" && (f.type === "SINGLE_SELECT" || f.type === "ProjectV2SingleSelectField"));
1046
+ if (!statusField) return {
1047
+ ok: false,
1048
+ error: "Status field not found on project board. This is unexpected for a Projects v2 board.",
1049
+ code: "NOT_FOUND"
1050
+ };
1051
+ const statusOptions = statusField.options ?? [];
1052
+ const statusOptionsMap = {};
1053
+ for (const opt of statusOptions) statusOptionsMap[opt.name] = opt.id;
1054
+ if (!statusOptionsMap["In Review"]) {
1055
+ const addResult = await addStatusOption(projectId, statusField.id, "In Review", statusOptions);
1056
+ if (!addResult.ok) return fail$2(addResult);
1057
+ statusOptionsMap["In Review"] = addResult.data;
1058
+ }
1059
+ if (statusOptionsMap["Todo"] && !statusOptionsMap["To Do"]) statusOptionsMap["To Do"] = statusOptionsMap["Todo"];
1060
+ const estimateField = fields.find((f) => f.name === "Estimate");
1061
+ let estimateFieldId = estimateField?.id ?? "";
1062
+ if (!estimateField) {
1063
+ const createFieldResult = await ghExec([
1064
+ "project",
1065
+ "field-create",
1066
+ String(projectNum),
1067
+ "--owner",
1068
+ "@me",
1069
+ "--name",
1070
+ "Estimate",
1071
+ "--data-type",
1072
+ "NUMBER"
1073
+ ]);
1074
+ if (!createFieldResult.ok) return fail$2(createFieldResult);
1075
+ const refetch = await getProjectFields(projectNum);
1076
+ if (refetch.ok) {
1077
+ const est = refetch.data.find((f) => f.name === "Estimate");
1078
+ if (est) estimateFieldId = est.id;
1079
+ }
1080
+ }
1081
+ const repoResult = await ghExec([
1082
+ "repo",
1083
+ "view",
1084
+ "--json",
1085
+ "nameWithOwner",
1086
+ "--jq",
1087
+ ".nameWithOwner"
1088
+ ]);
1089
+ const repo = repoResult.ok ? repoResult.data.trim() : "";
1090
+ const mapping = loadMapping(cwd) ?? createEmptyMapping(repo);
1091
+ mapping.project_number = projectNum;
1092
+ mapping.project_id = projectId;
1093
+ mapping.status_field_id = statusField.id;
1094
+ mapping.status_options = statusOptionsMap;
1095
+ mapping.estimate_field_id = estimateFieldId;
1096
+ if (repo && !mapping.repo) mapping.repo = repo;
1097
+ saveMapping(cwd, mapping);
1098
+ return {
1099
+ ok: true,
1100
+ data: void 0
1101
+ };
1102
+ }
1103
+ /**
1104
+ * Add an issue to a project board.
1105
+ *
1106
+ * Runs `gh project item-add {num} --owner @me --url {issueUrl} --format json`.
1107
+ * Returns the project item ID (different from the issue ID).
1108
+ */
1109
+ async function addItemToProject(projectNum, issueUrl) {
1110
+ const result = await ghExec([
1111
+ "project",
1112
+ "item-add",
1113
+ String(projectNum),
1114
+ "--owner",
1115
+ "@me",
1116
+ "--url",
1117
+ issueUrl,
1118
+ "--format",
1119
+ "json"
1120
+ ], { parseJson: true });
1121
+ if (!result.ok) return fail$2(result);
1122
+ return {
1123
+ ok: true,
1124
+ data: { item_id: result.data.id }
1125
+ };
1126
+ }
1127
+ /**
1128
+ * Move a project item to a specific status column.
1129
+ *
1130
+ * Runs `gh project item-edit` with single-select-option-id for the
1131
+ * Status field.
1132
+ */
1133
+ async function moveItemToStatus(projectId, itemId, statusFieldId, statusOptionId) {
1134
+ const result = await ghExec([
1135
+ "project",
1136
+ "item-edit",
1137
+ "--project-id",
1138
+ projectId,
1139
+ "--id",
1140
+ itemId,
1141
+ "--field-id",
1142
+ statusFieldId,
1143
+ "--single-select-option-id",
1144
+ statusOptionId
1145
+ ]);
1146
+ if (!result.ok) return fail$2(result);
1147
+ return {
1148
+ ok: true,
1149
+ data: void 0
1150
+ };
1151
+ }
1152
+ /**
1153
+ * Set the Estimate (story points) field on a project item.
1154
+ *
1155
+ * Runs `gh project item-edit` with --number flag for the Estimate field.
1156
+ */
1157
+ async function setEstimate(projectId, itemId, estimateFieldId, points) {
1158
+ const result = await ghExec([
1159
+ "project",
1160
+ "item-edit",
1161
+ "--project-id",
1162
+ projectId,
1163
+ "--id",
1164
+ itemId,
1165
+ "--field-id",
1166
+ estimateFieldId,
1167
+ "--number",
1168
+ String(points)
1169
+ ]);
1170
+ if (!result.ok) return fail$2(result);
1171
+ return {
1172
+ ok: true,
1173
+ data: void 0
1174
+ };
1175
+ }
1176
+
1177
+ //#endregion
1178
+ //#region src/github/milestones.ts
1179
+ /**
1180
+ * Re-wrap a failed GhResult for a different generic type.
1181
+ */
1182
+ function fail$1(result) {
1183
+ return {
1184
+ ok: false,
1185
+ error: result.error,
1186
+ code: result.code
1187
+ };
1188
+ }
1189
+ /**
1190
+ * Create a new GitHub milestone.
1191
+ *
1192
+ * Uses the REST API: `POST /repos/{owner}/{repo}/milestones`.
1193
+ * The `{owner}` and `{repo}` placeholders are auto-resolved by `gh api`.
1194
+ *
1195
+ * Returns the milestone number and internal ID.
1196
+ */
1197
+ async function createMilestone(title, description) {
1198
+ const args = [
1199
+ "api",
1200
+ "repos/{owner}/{repo}/milestones",
1201
+ "-X",
1202
+ "POST",
1203
+ "-f",
1204
+ `title=${title}`,
1205
+ "-f",
1206
+ "state=open"
1207
+ ];
1208
+ if (description) args.push("-f", `description=${description}`);
1209
+ const result = await ghExec(args, { parseJson: true });
1210
+ if (!result.ok) return result;
1211
+ return {
1212
+ ok: true,
1213
+ data: {
1214
+ number: result.data.number,
1215
+ id: result.data.id
1216
+ }
1217
+ };
1218
+ }
1219
+ /**
1220
+ * Find an existing milestone by title.
1221
+ *
1222
+ * Uses the REST API: `GET /repos/{owner}/{repo}/milestones`.
1223
+ * Fetches all open milestones and filters by exact title match.
1224
+ *
1225
+ * Returns null if no milestone with the given title exists.
1226
+ */
1227
+ async function findMilestone(title) {
1228
+ const result = await ghExec([
1229
+ "api",
1230
+ "repos/{owner}/{repo}/milestones",
1231
+ "--paginate"
1232
+ ], { parseJson: true });
1233
+ if (!result.ok) return fail$1(result);
1234
+ const match = result.data.find((m) => m.title === title);
1235
+ if (!match) return {
1236
+ ok: true,
1237
+ data: null
1238
+ };
1239
+ return {
1240
+ ok: true,
1241
+ data: {
1242
+ number: match.number,
1243
+ id: match.id
1244
+ }
1245
+ };
1246
+ }
1247
+ /**
1248
+ * Ensure a milestone exists, creating it if needed. Idempotent.
1249
+ *
1250
+ * First attempts to find an existing milestone with the given title.
1251
+ * If not found, creates a new one. Returns whether it was newly created.
1252
+ */
1253
+ async function ensureMilestone(title, description) {
1254
+ const findResult = await findMilestone(title);
1255
+ if (!findResult.ok) return fail$1(findResult);
1256
+ if (findResult.data) return {
1257
+ ok: true,
1258
+ data: {
1259
+ ...findResult.data,
1260
+ created: false
1261
+ }
1262
+ };
1263
+ const createResult = await createMilestone(title, description);
1264
+ if (!createResult.ok) return fail$1(createResult);
1265
+ return {
1266
+ ok: true,
1267
+ data: {
1268
+ ...createResult.data,
1269
+ created: true
1270
+ }
1271
+ };
1272
+ }
1273
+ /**
1274
+ * Close a milestone if all its issues are closed.
1275
+ *
1276
+ * Fetches milestone details via REST API to check `open_issues` count.
1277
+ * If open_issues === 0, patches the milestone state to "closed".
1278
+ *
1279
+ * This implements AC-12: milestones auto-close when all issues are closed.
1280
+ */
1281
+ async function closeMilestoneIfComplete(milestoneNumber) {
1282
+ const detailResult = await ghExec(["api", `repos/{owner}/{repo}/milestones/${milestoneNumber}`], { parseJson: true });
1283
+ if (!detailResult.ok) return fail$1(detailResult);
1284
+ const milestone = detailResult.data;
1285
+ if (milestone.state === "closed") return {
1286
+ ok: true,
1287
+ data: { closed: true }
1288
+ };
1289
+ if (milestone.open_issues > 0) return {
1290
+ ok: true,
1291
+ data: { closed: false }
1292
+ };
1293
+ const closeResult = await ghExec([
1294
+ "api",
1295
+ `repos/{owner}/{repo}/milestones/${milestoneNumber}`,
1296
+ "-X",
1297
+ "PATCH",
1298
+ "-f",
1299
+ "state=closed"
1300
+ ]);
1301
+ if (!closeResult.ok) return fail$1(closeResult);
1302
+ return {
1303
+ ok: true,
1304
+ data: { closed: true }
1305
+ };
1306
+ }
1307
+
1308
+ //#endregion
1309
+ //#region src/github/sync.ts
1310
+ /**
1311
+ * Re-wrap a failed GhResult for a different generic type.
1312
+ */
1313
+ function fail(result) {
1314
+ return {
1315
+ ok: false,
1316
+ error: result.error,
1317
+ code: result.code
1318
+ };
1319
+ }
1320
+ /**
1321
+ * Batch-fetch issue details via a single GraphQL query.
1322
+ *
1323
+ * Fetches up to 100 issues per query using node ID lookups.
1324
+ * Falls back to sequential `gh issue view` if GraphQL fails.
1325
+ */
1326
+ async function batchFetchIssues(repo, issueNumbers) {
1327
+ if (issueNumbers.length === 0) return {
1328
+ ok: true,
1329
+ data: /* @__PURE__ */ new Map()
1330
+ };
1331
+ const [owner, name] = repo.split("/");
1332
+ if (!owner || !name) return {
1333
+ ok: false,
1334
+ error: `Invalid repo format: ${repo}. Expected "owner/repo".`,
1335
+ code: "UNKNOWN"
1336
+ };
1337
+ const BATCH_SIZE = 100;
1338
+ const resultMap = /* @__PURE__ */ new Map();
1339
+ for (let i = 0; i < issueNumbers.length; i += BATCH_SIZE) {
1340
+ const batch = issueNumbers.slice(i, i + BATCH_SIZE);
1341
+ const result = await ghGraphQL(`
1342
+ query {
1343
+ repository(owner: "${owner}", name: "${name}") {
1344
+ ${batch.map((num, idx) => `issue_${idx}: issue(number: ${num}) { number state title labels(first: 20) { nodes { name } } }`).join("\n ")}
1345
+ }
1346
+ }
1347
+ `);
1348
+ if (!result.ok) return batchFetchIssuesSequential(issueNumbers);
1349
+ const repoData = result.data.repository;
1350
+ for (let idx = 0; idx < batch.length; idx++) {
1351
+ const issueData = repoData[`issue_${idx}`];
1352
+ if (issueData) resultMap.set(issueData.number, {
1353
+ state: issueData.state.toLowerCase(),
1354
+ title: issueData.title,
1355
+ labels: issueData.labels.nodes.map((l) => l.name)
1356
+ });
1357
+ }
1358
+ }
1359
+ return {
1360
+ ok: true,
1361
+ data: resultMap
1362
+ };
1363
+ }
1364
+ /**
1365
+ * Sequential fallback: fetch issues one at a time via `gh issue view`.
1366
+ */
1367
+ async function batchFetchIssuesSequential(issueNumbers) {
1368
+ const resultMap = /* @__PURE__ */ new Map();
1369
+ for (const num of issueNumbers) {
1370
+ const result = await ghExec([
1371
+ "issue",
1372
+ "view",
1373
+ String(num),
1374
+ "--json",
1375
+ "state,title,labels"
1376
+ ], { parseJson: true });
1377
+ if (result.ok) resultMap.set(num, {
1378
+ state: result.data.state.toLowerCase(),
1379
+ title: result.data.title,
1380
+ labels: result.data.labels.map((l) => l.name)
1381
+ });
1382
+ }
1383
+ return {
1384
+ ok: true,
1385
+ data: resultMap
1386
+ };
1387
+ }
1388
+ /**
1389
+ * Compare local mapping file against GitHub reality.
1390
+ *
1391
+ * For each tracked issue (phases + todos), fetches current GitHub state
1392
+ * and compares against the local mapping. Reports discrepancies in
1393
+ * state, title, and labels.
1394
+ *
1395
+ * Uses batched GraphQL for efficiency (single query for up to 100 issues).
1396
+ */
1397
+ async function syncCheck(cwd) {
1398
+ const mapping = loadMapping(cwd);
1399
+ if (!mapping) return {
1400
+ ok: false,
1401
+ error: "github-issues.json does not exist. Run project setup first.",
1402
+ code: "NOT_FOUND"
1403
+ };
1404
+ if (!mapping.repo) return {
1405
+ ok: false,
1406
+ error: "No repo configured in github-issues.json.",
1407
+ code: "NOT_FOUND"
1408
+ };
1409
+ const trackedIssues = [];
1410
+ for (const [phaseNum, phase] of Object.entries(mapping.phases)) {
1411
+ if (phase.tracking_issue.number > 0) trackedIssues.push({
1412
+ issueNumber: phase.tracking_issue.number,
1413
+ localStatus: phase.tracking_issue.status,
1414
+ source: `phase ${phaseNum} tracking`
1415
+ });
1416
+ for (const [taskId, task] of Object.entries(phase.tasks)) if (task.number > 0) trackedIssues.push({
1417
+ issueNumber: task.number,
1418
+ localStatus: task.status,
1419
+ source: `phase ${phaseNum}, task ${taskId}`
1420
+ });
1421
+ }
1422
+ if (mapping.todos) {
1423
+ for (const [todoId, todo] of Object.entries(mapping.todos)) if (todo.number > 0) trackedIssues.push({
1424
+ issueNumber: todo.number,
1425
+ localStatus: todo.status,
1426
+ source: `todo ${todoId}`
1427
+ });
1428
+ }
1429
+ if (trackedIssues.length === 0) return {
1430
+ ok: true,
1431
+ data: {
1432
+ inSync: true,
1433
+ changes: []
1434
+ }
1435
+ };
1436
+ const issueNumbers = trackedIssues.map((t) => t.issueNumber);
1437
+ const fetchResult = await batchFetchIssues(mapping.repo, issueNumbers);
1438
+ if (!fetchResult.ok) return fail(fetchResult);
1439
+ const remoteStates = fetchResult.data;
1440
+ const changes = [];
1441
+ for (const tracked of trackedIssues) {
1442
+ const remote = remoteStates.get(tracked.issueNumber);
1443
+ if (!remote) {
1444
+ changes.push({
1445
+ issueNumber: tracked.issueNumber,
1446
+ field: "existence",
1447
+ localValue: "exists",
1448
+ remoteValue: "not found"
1449
+ });
1450
+ continue;
1451
+ }
1452
+ const isRemoteClosed = remote.state === "closed";
1453
+ const isLocalDone = tracked.localStatus === "Done";
1454
+ if (isRemoteClosed && !isLocalDone) changes.push({
1455
+ issueNumber: tracked.issueNumber,
1456
+ field: "state",
1457
+ localValue: tracked.localStatus,
1458
+ remoteValue: "closed (Done)"
1459
+ });
1460
+ else if (!isRemoteClosed && isLocalDone) changes.push({
1461
+ issueNumber: tracked.issueNumber,
1462
+ field: "state",
1463
+ localValue: "Done",
1464
+ remoteValue: `open (${remote.state})`
1465
+ });
1466
+ }
1467
+ return {
1468
+ ok: true,
1469
+ data: {
1470
+ inSync: changes.length === 0,
1471
+ changes
1472
+ }
1473
+ };
1474
+ }
1475
+
1476
+ //#endregion
19
1477
  //#region src/mcp/utils.ts
20
1478
  /**
21
1479
  * MCP Utilities — Shared helpers for MCP tools
@@ -84,6 +1542,10 @@ function mcpError(error, summary) {
84
1542
  /**
85
1543
  * Phase CRUD MCP Tools — Phase operations exposed as MCP tools
86
1544
  *
1545
+ * Integrates with GitHub: phase completion triggers sync check, issue close,
1546
+ * board move to Done, and milestone completion check. Find/list enrich
1547
+ * responses with GitHub issue data when available.
1548
+ *
87
1549
  * CRITICAL: Never import output() or error() from core — they call process.exit().
88
1550
  * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.
89
1551
  * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.
@@ -98,6 +1560,31 @@ function registerPhaseTools(server) {
98
1560
  if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
99
1561
  const result = require_cli.findPhaseInternal(cwd, phase);
100
1562
  if (!result) return mcpError(`Phase ${phase} not found`, "Phase not found");
1563
+ let githubTracking = null;
1564
+ let githubTaskIssues = null;
1565
+ let githubWarning;
1566
+ try {
1567
+ const mapping = loadMapping(cwd);
1568
+ if (mapping && result.phase_number) {
1569
+ const phaseMapping = mapping.phases[result.phase_number];
1570
+ if (phaseMapping) {
1571
+ if (phaseMapping.tracking_issue.number > 0) githubTracking = {
1572
+ number: phaseMapping.tracking_issue.number,
1573
+ status: phaseMapping.tracking_issue.status
1574
+ };
1575
+ const taskEntries = Object.entries(phaseMapping.tasks);
1576
+ if (taskEntries.length > 0) {
1577
+ githubTaskIssues = {};
1578
+ for (const [taskId, task] of taskEntries) if (task.number > 0) githubTaskIssues[taskId] = {
1579
+ number: task.number,
1580
+ status: task.status
1581
+ };
1582
+ }
1583
+ }
1584
+ }
1585
+ } catch (e) {
1586
+ githubWarning = `GitHub data enrichment failed: ${e.message}`;
1587
+ }
101
1588
  return mcpSuccess({
102
1589
  found: result.found,
103
1590
  directory: result.directory,
@@ -110,7 +1597,10 @@ function registerPhaseTools(server) {
110
1597
  has_research: result.has_research,
111
1598
  has_context: result.has_context,
112
1599
  has_verification: result.has_verification,
113
- archived: result.archived ?? null
1600
+ archived: result.archived ?? null,
1601
+ github_tracking_issue: githubTracking,
1602
+ github_task_issues: githubTaskIssues,
1603
+ ...githubWarning ? { github_warning: githubWarning } : {}
114
1604
  }, `Found phase ${result.phase_number}: ${result.phase_name ?? "unnamed"}`);
115
1605
  } catch (e) {
116
1606
  return mcpError(e.message, "Operation failed");
@@ -142,13 +1632,37 @@ function registerPhaseTools(server) {
142
1632
  const total_count = dirs.length;
143
1633
  const paginated = dirs.slice(offset, offset + limit);
144
1634
  const has_more = offset + limit < total_count;
1635
+ let githubIssueCounts = null;
1636
+ let githubWarning;
1637
+ try {
1638
+ if (await detectGitHubMode() === "full") {
1639
+ const mapping = loadMapping(cwd);
1640
+ if (mapping && Object.keys(mapping.phases).length > 0) {
1641
+ githubIssueCounts = {};
1642
+ for (const [phaseNum, phaseData] of Object.entries(mapping.phases)) {
1643
+ let open = 0;
1644
+ let closed = 0;
1645
+ for (const task of Object.values(phaseData.tasks)) if (task.number > 0) if (task.status === "Done") closed++;
1646
+ else open++;
1647
+ githubIssueCounts[phaseNum] = {
1648
+ open,
1649
+ closed
1650
+ };
1651
+ }
1652
+ }
1653
+ }
1654
+ } catch (e) {
1655
+ githubWarning = `GitHub enrichment failed: ${e.message}`;
1656
+ }
145
1657
  return mcpSuccess({
146
1658
  directories: paginated,
147
1659
  count: paginated.length,
148
1660
  total_count,
149
1661
  offset,
150
1662
  limit,
151
- has_more
1663
+ has_more,
1664
+ github_issue_counts: githubIssueCounts,
1665
+ ...githubWarning ? { github_warning: githubWarning } : {}
152
1666
  }, `Showing ${paginated.length} of ${total_count} phase(s)`);
153
1667
  } catch (e) {
154
1668
  return mcpError(e.message, "Operation failed");
@@ -195,7 +1709,50 @@ function registerPhaseTools(server) {
195
1709
  try {
196
1710
  const cwd = detectProjectRoot();
197
1711
  if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
1712
+ let syncDiscrepancies = [];
1713
+ let githubWarning;
1714
+ try {
1715
+ if (await detectGitHubMode() === "full") {
1716
+ const syncResult = await syncCheck(cwd);
1717
+ if (syncResult.ok && !syncResult.data.inSync) syncDiscrepancies = syncResult.data.changes;
1718
+ }
1719
+ } catch (e) {
1720
+ githubWarning = `Sync check failed: ${e.message}`;
1721
+ }
198
1722
  const result = await require_cli.phaseCompleteCore(cwd, phase);
1723
+ let githubClosed = false;
1724
+ let milestoneClosed = false;
1725
+ try {
1726
+ if (await detectGitHubMode() === "full") {
1727
+ const mapping = loadMapping(cwd);
1728
+ if (mapping) {
1729
+ const phaseMapping = mapping.phases[phase];
1730
+ if (phaseMapping) {
1731
+ if (phaseMapping.tracking_issue.number > 0) {
1732
+ if ((await closeIssue(phaseMapping.tracking_issue.number, "completed")).ok) {
1733
+ githubClosed = true;
1734
+ phaseMapping.tracking_issue.status = "Done";
1735
+ if (phaseMapping.tracking_issue.item_id && mapping.status_field_id && mapping.status_options["Done"]) await moveItemToStatus(mapping.project_id, phaseMapping.tracking_issue.item_id, mapping.status_field_id, mapping.status_options["Done"]);
1736
+ }
1737
+ }
1738
+ for (const [_taskId, task] of Object.entries(phaseMapping.tasks)) if (task.number > 0 && task.status !== "Done") {
1739
+ if ((await closeIssue(task.number, "completed")).ok) {
1740
+ task.status = "Done";
1741
+ if (task.item_id && mapping.status_field_id && mapping.status_options["Done"]) await moveItemToStatus(mapping.project_id, task.item_id, mapping.status_field_id, mapping.status_options["Done"]);
1742
+ if (phaseMapping.tracking_issue.number > 0) await updateParentTaskList(phaseMapping.tracking_issue.number, task.number, true);
1743
+ }
1744
+ }
1745
+ saveMapping(cwd, mapping);
1746
+ if (mapping.milestone_id > 0) {
1747
+ const msResult = await closeMilestoneIfComplete(mapping.milestone_id);
1748
+ if (msResult.ok) milestoneClosed = msResult.data.closed;
1749
+ }
1750
+ }
1751
+ }
1752
+ }
1753
+ } catch (e) {
1754
+ githubWarning = (githubWarning ? githubWarning + "; " : "") + `GitHub completion operations failed: ${e.message}`;
1755
+ }
199
1756
  return mcpSuccess({
200
1757
  completed_phase: result.completed_phase,
201
1758
  phase_name: result.phase_name,
@@ -205,12 +1762,118 @@ function registerPhaseTools(server) {
205
1762
  is_last_phase: result.is_last_phase,
206
1763
  date: result.date,
207
1764
  roadmap_updated: result.roadmap_updated,
208
- state_updated: result.state_updated
1765
+ state_updated: result.state_updated,
1766
+ sync_discrepancies: syncDiscrepancies.length > 0 ? syncDiscrepancies : null,
1767
+ github_closed: githubClosed,
1768
+ milestone_closed: milestoneClosed,
1769
+ ...githubWarning ? { github_warning: githubWarning } : {}
209
1770
  }, `Phase ${phase} marked as complete${result.next_phase ? `, next: Phase ${result.next_phase}` : ""}`);
210
1771
  } catch (e) {
211
1772
  return mcpError(e.message, "Operation failed");
212
1773
  }
213
1774
  });
1775
+ server.tool("mcp_bounce_issue", "Bounce a task back from In Review to In Progress with a detailed comment explaining what failed. Implements reviewer feedback loop (AC-05).", {
1776
+ issue_number: zod.z.number().describe("GitHub issue number to bounce back"),
1777
+ reason: zod.z.string().describe("Detailed reason why the task is being bounced back (reviewer feedback)")
1778
+ }, async ({ issue_number, reason }) => {
1779
+ try {
1780
+ const cwd = detectProjectRoot();
1781
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
1782
+ if (await detectGitHubMode() === "local-only") {
1783
+ const mapping = loadMapping(cwd);
1784
+ if (mapping) {
1785
+ if (updateLocalMappingStatus$1(mapping, issue_number, "In Progress")) {
1786
+ saveMapping(cwd, mapping);
1787
+ return mcpSuccess({
1788
+ mode: "local-only",
1789
+ issue_number,
1790
+ status: "In Progress",
1791
+ local_updated: true,
1792
+ reason
1793
+ }, `Local-only: issue #${issue_number} bounced to In Progress (reason recorded locally)`);
1794
+ }
1795
+ }
1796
+ return mcpSuccess({
1797
+ mode: "local-only",
1798
+ issue_number,
1799
+ reason,
1800
+ note: "Bounce recorded locally. GitHub operations skipped."
1801
+ }, `Local-only: bounce for issue #${issue_number} recorded`);
1802
+ }
1803
+ const mapping = loadMapping(cwd);
1804
+ let githubWarning;
1805
+ let moved = false;
1806
+ let commented = false;
1807
+ try {
1808
+ const commentResult = await postComment(issue_number, `## Bounced Back to In Progress\n\n**Reason:** ${reason}\n\n---\n*Review feedback posted by MAXSIM*`);
1809
+ commented = commentResult.ok;
1810
+ if (!commentResult.ok) githubWarning = `Comment failed: ${commentResult.error}`;
1811
+ } catch (e) {
1812
+ githubWarning = `Comment failed: ${e.message}`;
1813
+ }
1814
+ try {
1815
+ if (mapping) {
1816
+ const issueEntry = findIssueInMapping$2(mapping, issue_number);
1817
+ if (issueEntry?.item_id && mapping.status_field_id && mapping.status_options["In Progress"]) {
1818
+ const moveResult = await moveItemToStatus(mapping.project_id, issueEntry.item_id, mapping.status_field_id, mapping.status_options["In Progress"]);
1819
+ moved = moveResult.ok;
1820
+ if (!moveResult.ok) githubWarning = (githubWarning ? githubWarning + "; " : "") + `Board move failed: ${moveResult.error}`;
1821
+ }
1822
+ updateLocalMappingStatus$1(mapping, issue_number, "In Progress");
1823
+ saveMapping(cwd, mapping);
1824
+ }
1825
+ } catch (e) {
1826
+ githubWarning = (githubWarning ? githubWarning + "; " : "") + `Board move failed: ${e.message}`;
1827
+ }
1828
+ return mcpSuccess({
1829
+ mode: "full",
1830
+ issue_number,
1831
+ status: "In Progress",
1832
+ commented,
1833
+ moved,
1834
+ reason,
1835
+ ...githubWarning ? { github_warning: githubWarning } : {}
1836
+ }, `Issue #${issue_number} bounced to In Progress${commented ? " with feedback comment" : ""}`);
1837
+ } catch (e) {
1838
+ return mcpError(e.message, "Operation failed");
1839
+ }
1840
+ });
1841
+ }
1842
+ /**
1843
+ * Find an issue entry in the mapping file (searches phases and todos).
1844
+ */
1845
+ function findIssueInMapping$2(mapping, issueNumber) {
1846
+ for (const phase of Object.values(mapping.phases)) {
1847
+ if (phase.tracking_issue.number === issueNumber) return phase.tracking_issue;
1848
+ for (const task of Object.values(phase.tasks)) if (task.number === issueNumber) return task;
1849
+ }
1850
+ if (mapping.todos) {
1851
+ for (const todo of Object.values(mapping.todos)) if (todo.number === issueNumber) return todo;
1852
+ }
1853
+ return null;
1854
+ }
1855
+ /**
1856
+ * Update local mapping status for an issue (mutates mapping in-place).
1857
+ * Returns true if the issue was found and updated.
1858
+ */
1859
+ function updateLocalMappingStatus$1(mapping, issueNumber, status) {
1860
+ for (const phase of Object.values(mapping.phases)) {
1861
+ if (phase.tracking_issue.number === issueNumber) {
1862
+ phase.tracking_issue.status = status;
1863
+ return true;
1864
+ }
1865
+ for (const task of Object.values(phase.tasks)) if (task.number === issueNumber) {
1866
+ task.status = status;
1867
+ return true;
1868
+ }
1869
+ }
1870
+ if (mapping.todos) {
1871
+ for (const todo of Object.values(mapping.todos)) if (todo.number === issueNumber) {
1872
+ todo.status = status;
1873
+ return true;
1874
+ }
1875
+ }
1876
+ return false;
214
1877
  }
215
1878
 
216
1879
  //#endregion
@@ -218,6 +1881,10 @@ function registerPhaseTools(server) {
218
1881
  /**
219
1882
  * Todo CRUD MCP Tools — Todo operations exposed as MCP tools
220
1883
  *
1884
+ * Integrates with GitHub: todo add creates GitHub issue in 'full' mode,
1885
+ * todo complete closes GitHub issue and moves to Done on board,
1886
+ * todo list enriches with GitHub issue data when available.
1887
+ *
221
1888
  * CRITICAL: Never import output() or error() from core — they call process.exit().
222
1889
  * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.
223
1890
  * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.
@@ -243,12 +1910,55 @@ function registerTodoTools(server) {
243
1910
  const filePath = node_path.default.join(pendingDir, filename);
244
1911
  const content = `---\ncreated: ${today}\ntitle: ${title}\narea: ${area || "general"}\nphase: ${phase || "unassigned"}\n---\n${description || ""}\n`;
245
1912
  node_fs.default.writeFileSync(filePath, content, "utf-8");
1913
+ let githubIssueNumber = null;
1914
+ let githubIssueUrl = null;
1915
+ let githubWarning;
1916
+ try {
1917
+ if (await detectGitHubMode() === "full") {
1918
+ const mapping = loadMapping(cwd);
1919
+ const issueResult = await createTodoIssue({
1920
+ title,
1921
+ description: description || void 0,
1922
+ milestone: mapping?.milestone_title || void 0
1923
+ });
1924
+ if (issueResult.ok) {
1925
+ githubIssueNumber = issueResult.data.number;
1926
+ githubIssueUrl = issueResult.data.url;
1927
+ if (mapping && mapping.project_number > 0) {
1928
+ const issueUrl = `https://github.com/${mapping.repo}/issues/${issueResult.data.number}`;
1929
+ const addResult = await addItemToProject(mapping.project_number, issueUrl);
1930
+ if (addResult.ok) {
1931
+ updateTodoMapping(cwd, filename, {
1932
+ number: issueResult.data.number,
1933
+ node_id: issueResult.data.node_id,
1934
+ item_id: addResult.data.item_id,
1935
+ status: "To Do"
1936
+ });
1937
+ if (mapping.status_field_id && mapping.status_options["To Do"]) await moveItemToStatus(mapping.project_id, addResult.data.item_id, mapping.status_field_id, mapping.status_options["To Do"]);
1938
+ } else {
1939
+ updateTodoMapping(cwd, filename, {
1940
+ number: issueResult.data.number,
1941
+ node_id: issueResult.data.node_id,
1942
+ item_id: "",
1943
+ status: "To Do"
1944
+ });
1945
+ githubWarning = `Issue created but board add failed: ${addResult.error}`;
1946
+ }
1947
+ } else githubWarning = "Issue created but no project board configured for board tracking.";
1948
+ } else githubWarning = `GitHub issue creation failed: ${issueResult.error}`;
1949
+ }
1950
+ } catch (e) {
1951
+ githubWarning = `GitHub operation failed: ${e.message}`;
1952
+ }
246
1953
  return mcpSuccess({
247
1954
  file: filename,
248
1955
  path: `.planning/todos/pending/${filename}`,
249
1956
  title,
250
- area: area || "general"
251
- }, `Todo created: ${title}`);
1957
+ area: area || "general",
1958
+ github_issue_number: githubIssueNumber,
1959
+ github_issue_url: githubIssueUrl,
1960
+ ...githubWarning ? { github_warning: githubWarning } : {}
1961
+ }, `Todo created: ${title}${githubIssueNumber ? ` (GitHub #${githubIssueNumber})` : ""}`);
252
1962
  } catch (e) {
253
1963
  return mcpError(e.message, "Operation failed");
254
1964
  }
@@ -267,11 +1977,33 @@ function registerTodoTools(server) {
267
1977
  content = `completed: ${today}\n` + content;
268
1978
  node_fs.default.writeFileSync(node_path.default.join(completedDir, todo_id), content, "utf-8");
269
1979
  node_fs.default.unlinkSync(sourcePath);
1980
+ let githubClosed = false;
1981
+ let githubWarning;
1982
+ try {
1983
+ if (await detectGitHubMode() === "full") {
1984
+ const mapping = loadMapping(cwd);
1985
+ if (mapping?.todos?.[todo_id]) {
1986
+ const todoMapping = mapping.todos[todo_id];
1987
+ if (todoMapping.number > 0) {
1988
+ const closeResult = await closeIssue(todoMapping.number, "completed");
1989
+ githubClosed = closeResult.ok;
1990
+ if (!closeResult.ok) githubWarning = `GitHub issue close failed: ${closeResult.error}`;
1991
+ if (todoMapping.item_id && mapping.status_field_id && mapping.status_options["Done"]) await moveItemToStatus(mapping.project_id, todoMapping.item_id, mapping.status_field_id, mapping.status_options["Done"]);
1992
+ todoMapping.status = "Done";
1993
+ saveMapping(cwd, mapping);
1994
+ }
1995
+ }
1996
+ }
1997
+ } catch (e) {
1998
+ githubWarning = `GitHub operation failed: ${e.message}`;
1999
+ }
270
2000
  return mcpSuccess({
271
2001
  completed: true,
272
2002
  file: todo_id,
273
- date: today
274
- }, `Todo completed: ${todo_id}`);
2003
+ date: today,
2004
+ github_closed: githubClosed,
2005
+ ...githubWarning ? { github_warning: githubWarning } : {}
2006
+ }, `Todo completed: ${todo_id}${githubClosed ? " (GitHub issue closed)" : ""}`);
275
2007
  } catch (e) {
276
2008
  return mcpError(e.message, "Operation failed");
277
2009
  }
@@ -292,6 +2024,22 @@ function registerTodoTools(server) {
292
2024
  if (status === "pending" || status === "all") dirs.push(node_path.default.join(todosBase, "pending"));
293
2025
  if (status === "completed" || status === "all") dirs.push(node_path.default.join(todosBase, "completed"));
294
2026
  const todos = [];
2027
+ let todoMappings = null;
2028
+ let githubWarning;
2029
+ try {
2030
+ if (await detectGitHubMode() === "full") {
2031
+ const mapping = loadMapping(cwd);
2032
+ if (mapping?.todos) {
2033
+ todoMappings = {};
2034
+ for (const [todoId, data] of Object.entries(mapping.todos)) if (data.number > 0) todoMappings[todoId] = {
2035
+ number: data.number,
2036
+ status: data.status
2037
+ };
2038
+ }
2039
+ }
2040
+ } catch (e) {
2041
+ githubWarning = `GitHub enrichment failed: ${e.message}`;
2042
+ }
295
2043
  for (const dir of dirs) {
296
2044
  const dirStatus = dir.endsWith("pending") ? "pending" : "completed";
297
2045
  let files = [];
@@ -303,19 +2051,25 @@ function registerTodoTools(server) {
303
2051
  for (const file of files) try {
304
2052
  const fm = require_cli.parseTodoFrontmatter(node_fs.default.readFileSync(node_path.default.join(dir, file), "utf-8"));
305
2053
  if (area && fm.area !== area) continue;
306
- todos.push({
2054
+ const todoEntry = {
307
2055
  file,
308
2056
  created: fm.created,
309
2057
  title: fm.title,
310
2058
  area: fm.area,
311
2059
  status: dirStatus,
312
2060
  path: `.planning/todos/${dirStatus}/${file}`
313
- });
2061
+ };
2062
+ if (todoMappings?.[file]) {
2063
+ todoEntry.github_issue_number = todoMappings[file].number;
2064
+ todoEntry.github_status = todoMappings[file].status;
2065
+ }
2066
+ todos.push(todoEntry);
314
2067
  } catch {}
315
2068
  }
316
2069
  return mcpSuccess({
317
2070
  count: todos.length,
318
- todos
2071
+ todos,
2072
+ ...githubWarning ? { github_warning: githubWarning } : {}
319
2073
  }, `${todos.length} todos found`);
320
2074
  } catch (e) {
321
2075
  return mcpError(e.message, "Operation failed");
@@ -328,11 +2082,29 @@ function registerTodoTools(server) {
328
2082
  /**
329
2083
  * State Management MCP Tools — STATE.md operations exposed as MCP tools
330
2084
  *
2085
+ * Integrates with GitHub: blocker add/resolve uses best-effort GitHub
2086
+ * issue linking when blocker text references issue numbers.
2087
+ *
331
2088
  * CRITICAL: Never import output() or error() from core — they call process.exit().
332
2089
  * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.
333
2090
  * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.
334
2091
  */
335
2092
  /**
2093
+ * Extract GitHub issue numbers from text.
2094
+ *
2095
+ * Matches patterns like "#42", "issue 42", "issue #42", "blocked by #42".
2096
+ * Returns unique issue numbers found.
2097
+ */
2098
+ function extractIssueNumbers(text) {
2099
+ const matches = text.matchAll(/#(\d+)|issue\s+#?(\d+)/gi);
2100
+ const numbers = /* @__PURE__ */ new Set();
2101
+ for (const match of matches) {
2102
+ const num = parseInt(match[1] || match[2], 10);
2103
+ if (!Number.isNaN(num) && num > 0) numbers.add(num);
2104
+ }
2105
+ return Array.from(numbers);
2106
+ }
2107
+ /**
336
2108
  * Register all state management tools on the MCP server.
337
2109
  */
338
2110
  function registerStateTools(server) {
@@ -414,10 +2186,24 @@ function registerStateTools(server) {
414
2186
  const updated = require_cli.appendToStateSection(node_fs.default.readFileSync(stPath, "utf-8"), /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i, `- ${text}`, [/None\.?\s*\n?/gi, /None yet\.?\s*\n?/gi]);
415
2187
  if (!updated) return mcpError("Blockers section not found in STATE.md", "Section not found");
416
2188
  node_fs.default.writeFileSync(stPath, updated, "utf-8");
2189
+ let githubLinked = [];
2190
+ let githubWarning;
2191
+ try {
2192
+ if (await detectGitHubMode() === "full") {
2193
+ const issueNumbers = extractIssueNumbers(text);
2194
+ if (issueNumbers.length > 0) {
2195
+ for (const issueNum of issueNumbers) if ((await postComment(issueNum, `**Blocker added in MAXSIM:**\n\n${text}\n\n---\n*Posted by MAXSIM blocker tracking*`)).ok) githubLinked.push(issueNum);
2196
+ }
2197
+ }
2198
+ } catch (e) {
2199
+ githubWarning = `GitHub linking failed: ${e.message}`;
2200
+ }
417
2201
  return mcpSuccess({
418
2202
  added: true,
419
- blocker: text
420
- }, "Blocker added");
2203
+ blocker: text,
2204
+ github_linked_issues: githubLinked.length > 0 ? githubLinked : null,
2205
+ ...githubWarning ? { github_warning: githubWarning } : {}
2206
+ }, `Blocker added${githubLinked.length > 0 ? ` (linked to ${githubLinked.map((n) => `#${n}`).join(", ")})` : ""}`);
421
2207
  } catch (e) {
422
2208
  return mcpError(e.message, "Operation failed");
423
2209
  }
@@ -432,17 +2218,37 @@ function registerStateTools(server) {
432
2218
  const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
433
2219
  const match = content.match(sectionPattern);
434
2220
  if (!match) return mcpError("Blockers section not found in STATE.md", "Section not found");
435
- let newBody = match[2].split("\n").filter((line) => {
2221
+ const lines = match[2].split("\n");
2222
+ const matchingLines = [];
2223
+ let newBody = lines.filter((line) => {
436
2224
  if (!line.startsWith("- ")) return true;
437
- return !line.toLowerCase().includes(text.toLowerCase());
2225
+ if (line.toLowerCase().includes(text.toLowerCase())) {
2226
+ matchingLines.push(line);
2227
+ return false;
2228
+ }
2229
+ return true;
438
2230
  }).join("\n");
439
2231
  if (!newBody.trim() || !newBody.includes("- ")) newBody = "None\n";
440
2232
  content = content.replace(sectionPattern, (_match, header) => `${header}${newBody}`);
441
2233
  node_fs.default.writeFileSync(stPath, content, "utf-8");
2234
+ let githubCommented = [];
2235
+ let githubWarning;
2236
+ try {
2237
+ if (await detectGitHubMode() === "full") {
2238
+ const issueNumbers = extractIssueNumbers(matchingLines.join(" ") + " " + text);
2239
+ if (issueNumbers.length > 0) {
2240
+ for (const issueNum of issueNumbers) if ((await postComment(issueNum, `**Blocker resolved in MAXSIM:**\n\nResolved blocker matching: "${text}"\n\n---\n*Posted by MAXSIM blocker tracking*`)).ok) githubCommented.push(issueNum);
2241
+ }
2242
+ }
2243
+ } catch (e) {
2244
+ githubWarning = `GitHub comment failed: ${e.message}`;
2245
+ }
442
2246
  return mcpSuccess({
443
2247
  resolved: true,
444
- blocker: text
445
- }, "Blocker resolved");
2248
+ blocker: text,
2249
+ github_commented_issues: githubCommented.length > 0 ? githubCommented : null,
2250
+ ...githubWarning ? { github_warning: githubWarning } : {}
2251
+ }, `Blocker resolved${githubCommented.length > 0 ? ` (commented on ${githubCommented.map((n) => `#${n}`).join(", ")})` : ""}`);
446
2252
  } catch (e) {
447
2253
  return mcpError(e.message, "Operation failed");
448
2254
  }
@@ -670,6 +2476,897 @@ function registerConfigTools(server) {
670
2476
  });
671
2477
  }
672
2478
 
2479
+ //#endregion
2480
+ //#region src/github/types.ts
2481
+ const MAXSIM_LABELS = [
2482
+ {
2483
+ name: "maxsim",
2484
+ color: "6f42c1",
2485
+ description: "MAXSIM managed issue"
2486
+ },
2487
+ {
2488
+ name: "phase-task",
2489
+ color: "0075ca",
2490
+ description: "MAXSIM phase task"
2491
+ },
2492
+ {
2493
+ name: "todo",
2494
+ color: "fbca04",
2495
+ description: "MAXSIM todo item"
2496
+ },
2497
+ {
2498
+ name: "imported",
2499
+ color: "e4e669",
2500
+ description: "Imported into MAXSIM tracking"
2501
+ },
2502
+ {
2503
+ name: "superseded",
2504
+ color: "d73a4a",
2505
+ description: "Superseded by newer plan"
2506
+ }
2507
+ ];
2508
+ const FIBONACCI_POINTS = [
2509
+ 1,
2510
+ 2,
2511
+ 3,
2512
+ 5,
2513
+ 8,
2514
+ 13,
2515
+ 21,
2516
+ 34
2517
+ ];
2518
+
2519
+ //#endregion
2520
+ //#region src/github/labels.ts
2521
+ /**
2522
+ * Ensure all MAXSIM labels exist on the repository.
2523
+ *
2524
+ * Iterates over MAXSIM_LABELS and runs `gh label create` with `--force`
2525
+ * for each label. The `--force` flag updates existing labels with the
2526
+ * specified color and description.
2527
+ *
2528
+ * Continues on individual label failures (logs to stderr).
2529
+ * Only fails if ALL labels fail to create.
2530
+ */
2531
+ async function ensureLabels() {
2532
+ let successCount = 0;
2533
+ const errors = [];
2534
+ for (const label of MAXSIM_LABELS) {
2535
+ const result = await ghExec([
2536
+ "label",
2537
+ "create",
2538
+ label.name,
2539
+ "--color",
2540
+ label.color,
2541
+ "--description",
2542
+ label.description,
2543
+ "--force"
2544
+ ]);
2545
+ if (result.ok) successCount++;
2546
+ else {
2547
+ const errMsg = result.error;
2548
+ console.error(`[maxsim] Failed to create label "${label.name}": ${errMsg}`);
2549
+ errors.push(`${label.name}: ${errMsg}`);
2550
+ }
2551
+ }
2552
+ if (successCount === 0 && errors.length > 0) return {
2553
+ ok: false,
2554
+ error: `All labels failed to create: ${errors.join("; ")}`,
2555
+ code: "UNKNOWN"
2556
+ };
2557
+ return {
2558
+ ok: true,
2559
+ data: void 0
2560
+ };
2561
+ }
2562
+
2563
+ //#endregion
2564
+ //#region src/github/templates.ts
2565
+ /**
2566
+ * GitHub Issue Templates — Template file generation
2567
+ *
2568
+ * Installs GitHub Issue Form YAML templates into `.github/ISSUE_TEMPLATE/`
2569
+ * for the MAXSIM-managed issue types: phase tasks and todos.
2570
+ *
2571
+ * These are file-system operations only (no gh CLI needed).
2572
+ * Uses synchronous fs to match existing core module patterns.
2573
+ *
2574
+ * CRITICAL: Never call process.exit().
2575
+ */
2576
+ /**
2577
+ * Phase task issue template (GitHub Issue Forms YAML format).
2578
+ *
2579
+ * Used for issues created from MAXSIM phase plans.
2580
+ * Labels: maxsim, phase-task
2581
+ */
2582
+ const PHASE_TASK_TEMPLATE = `name: "MAXSIM Phase Task"
2583
+ description: "Task generated by MAXSIM phase planning"
2584
+ labels: ["maxsim", "phase-task"]
2585
+ body:
2586
+ - type: markdown
2587
+ attributes:
2588
+ value: |
2589
+ This issue was auto-generated by MAXSIM.
2590
+
2591
+ - type: textarea
2592
+ id: summary
2593
+ attributes:
2594
+ label: Summary
2595
+ description: Task summary
2596
+ validations:
2597
+ required: true
2598
+
2599
+ - type: textarea
2600
+ id: spec
2601
+ attributes:
2602
+ label: Full Specification
2603
+ description: Detailed task specification including actions, criteria, and dependencies
2604
+ `;
2605
+ /**
2606
+ * Todo issue template (GitHub Issue Forms YAML format).
2607
+ *
2608
+ * Used for issues created from MAXSIM todo items.
2609
+ * Labels: maxsim, todo
2610
+ */
2611
+ const TODO_TEMPLATE = `name: "MAXSIM Todo"
2612
+ description: "Todo item tracked by MAXSIM"
2613
+ labels: ["maxsim", "todo"]
2614
+ body:
2615
+ - type: textarea
2616
+ id: description
2617
+ attributes:
2618
+ label: Description
2619
+ description: Brief description of the todo item
2620
+ validations:
2621
+ required: true
2622
+
2623
+ - type: textarea
2624
+ id: acceptance
2625
+ attributes:
2626
+ label: Acceptance Criteria
2627
+ description: What defines "done" for this todo?
2628
+ `;
2629
+ /**
2630
+ * Install MAXSIM issue templates into the project's `.github/ISSUE_TEMPLATE/` directory.
2631
+ *
2632
+ * Creates the directory recursively if it does not exist.
2633
+ * Writes two YAML files:
2634
+ * - phase-task.yml (for phase plan tasks)
2635
+ * - todo.yml (for todo items)
2636
+ *
2637
+ * Overwrites existing templates if present (to ensure latest version).
2638
+ * This is a synchronous file write operation (no gh CLI needed).
2639
+ */
2640
+ function installIssueTemplates(cwd) {
2641
+ const templateDir = node_path.default.join(cwd, ".github", "ISSUE_TEMPLATE");
2642
+ node_fs.default.mkdirSync(templateDir, { recursive: true });
2643
+ node_fs.default.writeFileSync(node_path.default.join(templateDir, "phase-task.yml"), PHASE_TASK_TEMPLATE, "utf-8");
2644
+ node_fs.default.writeFileSync(node_path.default.join(templateDir, "todo.yml"), TODO_TEMPLATE, "utf-8");
2645
+ }
2646
+
2647
+ //#endregion
2648
+ //#region src/mcp/github-tools.ts
2649
+ /**
2650
+ * GitHub Issue Lifecycle MCP Tools — GitHub operations exposed as MCP tools
2651
+ *
2652
+ * Provides MCP tools for issue CRUD, PR creation with auto-close linking (AC-08),
2653
+ * sync checking (AC-09), and issue import. Every tool checks detectGitHubMode()
2654
+ * and degrades gracefully to local-only behavior when GitHub is not configured.
2655
+ *
2656
+ * CRITICAL: Never import output() or error() from core — they call process.exit().
2657
+ * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.
2658
+ * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.
2659
+ */
2660
+ /**
2661
+ * Register all GitHub issue lifecycle tools on the MCP server.
2662
+ */
2663
+ function registerGitHubTools(server) {
2664
+ server.tool("mcp_github_setup", "Set up GitHub integration: create project board, labels, milestone, and issue templates.", { milestone_title: zod.z.string().optional().describe("Milestone title (defaults to current milestone from STATE.md)") }, async ({ milestone_title }) => {
2665
+ try {
2666
+ const cwd = detectProjectRoot();
2667
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
2668
+ if (await detectGitHubMode() === "local-only") {
2669
+ installIssueTemplates(cwd);
2670
+ return mcpSuccess({
2671
+ mode: "local-only",
2672
+ templates_installed: true,
2673
+ board_created: false,
2674
+ labels_created: false,
2675
+ milestone_created: false
2676
+ }, "Local-only mode: installed issue templates only. Run `gh auth login` with project scope for full GitHub integration.");
2677
+ }
2678
+ const boardResult = await ensureProjectBoard("MAXSIM Task Board", cwd);
2679
+ if (!boardResult.ok) return mcpError(`Board setup failed: ${boardResult.error}`, "Setup failed");
2680
+ const labelsResult = await ensureLabels();
2681
+ if (!labelsResult.ok) return mcpError(`Label setup failed: ${labelsResult.error}`, "Setup failed");
2682
+ let milestoneData = null;
2683
+ if (milestone_title) {
2684
+ const msResult = await ensureMilestone(milestone_title);
2685
+ if (msResult.ok) {
2686
+ milestoneData = msResult.data;
2687
+ const mapping = loadMapping(cwd);
2688
+ if (mapping) {
2689
+ mapping.milestone_id = msResult.data.number;
2690
+ mapping.milestone_title = milestone_title;
2691
+ saveMapping(cwd, mapping);
2692
+ }
2693
+ }
2694
+ }
2695
+ installIssueTemplates(cwd);
2696
+ return mcpSuccess({
2697
+ mode: "full",
2698
+ board: {
2699
+ number: boardResult.data.number,
2700
+ created: boardResult.data.created
2701
+ },
2702
+ labels_created: true,
2703
+ milestone: milestoneData ? {
2704
+ number: milestoneData.number,
2705
+ title: milestone_title,
2706
+ created: milestoneData.created
2707
+ } : null,
2708
+ templates_installed: true
2709
+ }, `GitHub integration set up: board #${boardResult.data.number}, labels, ${milestoneData ? `milestone "${milestone_title}"` : "no milestone"}, templates`);
2710
+ } catch (e) {
2711
+ return mcpError(e.message, "Operation failed");
2712
+ }
2713
+ });
2714
+ server.tool("mcp_create_plan_issues", "Create GitHub issues for all tasks in a finalized plan. Creates task issues and parent tracking issue.", {
2715
+ phase: zod.z.string().describe("Phase number (e.g. \"01\")"),
2716
+ plan: zod.z.string().describe("Plan number (e.g. \"01\")"),
2717
+ phase_name: zod.z.string().describe("Phase description for the tracking issue title"),
2718
+ tasks: zod.z.array(zod.z.object({
2719
+ taskId: zod.z.string(),
2720
+ title: zod.z.string(),
2721
+ summary: zod.z.string(),
2722
+ actions: zod.z.array(zod.z.string()),
2723
+ acceptanceCriteria: zod.z.array(zod.z.string()),
2724
+ dependencies: zod.z.array(zod.z.string()).optional(),
2725
+ estimate: zod.z.number().optional()
2726
+ })).describe("Array of task objects to create issues for"),
2727
+ milestone: zod.z.string().optional().describe("Milestone title to assign")
2728
+ }, async ({ phase, plan, phase_name, tasks, milestone }) => {
2729
+ try {
2730
+ const cwd = detectProjectRoot();
2731
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
2732
+ if (await detectGitHubMode() === "local-only") return mcpSuccess({
2733
+ mode: "local-only",
2734
+ warning: "GitHub not configured, issues not created",
2735
+ tasks_count: tasks.length
2736
+ }, "Local-only mode: GitHub issues not created. Run `gh auth login` for full integration.");
2737
+ const mapping = loadMapping(cwd);
2738
+ const result = await createAllPlanIssues({
2739
+ phaseNum: phase,
2740
+ planNum: plan,
2741
+ phaseName: phase_name,
2742
+ tasks,
2743
+ milestone,
2744
+ projectTitle: mapping?.project_number ? void 0 : void 0,
2745
+ cwd
2746
+ });
2747
+ if (!result.ok) return mcpError(`Issue creation failed: ${result.error}`, "Creation failed");
2748
+ if (mapping && mapping.project_number > 0) {
2749
+ const repo = mapping.repo;
2750
+ const allIssueNumbers = [result.data.parentIssue, ...result.data.taskIssues.map((t) => t.issueNumber)];
2751
+ for (const issueNum of allIssueNumbers) {
2752
+ const issueUrl = `https://github.com/${repo}/issues/${issueNum}`;
2753
+ const addResult = await addItemToProject(mapping.project_number, issueUrl);
2754
+ if (addResult.ok) {
2755
+ const taskEntry = result.data.taskIssues.find((t) => t.issueNumber === issueNum);
2756
+ if (taskEntry) updateTaskMapping(cwd, phase, taskEntry.taskId, { item_id: addResult.data.item_id });
2757
+ if (mapping.status_options["To Do"] && mapping.status_field_id) await moveItemToStatus(mapping.project_id, addResult.data.item_id, mapping.status_field_id, mapping.status_options["To Do"]);
2758
+ if (taskEntry && mapping.estimate_field_id) {
2759
+ const taskDef = tasks.find((t) => t.taskId === taskEntry.taskId);
2760
+ if (taskDef?.estimate) await setEstimate(mapping.project_id, addResult.data.item_id, mapping.estimate_field_id, taskDef.estimate);
2761
+ }
2762
+ }
2763
+ }
2764
+ }
2765
+ return mcpSuccess({
2766
+ mode: "full",
2767
+ parent_issue: result.data.parentIssue,
2768
+ task_issues: result.data.taskIssues,
2769
+ total_created: result.data.taskIssues.length + 1
2770
+ }, `Created ${result.data.taskIssues.length} task issues + parent tracking issue #${result.data.parentIssue}`);
2771
+ } catch (e) {
2772
+ return mcpError(e.message, "Operation failed");
2773
+ }
2774
+ });
2775
+ server.tool("mcp_create_todo_issue", "Create a GitHub issue for a todo item.", {
2776
+ title: zod.z.string().describe("Todo title"),
2777
+ description: zod.z.string().optional().describe("Todo description"),
2778
+ acceptance_criteria: zod.z.array(zod.z.string()).optional().describe("Acceptance criteria list")
2779
+ }, async ({ title, description, acceptance_criteria }) => {
2780
+ try {
2781
+ const cwd = detectProjectRoot();
2782
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
2783
+ if (await detectGitHubMode() === "local-only") return mcpSuccess({
2784
+ mode: "local-only",
2785
+ warning: "GitHub not configured. Use mcp_add_todo for local todo tracking.",
2786
+ title
2787
+ }, "Local-only mode: GitHub todo issue not created.");
2788
+ const mapping = loadMapping(cwd);
2789
+ const result = await createTodoIssue({
2790
+ title,
2791
+ description,
2792
+ acceptanceCriteria: acceptance_criteria,
2793
+ milestone: mapping?.milestone_title || void 0
2794
+ });
2795
+ if (!result.ok) return mcpError(`Todo issue creation failed: ${result.error}`, "Creation failed");
2796
+ if (mapping && mapping.project_number > 0) {
2797
+ const issueUrl = `https://github.com/${mapping.repo}/issues/${result.data.number}`;
2798
+ const addResult = await addItemToProject(mapping.project_number, issueUrl);
2799
+ if (addResult.ok && mapping) {
2800
+ if (!mapping.todos) mapping.todos = {};
2801
+ mapping.todos[`todo-${result.data.number}`] = {
2802
+ number: result.data.number,
2803
+ node_id: result.data.node_id,
2804
+ item_id: addResult.data.item_id,
2805
+ status: "To Do"
2806
+ };
2807
+ saveMapping(cwd, mapping);
2808
+ }
2809
+ }
2810
+ return mcpSuccess({
2811
+ mode: "full",
2812
+ issue_number: result.data.number,
2813
+ url: result.data.url
2814
+ }, `Created todo issue #${result.data.number}: ${title}`);
2815
+ } catch (e) {
2816
+ return mcpError(e.message, "Operation failed");
2817
+ }
2818
+ });
2819
+ server.tool("mcp_move_issue", "Move a GitHub issue to a new status column (To Do, In Progress, In Review, Done).", {
2820
+ issue_number: zod.z.number().describe("GitHub issue number"),
2821
+ status: zod.z.enum([
2822
+ "To Do",
2823
+ "In Progress",
2824
+ "In Review",
2825
+ "Done"
2826
+ ]).describe("Target status column")
2827
+ }, async ({ issue_number, status }) => {
2828
+ try {
2829
+ const cwd = detectProjectRoot();
2830
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
2831
+ const mode = await detectGitHubMode();
2832
+ const mapping = loadMapping(cwd);
2833
+ if (mode === "local-only") {
2834
+ if (mapping) {
2835
+ if (updateLocalMappingStatus(mapping, issue_number, status)) {
2836
+ saveMapping(cwd, mapping);
2837
+ return mcpSuccess({
2838
+ mode: "local-only",
2839
+ issue_number,
2840
+ status,
2841
+ local_updated: true
2842
+ }, `Local mapping updated: issue #${issue_number} -> ${status}`);
2843
+ }
2844
+ }
2845
+ return mcpError(`Issue #${issue_number} not found in local mapping`, "Issue not tracked");
2846
+ }
2847
+ if (!mapping) return mcpError("github-issues.json not found. Run mcp_github_setup first.", "Setup required");
2848
+ const issueEntry = findIssueInMapping$1(mapping, issue_number);
2849
+ if (!issueEntry) return mcpError(`Issue #${issue_number} not found in local mapping`, "Issue not tracked");
2850
+ if (!issueEntry.item_id) return mcpError(`Issue #${issue_number} has no project item_id. It may not have been added to the board.`, "Not on board");
2851
+ const statusOptionId = mapping.status_options[status];
2852
+ if (!statusOptionId) return mcpError(`Status "${status}" not found in project board options`, "Invalid status");
2853
+ const moveResult = await moveItemToStatus(mapping.project_id, issueEntry.item_id, mapping.status_field_id, statusOptionId);
2854
+ if (!moveResult.ok) return mcpError(`Move failed: ${moveResult.error}`, "Move failed");
2855
+ updateLocalMappingStatus(mapping, issue_number, status);
2856
+ saveMapping(cwd, mapping);
2857
+ return mcpSuccess({
2858
+ mode: "full",
2859
+ issue_number,
2860
+ status,
2861
+ moved: true
2862
+ }, `Issue #${issue_number} moved to "${status}"`);
2863
+ } catch (e) {
2864
+ return mcpError(e.message, "Operation failed");
2865
+ }
2866
+ });
2867
+ server.tool("mcp_close_issue", "Close a GitHub issue as completed or not planned.", {
2868
+ issue_number: zod.z.number().describe("GitHub issue number"),
2869
+ reason: zod.z.enum(["completed", "not_planned"]).optional().default("completed").describe("Close reason")
2870
+ }, async ({ issue_number, reason }) => {
2871
+ try {
2872
+ const cwd = detectProjectRoot();
2873
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
2874
+ if (await detectGitHubMode() === "local-only") return mcpSuccess({
2875
+ mode: "local-only",
2876
+ warning: "GitHub not configured. Cannot close remote issue.",
2877
+ issue_number
2878
+ }, "Local-only mode: cannot close GitHub issue.");
2879
+ const result = await closeIssue(issue_number, reason);
2880
+ if (!result.ok) return mcpError(`Close failed: ${result.error}`, "Close failed");
2881
+ const mapping = loadMapping(cwd);
2882
+ if (mapping) {
2883
+ const issueEntry = findIssueInMapping$1(mapping, issue_number);
2884
+ if (issueEntry?.item_id && mapping.status_options["Done"] && mapping.status_field_id) await moveItemToStatus(mapping.project_id, issueEntry.item_id, mapping.status_field_id, mapping.status_options["Done"]);
2885
+ updateLocalMappingStatus(mapping, issue_number, "Done");
2886
+ saveMapping(cwd, mapping);
2887
+ }
2888
+ return mcpSuccess({
2889
+ mode: "full",
2890
+ issue_number,
2891
+ reason,
2892
+ closed: true
2893
+ }, `Issue #${issue_number} closed (${reason})`);
2894
+ } catch (e) {
2895
+ return mcpError(e.message, "Operation failed");
2896
+ }
2897
+ });
2898
+ server.tool("mcp_post_comment", "Post a progress comment on a GitHub issue.", {
2899
+ issue_number: zod.z.number().describe("GitHub issue number"),
2900
+ body: zod.z.string().describe("Comment body (markdown supported)")
2901
+ }, async ({ issue_number, body }) => {
2902
+ try {
2903
+ if (await detectGitHubMode() === "local-only") return mcpSuccess({
2904
+ mode: "local-only",
2905
+ warning: "GitHub not configured. Cannot post comment.",
2906
+ issue_number
2907
+ }, "Local-only mode: cannot post comment on GitHub issue.");
2908
+ const result = await postComment(issue_number, body);
2909
+ if (!result.ok) return mcpError(`Comment failed: ${result.error}`, "Comment failed");
2910
+ return mcpSuccess({
2911
+ mode: "full",
2912
+ issue_number,
2913
+ commented: true
2914
+ }, `Comment posted on issue #${issue_number}`);
2915
+ } catch (e) {
2916
+ return mcpError(e.message, "Operation failed");
2917
+ }
2918
+ });
2919
+ server.tool("mcp_import_issue", "Import an external GitHub issue into MAXSIM tracking.", { issue_number: zod.z.number().describe("GitHub issue number to import") }, async ({ issue_number }) => {
2920
+ try {
2921
+ if (await detectGitHubMode() === "local-only") return mcpSuccess({
2922
+ mode: "local-only",
2923
+ warning: "GitHub not configured. Cannot import issue.",
2924
+ issue_number
2925
+ }, "Local-only mode: cannot import GitHub issue.");
2926
+ const result = await importExternalIssue(issue_number);
2927
+ if (!result.ok) return mcpError(`Import failed: ${result.error}`, "Import failed");
2928
+ return mcpSuccess({
2929
+ mode: "full",
2930
+ issue_number: result.data.number,
2931
+ title: result.data.title,
2932
+ labels: result.data.labels,
2933
+ imported: true
2934
+ }, `Imported issue #${result.data.number}: "${result.data.title}". Assign to a phase or todo for tracking.`);
2935
+ } catch (e) {
2936
+ return mcpError(e.message, "Operation failed");
2937
+ }
2938
+ });
2939
+ server.tool("mcp_sync_check", "Check for external changes to tracked GitHub issues.", {}, async () => {
2940
+ try {
2941
+ const cwd = detectProjectRoot();
2942
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
2943
+ if (await detectGitHubMode() === "local-only") return mcpSuccess({
2944
+ mode: "local-only",
2945
+ warning: "GitHub not configured. Sync check not available.",
2946
+ in_sync: true,
2947
+ changes: []
2948
+ }, "Local-only mode: sync check skipped.");
2949
+ const result = await syncCheck(cwd);
2950
+ if (!result.ok) return mcpError(`Sync check failed: ${result.error}`, "Sync failed");
2951
+ return mcpSuccess({
2952
+ mode: "full",
2953
+ in_sync: result.data.inSync,
2954
+ changes: result.data.changes,
2955
+ change_count: result.data.changes.length
2956
+ }, result.data.inSync ? "All tracked issues are in sync with GitHub." : `${result.data.changes.length} discrepancies found between local mapping and GitHub.`);
2957
+ } catch (e) {
2958
+ return mcpError(e.message, "Operation failed");
2959
+ }
2960
+ });
2961
+ server.tool("mcp_supersede_plan", "Close old plan issues and link to new plan issues.", {
2962
+ phase: zod.z.string().describe("Phase number"),
2963
+ old_plan: zod.z.string().describe("Old plan number to supersede"),
2964
+ new_plan: zod.z.string().describe("New plan number that replaces it")
2965
+ }, async ({ phase, old_plan, new_plan }) => {
2966
+ try {
2967
+ const cwd = detectProjectRoot();
2968
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
2969
+ if (await detectGitHubMode() === "local-only") return mcpSuccess({
2970
+ mode: "local-only",
2971
+ warning: "GitHub not configured. Cannot supersede plan issues.",
2972
+ phase,
2973
+ old_plan,
2974
+ new_plan
2975
+ }, "Local-only mode: plan supersession skipped.");
2976
+ const mapping = loadMapping(cwd);
2977
+ if (!mapping) return mcpError("github-issues.json not found. Run mcp_github_setup first.", "Setup required");
2978
+ const newPhaseMapping = mapping.phases[phase];
2979
+ if (!newPhaseMapping) return mcpError(`Phase ${phase} not found in mapping. Create new plan issues first.`, "Phase not found");
2980
+ const result = await supersedePlanIssues({
2981
+ phaseNum: phase,
2982
+ oldPlanNum: old_plan,
2983
+ newPlanNum: new_plan,
2984
+ newIssueNumbers: Object.entries(newPhaseMapping.tasks).map(([taskId, task]) => ({
2985
+ taskId,
2986
+ issueNumber: task.number
2987
+ })),
2988
+ cwd
2989
+ });
2990
+ if (!result.ok) return mcpError(`Supersession failed: ${result.error}`, "Supersession failed");
2991
+ return mcpSuccess({
2992
+ mode: "full",
2993
+ phase,
2994
+ old_plan,
2995
+ new_plan,
2996
+ superseded: true
2997
+ }, `Plan ${phase}-${old_plan} superseded by ${phase}-${new_plan}`);
2998
+ } catch (e) {
2999
+ return mcpError(e.message, "Operation failed");
3000
+ }
3001
+ });
3002
+ server.tool("mcp_create_pr", "Create a pull request with auto-close linking for tracked GitHub issues. Generates PR description with Closes #N lines (AC-08).", {
3003
+ issue_numbers: zod.z.array(zod.z.number()).describe("Issue numbers to auto-close when PR merges"),
3004
+ branch: zod.z.string().describe("Source branch name for the PR"),
3005
+ title: zod.z.string().describe("PR title"),
3006
+ base: zod.z.string().optional().default("main").describe("Base branch (default: main)"),
3007
+ additional_context: zod.z.string().optional().describe("Additional context to include in PR body"),
3008
+ draft: zod.z.boolean().optional().default(false).describe("Create as draft PR")
3009
+ }, async ({ issue_numbers, branch, title, base, additional_context, draft }) => {
3010
+ try {
3011
+ const mode = await detectGitHubMode();
3012
+ const prBody = buildPrBody(issue_numbers, additional_context);
3013
+ if (mode === "local-only") return mcpSuccess({
3014
+ mode: "local-only",
3015
+ warning: "GitHub not configured. PR not created. Use the body below to create manually.",
3016
+ pr_body: prBody,
3017
+ issues_linked: issue_numbers
3018
+ }, "Local-only mode: PR body generated but PR not created.");
3019
+ const args = [
3020
+ "pr",
3021
+ "create",
3022
+ "--title",
3023
+ title,
3024
+ "--body",
3025
+ prBody,
3026
+ "--head",
3027
+ branch
3028
+ ];
3029
+ if (base) args.push("--base", base);
3030
+ if (draft) args.push("--draft");
3031
+ const createResult = await ghExec(args);
3032
+ if (!createResult.ok) return mcpError(`PR creation failed: ${createResult.error}`, "PR creation failed");
3033
+ const prUrl = createResult.data.trim();
3034
+ const prNumberMatch = prUrl.match(/\/pull\/(\d+)/);
3035
+ return mcpSuccess({
3036
+ mode: "full",
3037
+ pr_number: prNumberMatch ? parseInt(prNumberMatch[1], 10) : null,
3038
+ pr_url: prUrl,
3039
+ issues_linked: issue_numbers,
3040
+ draft
3041
+ }, `PR${draft ? " (draft)" : ""} created: ${prUrl} — auto-closes ${issue_numbers.map((n) => `#${n}`).join(", ")}`);
3042
+ } catch (e) {
3043
+ return mcpError(e.message, "Operation failed");
3044
+ }
3045
+ });
3046
+ }
3047
+ /**
3048
+ * Find an issue entry in the mapping file (searches phases and todos).
3049
+ */
3050
+ function findIssueInMapping$1(mapping, issueNumber) {
3051
+ for (const phase of Object.values(mapping.phases)) {
3052
+ if (phase.tracking_issue.number === issueNumber) return phase.tracking_issue;
3053
+ for (const task of Object.values(phase.tasks)) if (task.number === issueNumber) return task;
3054
+ }
3055
+ if (mapping.todos) {
3056
+ for (const todo of Object.values(mapping.todos)) if (todo.number === issueNumber) return todo;
3057
+ }
3058
+ return null;
3059
+ }
3060
+ /**
3061
+ * Update local mapping status for an issue (mutates mapping in-place).
3062
+ * Returns true if the issue was found and updated.
3063
+ */
3064
+ function updateLocalMappingStatus(mapping, issueNumber, status) {
3065
+ for (const phase of Object.values(mapping.phases)) {
3066
+ if (phase.tracking_issue.number === issueNumber) {
3067
+ phase.tracking_issue.status = status;
3068
+ return true;
3069
+ }
3070
+ for (const task of Object.values(phase.tasks)) if (task.number === issueNumber) {
3071
+ task.status = status;
3072
+ return true;
3073
+ }
3074
+ }
3075
+ if (mapping.todos) {
3076
+ for (const todo of Object.values(mapping.todos)) if (todo.number === issueNumber) {
3077
+ todo.status = status;
3078
+ return true;
3079
+ }
3080
+ }
3081
+ return false;
3082
+ }
3083
+
3084
+ //#endregion
3085
+ //#region src/mcp/board-tools.ts
3086
+ /**
3087
+ * Board Query MCP Tools — Project board operations exposed as MCP tools
3088
+ *
3089
+ * Provides MCP tools for querying the GitHub project board, searching issues,
3090
+ * getting issue details, and setting estimates. Every tool checks detectGitHubMode()
3091
+ * and degrades gracefully to local-only behavior when GitHub is not configured.
3092
+ *
3093
+ * CRITICAL: Never import output() or error() from core — they call process.exit().
3094
+ * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.
3095
+ * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.
3096
+ */
3097
+ /**
3098
+ * Register all board query tools on the MCP server.
3099
+ */
3100
+ function registerBoardTools(server) {
3101
+ server.tool("mcp_query_board", "Query the GitHub project board. Returns all items with their status, estimates, and issue details.", {
3102
+ status: zod.z.enum([
3103
+ "To Do",
3104
+ "In Progress",
3105
+ "In Review",
3106
+ "Done"
3107
+ ]).optional().describe("Filter by status column"),
3108
+ phase: zod.z.string().optional().describe("Filter by phase number (matches issue title prefix)")
3109
+ }, async ({ status, phase }) => {
3110
+ try {
3111
+ const cwd = detectProjectRoot();
3112
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
3113
+ const mode = await detectGitHubMode();
3114
+ const mapping = loadMapping(cwd);
3115
+ if (mode === "local-only") {
3116
+ if (!mapping) return mcpSuccess({
3117
+ mode: "local-only",
3118
+ items: [],
3119
+ count: 0
3120
+ }, "Local-only mode: no mapping file found.");
3121
+ const items = buildLocalBoardItems(mapping, status, phase);
3122
+ return mcpSuccess({
3123
+ mode: "local-only",
3124
+ items,
3125
+ count: items.length
3126
+ }, `Local-only mode: ${items.length} items from local mapping.`);
3127
+ }
3128
+ if (!mapping || !mapping.project_number) return mcpError("No project board configured. Run mcp_github_setup first.", "Setup required");
3129
+ const result = await ghExec([
3130
+ "project",
3131
+ "item-list",
3132
+ String(mapping.project_number),
3133
+ "--owner",
3134
+ "@me",
3135
+ "--format",
3136
+ "json"
3137
+ ], { parseJson: true });
3138
+ if (!result.ok) return mcpError(`Board query failed: ${result.error}`, "Query failed");
3139
+ let items = result.data.items || [];
3140
+ if (status) items = items.filter((item) => item.status === status);
3141
+ if (phase) {
3142
+ const phasePrefix = `[P${phase}]`;
3143
+ const phasePrefixAlt = `[Phase ${phase}]`;
3144
+ items = items.filter((item) => item.title?.includes(phasePrefix) || item.title?.includes(phasePrefixAlt) || item.content?.title?.includes(phasePrefix) || item.content?.title?.includes(phasePrefixAlt));
3145
+ }
3146
+ const formatted = items.map((item) => ({
3147
+ item_id: item.id,
3148
+ title: item.content?.title ?? item.title,
3149
+ issue_number: item.content?.number ?? null,
3150
+ status: item.status ?? "No Status",
3151
+ url: item.content?.url ?? null
3152
+ }));
3153
+ return mcpSuccess({
3154
+ mode: "full",
3155
+ items: formatted,
3156
+ count: formatted.length
3157
+ }, `Board query: ${formatted.length} items${status ? ` in "${status}"` : ""}${phase ? ` for phase ${phase}` : ""}`);
3158
+ } catch (e) {
3159
+ return mcpError(e.message, "Operation failed");
3160
+ }
3161
+ });
3162
+ server.tool("mcp_search_issues", "Search GitHub issues by label, milestone, state, or text query.", {
3163
+ labels: zod.z.array(zod.z.string()).optional().describe("Filter by label names"),
3164
+ milestone: zod.z.string().optional().describe("Filter by milestone title"),
3165
+ state: zod.z.enum([
3166
+ "open",
3167
+ "closed",
3168
+ "all"
3169
+ ]).optional().default("open").describe("Filter by issue state"),
3170
+ query: zod.z.string().optional().describe("Text search query")
3171
+ }, async ({ labels, milestone, state, query }) => {
3172
+ try {
3173
+ const cwd = detectProjectRoot();
3174
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
3175
+ if (await detectGitHubMode() === "local-only") {
3176
+ const mapping = loadMapping(cwd);
3177
+ if (!mapping) return mcpSuccess({
3178
+ mode: "local-only",
3179
+ issues: [],
3180
+ count: 0
3181
+ }, "Local-only mode: no mapping file found.");
3182
+ const items = buildLocalSearchResults(mapping, state);
3183
+ return mcpSuccess({
3184
+ mode: "local-only",
3185
+ issues: items,
3186
+ count: items.length
3187
+ }, `Local-only mode: ${items.length} items from local mapping.`);
3188
+ }
3189
+ const args = [
3190
+ "issue",
3191
+ "list",
3192
+ "--json",
3193
+ "number,title,state,labels,milestone",
3194
+ "--limit",
3195
+ "100"
3196
+ ];
3197
+ if (state && state !== "all") args.push("--state", state);
3198
+ else if (state === "all") args.push("--state", "all");
3199
+ if (labels && labels.length > 0) for (const label of labels) args.push("--label", label);
3200
+ if (milestone) args.push("--milestone", milestone);
3201
+ if (query) args.push("--search", query);
3202
+ const result = await ghExec(args, { parseJson: true });
3203
+ if (!result.ok) return mcpError(`Search failed: ${result.error}`, "Search failed");
3204
+ const issues = result.data.map((issue) => ({
3205
+ number: issue.number,
3206
+ title: issue.title,
3207
+ state: issue.state,
3208
+ labels: issue.labels.map((l) => l.name),
3209
+ milestone: issue.milestone?.title ?? null
3210
+ }));
3211
+ return mcpSuccess({
3212
+ mode: "full",
3213
+ issues,
3214
+ count: issues.length
3215
+ }, `Found ${issues.length} issues`);
3216
+ } catch (e) {
3217
+ return mcpError(e.message, "Operation failed");
3218
+ }
3219
+ });
3220
+ server.tool("mcp_get_issue_detail", "Get full details of a specific GitHub issue including comments.", { issue_number: zod.z.number().describe("GitHub issue number") }, async ({ issue_number }) => {
3221
+ try {
3222
+ if (await detectGitHubMode() === "local-only") return mcpSuccess({
3223
+ mode: "local-only",
3224
+ warning: "GitHub not configured. Cannot fetch issue details.",
3225
+ issue_number
3226
+ }, "Local-only mode: cannot fetch issue details.");
3227
+ const result = await ghExec([
3228
+ "issue",
3229
+ "view",
3230
+ String(issue_number),
3231
+ "--json",
3232
+ "number,title,body,state,labels,comments,assignees"
3233
+ ], { parseJson: true });
3234
+ if (!result.ok) return mcpError(`Fetch failed: ${result.error}`, "Fetch failed");
3235
+ const issue = result.data;
3236
+ return mcpSuccess({
3237
+ mode: "full",
3238
+ number: issue.number,
3239
+ title: issue.title,
3240
+ body: issue.body,
3241
+ state: issue.state,
3242
+ labels: issue.labels.map((l) => l.name),
3243
+ assignees: issue.assignees.map((a) => a.login),
3244
+ comments: issue.comments.map((c) => ({
3245
+ author: c.author.login,
3246
+ body: c.body,
3247
+ created_at: c.createdAt
3248
+ })),
3249
+ comment_count: issue.comments.length
3250
+ }, `Issue #${issue.number}: ${issue.title} (${issue.state})`);
3251
+ } catch (e) {
3252
+ return mcpError(e.message, "Operation failed");
3253
+ }
3254
+ });
3255
+ server.tool("mcp_set_estimate", "Set Fibonacci story points on a GitHub issue.", {
3256
+ issue_number: zod.z.number().describe("GitHub issue number"),
3257
+ points: zod.z.number().describe("Fibonacci story points (1, 2, 3, 5, 8, 13, 21, 34)")
3258
+ }, async ({ issue_number, points }) => {
3259
+ try {
3260
+ const cwd = detectProjectRoot();
3261
+ if (!cwd) return mcpError("No .planning/ directory found", "Project not detected");
3262
+ if (!FIBONACCI_POINTS.includes(points)) return mcpError(`Invalid points: ${points}. Must be one of: ${FIBONACCI_POINTS.join(", ")}`, "Validation failed");
3263
+ if (await detectGitHubMode() === "local-only") return mcpSuccess({
3264
+ mode: "local-only",
3265
+ warning: "GitHub not configured. Cannot set estimate.",
3266
+ issue_number,
3267
+ points
3268
+ }, "Local-only mode: cannot set estimate on GitHub project.");
3269
+ const mapping = loadMapping(cwd);
3270
+ if (!mapping) return mcpError("github-issues.json not found. Run mcp_github_setup first.", "Setup required");
3271
+ if (!mapping.estimate_field_id) return mcpError("Estimate field not configured. Re-run mcp_github_setup.", "Setup required");
3272
+ const issueEntry = findIssueInMapping(mapping, issue_number);
3273
+ if (!issueEntry) return mcpError(`Issue #${issue_number} not found in local mapping`, "Issue not tracked");
3274
+ if (!issueEntry.item_id) return mcpError(`Issue #${issue_number} has no project item_id. It may not have been added to the board.`, "Not on board");
3275
+ const result = await setEstimate(mapping.project_id, issueEntry.item_id, mapping.estimate_field_id, points);
3276
+ if (!result.ok) return mcpError(`Set estimate failed: ${result.error}`, "Estimate failed");
3277
+ return mcpSuccess({
3278
+ mode: "full",
3279
+ issue_number,
3280
+ points,
3281
+ set: true
3282
+ }, `Estimate set: issue #${issue_number} = ${points} points`);
3283
+ } catch (e) {
3284
+ return mcpError(e.message, "Operation failed");
3285
+ }
3286
+ });
3287
+ }
3288
+ /**
3289
+ * Find an issue entry in the mapping file (searches phases and todos).
3290
+ */
3291
+ function findIssueInMapping(mapping, issueNumber) {
3292
+ for (const phase of Object.values(mapping.phases)) {
3293
+ if (phase.tracking_issue.number === issueNumber) return phase.tracking_issue;
3294
+ for (const task of Object.values(phase.tasks)) if (task.number === issueNumber) return task;
3295
+ }
3296
+ if (mapping.todos) {
3297
+ for (const todo of Object.values(mapping.todos)) if (todo.number === issueNumber) return todo;
3298
+ }
3299
+ return null;
3300
+ }
3301
+ /**
3302
+ * Build local board items from the mapping file (for local-only mode).
3303
+ */
3304
+ function buildLocalBoardItems(mapping, statusFilter, phaseFilter) {
3305
+ const items = [];
3306
+ for (const [phaseNum, phase] of Object.entries(mapping.phases)) {
3307
+ if (phaseFilter && phaseNum !== phaseFilter) continue;
3308
+ if (phase.tracking_issue.number > 0) {
3309
+ const entry = {
3310
+ issue_number: phase.tracking_issue.number,
3311
+ title: `[Phase ${phaseNum}] Tracking`,
3312
+ status: phase.tracking_issue.status,
3313
+ source: `phase ${phaseNum}`
3314
+ };
3315
+ if (!statusFilter || entry.status === statusFilter) items.push(entry);
3316
+ }
3317
+ for (const [taskId, task] of Object.entries(phase.tasks)) if (task.number > 0) {
3318
+ const entry = {
3319
+ issue_number: task.number,
3320
+ title: `[P${phaseNum}] Task ${taskId}`,
3321
+ status: task.status,
3322
+ source: `phase ${phaseNum}, task ${taskId}`
3323
+ };
3324
+ if (!statusFilter || entry.status === statusFilter) items.push(entry);
3325
+ }
3326
+ }
3327
+ if (!phaseFilter && mapping.todos) {
3328
+ for (const [todoId, todo] of Object.entries(mapping.todos)) if (todo.number > 0) {
3329
+ const entry = {
3330
+ issue_number: todo.number,
3331
+ title: `Todo: ${todoId}`,
3332
+ status: todo.status,
3333
+ source: `todo ${todoId}`
3334
+ };
3335
+ if (!statusFilter || entry.status === statusFilter) items.push(entry);
3336
+ }
3337
+ }
3338
+ return items;
3339
+ }
3340
+ /**
3341
+ * Build local search results from the mapping file (for local-only mode).
3342
+ */
3343
+ function buildLocalSearchResults(mapping, stateFilter) {
3344
+ const items = [];
3345
+ for (const [phaseNum, phase] of Object.entries(mapping.phases)) for (const [taskId, task] of Object.entries(phase.tasks)) if (task.number > 0) {
3346
+ const state = task.status === "Done" ? "closed" : "open";
3347
+ if (stateFilter && stateFilter !== "all" && state !== stateFilter) continue;
3348
+ items.push({
3349
+ issue_number: task.number,
3350
+ title: `[P${phaseNum}] Task ${taskId}`,
3351
+ state,
3352
+ source: `phase ${phaseNum}`
3353
+ });
3354
+ }
3355
+ if (mapping.todos) {
3356
+ for (const [todoId, todo] of Object.entries(mapping.todos)) if (todo.number > 0) {
3357
+ const state = todo.status === "Done" ? "closed" : "open";
3358
+ if (stateFilter && stateFilter !== "all" && state !== stateFilter) continue;
3359
+ items.push({
3360
+ issue_number: todo.number,
3361
+ title: `Todo: ${todoId}`,
3362
+ state,
3363
+ source: "todo"
3364
+ });
3365
+ }
3366
+ }
3367
+ return items;
3368
+ }
3369
+
673
3370
  //#endregion
674
3371
  //#region src/mcp/index.ts
675
3372
  /**
@@ -682,6 +3379,8 @@ function registerAllTools(server) {
682
3379
  registerContextTools(server);
683
3380
  registerRoadmapTools(server);
684
3381
  registerConfigTools(server);
3382
+ registerGitHubTools(server);
3383
+ registerBoardTools(server);
685
3384
  }
686
3385
 
687
3386
  //#endregion
@@ -2992,4 +5691,4 @@ function getLocalNetworkIp() {
2992
5691
 
2993
5692
  //#endregion
2994
5693
  exports.createBackendServer = createBackendServer;
2995
- //# sourceMappingURL=server-By0TN-nC.cjs.map
5694
+ //# sourceMappingURL=server-BAHfh_vw.cjs.map