maxsimcli 4.6.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 +16 -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
@@ -1 +0,0 @@
1
- {"version":3,"file":"server-By0TN-nC.cjs","names":["path","fs","z","findPhaseInternal","phasesPath","fs","listSubDirs","getArchivedPhaseDirs","comparePhaseNum","phaseAddCore","phaseInsertCore","phaseCompleteCore","z","planningPath","todayISO","generateSlugInternal","path","fs","parseTodoFrontmatter","z","statePath","fs","stateExtractField","escapeStringRegexp","stateReplaceField","appendToStateSection","cmdRoadmapAnalyze","safeReadFile","planningPath","stateExtractField","z","loadConfig","findPhaseInternal","path","cmdContextLoad","fs","cmdRoadmapAnalyze","z","cmdConfigGet","loadConfig","cmdConfigSet","fs","path","path","fs","getPhasePattern","normalizePhaseName","stateExtractField","comparePhaseNum","extractFrontmatter","WebSocketServer","WebSocket","stateReplaceField","McpServer","StreamableHTTPServerTransport","ws","os"],"sources":["../src/mcp/utils.ts","../src/mcp/phase-tools.ts","../src/mcp/todo-tools.ts","../src/mcp/state-tools.ts","../src/mcp/context-tools.ts","../src/mcp/roadmap-tools.ts","../src/mcp/config-tools.ts","../src/mcp/index.ts","../../../node_modules/node-pty/lib/utils.js","../../../node_modules/node-pty/lib/eventEmitter2.js","../../../node_modules/node-pty/lib/terminal.js","../../../node_modules/node-pty/lib/shared/conout.js","../../../node_modules/node-pty/lib/windowsConoutConnection.js","../../../node_modules/node-pty/lib/windowsPtyAgent.js","../../../node_modules/node-pty/lib/windowsTerminal.js","../../../node_modules/node-pty/lib/unixTerminal.js","../../../node_modules/node-pty/lib/index.js","../src/backend/terminal.ts","../src/backend/server.ts"],"sourcesContent":["/**\n * MCP Utilities — Shared helpers for MCP tools\n *\n * CRITICAL: Never import output() or error() from core — they call process.exit().\n * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Walk up from startDir to find a directory containing `.planning/`.\n * Returns the directory containing `.planning/` or null if not found.\n */\nlet _cachedRoot: string | null | undefined;\n\nexport function detectProjectRoot(startDir?: string): string | null {\n // Only cache when using default startDir (cwd)\n if (startDir === undefined && _cachedRoot !== undefined) {\n return _cachedRoot;\n }\n\n let dir = startDir || process.cwd();\n\n // Safety limit to prevent infinite loops\n for (let i = 0; i < 100; i++) {\n const planningDir = path.join(dir, '.planning');\n try {\n const stat = fs.statSync(planningDir);\n if (stat.isDirectory()) {\n if (startDir === undefined) _cachedRoot = dir;\n return dir;\n }\n } catch {\n // Not found here, walk up\n }\n\n const parent = path.dirname(dir);\n if (parent === dir) {\n // Reached filesystem root\n if (startDir === undefined) _cachedRoot = null;\n return null;\n }\n dir = parent;\n }\n\n if (startDir === undefined) _cachedRoot = null;\n return null;\n}\n\n/**\n * Return a structured MCP success response.\n */\nexport function mcpSuccess(data: Record<string, unknown>, summary: string) {\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ success: true, data, summary }, null, 2),\n },\n ],\n };\n}\n\n/**\n * Return a structured MCP error response.\n */\nexport function mcpError(error: string, summary: string) {\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ success: false, error, summary }, null, 2),\n },\n ],\n isError: true as const,\n };\n}\n","/**\n * Phase CRUD MCP Tools — Phase operations exposed as MCP tools\n *\n * CRITICAL: Never import output() or error() from core — they call process.exit().\n * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.\n * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.\n */\n\nimport fs from 'node:fs';\nimport { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport {\n findPhaseInternal,\n comparePhaseNum,\n getArchivedPhaseDirs,\n phasesPath,\n listSubDirs,\n} from '../core/core.js';\n\nimport {\n phaseAddCore,\n phaseInsertCore,\n phaseCompleteCore,\n} from '../core/phase.js';\n\nimport { detectProjectRoot, mcpSuccess, mcpError } from './utils.js';\n\n/**\n * Register all phase CRUD tools on the MCP server.\n */\nexport function registerPhaseTools(server: McpServer): void {\n // ── mcp_find_phase ──────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_find_phase',\n 'Find a phase directory by number or name. Returns phase details including plans, summaries, and status.',\n {\n phase: z.string().describe('Phase number or name (e.g. \"01\", \"1\", \"01A\", \"1.1\")'),\n },\n async ({ phase }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const result = findPhaseInternal(cwd, phase);\n if (!result) {\n return mcpError(`Phase ${phase} not found`, 'Phase not found');\n }\n\n return mcpSuccess(\n {\n found: result.found,\n directory: result.directory,\n phase_number: result.phase_number,\n phase_name: result.phase_name,\n phase_slug: result.phase_slug,\n plans: result.plans,\n summaries: result.summaries,\n incomplete_plans: result.incomplete_plans,\n has_research: result.has_research,\n has_context: result.has_context,\n has_verification: result.has_verification,\n archived: result.archived ?? null,\n },\n `Found phase ${result.phase_number}: ${result.phase_name ?? 'unnamed'}`,\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_list_phases ─────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_list_phases',\n 'List phase directories with pagination. Returns sorted phases with offset/limit support.',\n {\n include_archived: z\n .boolean()\n .optional()\n .default(false)\n .describe('Include archived phases from completed milestones'),\n offset: z\n .number()\n .optional()\n .default(0)\n .describe('Number of phases to skip (for pagination)'),\n limit: z\n .number()\n .optional()\n .default(20)\n .describe('Maximum number of phases to return'),\n },\n async ({ include_archived, offset, limit }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const phasesDir = phasesPath(cwd);\n if (!fs.existsSync(phasesDir)) {\n return mcpSuccess(\n { directories: [], count: 0, total_count: 0, offset, limit, has_more: false },\n 'No phases directory found',\n );\n }\n\n let dirs = listSubDirs(phasesDir);\n\n if (include_archived) {\n const archived = getArchivedPhaseDirs(cwd);\n for (const a of archived) {\n dirs.push(`${a.name} [${a.milestone}]`);\n }\n }\n\n dirs.sort((a, b) => comparePhaseNum(a, b));\n\n const total_count = dirs.length;\n const paginated = dirs.slice(offset, offset + limit);\n const has_more = offset + limit < total_count;\n\n return mcpSuccess(\n { directories: paginated, count: paginated.length, total_count, offset, limit, has_more },\n `Showing ${paginated.length} of ${total_count} phase(s)`,\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_create_phase ────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_create_phase',\n 'Create a new phase. Adds the next sequential phase directory and appends to ROADMAP.md.',\n {\n name: z.string().describe('Phase description/name (e.g. \"Authentication System\")'),\n },\n async ({ name }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n if (!name || !name.trim()) {\n return mcpError('Phase name must not be empty', 'Validation failed');\n }\n\n const result = await phaseAddCore(cwd, name, { includeStubs: true });\n\n return mcpSuccess(\n {\n phase_number: result.phase_number,\n padded: result.padded,\n name: result.description,\n slug: result.slug,\n directory: result.directory,\n },\n `Created Phase ${result.phase_number}: ${result.description}`,\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_insert_phase ────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_insert_phase',\n 'Insert a decimal phase after a specified phase (e.g. 01.1 after 01). Creates directory and updates ROADMAP.md.',\n {\n name: z.string().describe('Phase description/name'),\n after: z.string().describe('Phase number to insert after (e.g. \"01\", \"1\")'),\n },\n async ({ name, after }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n if (!name || !name.trim()) {\n return mcpError('Phase name must not be empty', 'Validation failed');\n }\n\n const result = await phaseInsertCore(cwd, after, name, { includeStubs: true });\n\n return mcpSuccess(\n {\n phase_number: result.phase_number,\n after_phase: result.after_phase,\n name: result.description,\n slug: result.slug,\n directory: result.directory,\n },\n `Inserted Phase ${result.phase_number}: ${result.description} after Phase ${result.after_phase}`,\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_complete_phase ──────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_complete_phase',\n 'Mark a phase as complete. Updates ROADMAP.md checkbox, progress table, plan count, STATE.md, and REQUIREMENTS.md.',\n {\n phase: z.string().describe('Phase number to complete (e.g. \"01\", \"1\", \"1.1\")'),\n },\n async ({ phase }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const result = await phaseCompleteCore(cwd, phase);\n\n return mcpSuccess(\n {\n completed_phase: result.completed_phase,\n phase_name: result.phase_name,\n plans_executed: result.plans_executed,\n next_phase: result.next_phase,\n next_phase_name: result.next_phase_name,\n is_last_phase: result.is_last_phase,\n date: result.date,\n roadmap_updated: result.roadmap_updated,\n state_updated: result.state_updated,\n },\n `Phase ${phase} marked as complete${result.next_phase ? `, next: Phase ${result.next_phase}` : ''}`,\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n}\n","/**\n * Todo CRUD MCP Tools — Todo operations exposed as MCP tools\n *\n * CRITICAL: Never import output() or error() from core — they call process.exit().\n * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.\n * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport { generateSlugInternal, todayISO, planningPath } from '../core/core.js';\nimport { parseTodoFrontmatter } from '../core/commands.js';\nimport { detectProjectRoot, mcpSuccess, mcpError } from './utils.js';\n\n/**\n * Register all todo CRUD tools on the MCP server.\n */\nexport function registerTodoTools(server: McpServer): void {\n // ── mcp_add_todo ────────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_add_todo',\n 'Create a new todo item in .planning/todos/pending/ with frontmatter metadata.',\n {\n title: z.string().describe('Title of the todo item'),\n description: z.string().optional().describe('Optional description body'),\n area: z.string().optional().default('general').describe('Area/category (default: general)'),\n phase: z.string().optional().describe('Associated phase number'),\n },\n async ({ title, description, area, phase }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const pendingDir = planningPath(cwd, 'todos', 'pending');\n fs.mkdirSync(pendingDir, { recursive: true });\n\n const today = todayISO();\n const slug = generateSlugInternal(title) || 'untitled';\n const timestamp = Date.now();\n const filename = `${timestamp}-${slug}.md`;\n const filePath = path.join(pendingDir, filename);\n\n const content = `---\\ncreated: ${today}\\ntitle: ${title}\\narea: ${area || 'general'}\\nphase: ${phase || 'unassigned'}\\n---\\n${description || ''}\\n`;\n\n fs.writeFileSync(filePath, content, 'utf-8');\n\n return mcpSuccess(\n {\n file: filename,\n path: `.planning/todos/pending/${filename}`,\n title,\n area: area || 'general',\n },\n `Todo created: ${title}`,\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_complete_todo ───────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_complete_todo',\n 'Mark a pending todo as completed by moving it from pending/ to completed/ with a completion timestamp.',\n {\n todo_id: z.string().describe('Filename of the todo (e.g., 1234567890-my-task.md)'),\n },\n async ({ todo_id }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const pendingDir = planningPath(cwd, 'todos', 'pending');\n const completedDir = planningPath(cwd, 'todos', 'completed');\n const sourcePath = path.join(pendingDir, todo_id);\n\n if (!fs.existsSync(sourcePath)) {\n return mcpError(`Todo not found in pending: ${todo_id}`, 'Todo not found');\n }\n\n fs.mkdirSync(completedDir, { recursive: true });\n\n let content = fs.readFileSync(sourcePath, 'utf-8');\n const today = todayISO();\n content = `completed: ${today}\\n` + content;\n\n fs.writeFileSync(path.join(completedDir, todo_id), content, 'utf-8');\n fs.unlinkSync(sourcePath);\n\n return mcpSuccess(\n { completed: true, file: todo_id, date: today },\n `Todo completed: ${todo_id}`,\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_list_todos ──────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_list_todos',\n 'List todo items, optionally filtered by area and status (pending, completed, or all).',\n {\n area: z.string().optional().describe('Filter by area/category'),\n status: z\n .enum(['pending', 'completed', 'all'])\n .optional()\n .default('pending')\n .describe('Which todos to list (default: pending)'),\n },\n async ({ area, status }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const todosBase = planningPath(cwd, 'todos');\n const dirs: string[] = [];\n\n if (status === 'pending' || status === 'all') {\n dirs.push(path.join(todosBase, 'pending'));\n }\n if (status === 'completed' || status === 'all') {\n dirs.push(path.join(todosBase, 'completed'));\n }\n\n const todos: Array<{\n file: string;\n created: string;\n title: string;\n area: string;\n status: string;\n path: string;\n }> = [];\n\n for (const dir of dirs) {\n const dirStatus = dir.endsWith('pending') ? 'pending' : 'completed';\n\n let files: string[] = [];\n try {\n files = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));\n } catch {\n // Directory may not exist\n continue;\n }\n\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(dir, file), 'utf-8');\n const fm = parseTodoFrontmatter(content);\n\n if (area && fm.area !== area) continue;\n\n todos.push({\n file,\n created: fm.created,\n title: fm.title,\n area: fm.area,\n status: dirStatus,\n path: `.planning/todos/${dirStatus}/${file}`,\n });\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return mcpSuccess(\n { count: todos.length, todos },\n `${todos.length} todos found`,\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n}\n","/**\n * State Management MCP Tools — STATE.md operations exposed as MCP tools\n *\n * CRITICAL: Never import output() or error() from core — they call process.exit().\n * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.\n * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.\n */\n\nimport fs from 'node:fs';\nimport { z } from 'zod';\nimport escapeStringRegexp from 'escape-string-regexp';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport { statePath } from '../core/core.js';\nimport { stateExtractField, stateReplaceField, appendToStateSection } from '../core/state.js';\nimport { detectProjectRoot, mcpSuccess, mcpError } from './utils.js';\n\n/**\n * Register all state management tools on the MCP server.\n */\nexport function registerStateTools(server: McpServer): void {\n // ── mcp_get_state ───────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_get_state',\n 'Read STATE.md content — full file, a specific **field:** value, or a ## section.',\n {\n field: z\n .string()\n .optional()\n .describe('Specific field or section name, or omit for full STATE.md'),\n },\n async ({ field }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const stPath = statePath(cwd);\n if (!fs.existsSync(stPath)) {\n return mcpError('STATE.md not found', 'STATE.md missing');\n }\n\n const content = fs.readFileSync(stPath, 'utf-8');\n\n if (!field) {\n return mcpSuccess({ content }, 'Full STATE.md retrieved');\n }\n\n // Try **field:** value pattern first\n const fieldValue = stateExtractField(content, field);\n if (fieldValue) {\n return mcpSuccess(\n { content: fieldValue, field },\n `State field retrieved: ${field}`,\n );\n }\n\n // Try ## Section pattern\n const fieldEscaped = escapeStringRegexp(field);\n const sectionPattern = new RegExp(\n `##\\\\s*${fieldEscaped}\\\\s*\\n([\\\\s\\\\S]*?)(?=\\\\n##|$)`,\n 'i',\n );\n const sectionMatch = content.match(sectionPattern);\n if (sectionMatch) {\n return mcpSuccess(\n { content: sectionMatch[1].trim(), field },\n `State section retrieved: ${field}`,\n );\n }\n\n return mcpError(\n `Section or field \"${field}\" not found in STATE.md`,\n 'Field not found',\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_update_state ────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_update_state',\n 'Update a **field:** value in STATE.md (e.g., \"Status\", \"Current focus\").',\n {\n field: z.string().describe('Field name (e.g., \"Status\", \"Current focus\")'),\n value: z.string().describe('New value for the field'),\n },\n async ({ field, value }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const stPath = statePath(cwd);\n if (!fs.existsSync(stPath)) {\n return mcpError('STATE.md not found', 'STATE.md missing');\n }\n\n const content = fs.readFileSync(stPath, 'utf-8');\n const updated = stateReplaceField(content, field, value);\n\n if (!updated) {\n return mcpError(\n `Field \"${field}\" not found in STATE.md`,\n 'Field not found',\n );\n }\n\n fs.writeFileSync(stPath, updated, 'utf-8');\n\n return mcpSuccess(\n { updated: true, field, value },\n `State updated: ${field}`,\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_add_decision ────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_add_decision',\n 'Record a decision in the Decisions section of STATE.md.',\n {\n summary: z.string().describe('Decision summary'),\n rationale: z.string().optional().describe('Optional rationale'),\n phase: z.string().optional().describe('Associated phase number'),\n },\n async ({ summary, rationale, phase }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const stPath = statePath(cwd);\n if (!fs.existsSync(stPath)) {\n return mcpError('STATE.md not found', 'STATE.md missing');\n }\n\n const content = fs.readFileSync(stPath, 'utf-8');\n const entry = `- [Phase ${phase || '?'}]: ${summary}${rationale ? ` -- ${rationale}` : ''}`;\n\n const sectionPattern =\n /(###?\\s*(?:Decisions|Decisions Made|Accumulated.*Decisions)\\s*\\n)([\\s\\S]*?)(?=\\n###?|\\n##[^#]|$)/i;\n const updated = appendToStateSection(content, sectionPattern, entry, [/None yet\\.?\\s*\\n?/gi, /No decisions yet\\.?\\s*\\n?/gi]);\n\n if (!updated) {\n return mcpError(\n 'Decisions section not found in STATE.md',\n 'Section not found',\n );\n }\n\n fs.writeFileSync(stPath, updated, 'utf-8');\n\n return mcpSuccess(\n { added: true, decision: entry },\n 'Decision recorded',\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_add_blocker ─────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_add_blocker',\n 'Add a blocker entry to the Blockers section of STATE.md.',\n {\n text: z.string().describe('Blocker description'),\n },\n async ({ text }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const stPath = statePath(cwd);\n if (!fs.existsSync(stPath)) {\n return mcpError('STATE.md not found', 'STATE.md missing');\n }\n\n const content = fs.readFileSync(stPath, 'utf-8');\n const entry = `- ${text}`;\n\n const sectionPattern =\n /(###?\\s*(?:Blockers|Blockers\\/Concerns|Concerns)\\s*\\n)([\\s\\S]*?)(?=\\n###?|\\n##[^#]|$)/i;\n const updated = appendToStateSection(content, sectionPattern, entry, [/None\\.?\\s*\\n?/gi, /None yet\\.?\\s*\\n?/gi]);\n\n if (!updated) {\n return mcpError(\n 'Blockers section not found in STATE.md',\n 'Section not found',\n );\n }\n\n fs.writeFileSync(stPath, updated, 'utf-8');\n\n return mcpSuccess(\n { added: true, blocker: text },\n 'Blocker added',\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n\n // ── mcp_resolve_blocker ─────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_resolve_blocker',\n 'Remove a blocker from STATE.md by matching text (case-insensitive partial match).',\n {\n text: z\n .string()\n .describe('Text to match against blocker entries (case-insensitive partial match)'),\n },\n async ({ text }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const stPath = statePath(cwd);\n if (!fs.existsSync(stPath)) {\n return mcpError('STATE.md not found', 'STATE.md missing');\n }\n\n let content = fs.readFileSync(stPath, 'utf-8');\n\n const sectionPattern =\n /(###?\\s*(?:Blockers|Blockers\\/Concerns|Concerns)\\s*\\n)([\\s\\S]*?)(?=\\n###?|\\n##[^#]|$)/i;\n const match = content.match(sectionPattern);\n\n if (!match) {\n return mcpError(\n 'Blockers section not found in STATE.md',\n 'Section not found',\n );\n }\n\n const sectionBody = match[2];\n const lines = sectionBody.split('\\n');\n const filtered = lines.filter((line) => {\n if (!line.startsWith('- ')) return true;\n return !line.toLowerCase().includes(text.toLowerCase());\n });\n\n let newBody = filtered.join('\\n');\n if (!newBody.trim() || !newBody.includes('- ')) {\n newBody = 'None\\n';\n }\n\n content = content.replace(\n sectionPattern,\n (_match, header: string) => `${header}${newBody}`,\n );\n\n fs.writeFileSync(stPath, content, 'utf-8');\n\n return mcpSuccess(\n { resolved: true, blocker: text },\n 'Blocker resolved',\n );\n } catch (e) {\n return mcpError((e as Error).message, 'Operation failed');\n }\n },\n );\n}\n","/**\n * Context Query MCP Tools — Project context exposed as MCP tools\n *\n * CRITICAL: Never import output() or error() from core — they call process.exit().\n * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.\n * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport {\n findPhaseInternal,\n planningPath,\n safeReadFile,\n loadConfig,\n} from '../core/core.js';\n\nimport { cmdRoadmapAnalyze } from '../core/roadmap.js';\nimport { stateExtractField } from '../core/state.js';\nimport { cmdContextLoad } from '../core/context-loader.js';\nimport { detectProjectRoot, mcpSuccess, mcpError } from './utils.js';\n\n/**\n * Register all context query tools on the MCP server.\n */\nexport function registerContextTools(server: McpServer): void {\n // ── mcp_get_active_phase ────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_get_active_phase',\n 'Get the currently active phase and next phase from roadmap analysis and STATE.md.',\n {},\n async () => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const roadmapResult = await cmdRoadmapAnalyze(cwd);\n let current_phase: unknown = null;\n let next_phase: unknown = null;\n let phase_name: string | null = null;\n let status: string | null = null;\n\n if (roadmapResult.ok) {\n const data = roadmapResult.result as Record<string, unknown>;\n current_phase = data.current_phase ?? null;\n next_phase = data.next_phase ?? null;\n }\n\n // Also read STATE.md for current phase field\n const stateContent = safeReadFile(planningPath(cwd, 'STATE.md'));\n if (stateContent) {\n const statePhase = stateExtractField(stateContent, 'Current Phase');\n if (statePhase) phase_name = statePhase;\n const stateStatus = stateExtractField(stateContent, 'Status');\n if (stateStatus) status = stateStatus;\n }\n\n return mcpSuccess(\n { current_phase, next_phase, phase_name, status },\n `Active phase: ${phase_name ?? current_phase ?? 'unknown'}`,\n );\n } catch (e: unknown) {\n return mcpError('Failed: ' + (e as Error).message, 'Error occurred');\n }\n },\n );\n\n // ── mcp_get_guidelines ──────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_get_guidelines',\n 'Get project guidelines: PROJECT.md vision, config, and optionally phase-specific context.',\n {\n phase: z\n .string()\n .optional()\n .describe('Optional phase number to include phase-specific context'),\n },\n async ({ phase }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const project_vision = safeReadFile(planningPath(cwd, 'PROJECT.md'));\n const config = loadConfig(cwd);\n\n let phase_context: string | null = null;\n if (phase) {\n const phaseInfo = findPhaseInternal(cwd, phase);\n if (phaseInfo) {\n const contextPath = path.join(\n phaseInfo.directory,\n `${phaseInfo.phase_number}-CONTEXT.md`,\n );\n phase_context = safeReadFile(contextPath);\n }\n }\n\n return mcpSuccess(\n { project_vision, config, phase_context },\n `Guidelines loaded${phase ? ` with phase ${phase} context` : ''}`,\n );\n } catch (e: unknown) {\n return mcpError('Failed: ' + (e as Error).message, 'Error occurred');\n }\n },\n );\n\n // ── mcp_get_context_for_task ────────────────────────────────────────────────\n\n server.tool(\n 'mcp_get_context_for_task',\n 'Load context files for a task. Includes project context, roadmap, artefakte, and codebase docs filtered by topic. ' +\n 'Topic keywords select relevant codebase docs: \"ui/frontend\" loads CONVENTIONS+STRUCTURE, ' +\n '\"api/backend\" loads ARCHITECTURE+CONVENTIONS, \"testing\" loads TESTING+CONVENTIONS, ' +\n '\"database\" loads ARCHITECTURE+STACK, \"refactor\" loads CONCERNS+ARCHITECTURE. ' +\n 'Without topic, defaults to STACK+ARCHITECTURE.',\n {\n phase: z\n .string()\n .optional()\n .describe('Phase number to scope context to'),\n topic: z\n .string()\n .optional()\n .describe('Topic keywords to filter codebase docs (e.g. \"frontend\", \"api\", \"testing\", \"database\", \"refactor\")'),\n },\n async ({ phase, topic }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const result = cmdContextLoad(cwd, phase, topic, true);\n if (!result.ok) {\n return mcpError(result.error, 'Context load failed');\n }\n\n return mcpSuccess(\n { context: result.result },\n `Context loaded${phase ? ` for phase ${phase}` : ''}${topic ? ` topic \"${topic}\"` : ''}`,\n );\n } catch (e: unknown) {\n return mcpError('Failed: ' + (e as Error).message, 'Error occurred');\n }\n },\n );\n\n // ── mcp_get_project_overview ────────────────────────────────────────────────\n\n server.tool(\n 'mcp_get_project_overview',\n 'Get a high-level project overview: PROJECT.md, REQUIREMENTS.md, and STATE.md contents.',\n {},\n async () => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const project = safeReadFile(planningPath(cwd, 'PROJECT.md'));\n const requirements = safeReadFile(planningPath(cwd, 'REQUIREMENTS.md'));\n const state = safeReadFile(planningPath(cwd, 'STATE.md'));\n\n return mcpSuccess(\n { project, requirements, state },\n 'Project overview loaded',\n );\n } catch (e: unknown) {\n return mcpError('Failed: ' + (e as Error).message, 'Error occurred');\n }\n },\n );\n\n // ── mcp_get_phase_detail ────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_get_phase_detail',\n 'Get detailed information about a specific phase including all its files (plans, summaries, context, research, verification).',\n {\n phase: z.string().describe('Phase number or name (e.g. \"01\", \"1\", \"01A\")'),\n },\n async ({ phase }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const phaseInfo = findPhaseInternal(cwd, phase);\n if (!phaseInfo) {\n return mcpError(`Phase ${phase} not found`, 'Phase not found');\n }\n\n // Read all files in the phase directory\n const files: Array<{ name: string; content: string | null }> = [];\n try {\n const entries = fs.readdirSync(phaseInfo.directory);\n for (const entry of entries) {\n const fullPath = path.join(phaseInfo.directory, entry);\n const stat = fs.statSync(fullPath);\n if (stat.isFile()) {\n files.push({\n name: entry,\n content: safeReadFile(fullPath),\n });\n }\n }\n } catch {\n // Directory may not exist or be empty\n }\n\n return mcpSuccess(\n {\n phase_number: phaseInfo.phase_number,\n phase_name: phaseInfo.phase_name,\n directory: phaseInfo.directory,\n files,\n },\n `Phase ${phaseInfo.phase_number} detail: ${files.length} file(s)`,\n );\n } catch (e: unknown) {\n return mcpError('Failed: ' + (e as Error).message, 'Error occurred');\n }\n },\n );\n}\n","/**\n * Roadmap Query MCP Tools — Roadmap analysis exposed as MCP tools\n *\n * CRITICAL: Never import output() or error() from core — they call process.exit().\n * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.\n * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport { cmdRoadmapAnalyze } from '../core/roadmap.js';\nimport { detectProjectRoot, mcpSuccess, mcpError } from './utils.js';\n\n/**\n * Register all roadmap query tools on the MCP server.\n */\nexport function registerRoadmapTools(server: McpServer): void {\n // ── mcp_get_roadmap ─────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_get_roadmap',\n 'Get the full roadmap analysis including all phases, their status, and progress.',\n {},\n async () => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const result = await cmdRoadmapAnalyze(cwd);\n if (!result.ok) {\n return mcpError(result.error, 'Roadmap analysis failed');\n }\n\n return mcpSuccess(\n { roadmap: result.result },\n 'Roadmap analysis complete',\n );\n } catch (e: unknown) {\n return mcpError('Failed: ' + (e as Error).message, 'Error occurred');\n }\n },\n );\n\n // ── mcp_get_roadmap_progress ────────────────────────────────────────────────\n\n server.tool(\n 'mcp_get_roadmap_progress',\n 'Get a focused progress summary: total phases, completed, in-progress, not started, and progress percentage.',\n {},\n async () => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const result = await cmdRoadmapAnalyze(cwd);\n if (!result.ok) {\n return mcpError(result.error, 'Roadmap analysis failed');\n }\n\n const data = result.result as Record<string, unknown>;\n const phases = (data.phases ?? []) as Array<Record<string, unknown>>;\n\n const total_phases = phases.length;\n let completed = 0;\n let in_progress = 0;\n let not_started = 0;\n\n for (const p of phases) {\n const status = String(p.status ?? '').toLowerCase();\n if (status === 'completed' || status === 'done') {\n completed++;\n } else if (status === 'in-progress' || status === 'in_progress' || status === 'active') {\n in_progress++;\n } else {\n not_started++;\n }\n }\n\n const progress_percent =\n total_phases > 0 ? Math.round((completed / total_phases) * 100) : 0;\n\n return mcpSuccess(\n {\n total_phases,\n completed,\n in_progress,\n not_started,\n progress_percent,\n current_phase: data.current_phase ?? null,\n next_phase: data.next_phase ?? null,\n },\n `Progress: ${completed}/${total_phases} phases complete (${progress_percent}%)`,\n );\n } catch (e: unknown) {\n return mcpError('Failed: ' + (e as Error).message, 'Error occurred');\n }\n },\n );\n}\n","/**\n * Config Query MCP Tools — Project configuration exposed as MCP tools\n *\n * CRITICAL: Never import output() or error() from core — they call process.exit().\n * CRITICAL: Never write to stdout — it is reserved for MCP JSON-RPC protocol.\n * CRITICAL: Never call process.exit() — the server must stay alive after every tool call.\n */\n\nimport { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport { loadConfig } from '../core/core.js';\nimport { cmdConfigGet, cmdConfigSet } from '../core/config.js';\nimport { detectProjectRoot, mcpSuccess, mcpError } from './utils.js';\n\n/**\n * Register all config query tools on the MCP server.\n */\nexport function registerConfigTools(server: McpServer): void {\n // ── mcp_get_config ──────────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_get_config',\n 'Get project configuration. Optionally provide a key path to get a specific value.',\n {\n key: z\n .string()\n .optional()\n .describe('Optional dot-separated key path (e.g. \"model_profile\", \"branching.strategy\")'),\n },\n async ({ key }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n if (key) {\n const result = cmdConfigGet(cwd, key, true);\n if (!result.ok) {\n return mcpError(result.error, 'Config get failed');\n }\n return mcpSuccess(\n { key, value: result.rawValue ?? result.result },\n `Config value for \"${key}\"`,\n );\n }\n\n const config = loadConfig(cwd);\n return mcpSuccess(\n { config },\n 'Full configuration loaded',\n );\n } catch (e: unknown) {\n return mcpError('Failed: ' + (e as Error).message, 'Error occurred');\n }\n },\n );\n\n // ── mcp_update_config ───────────────────────────────────────────────────────\n\n server.tool(\n 'mcp_update_config',\n 'Update a project configuration value by key path.',\n {\n key: z.string().describe('Dot-separated key path (e.g. \"model_profile\", \"branching.strategy\")'),\n value: z.string().describe('New value to set'),\n },\n async ({ key, value }) => {\n try {\n const cwd = detectProjectRoot();\n if (!cwd) {\n return mcpError('No .planning/ directory found', 'Project not detected');\n }\n\n const result = cmdConfigSet(cwd, key, value, true);\n if (!result.ok) {\n return mcpError(result.error, 'Config update failed');\n }\n\n return mcpSuccess(\n { updated: true, key, value },\n `Config \"${key}\" updated to \"${value}\"`,\n );\n } catch (e: unknown) {\n return mcpError('Failed: ' + (e as Error).message, 'Error occurred');\n }\n },\n );\n}\n","/**\n * MCP Tool Registration — Orchestrates all tool registrations\n *\n * This is the single entry point for registering MCP tools on the server.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { registerPhaseTools } from './phase-tools.js';\nimport { registerTodoTools } from './todo-tools.js';\nimport { registerStateTools } from './state-tools.js';\nimport { registerContextTools } from './context-tools.js';\nimport { registerRoadmapTools } from './roadmap-tools.js';\nimport { registerConfigTools } from './config-tools.js';\n\n/**\n * Register all MCP tools on the given server instance.\n */\nexport function registerAllTools(server: McpServer): void {\n registerPhaseTools(server);\n registerTodoTools(server);\n registerStateTools(server);\n registerContextTools(server);\n registerRoadmapTools(server);\n registerConfigTools(server);\n}\n","\"use strict\";\n/**\n * Copyright (c) 2017, Daniel Imms (MIT License).\n * Copyright (c) 2018, Microsoft Corporation (MIT License).\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.loadNativeModule = exports.assign = void 0;\nfunction assign(target) {\n var sources = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n sources[_i - 1] = arguments[_i];\n }\n sources.forEach(function (source) { return Object.keys(source).forEach(function (key) { return target[key] = source[key]; }); });\n return target;\n}\nexports.assign = assign;\nfunction loadNativeModule(name) {\n // Check build, debug, and then prebuilds.\n var dirs = ['build/Release', 'build/Debug', \"prebuilds/\" + process.platform + \"-\" + process.arch];\n // Check relative to the parent dir for unbundled and then the current dir for bundled\n var relative = ['..', '.'];\n var lastError;\n for (var _i = 0, dirs_1 = dirs; _i < dirs_1.length; _i++) {\n var d = dirs_1[_i];\n for (var _a = 0, relative_1 = relative; _a < relative_1.length; _a++) {\n var r = relative_1[_a];\n var dir = r + \"/\" + d + \"/\";\n try {\n return { dir: dir, module: require(dir + \"/\" + name + \".node\") };\n }\n catch (e) {\n lastError = e;\n }\n }\n }\n throw new Error(\"Failed to load native module: \" + name + \".node, checked: \" + dirs.join(', ') + \": \" + lastError);\n}\nexports.loadNativeModule = loadNativeModule;\n//# sourceMappingURL=utils.js.map","\"use strict\";\n/**\n * Copyright (c) 2019, Microsoft Corporation (MIT License).\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EventEmitter2 = void 0;\nvar EventEmitter2 = /** @class */ (function () {\n function EventEmitter2() {\n this._listeners = [];\n }\n Object.defineProperty(EventEmitter2.prototype, \"event\", {\n get: function () {\n var _this = this;\n if (!this._event) {\n this._event = function (listener) {\n _this._listeners.push(listener);\n var disposable = {\n dispose: function () {\n for (var i = 0; i < _this._listeners.length; i++) {\n if (_this._listeners[i] === listener) {\n _this._listeners.splice(i, 1);\n return;\n }\n }\n }\n };\n return disposable;\n };\n }\n return this._event;\n },\n enumerable: false,\n configurable: true\n });\n EventEmitter2.prototype.fire = function (data) {\n var queue = [];\n for (var i = 0; i < this._listeners.length; i++) {\n queue.push(this._listeners[i]);\n }\n for (var i = 0; i < queue.length; i++) {\n queue[i].call(undefined, data);\n }\n };\n return EventEmitter2;\n}());\nexports.EventEmitter2 = EventEmitter2;\n//# sourceMappingURL=eventEmitter2.js.map","\"use strict\";\n/**\n * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)\n * Copyright (c) 2016, Daniel Imms (MIT License).\n * Copyright (c) 2018, Microsoft Corporation (MIT License).\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Terminal = exports.DEFAULT_ROWS = exports.DEFAULT_COLS = void 0;\nvar events_1 = require(\"events\");\nvar eventEmitter2_1 = require(\"./eventEmitter2\");\nexports.DEFAULT_COLS = 80;\nexports.DEFAULT_ROWS = 24;\n/**\n * Default messages to indicate PAUSE/RESUME for automatic flow control.\n * To avoid conflicts with rebound XON/XOFF control codes (such as on-my-zsh),\n * the sequences can be customized in `IPtyForkOptions`.\n */\nvar FLOW_CONTROL_PAUSE = '\\x13'; // defaults to XOFF\nvar FLOW_CONTROL_RESUME = '\\x11'; // defaults to XON\nvar Terminal = /** @class */ (function () {\n function Terminal(opt) {\n this._pid = 0;\n this._fd = 0;\n this._cols = 0;\n this._rows = 0;\n this._readable = false;\n this._writable = false;\n this._onData = new eventEmitter2_1.EventEmitter2();\n this._onExit = new eventEmitter2_1.EventEmitter2();\n // for 'close'\n this._internalee = new events_1.EventEmitter();\n // setup flow control handling\n this.handleFlowControl = !!(opt === null || opt === void 0 ? void 0 : opt.handleFlowControl);\n this._flowControlPause = (opt === null || opt === void 0 ? void 0 : opt.flowControlPause) || FLOW_CONTROL_PAUSE;\n this._flowControlResume = (opt === null || opt === void 0 ? void 0 : opt.flowControlResume) || FLOW_CONTROL_RESUME;\n if (!opt) {\n return;\n }\n // Do basic type checks here in case node-pty is being used within JavaScript. If the wrong\n // types go through to the C++ side it can lead to hard to diagnose exceptions.\n this._checkType('name', opt.name ? opt.name : undefined, 'string');\n this._checkType('cols', opt.cols ? opt.cols : undefined, 'number');\n this._checkType('rows', opt.rows ? opt.rows : undefined, 'number');\n this._checkType('cwd', opt.cwd ? opt.cwd : undefined, 'string');\n this._checkType('env', opt.env ? opt.env : undefined, 'object');\n this._checkType('uid', opt.uid ? opt.uid : undefined, 'number');\n this._checkType('gid', opt.gid ? opt.gid : undefined, 'number');\n this._checkType('encoding', opt.encoding ? opt.encoding : undefined, 'string');\n }\n Object.defineProperty(Terminal.prototype, \"onData\", {\n get: function () { return this._onData.event; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Terminal.prototype, \"onExit\", {\n get: function () { return this._onExit.event; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Terminal.prototype, \"pid\", {\n get: function () { return this._pid; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Terminal.prototype, \"cols\", {\n get: function () { return this._cols; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Terminal.prototype, \"rows\", {\n get: function () { return this._rows; },\n enumerable: false,\n configurable: true\n });\n Terminal.prototype.write = function (data) {\n if (this.handleFlowControl) {\n // PAUSE/RESUME messages are not forwarded to the pty\n if (data === this._flowControlPause) {\n this.pause();\n return;\n }\n if (data === this._flowControlResume) {\n this.resume();\n return;\n }\n }\n // everything else goes to the real pty\n this._write(data);\n };\n Terminal.prototype._forwardEvents = function () {\n var _this = this;\n this.on('data', function (e) { return _this._onData.fire(e); });\n this.on('exit', function (exitCode, signal) { return _this._onExit.fire({ exitCode: exitCode, signal: signal }); });\n };\n Terminal.prototype._checkType = function (name, value, type, allowArray) {\n if (allowArray === void 0) { allowArray = false; }\n if (value === undefined) {\n return;\n }\n if (allowArray) {\n if (Array.isArray(value)) {\n value.forEach(function (v, i) {\n if (typeof v !== type) {\n throw new Error(name + \"[\" + i + \"] must be a \" + type + \" (not a \" + typeof v[i] + \")\");\n }\n });\n return;\n }\n }\n if (typeof value !== type) {\n throw new Error(name + \" must be a \" + type + \" (not a \" + typeof value + \")\");\n }\n };\n /** See net.Socket.end */\n Terminal.prototype.end = function (data) {\n this._socket.end(data);\n };\n /** See stream.Readable.pipe */\n Terminal.prototype.pipe = function (dest, options) {\n return this._socket.pipe(dest, options);\n };\n /** See net.Socket.pause */\n Terminal.prototype.pause = function () {\n return this._socket.pause();\n };\n /** See net.Socket.resume */\n Terminal.prototype.resume = function () {\n return this._socket.resume();\n };\n /** See net.Socket.setEncoding */\n Terminal.prototype.setEncoding = function (encoding) {\n if (this._socket._decoder) {\n delete this._socket._decoder;\n }\n if (encoding) {\n this._socket.setEncoding(encoding);\n }\n };\n Terminal.prototype.addListener = function (eventName, listener) { this.on(eventName, listener); };\n Terminal.prototype.on = function (eventName, listener) {\n if (eventName === 'close') {\n this._internalee.on('close', listener);\n return;\n }\n this._socket.on(eventName, listener);\n };\n Terminal.prototype.emit = function (eventName) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (eventName === 'close') {\n return this._internalee.emit.apply(this._internalee, arguments);\n }\n return this._socket.emit.apply(this._socket, arguments);\n };\n Terminal.prototype.listeners = function (eventName) {\n return this._socket.listeners(eventName);\n };\n Terminal.prototype.removeListener = function (eventName, listener) {\n this._socket.removeListener(eventName, listener);\n };\n Terminal.prototype.removeAllListeners = function (eventName) {\n this._socket.removeAllListeners(eventName);\n };\n Terminal.prototype.once = function (eventName, listener) {\n this._socket.once(eventName, listener);\n };\n Terminal.prototype._close = function () {\n this._socket.readable = false;\n this.write = function () { };\n this.end = function () { };\n this._writable = false;\n this._readable = false;\n };\n Terminal.prototype._parseEnv = function (env) {\n var keys = Object.keys(env || {});\n var pairs = [];\n for (var i = 0; i < keys.length; i++) {\n if (keys[i] === undefined) {\n continue;\n }\n pairs.push(keys[i] + '=' + env[keys[i]]);\n }\n return pairs;\n };\n return Terminal;\n}());\nexports.Terminal = Terminal;\n//# sourceMappingURL=terminal.js.map","\"use strict\";\n/**\n * Copyright (c) 2020, Microsoft Corporation (MIT License).\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getWorkerPipeName = void 0;\nfunction getWorkerPipeName(conoutPipeName) {\n return conoutPipeName + \"-worker\";\n}\nexports.getWorkerPipeName = getWorkerPipeName;\n//# sourceMappingURL=conout.js.map","\"use strict\";\n/**\n * Copyright (c) 2020, Microsoft Corporation (MIT License).\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ConoutConnection = void 0;\nvar worker_threads_1 = require(\"worker_threads\");\nvar conout_1 = require(\"./shared/conout\");\nvar path_1 = require(\"path\");\nvar eventEmitter2_1 = require(\"./eventEmitter2\");\n/**\n * The amount of time to wait for additional data after the conpty shell process has exited before\n * shutting down the worker and sockets. The timer will be reset if a new data event comes in after\n * the timer has started.\n */\nvar FLUSH_DATA_INTERVAL = 1000;\n/**\n * Connects to and manages the lifecycle of the conout socket. This socket must be drained on\n * another thread in order to avoid deadlocks where Conpty waits for the out socket to drain\n * when `ClosePseudoConsole` is called. This happens when data is being written to the terminal when\n * the pty is closed.\n *\n * See also:\n * - https://github.com/microsoft/node-pty/issues/375\n * - https://github.com/microsoft/vscode/issues/76548\n * - https://github.com/microsoft/terminal/issues/1810\n * - https://docs.microsoft.com/en-us/windows/console/closepseudoconsole\n */\nvar ConoutConnection = /** @class */ (function () {\n function ConoutConnection(_conoutPipeName, _useConptyDll) {\n var _this = this;\n this._conoutPipeName = _conoutPipeName;\n this._useConptyDll = _useConptyDll;\n this._isDisposed = false;\n this._onReady = new eventEmitter2_1.EventEmitter2();\n var workerData = {\n conoutPipeName: _conoutPipeName\n };\n var scriptPath = __dirname.replace('node_modules.asar', 'node_modules.asar.unpacked');\n this._worker = new worker_threads_1.Worker(path_1.join(scriptPath, 'worker/conoutSocketWorker.js'), { workerData: workerData });\n this._worker.on('message', function (message) {\n switch (message) {\n case 1 /* READY */:\n _this._onReady.fire();\n return;\n default:\n console.warn('Unexpected ConoutWorkerMessage', message);\n }\n });\n }\n Object.defineProperty(ConoutConnection.prototype, \"onReady\", {\n get: function () { return this._onReady.event; },\n enumerable: false,\n configurable: true\n });\n ConoutConnection.prototype.dispose = function () {\n if (!this._useConptyDll && this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n // Drain all data from the socket before closing\n this._drainDataAndClose();\n };\n ConoutConnection.prototype.connectSocket = function (socket) {\n socket.connect(conout_1.getWorkerPipeName(this._conoutPipeName));\n };\n ConoutConnection.prototype._drainDataAndClose = function () {\n var _this = this;\n if (this._drainTimeout) {\n clearTimeout(this._drainTimeout);\n }\n this._drainTimeout = setTimeout(function () { return _this._destroySocket(); }, FLUSH_DATA_INTERVAL);\n };\n ConoutConnection.prototype._destroySocket = function () {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this._worker.terminate()];\n case 1:\n _a.sent();\n return [2 /*return*/];\n }\n });\n });\n };\n return ConoutConnection;\n}());\nexports.ConoutConnection = ConoutConnection;\n//# sourceMappingURL=windowsConoutConnection.js.map","\"use strict\";\n/**\n * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)\n * Copyright (c) 2016, Daniel Imms (MIT License).\n * Copyright (c) 2018, Microsoft Corporation (MIT License).\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.argsToCommandLine = exports.WindowsPtyAgent = void 0;\nvar fs = require(\"fs\");\nvar os = require(\"os\");\nvar path = require(\"path\");\nvar child_process_1 = require(\"child_process\");\nvar net_1 = require(\"net\");\nvar windowsConoutConnection_1 = require(\"./windowsConoutConnection\");\nvar utils_1 = require(\"./utils\");\nvar conptyNative;\nvar winptyNative;\n/**\n * The amount of time to wait for additional data after the conpty shell process has exited before\n * shutting down the socket. The timer will be reset if a new data event comes in after the timer\n * has started.\n */\nvar FLUSH_DATA_INTERVAL = 1000;\n/**\n * This agent sits between the WindowsTerminal class and provides a common interface for both conpty\n * and winpty.\n */\nvar WindowsPtyAgent = /** @class */ (function () {\n function WindowsPtyAgent(file, args, env, cwd, cols, rows, debug, _useConpty, _useConptyDll, conptyInheritCursor) {\n var _this = this;\n if (_useConptyDll === void 0) { _useConptyDll = false; }\n if (conptyInheritCursor === void 0) { conptyInheritCursor = false; }\n this._useConpty = _useConpty;\n this._useConptyDll = _useConptyDll;\n this._pid = 0;\n this._innerPid = 0;\n if (this._useConpty === undefined || this._useConpty === true) {\n this._useConpty = this._getWindowsBuildNumber() >= 18309;\n }\n if (this._useConpty) {\n if (!conptyNative) {\n conptyNative = utils_1.loadNativeModule('conpty').module;\n }\n }\n else {\n if (!winptyNative) {\n winptyNative = utils_1.loadNativeModule('pty').module;\n }\n }\n this._ptyNative = this._useConpty ? conptyNative : winptyNative;\n // Sanitize input variable.\n cwd = path.resolve(cwd);\n // Compose command line\n var commandLine = argsToCommandLine(file, args);\n // Open pty session.\n var term;\n if (this._useConpty) {\n term = this._ptyNative.startProcess(file, cols, rows, debug, this._generatePipeName(), conptyInheritCursor, this._useConptyDll);\n }\n else {\n term = this._ptyNative.startProcess(file, commandLine, env, cwd, cols, rows, debug);\n this._pid = term.pid;\n this._innerPid = term.innerPid;\n }\n // Not available on windows.\n this._fd = term.fd;\n // Generated incremental number that has no real purpose besides using it\n // as a terminal id.\n this._pty = term.pty;\n // Create terminal pipe IPC channel and forward to a local unix socket.\n this._outSocket = new net_1.Socket();\n this._outSocket.setEncoding('utf8');\n // The conout socket must be ready out on another thread to avoid deadlocks\n this._conoutSocketWorker = new windowsConoutConnection_1.ConoutConnection(term.conout, this._useConptyDll);\n this._conoutSocketWorker.onReady(function () {\n _this._conoutSocketWorker.connectSocket(_this._outSocket);\n });\n this._outSocket.on('connect', function () {\n _this._outSocket.emit('ready_datapipe');\n });\n var inSocketFD = fs.openSync(term.conin, 'w');\n this._inSocket = new net_1.Socket({\n fd: inSocketFD,\n readable: false,\n writable: true\n });\n this._inSocket.setEncoding('utf8');\n if (this._useConpty) {\n var connect = this._ptyNative.connect(this._pty, commandLine, cwd, env, this._useConptyDll, function (c) { return _this._$onProcessExit(c); });\n this._innerPid = connect.pid;\n }\n }\n Object.defineProperty(WindowsPtyAgent.prototype, \"inSocket\", {\n get: function () { return this._inSocket; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(WindowsPtyAgent.prototype, \"outSocket\", {\n get: function () { return this._outSocket; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(WindowsPtyAgent.prototype, \"fd\", {\n get: function () { return this._fd; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(WindowsPtyAgent.prototype, \"innerPid\", {\n get: function () { return this._innerPid; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(WindowsPtyAgent.prototype, \"pty\", {\n get: function () { return this._pty; },\n enumerable: false,\n configurable: true\n });\n WindowsPtyAgent.prototype.resize = function (cols, rows) {\n if (this._useConpty) {\n if (this._exitCode !== undefined) {\n throw new Error('Cannot resize a pty that has already exited');\n }\n this._ptyNative.resize(this._pty, cols, rows, this._useConptyDll);\n return;\n }\n this._ptyNative.resize(this._pid, cols, rows);\n };\n WindowsPtyAgent.prototype.clear = function () {\n if (this._useConpty) {\n this._ptyNative.clear(this._pty, this._useConptyDll);\n }\n };\n WindowsPtyAgent.prototype.kill = function () {\n var _this = this;\n // Tell the agent to kill the pty, this releases handles to the process\n if (this._useConpty) {\n if (!this._useConptyDll) {\n this._inSocket.readable = false;\n this._outSocket.readable = false;\n this._getConsoleProcessList().then(function (consoleProcessList) {\n consoleProcessList.forEach(function (pid) {\n try {\n process.kill(pid);\n }\n catch (e) {\n // Ignore if process cannot be found (kill ESRCH error)\n }\n });\n });\n this._ptyNative.kill(this._pty, this._useConptyDll);\n this._conoutSocketWorker.dispose();\n }\n else {\n // Close the input write handle to signal the end of session.\n this._inSocket.destroy();\n this._ptyNative.kill(this._pty, this._useConptyDll);\n this._outSocket.on('data', function () {\n _this._conoutSocketWorker.dispose();\n });\n }\n }\n else {\n // Because pty.kill closes the handle, it will kill most processes by itself.\n // Process IDs can be reused as soon as all handles to them are\n // dropped, so we want to immediately kill the entire console process list.\n // If we do not force kill all processes here, node servers in particular\n // seem to become detached and remain running (see\n // Microsoft/vscode#26807).\n var processList = this._ptyNative.getProcessList(this._pid);\n this._ptyNative.kill(this._pid, this._innerPid);\n processList.forEach(function (pid) {\n try {\n process.kill(pid);\n }\n catch (e) {\n // Ignore if process cannot be found (kill ESRCH error)\n }\n });\n }\n };\n WindowsPtyAgent.prototype._getConsoleProcessList = function () {\n var _this = this;\n return new Promise(function (resolve) {\n var agent = child_process_1.fork(path.join(__dirname, 'conpty_console_list_agent'), [_this._innerPid.toString()]);\n agent.on('message', function (message) {\n clearTimeout(timeout);\n resolve(message.consoleProcessList);\n });\n var timeout = setTimeout(function () {\n // Something went wrong, just send back the shell PID\n agent.kill();\n resolve([_this._innerPid]);\n }, 5000);\n });\n };\n Object.defineProperty(WindowsPtyAgent.prototype, \"exitCode\", {\n get: function () {\n if (this._useConpty) {\n return this._exitCode;\n }\n var winptyExitCode = this._ptyNative.getExitCode(this._innerPid);\n return winptyExitCode === -1 ? undefined : winptyExitCode;\n },\n enumerable: false,\n configurable: true\n });\n WindowsPtyAgent.prototype._getWindowsBuildNumber = function () {\n var osVersion = (/(\\d+)\\.(\\d+)\\.(\\d+)/g).exec(os.release());\n var buildNumber = 0;\n if (osVersion && osVersion.length === 4) {\n buildNumber = parseInt(osVersion[3]);\n }\n return buildNumber;\n };\n WindowsPtyAgent.prototype._generatePipeName = function () {\n return \"conpty-\" + Math.random() * 10000000;\n };\n /**\n * Triggered from the native side when a contpy process exits.\n */\n WindowsPtyAgent.prototype._$onProcessExit = function (exitCode) {\n var _this = this;\n this._exitCode = exitCode;\n if (!this._useConptyDll) {\n this._flushDataAndCleanUp();\n this._outSocket.on('data', function () { return _this._flushDataAndCleanUp(); });\n }\n };\n WindowsPtyAgent.prototype._flushDataAndCleanUp = function () {\n var _this = this;\n if (this._useConptyDll) {\n return;\n }\n if (this._closeTimeout) {\n clearTimeout(this._closeTimeout);\n }\n this._closeTimeout = setTimeout(function () { return _this._cleanUpProcess(); }, FLUSH_DATA_INTERVAL);\n };\n WindowsPtyAgent.prototype._cleanUpProcess = function () {\n if (this._useConptyDll) {\n return;\n }\n this._inSocket.readable = false;\n this._outSocket.readable = false;\n this._outSocket.destroy();\n };\n return WindowsPtyAgent;\n}());\nexports.WindowsPtyAgent = WindowsPtyAgent;\n// Convert argc/argv into a Win32 command-line following the escaping convention\n// documented on MSDN (e.g. see CommandLineToArgvW documentation). Copied from\n// winpty project.\nfunction argsToCommandLine(file, args) {\n if (isCommandLine(args)) {\n if (args.length === 0) {\n return file;\n }\n return argsToCommandLine(file, []) + \" \" + args;\n }\n var argv = [file];\n Array.prototype.push.apply(argv, args);\n var result = '';\n for (var argIndex = 0; argIndex < argv.length; argIndex++) {\n if (argIndex > 0) {\n result += ' ';\n }\n var arg = argv[argIndex];\n // if it is empty or it contains whitespace and is not already quoted\n var hasLopsidedEnclosingQuote = xOr((arg[0] !== '\"'), (arg[arg.length - 1] !== '\"'));\n var hasNoEnclosingQuotes = ((arg[0] !== '\"') && (arg[arg.length - 1] !== '\"'));\n var quote = arg === '' ||\n (arg.indexOf(' ') !== -1 ||\n arg.indexOf('\\t') !== -1) &&\n ((arg.length > 1) &&\n (hasLopsidedEnclosingQuote || hasNoEnclosingQuotes));\n if (quote) {\n result += '\\\"';\n }\n var bsCount = 0;\n for (var i = 0; i < arg.length; i++) {\n var p = arg[i];\n if (p === '\\\\') {\n bsCount++;\n }\n else if (p === '\"') {\n result += repeatText('\\\\', bsCount * 2 + 1);\n result += '\"';\n bsCount = 0;\n }\n else {\n result += repeatText('\\\\', bsCount);\n bsCount = 0;\n result += p;\n }\n }\n if (quote) {\n result += repeatText('\\\\', bsCount * 2);\n result += '\\\"';\n }\n else {\n result += repeatText('\\\\', bsCount);\n }\n }\n return result;\n}\nexports.argsToCommandLine = argsToCommandLine;\nfunction isCommandLine(args) {\n return typeof args === 'string';\n}\nfunction repeatText(text, count) {\n var result = '';\n for (var i = 0; i < count; i++) {\n result += text;\n }\n return result;\n}\nfunction xOr(arg1, arg2) {\n return ((arg1 && !arg2) || (!arg1 && arg2));\n}\n//# sourceMappingURL=windowsPtyAgent.js.map","\"use strict\";\n/**\n * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)\n * Copyright (c) 2016, Daniel Imms (MIT License).\n * Copyright (c) 2018, Microsoft Corporation (MIT License).\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WindowsTerminal = void 0;\nvar terminal_1 = require(\"./terminal\");\nvar windowsPtyAgent_1 = require(\"./windowsPtyAgent\");\nvar utils_1 = require(\"./utils\");\nvar DEFAULT_FILE = 'cmd.exe';\nvar DEFAULT_NAME = 'Windows Shell';\nvar WindowsTerminal = /** @class */ (function (_super) {\n __extends(WindowsTerminal, _super);\n function WindowsTerminal(file, args, opt) {\n var _this = _super.call(this, opt) || this;\n _this._checkType('args', args, 'string', true);\n // Initialize arguments\n args = args || [];\n file = file || DEFAULT_FILE;\n opt = opt || {};\n opt.env = opt.env || process.env;\n if (opt.encoding) {\n console.warn('Setting encoding on Windows is not supported');\n }\n var env = utils_1.assign({}, opt.env);\n _this._cols = opt.cols || terminal_1.DEFAULT_COLS;\n _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;\n var cwd = opt.cwd || process.cwd();\n var name = opt.name || env.TERM || DEFAULT_NAME;\n var parsedEnv = _this._parseEnv(env);\n // If the terminal is ready\n _this._isReady = false;\n // Functions that need to run after `ready` event is emitted.\n _this._deferreds = [];\n // Create new termal.\n _this._agent = new windowsPtyAgent_1.WindowsPtyAgent(file, args, parsedEnv, cwd, _this._cols, _this._rows, false, opt.useConpty, opt.useConptyDll, opt.conptyInheritCursor);\n _this._socket = _this._agent.outSocket;\n // Not available until `ready` event emitted.\n _this._pid = _this._agent.innerPid;\n _this._fd = _this._agent.fd;\n _this._pty = _this._agent.pty;\n // The forked windows terminal is not available until `ready` event is\n // emitted.\n _this._socket.on('ready_datapipe', function () {\n // Run deferreds and set ready state once the first data event is received.\n _this._socket.once('data', function () {\n // Wait until the first data event is fired then we can run deferreds.\n if (!_this._isReady) {\n // Terminal is now ready and we can avoid having to defer method\n // calls.\n _this._isReady = true;\n // Execute all deferred methods\n _this._deferreds.forEach(function (fn) {\n // NB! In order to ensure that `this` has all its references\n // updated any variable that need to be available in `this` before\n // the deferred is run has to be declared above this forEach\n // statement.\n fn.run();\n });\n // Reset\n _this._deferreds = [];\n }\n });\n // Shutdown if `error` event is emitted.\n _this._socket.on('error', function (err) {\n // Close terminal session.\n _this._close();\n // EIO, happens when someone closes our child process: the only process\n // in the terminal.\n // node < 0.6.14: errno 5\n // node >= 0.6.14: read EIO\n if (err.code) {\n if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO'))\n return;\n }\n // Throw anything else.\n if (_this.listeners('error').length < 2) {\n throw err;\n }\n });\n // Cleanup after the socket is closed.\n _this._socket.on('close', function () {\n _this.emit('exit', _this._agent.exitCode);\n _this._close();\n });\n });\n _this._file = file;\n _this._name = name;\n _this._readable = true;\n _this._writable = true;\n _this._forwardEvents();\n return _this;\n }\n WindowsTerminal.prototype._write = function (data) {\n this._defer(this._doWrite, data);\n };\n WindowsTerminal.prototype._doWrite = function (data) {\n this._agent.inSocket.write(data);\n };\n /**\n * openpty\n */\n WindowsTerminal.open = function (options) {\n throw new Error('open() not supported on windows, use Fork() instead.');\n };\n /**\n * TTY\n */\n WindowsTerminal.prototype.resize = function (cols, rows) {\n var _this = this;\n if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {\n throw new Error('resizing must be done using positive cols and rows');\n }\n this._deferNoArgs(function () {\n _this._agent.resize(cols, rows);\n _this._cols = cols;\n _this._rows = rows;\n });\n };\n WindowsTerminal.prototype.clear = function () {\n var _this = this;\n this._deferNoArgs(function () {\n _this._agent.clear();\n });\n };\n WindowsTerminal.prototype.destroy = function () {\n var _this = this;\n this._deferNoArgs(function () {\n _this.kill();\n });\n };\n WindowsTerminal.prototype.kill = function (signal) {\n var _this = this;\n this._deferNoArgs(function () {\n if (signal) {\n throw new Error('Signals not supported on windows.');\n }\n _this._close();\n _this._agent.kill();\n });\n };\n WindowsTerminal.prototype._deferNoArgs = function (deferredFn) {\n var _this = this;\n // If the terminal is ready, execute.\n if (this._isReady) {\n deferredFn.call(this);\n return;\n }\n // Queue until terminal is ready.\n this._deferreds.push({\n run: function () { return deferredFn.call(_this); }\n });\n };\n WindowsTerminal.prototype._defer = function (deferredFn, arg) {\n var _this = this;\n // If the terminal is ready, execute.\n if (this._isReady) {\n deferredFn.call(this, arg);\n return;\n }\n // Queue until terminal is ready.\n this._deferreds.push({\n run: function () { return deferredFn.call(_this, arg); }\n });\n };\n Object.defineProperty(WindowsTerminal.prototype, \"process\", {\n get: function () { return this._name; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(WindowsTerminal.prototype, \"master\", {\n get: function () { throw new Error('master is not supported on Windows'); },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(WindowsTerminal.prototype, \"slave\", {\n get: function () { throw new Error('slave is not supported on Windows'); },\n enumerable: false,\n configurable: true\n });\n return WindowsTerminal;\n}(terminal_1.Terminal));\nexports.WindowsTerminal = WindowsTerminal;\n//# sourceMappingURL=windowsTerminal.js.map","\"use strict\";\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UnixTerminal = void 0;\n/**\n * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)\n * Copyright (c) 2016, Daniel Imms (MIT License).\n * Copyright (c) 2018, Microsoft Corporation (MIT License).\n */\nvar fs = require(\"fs\");\nvar path = require(\"path\");\nvar tty = require(\"tty\");\nvar terminal_1 = require(\"./terminal\");\nvar utils_1 = require(\"./utils\");\nvar native = utils_1.loadNativeModule('pty');\nvar pty = native.module;\nvar helperPath = native.dir + '/spawn-helper';\nhelperPath = path.resolve(__dirname, helperPath);\nhelperPath = helperPath.replace('app.asar', 'app.asar.unpacked');\nhelperPath = helperPath.replace('node_modules.asar', 'node_modules.asar.unpacked');\nvar DEFAULT_FILE = 'sh';\nvar DEFAULT_NAME = 'xterm';\nvar DESTROY_SOCKET_TIMEOUT_MS = 200;\nvar UnixTerminal = /** @class */ (function (_super) {\n __extends(UnixTerminal, _super);\n function UnixTerminal(file, args, opt) {\n var _a, _b;\n var _this = _super.call(this, opt) || this;\n _this._boundClose = false;\n _this._emittedClose = false;\n if (typeof args === 'string') {\n throw new Error('args as a string is not supported on unix.');\n }\n // Initialize arguments\n args = args || [];\n file = file || DEFAULT_FILE;\n opt = opt || {};\n opt.env = opt.env || process.env;\n _this._cols = opt.cols || terminal_1.DEFAULT_COLS;\n _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;\n var uid = (_a = opt.uid) !== null && _a !== void 0 ? _a : -1;\n var gid = (_b = opt.gid) !== null && _b !== void 0 ? _b : -1;\n var env = utils_1.assign({}, opt.env);\n if (opt.env === process.env) {\n _this._sanitizeEnv(env);\n }\n var cwd = opt.cwd || process.cwd();\n env.PWD = cwd;\n var name = opt.name || env.TERM || DEFAULT_NAME;\n env.TERM = name;\n var parsedEnv = _this._parseEnv(env);\n var encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);\n var onexit = function (code, signal) {\n // XXX Sometimes a data event is emitted after exit. Wait til socket is\n // destroyed.\n if (!_this._emittedClose) {\n if (_this._boundClose) {\n return;\n }\n _this._boundClose = true;\n // From macOS High Sierra 10.13.2 sometimes the socket never gets\n // closed. A timeout is applied here to avoid the terminal never being\n // destroyed when this occurs.\n var timeout_1 = setTimeout(function () {\n timeout_1 = null;\n // Destroying the socket now will cause the close event to fire\n _this._socket.destroy();\n }, DESTROY_SOCKET_TIMEOUT_MS);\n _this.once('close', function () {\n if (timeout_1 !== null) {\n clearTimeout(timeout_1);\n }\n _this.emit('exit', code, signal);\n });\n return;\n }\n _this.emit('exit', code, signal);\n };\n // fork\n var term = pty.fork(file, args, parsedEnv, cwd, _this._cols, _this._rows, uid, gid, (encoding === 'utf8'), helperPath, onexit);\n _this._socket = new tty.ReadStream(term.fd);\n if (encoding !== null) {\n _this._socket.setEncoding(encoding);\n }\n _this._writeStream = new CustomWriteStream(term.fd, (encoding || undefined));\n // setup\n _this._socket.on('error', function (err) {\n // NOTE: fs.ReadStream gets EAGAIN twice at first:\n if (err.code) {\n if (~err.code.indexOf('EAGAIN')) {\n return;\n }\n }\n // close\n _this._close();\n // EIO on exit from fs.ReadStream:\n if (!_this._emittedClose) {\n _this._emittedClose = true;\n _this.emit('close');\n }\n // EIO, happens when someone closes our child process: the only process in\n // the terminal.\n // node < 0.6.14: errno 5\n // node >= 0.6.14: read EIO\n if (err.code) {\n if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO')) {\n return;\n }\n }\n // throw anything else\n if (_this.listeners('error').length < 2) {\n throw err;\n }\n });\n _this._pid = term.pid;\n _this._fd = term.fd;\n _this._pty = term.pty;\n _this._file = file;\n _this._name = name;\n _this._readable = true;\n _this._writable = true;\n _this._socket.on('close', function () {\n if (_this._emittedClose) {\n return;\n }\n _this._emittedClose = true;\n _this._close();\n _this.emit('close');\n });\n _this._forwardEvents();\n return _this;\n }\n Object.defineProperty(UnixTerminal.prototype, \"master\", {\n get: function () { return this._master; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(UnixTerminal.prototype, \"slave\", {\n get: function () { return this._slave; },\n enumerable: false,\n configurable: true\n });\n UnixTerminal.prototype._write = function (data) {\n this._writeStream.write(data);\n };\n Object.defineProperty(UnixTerminal.prototype, \"fd\", {\n /* Accessors */\n get: function () { return this._fd; },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(UnixTerminal.prototype, \"ptsName\", {\n get: function () { return this._pty; },\n enumerable: false,\n configurable: true\n });\n /**\n * openpty\n */\n UnixTerminal.open = function (opt) {\n var self = Object.create(UnixTerminal.prototype);\n opt = opt || {};\n if (arguments.length > 1) {\n opt = {\n cols: arguments[1],\n rows: arguments[2]\n };\n }\n var cols = opt.cols || terminal_1.DEFAULT_COLS;\n var rows = opt.rows || terminal_1.DEFAULT_ROWS;\n var encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);\n // open\n var term = pty.open(cols, rows);\n self._master = new tty.ReadStream(term.master);\n if (encoding !== null) {\n self._master.setEncoding(encoding);\n }\n self._master.resume();\n self._slave = new tty.ReadStream(term.slave);\n if (encoding !== null) {\n self._slave.setEncoding(encoding);\n }\n self._slave.resume();\n self._socket = self._master;\n self._pid = -1;\n self._fd = term.master;\n self._pty = term.pty;\n self._file = process.argv[0] || 'node';\n self._name = process.env.TERM || '';\n self._readable = true;\n self._writable = true;\n self._socket.on('error', function (err) {\n self._close();\n if (self.listeners('error').length < 2) {\n throw err;\n }\n });\n self._socket.on('close', function () {\n self._close();\n });\n return self;\n };\n UnixTerminal.prototype.destroy = function () {\n var _this = this;\n this._close();\n // Need to close the read stream so node stops reading a dead file\n // descriptor. Then we can safely SIGHUP the shell.\n this._socket.once('close', function () {\n _this.kill('SIGHUP');\n });\n this._socket.destroy();\n this._writeStream.dispose();\n };\n UnixTerminal.prototype.kill = function (signal) {\n try {\n process.kill(this.pid, signal || 'SIGHUP');\n }\n catch (e) { /* swallow */ }\n };\n Object.defineProperty(UnixTerminal.prototype, \"process\", {\n /**\n * Gets the name of the process.\n */\n get: function () {\n if (process.platform === 'darwin') {\n var title = pty.process(this._fd);\n return (title !== 'kernel_task') ? title : this._file;\n }\n return pty.process(this._fd, this._pty) || this._file;\n },\n enumerable: false,\n configurable: true\n });\n /**\n * TTY\n */\n UnixTerminal.prototype.resize = function (cols, rows) {\n if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {\n throw new Error('resizing must be done using positive cols and rows');\n }\n pty.resize(this._fd, cols, rows);\n this._cols = cols;\n this._rows = rows;\n };\n UnixTerminal.prototype.clear = function () {\n };\n UnixTerminal.prototype._sanitizeEnv = function (env) {\n // Make sure we didn't start our server from inside tmux.\n delete env['TMUX'];\n delete env['TMUX_PANE'];\n // Make sure we didn't start our server from inside screen.\n // http://web.mit.edu/gnu/doc/html/screen_20.html\n delete env['STY'];\n delete env['WINDOW'];\n // Delete some variables that might confuse our terminal.\n delete env['WINDOWID'];\n delete env['TERMCAP'];\n delete env['COLUMNS'];\n delete env['LINES'];\n };\n return UnixTerminal;\n}(terminal_1.Terminal));\nexports.UnixTerminal = UnixTerminal;\n/**\n * A custom write stream that writes directly to a file descriptor with proper\n * handling of backpressure and errors. This avoids some event loop exhaustion\n * issues that can occur when using the standard APIs in Node.\n */\nvar CustomWriteStream = /** @class */ (function () {\n function CustomWriteStream(_fd, _encoding) {\n this._fd = _fd;\n this._encoding = _encoding;\n this._writeQueue = [];\n }\n CustomWriteStream.prototype.dispose = function () {\n clearImmediate(this._writeImmediate);\n this._writeImmediate = undefined;\n };\n CustomWriteStream.prototype.write = function (data) {\n // Writes are put in a queue and processed asynchronously in order to handle\n // backpressure from the kernel buffer.\n var buffer = typeof data === 'string'\n ? Buffer.from(data, this._encoding)\n : Buffer.from(data);\n if (buffer.byteLength !== 0) {\n this._writeQueue.push({ buffer: buffer, offset: 0 });\n if (this._writeQueue.length === 1) {\n this._processWriteQueue();\n }\n }\n };\n CustomWriteStream.prototype._processWriteQueue = function () {\n var _this = this;\n this._writeImmediate = undefined;\n if (this._writeQueue.length === 0) {\n return;\n }\n var task = this._writeQueue[0];\n // Write to the underlying file descriptor and handle it directly, rather\n // than using the `net.Socket`/`tty.WriteStream` wrappers which swallow and\n // mask errors like EAGAIN and can cause the thread to block indefinitely.\n fs.write(this._fd, task.buffer, task.offset, function (err, written) {\n if (err) {\n if ('code' in err && err.code === 'EAGAIN') {\n // `setImmediate` is used to yield to the event loop and re-attempt\n // the write later.\n _this._writeImmediate = setImmediate(function () { return _this._processWriteQueue(); });\n }\n else {\n // Stop processing immediately on unexpected error and log\n _this._writeQueue.length = 0;\n console.error('Unhandled pty write error', err);\n }\n return;\n }\n task.offset += written;\n if (task.offset >= task.buffer.byteLength) {\n _this._writeQueue.shift();\n }\n // Since there is more room in the kernel buffer, we can continue to write\n // until we hit EAGAIN or exhaust the queue.\n //\n // Note that old versions of bash, like v3.2 which ships in macOS, appears\n // to have a bug in its readline implementation that causes data\n // corruption when writes to the pty happens too quickly. Instead of\n // trying to workaround that we just accept it so that large pastes are as\n // fast as possible.\n // Context: https://github.com/microsoft/node-pty/issues/833\n _this._processWriteQueue();\n });\n };\n return CustomWriteStream;\n}());\n//# sourceMappingURL=unixTerminal.js.map","\"use strict\";\n/**\n * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)\n * Copyright (c) 2016, Daniel Imms (MIT License).\n * Copyright (c) 2018, Microsoft Corporation (MIT License).\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.native = exports.open = exports.createTerminal = exports.fork = exports.spawn = void 0;\nvar utils_1 = require(\"./utils\");\nvar terminalCtor;\nif (process.platform === 'win32') {\n terminalCtor = require('./windowsTerminal').WindowsTerminal;\n}\nelse {\n terminalCtor = require('./unixTerminal').UnixTerminal;\n}\n/**\n * Forks a process as a pseudoterminal.\n * @param file The file to launch.\n * @param args The file's arguments as argv (string[]) or in a pre-escaped\n * CommandLine format (string). Note that the CommandLine option is only\n * available on Windows and is expected to be escaped properly.\n * @param options The options of the terminal.\n * @throws When the file passed to spawn with does not exists.\n * @see CommandLineToArgvW https://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx\n * @see Parsing C++ Comamnd-Line Arguments https://msdn.microsoft.com/en-us/library/17w5ykft.aspx\n * @see GetCommandLine https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156.aspx\n */\nfunction spawn(file, args, opt) {\n return new terminalCtor(file, args, opt);\n}\nexports.spawn = spawn;\n/** @deprecated */\nfunction fork(file, args, opt) {\n return new terminalCtor(file, args, opt);\n}\nexports.fork = fork;\n/** @deprecated */\nfunction createTerminal(file, args, opt) {\n return new terminalCtor(file, args, opt);\n}\nexports.createTerminal = createTerminal;\nfunction open(options) {\n return terminalCtor.open(options);\n}\nexports.open = open;\n/**\n * Expose the native API when not Windows, note that this is not public API and\n * could be removed at any time.\n */\nexports.native = (process.platform !== 'win32' ? utils_1.loadNativeModule('pty').module : null);\n//# sourceMappingURL=index.js.map","/**\n * Backend Terminal — PTY management and scrollback session store\n *\n * Adapted from packages/dashboard/src/terminal/pty-manager.ts and session-store.ts.\n * Provides terminal support with graceful degradation when node-pty is unavailable.\n */\n\nimport type { WebSocket } from 'ws';\n\n// ─── Session Store ──────────────────────────────────────────────────────────\n\nconst MAX_SCROLLBACK = 50_000;\n\nexport class SessionStore {\n private scrollback: string[] = [];\n\n append(data: string): void {\n this.scrollback.push(data);\n if (this.scrollback.length > MAX_SCROLLBACK * 1.5) {\n this.scrollback = this.scrollback.slice(-MAX_SCROLLBACK);\n }\n }\n\n getAll(): string {\n return this.scrollback.join('');\n }\n\n clear(): void {\n this.scrollback = [];\n }\n}\n\n// ─── PTY Manager ────────────────────────────────────────────────────────────\n\ntype IPty = import('node-pty').IPty;\n\n// Lazy-load node-pty — it's a native C++ addon that may not be available\nlet pty: typeof import('node-pty') | null = null;\nlet ptyLoadError: string | null = null;\ntry {\n pty = require('node-pty');\n} catch (err) {\n ptyLoadError = err instanceof Error ? err.message : String(err);\n}\n\ninterface PtySession {\n process: IPty;\n pid: number;\n startTime: number;\n cwd: string;\n skipPermissions: boolean;\n disconnectTimer: ReturnType<typeof setTimeout> | null;\n store: SessionStore;\n}\n\ninterface PtyStatus {\n pid: number;\n uptime: number;\n cwd: string;\n memoryMB: number;\n isActive: boolean;\n skipPermissions: boolean;\n alive: boolean;\n}\n\nconst DISCONNECT_TIMEOUT_MS = 60_000;\nconst STATUS_INTERVAL_MS = 1_000;\nconst ACTIVE_THRESHOLD_MS = 2_000;\n\nfunction ptyLog(level: string, ...args: unknown[]): void {\n const ts = new Date().toISOString();\n const msg = args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');\n console.error(`[${ts}] [${level}] [pty-manager] ${msg}`);\n}\n\nexport class PtyManager {\n private static instance: PtyManager | null = null;\n private session: PtySession | null = null;\n private connectedClients = new Set<WebSocket>();\n private lastOutputTime = 0;\n private statusInterval: ReturnType<typeof setInterval> | null = null;\n\n static getInstance(): PtyManager {\n if (!PtyManager.instance) {\n PtyManager.instance = new PtyManager();\n }\n return PtyManager.instance;\n }\n\n spawn(opts: {\n skipPermissions: boolean;\n cwd: string;\n cols?: number;\n rows?: number;\n }): void {\n if (!pty) {\n ptyLog('ERROR', `node-pty not available: ${ptyLoadError}`);\n this.broadcastToClients({\n type: 'output',\n data: `\\r\\n\\x1b[31mTerminal unavailable: node-pty is not installed.\\r\\nError: ${ptyLoadError}\\r\\nRun: npm install node-pty\\x1b[0m\\r\\n`,\n });\n return;\n }\n\n if (this.session) {\n ptyLog('INFO', 'Killing existing session before spawn');\n this.kill();\n }\n\n const isWin = process.platform === 'win32';\n const shell = isWin ? 'cmd.exe' : '/bin/sh';\n const claudeCmd = `claude${opts.skipPermissions ? ' --dangerously-skip-permissions' : ''}`;\n const shellArgs = isWin ? ['/c', claudeCmd] : ['-c', claudeCmd];\n\n ptyLog('INFO', `Spawning: shell=${shell}, args=${JSON.stringify(shellArgs)}, cwd=${opts.cwd}`);\n\n const proc = pty.spawn(shell, shellArgs, {\n name: 'xterm-256color',\n cols: opts.cols ?? 120,\n rows: opts.rows ?? 30,\n cwd: opts.cwd,\n env: process.env as Record<string, string>,\n });\n\n ptyLog('INFO', `Process spawned with pid=${proc.pid}`);\n\n const store = new SessionStore();\n\n this.session = {\n process: proc,\n pid: proc.pid,\n startTime: Date.now(),\n cwd: opts.cwd,\n skipPermissions: opts.skipPermissions,\n disconnectTimer: null,\n store,\n };\n\n this.lastOutputTime = Date.now();\n\n proc.onData((data: string) => {\n this.lastOutputTime = Date.now();\n store.append(data);\n if (this.session?.pid === proc.pid) {\n this.broadcastToClients({ type: 'output', data });\n }\n });\n\n proc.onExit(({ exitCode }: { exitCode: number }) => {\n ptyLog('INFO', `Process exited with code=${exitCode}`);\n if (this.session?.pid !== proc.pid) {\n ptyLog('INFO', `Ignoring stale exit for old pid=${proc.pid}`);\n return;\n }\n this.broadcastToClients({ type: 'exit', code: exitCode });\n this.stopStatusBroadcast();\n this.session = null;\n });\n\n this.broadcastToClients({ type: 'started', pid: proc.pid });\n this.startStatusBroadcast();\n }\n\n write(data: string): void {\n if (this.session) {\n this.session.process.write(data);\n }\n }\n\n resize(cols: number, rows: number): void {\n if (this.session) {\n this.session.process.resize(cols, rows);\n }\n }\n\n kill(): void {\n if (this.session) {\n this.stopStatusBroadcast();\n try {\n this.session.process.kill();\n } catch {\n // process may already be dead\n }\n if (this.session.disconnectTimer) {\n clearTimeout(this.session.disconnectTimer);\n }\n this.session = null;\n }\n }\n\n getStatus(): PtyStatus | null {\n if (!this.session) return null;\n return {\n pid: this.session.pid,\n uptime: Math.floor((Date.now() - this.session.startTime) / 1000),\n cwd: this.session.cwd,\n memoryMB: Math.round((process.memoryUsage().rss / 1024 / 1024) * 10) / 10,\n isActive: Date.now() - this.lastOutputTime < ACTIVE_THRESHOLD_MS,\n skipPermissions: this.session.skipPermissions,\n alive: true,\n };\n }\n\n addClient(ws: WebSocket): void {\n this.connectedClients.add(ws);\n\n if (this.session?.disconnectTimer) {\n clearTimeout(this.session.disconnectTimer);\n this.session.disconnectTimer = null;\n }\n\n if (this.session) {\n const scrollback = this.session.store.getAll();\n if (scrollback) {\n ws.send(JSON.stringify({ type: 'scrollback', data: scrollback }));\n }\n const status = this.getStatus();\n if (status) {\n ws.send(JSON.stringify({ type: 'status', ...status }));\n }\n }\n }\n\n removeClient(ws: WebSocket): void {\n this.connectedClients.delete(ws);\n\n if (this.connectedClients.size === 0 && this.session) {\n this.session.disconnectTimer = setTimeout(() => {\n console.error('[pty] No clients connected for 60s, killing process');\n this.kill();\n }, DISCONNECT_TIMEOUT_MS);\n }\n }\n\n isAlive(): boolean {\n return this.session !== null;\n }\n\n isAvailable(): boolean {\n return pty !== null;\n }\n\n private broadcastToClients(message: Record<string, unknown>): void {\n const data = JSON.stringify(message);\n for (const client of this.connectedClients) {\n if ((client as { readyState: number }).readyState === 1 /* WebSocket.OPEN */) {\n client.send(data);\n }\n }\n }\n\n private startStatusBroadcast(): void {\n this.stopStatusBroadcast();\n this.statusInterval = setInterval(() => {\n const status = this.getStatus();\n if (status) {\n this.broadcastToClients({ type: 'status', ...status });\n }\n }, STATUS_INTERVAL_MS);\n }\n\n private stopStatusBroadcast(): void {\n if (this.statusInterval) {\n clearInterval(this.statusInterval);\n this.statusInterval = null;\n }\n }\n}\n","/**\n * MAXSIM Backend Server — Unified persistent backend service\n *\n * Consolidates HTTP API, WebSocket, MCP endpoint, terminal management,\n * and file watching into a single per-project process.\n *\n * CRITICAL: Never import output() or error() from core — they call process.exit().\n * CRITICAL: Never write to stdout directly — stdout may be reserved for protocol use.\n * All logging must go to stderr via console.error().\n */\n\nimport * as path from 'node:path';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport { createServer } from 'node:http';\nimport type { IncomingMessage } from 'node:http';\nimport type { Duplex } from 'node:stream';\n\nimport express, { type Request, type Response } from 'express';\nimport { WebSocketServer, WebSocket } from 'ws';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport detectPort from 'detect-port';\n\nimport {\n normalizePhaseName,\n comparePhaseNum,\n getPhasePattern,\n extractFrontmatter,\n stateExtractField,\n stateReplaceField,\n} from '../core/index.js';\n\nimport type {\n RoadmapPhase,\n RoadmapMilestone,\n RoadmapAnalysis,\n PhaseStatus,\n} from '../core/index.js';\n\nimport { registerAllTools } from '../mcp/index.js';\nimport { PtyManager } from './terminal.js';\n\nimport type {\n BackendConfig,\n BackendStatus,\n BackendServer,\n PendingQuestion,\n} from './types.js';\n\n// ─── Logging ──────────────────────────────────────────────────────────────\n\nfunction log(level: 'INFO' | 'WARN' | 'ERROR', tag: string, ...args: unknown[]): void {\n const ts = new Date().toISOString();\n const msg = args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');\n console.error(`[${ts}] [${level}] [${tag}] ${msg}`);\n}\n\n// ─── Path security ─────────────────────────────────────────────────────────\n\nfunction isWithinPlanning(cwd: string, targetPath: string): boolean {\n const planningDir = path.resolve(cwd, '.planning');\n const resolved = path.resolve(cwd, targetPath);\n return resolved.startsWith(planningDir);\n}\n\n// ─── Write-suppression for watcher loop prevention ─────────────────────────\n\nfunction normalizeFsPath(p: string): string {\n return p.replace(/\\\\/g, '/');\n}\n\n// ─── Types ─────────────────────────────────────────────────────────────────\n\ninterface DashboardPhase {\n number: string;\n name: string;\n goal: string;\n dependsOn: string[];\n planCount: number;\n summaryCount: number;\n diskStatus: 'complete' | 'partial' | 'planned' | 'discussed' | 'researched' | 'empty' | 'no_directory';\n roadmapComplete: boolean;\n hasContext: boolean;\n hasResearch: boolean;\n}\n\ninterface PlanTask {\n name: string;\n type: string;\n files: string[];\n action: string;\n verify: string;\n done: string;\n completed: boolean;\n}\n\ninterface PlanFile {\n path: string;\n content: string;\n frontmatter: Record<string, unknown>;\n tasks: PlanTask[];\n}\n\ninterface TodoItem {\n text: string;\n completed: boolean;\n file: string;\n}\n\ninterface ParsedState {\n position: string | null;\n lastActivity: string | null;\n currentPhase: string | null;\n currentPlan: string | null;\n status: string | null;\n progress: string | null;\n decisions: string[];\n blockers: string[];\n content: string;\n}\n\n// ─── Parsers ───────────────────────────────────────────────────────────────\n\nfunction parseRoadmap(cwd: string): RoadmapAnalysis | null {\n const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');\n if (!fs.existsSync(roadmapPath)) return null;\n\n const content = fs.readFileSync(roadmapPath, 'utf-8').replace(/\\r\\n/g, '\\n');\n const phasesDir = path.join(cwd, '.planning', 'phases');\n const phasePattern = getPhasePattern();\n const phases: RoadmapPhase[] = [];\n let match: RegExpExecArray | null;\n\n while ((match = phasePattern.exec(content)) !== null) {\n const phaseNum = match[1];\n const phaseName = match[2].replace(/\\(INSERTED\\)/i, '').trim();\n\n const sectionStart = match.index;\n const restOfContent = content.slice(sectionStart);\n const nextHeader = restOfContent.match(/\\n#{2,4}\\s+Phase\\s+\\d/i);\n const sectionEnd = nextHeader ? sectionStart + nextHeader.index! : content.length;\n const section = content.slice(sectionStart, sectionEnd);\n\n const goalMatch = section.match(/\\*\\*Goal(?::\\*\\*|\\*\\*:)\\s*([^\\n]+)/i);\n const goal = goalMatch ? goalMatch[1].trim() : null;\n\n const dependsMatch = section.match(/\\*\\*Depends on:\\*\\*\\s*([^\\n]+)/i);\n const depends_on = dependsMatch ? dependsMatch[1].trim() : null;\n\n const normalized = normalizePhaseName(phaseNum);\n let diskStatus: PhaseStatus = 'no_directory';\n let planCount = 0;\n let summaryCount = 0;\n let hasContext = false;\n let hasResearch = false;\n\n try {\n const entries = fs.readdirSync(phasesDir, { withFileTypes: true });\n const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);\n const dirMatch = dirs.find(d => d.startsWith(normalized + '-') || d === normalized);\n\n if (dirMatch) {\n const phaseFiles = fs.readdirSync(path.join(phasesDir, dirMatch));\n planCount = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;\n summaryCount = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;\n hasContext = phaseFiles.some(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');\n hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');\n\n if (summaryCount >= planCount && planCount > 0) diskStatus = 'complete';\n else if (summaryCount > 0) diskStatus = 'partial';\n else if (planCount > 0) diskStatus = 'planned';\n else if (hasResearch) diskStatus = 'researched';\n else if (hasContext) diskStatus = 'discussed';\n else diskStatus = 'empty';\n }\n } catch {\n // phases dir may not exist\n }\n\n const checkboxPattern = new RegExp(`-\\\\s*\\\\[(x| )\\\\]\\\\s*.*Phase\\\\s+${phaseNum.replace('.', '\\\\.')}`, 'i');\n const checkboxMatch = content.match(checkboxPattern);\n const roadmapComplete = checkboxMatch ? checkboxMatch[1] === 'x' : false;\n\n phases.push({\n number: phaseNum,\n name: phaseName,\n goal,\n depends_on,\n plan_count: planCount,\n summary_count: summaryCount,\n has_context: hasContext,\n has_research: hasResearch,\n disk_status: diskStatus,\n roadmap_complete: roadmapComplete,\n });\n }\n\n const milestones: RoadmapMilestone[] = [];\n const milestonePattern = /##\\s*(.*v(\\d+\\.\\d+)[^(\\n]*)/gi;\n let mMatch: RegExpExecArray | null;\n while ((mMatch = milestonePattern.exec(content)) !== null) {\n milestones.push({ heading: mMatch[1].trim(), version: 'v' + mMatch[2] });\n }\n\n const currentPhase = phases.find(p => p.disk_status === 'planned' || p.disk_status === 'partial') || null;\n const nextPhase = phases.find(p =>\n p.disk_status === 'empty' || p.disk_status === 'no_directory' ||\n p.disk_status === 'discussed' || p.disk_status === 'researched'\n ) || null;\n\n const totalPlans = phases.reduce((sum, p) => sum + p.plan_count, 0);\n const totalSummaries = phases.reduce((sum, p) => sum + p.summary_count, 0);\n const completedPhases = phases.filter(p => p.disk_status === 'complete').length;\n\n return {\n milestones,\n phases,\n phase_count: phases.length,\n completed_phases: completedPhases,\n total_plans: totalPlans,\n total_summaries: totalSummaries,\n progress_percent: totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0,\n current_phase: currentPhase ? currentPhase.number : null,\n next_phase: nextPhase ? nextPhase.number : null,\n missing_phase_details: null,\n };\n}\n\nfunction parseState(cwd: string): ParsedState | null {\n const statePath = path.join(cwd, '.planning', 'STATE.md');\n if (!fs.existsSync(statePath)) return null;\n\n const content = fs.readFileSync(statePath, 'utf-8').replace(/\\r\\n/g, '\\n');\n\n const position = stateExtractField(content, 'Current Position') || stateExtractField(content, 'Phase');\n const lastActivity = stateExtractField(content, 'Last activity') || stateExtractField(content, 'Last Activity');\n const currentPhase = stateExtractField(content, 'Current Phase') || stateExtractField(content, 'Phase');\n const currentPlan = stateExtractField(content, 'Current Plan') || stateExtractField(content, 'Plan');\n const status = stateExtractField(content, 'Status');\n const progress = stateExtractField(content, 'Progress');\n\n const decisions: string[] = [];\n const decisionsMatch = content.match(/###?\\s*Decisions\\s*\\n([\\s\\S]*?)(?=\\n###?|\\n##[^#]|$)/i);\n if (decisionsMatch) {\n const items = decisionsMatch[1].match(/^-\\s+(.+)$/gm) || [];\n for (const item of items) decisions.push(item.replace(/^-\\s+/, '').trim());\n }\n\n const blockers: string[] = [];\n const blockersMatch = content.match(/###?\\s*(?:Blockers|Blockers\\/Concerns)\\s*\\n([\\s\\S]*?)(?=\\n###?|\\n##[^#]|$)/i);\n if (blockersMatch) {\n const items = blockersMatch[1].match(/^-\\s+(.+)$/gm) || [];\n for (const item of items) blockers.push(item.replace(/^-\\s+/, '').trim());\n }\n\n return { position, lastActivity, currentPhase, currentPlan, status, progress, decisions, blockers, content };\n}\n\nfunction parsePhases(cwd: string): DashboardPhase[] {\n const phasesDir = path.join(cwd, '.planning', 'phases');\n if (!fs.existsSync(phasesDir)) return [];\n\n const phases: DashboardPhase[] = [];\n try {\n const entries = fs.readdirSync(phasesDir, { withFileTypes: true });\n const dirs = entries\n .filter(e => e.isDirectory())\n .map(e => e.name)\n .sort((a, b) => comparePhaseNum(a, b));\n\n for (const dir of dirs) {\n const dm = dir.match(/^(\\d+[A-Z]?(?:\\.\\d+)?)-?(.*)/i);\n const phaseNum = dm ? dm[1] : dir;\n const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';\n\n const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));\n const planCount = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;\n const summaryCount = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;\n const hasContext = phaseFiles.some(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');\n const hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');\n\n let diskStatus: DashboardPhase['diskStatus'] = 'no_directory';\n if (summaryCount >= planCount && planCount > 0) diskStatus = 'complete';\n else if (summaryCount > 0) diskStatus = 'partial';\n else if (planCount > 0) diskStatus = 'planned';\n else if (hasResearch) diskStatus = 'researched';\n else if (hasContext) diskStatus = 'discussed';\n else diskStatus = 'empty';\n\n phases.push({\n number: phaseNum,\n name: phaseName,\n goal: '',\n dependsOn: [],\n planCount,\n summaryCount,\n diskStatus,\n roadmapComplete: diskStatus === 'complete',\n hasContext,\n hasResearch,\n });\n }\n } catch {\n // phases dir may not exist or be empty\n }\n\n return phases;\n}\n\nfunction parsePhaseDetail(\n cwd: string,\n phaseId: string\n): { plans: PlanFile[]; context: string | null; research: string | null } | null {\n const phasesDir = path.join(cwd, '.planning', 'phases');\n if (!fs.existsSync(phasesDir)) return null;\n\n const normalized = normalizePhaseName(phaseId);\n try {\n const entries = fs.readdirSync(phasesDir, { withFileTypes: true });\n const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);\n const dirMatch = dirs.find(d => d.startsWith(normalized + '-') || d === normalized);\n if (!dirMatch) return null;\n\n const phaseDir = path.join(phasesDir, dirMatch);\n const phaseFiles = fs.readdirSync(phaseDir);\n\n const planFileNames = phaseFiles\n .filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md')\n .sort();\n\n const plans: PlanFile[] = [];\n for (const planFileName of planFileNames) {\n const planPath = path.join(phaseDir, planFileName);\n const content = fs.readFileSync(planPath, 'utf-8').replace(/\\r\\n/g, '\\n');\n const frontmatter = extractFrontmatter(content) as Record<string, unknown>;\n\n const tasks: PlanTask[] = [];\n const taskRegex = /<task\\s+type=\"([^\"]*)\"[^>]*>\\s*<name>([^<]+)<\\/name>([\\s\\S]*?)<\\/task>/g;\n let taskMatch: RegExpExecArray | null;\n\n while ((taskMatch = taskRegex.exec(content)) !== null) {\n const taskType = taskMatch[1];\n const taskName = taskMatch[2].trim();\n const taskBody = taskMatch[3];\n\n const filesMatch = taskBody.match(/<files>([\\s\\S]*?)<\\/files>/);\n const actionMatch = taskBody.match(/<action>([\\s\\S]*?)<\\/action>/);\n const verifyMatch = taskBody.match(/<verify>([\\s\\S]*?)<\\/verify>/);\n const doneMatch = taskBody.match(/<done>([\\s\\S]*?)<\\/done>/);\n\n const files = filesMatch\n ? filesMatch[1].trim().split('\\n').map(f => f.trim()).filter(Boolean)\n : [];\n\n const doneText = doneMatch ? doneMatch[1].trim() : '';\n tasks.push({\n name: taskName,\n type: taskType,\n files,\n action: actionMatch ? actionMatch[1].trim() : '',\n verify: verifyMatch ? verifyMatch[1].trim() : '',\n done: doneText,\n completed: /^\\[x\\]/i.test(doneText),\n });\n }\n\n plans.push({\n path: path.join('.planning', 'phases', dirMatch, planFileName),\n content,\n frontmatter,\n tasks,\n });\n }\n\n let context: string | null = null;\n const contextFile = phaseFiles.find(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');\n if (contextFile) context = fs.readFileSync(path.join(phaseDir, contextFile), 'utf-8');\n\n let research: string | null = null;\n const researchFile = phaseFiles.find(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');\n if (researchFile) research = fs.readFileSync(path.join(phaseDir, researchFile), 'utf-8');\n\n return { plans, context, research };\n } catch {\n return null;\n }\n}\n\nfunction parseTodos(cwd: string): { pending: TodoItem[]; completed: TodoItem[] } {\n const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');\n const completedDir = path.join(cwd, '.planning', 'todos', 'completed');\n\n const pending: TodoItem[] = [];\n const completed: TodoItem[] = [];\n\n if (fs.existsSync(pendingDir)) {\n try {\n const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(pendingDir, file), 'utf-8');\n const titleMatch = content.match(/^title:\\s*(.+)$/m);\n pending.push({ text: titleMatch ? titleMatch[1].trim() : file.replace('.md', ''), completed: false, file });\n } catch { /* skip unreadable */ }\n }\n } catch { /* pending dir may not exist */ }\n }\n\n if (fs.existsSync(completedDir)) {\n try {\n const files = fs.readdirSync(completedDir).filter(f => f.endsWith('.md'));\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(completedDir, file), 'utf-8');\n const titleMatch = content.match(/^title:\\s*(.+)$/m);\n completed.push({ text: titleMatch ? titleMatch[1].trim() : file.replace('.md', ''), completed: true, file });\n } catch { /* skip unreadable */ }\n }\n } catch { /* completed dir may not exist */ }\n }\n\n return { pending, completed };\n}\n\nfunction parseProject(cwd: string): { project: string | null; requirements: string | null } {\n const projectPath = path.join(cwd, '.planning', 'PROJECT.md');\n const requirementsPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');\n const project = fs.existsSync(projectPath) ? fs.readFileSync(projectPath, 'utf-8') : null;\n const requirements = fs.existsSync(requirementsPath) ? fs.readFileSync(requirementsPath, 'utf-8') : null;\n return { project, requirements };\n}\n\n// ─── Server Factory ────────────────────────────────────────────────────────\n\nexport function createBackendServer(config: BackendConfig): BackendServer {\n const {\n projectCwd,\n host,\n enableTerminal,\n enableFileWatcher,\n enableMcp,\n logDir,\n } = config;\n\n let resolvedPort = config.port;\n const startTime = Date.now();\n let serverReady = false;\n\n // Logging\n fs.mkdirSync(logDir, { recursive: true });\n\n // ─── Write suppression ─────────────────────────────────────────────────\n const suppressedPaths = new Map<string, number>();\n const SUPPRESS_TTL_MS = 500;\n\n function suppressPath(filePath: string): void {\n suppressedPaths.set(normalizeFsPath(filePath), Date.now());\n }\n\n function isSuppressed(filePath: string): boolean {\n const normalized = normalizeFsPath(filePath);\n const timestamp = suppressedPaths.get(normalized);\n if (timestamp === undefined) return false;\n if (Date.now() - timestamp > SUPPRESS_TTL_MS) {\n suppressedPaths.delete(normalized);\n return false;\n }\n return true;\n }\n\n // Periodic cleanup of stale suppressed paths\n const cleanupInterval = setInterval(() => {\n const now = Date.now();\n for (const [p, ts] of suppressedPaths.entries()) {\n if (now - ts > SUPPRESS_TTL_MS) suppressedPaths.delete(p);\n }\n }, 60_000);\n cleanupInterval.unref();\n\n // ─── MCP shared state ──────────────────────────────────────────────────\n const questionQueue: PendingQuestion[] = [];\n const pendingAnswers = new Map<string, (answer: string) => void>();\n\n // ─── WebSocket ─────────────────────────────────────────────────────────\n let clientCount = 0;\n\n const wss = new WebSocketServer({ noServer: true });\n\n wss.on('connection', (ws) => {\n clientCount++;\n log('INFO', 'ws', `Client connected (${clientCount} total)`);\n\n ws.on('close', () => {\n clientCount--;\n log('INFO', 'ws', `Client disconnected (${clientCount} total)`);\n });\n\n ws.on('error', (err) => {\n log('ERROR', 'ws', `Client error: ${err.message}`);\n });\n\n ws.send(JSON.stringify({ type: 'connected', timestamp: Date.now() }));\n\n // Send queued questions on reconnect\n if (questionQueue.length > 0) {\n ws.send(JSON.stringify({\n type: 'questions-queued',\n questions: questionQueue,\n count: questionQueue.length,\n }));\n }\n });\n\n function broadcast(message: Record<string, unknown>): void {\n const data = JSON.stringify(message);\n for (const client of wss.clients) {\n if (client.readyState === WebSocket.OPEN) {\n client.send(data);\n }\n }\n }\n\n // ─── File watcher ──────────────────────────────────────────────────────\n let watcher: { close(): Promise<void> } | null = null;\n\n async function setupWatcher(): Promise<void> {\n if (!enableFileWatcher) return;\n\n const planningDir = path.join(projectCwd, '.planning');\n if (!fs.existsSync(planningDir)) {\n log('WARN', 'watcher', `.planning/ directory not found at ${planningDir}`);\n return;\n }\n\n try {\n const chokidar = await import('chokidar');\n const changedPaths = new Set<string>();\n let flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n function flushChanges(): void {\n if (changedPaths.size > 0) {\n const changes = Array.from(changedPaths);\n changedPaths.clear();\n log('INFO', 'watcher', `Broadcasting ${changes.length} change(s)`);\n broadcast({ type: 'file-changes', changes, timestamp: Date.now() });\n }\n }\n\n function onFileChange(filePath: string): void {\n const normalized = normalizeFsPath(filePath);\n if (isSuppressed(normalized)) return;\n changedPaths.add(normalized);\n if (flushTimer) clearTimeout(flushTimer);\n flushTimer = setTimeout(flushChanges, 500);\n }\n\n const w = chokidar.watch(planningDir, {\n persistent: true,\n ignoreInitial: true,\n depth: 5,\n });\n\n w.on('add', onFileChange);\n w.on('change', onFileChange);\n w.on('unlink', onFileChange);\n w.on('error', (err: unknown) => {\n log('ERROR', 'watcher', `Error: ${(err as Error).message}`);\n });\n\n watcher = w;\n log('INFO', 'watcher', `Watching ${planningDir}`);\n } catch (err) {\n log('ERROR', 'watcher', `Failed to start file watcher: ${(err as Error).message}`);\n }\n }\n\n // ─── Express app ───────────────────────────────────────────────────────\n const app = express();\n app.use(express.json());\n\n // ── Health ──\n app.get('/api/health', (_req: Request, res: Response) => {\n res.json({\n status: 'ok' as const,\n ready: serverReady,\n port: resolvedPort,\n cwd: projectCwd,\n uptime: (Date.now() - startTime) / 1000,\n pid: process.pid,\n mcpEndpoint: enableMcp ? `http://127.0.0.1:${resolvedPort}/mcp` : null,\n terminalAvailable: enableTerminal && PtyManager.getInstance().isAvailable(),\n connectedClients: clientCount,\n });\n });\n\n app.get('/api/ready', (_req: Request, res: Response) => {\n if (serverReady) {\n return res.json({ ready: true, port: resolvedPort, cwd: projectCwd });\n }\n return res.status(503).json({ ready: false, message: 'Server is starting up' });\n });\n\n // ── Roadmap ──\n app.get('/api/roadmap', (_req: Request, res: Response) => {\n try {\n const data = parseRoadmap(projectCwd);\n if (!data) return res.status(404).json({ error: 'ROADMAP.md not found' });\n return res.json(data);\n } catch (err) {\n log('ERROR', 'api', `GET /api/roadmap failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n app.patch('/api/roadmap', (req: Request, res: Response) => {\n try {\n const roadmapPath = path.join(projectCwd, '.planning', 'ROADMAP.md');\n if (!fs.existsSync(roadmapPath)) return res.status(404).json({ error: 'ROADMAP.md not found' });\n\n const { phaseNumber, checked } = req.body as { phaseNumber?: string; checked?: boolean };\n if (!phaseNumber || checked === undefined) {\n return res.status(400).json({ error: 'phaseNumber and checked are required' });\n }\n\n let content = fs.readFileSync(roadmapPath, 'utf-8').replace(/\\r\\n/g, '\\n');\n const escapedNum = phaseNumber.replace('.', '\\\\.');\n const pattern = new RegExp(`(-\\\\s*\\\\[)(x| )(\\\\]\\\\s*.*Phase\\\\s+${escapedNum})`, 'i');\n const match = content.match(pattern);\n\n if (!match) return res.status(404).json({ error: `Phase ${phaseNumber} checkbox not found` });\n\n content = content.replace(pattern, `$1${checked ? 'x' : ' '}$3`);\n suppressPath(roadmapPath);\n fs.writeFileSync(roadmapPath, content, 'utf-8');\n return res.json({ updated: true, phaseNumber, checked });\n } catch (err) {\n log('ERROR', 'api', `PATCH /api/roadmap failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n // ── State ──\n app.get('/api/state', (_req: Request, res: Response) => {\n try {\n const data = parseState(projectCwd);\n if (!data) return res.status(404).json({ error: 'STATE.md not found' });\n return res.json(data);\n } catch (err) {\n log('ERROR', 'api', `GET /api/state failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n app.patch('/api/state', (req: Request, res: Response) => {\n try {\n const statePath = path.join(projectCwd, '.planning', 'STATE.md');\n if (!fs.existsSync(statePath)) return res.status(404).json({ error: 'STATE.md not found' });\n\n const { field, value } = req.body as { field?: string; value?: string };\n if (!field || value === undefined) {\n return res.status(400).json({ error: 'field and value are required' });\n }\n\n const content = fs.readFileSync(statePath, 'utf-8').replace(/\\r\\n/g, '\\n');\n const updated = stateReplaceField(content, field, value);\n if (!updated) return res.status(404).json({ error: `Field \"${field}\" not found in STATE.md` });\n\n suppressPath(statePath);\n fs.writeFileSync(statePath, updated, 'utf-8');\n return res.json({ updated: true, field });\n } catch (err) {\n log('ERROR', 'api', `PATCH /api/state failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n // Helper: ensure STATE.md exists\n function ensureStateMd(statePath: string): void {\n if (fs.existsSync(statePath)) return;\n const planningDir = path.dirname(statePath);\n fs.mkdirSync(planningDir, { recursive: true });\n const template = `# Project State\n\n## Current Position\n\nPhase: 1\nStatus: In progress\nLast activity: ${new Date().toISOString().split('T')[0]} — State file created\n\n## Accumulated Context\n\n### Decisions\n\nNone yet.\n\n### Blockers/Concerns\n\nNone yet.\n`;\n fs.writeFileSync(statePath, template, 'utf-8');\n }\n\n // Helper: append to a STATE.md section\n function appendToStateSection(\n statePath: string,\n sectionPattern: RegExp,\n entry: string,\n fallbackSection: string,\n ): void {\n let content = fs.readFileSync(statePath, 'utf-8').replace(/\\r\\n/g, '\\n');\n const match = content.match(sectionPattern);\n\n if (match) {\n let sectionBody = match[2];\n sectionBody = sectionBody\n .replace(/None yet\\.?\\s*\\n?/gi, '')\n .replace(/No decisions yet\\.?\\s*\\n?/gi, '')\n .replace(/None\\.?\\s*\\n?/gi, '');\n sectionBody = sectionBody.trimEnd() + '\\n' + entry + '\\n';\n content = content.replace(sectionPattern, (_m, header: string) => `${header}${sectionBody}`);\n } else {\n content = content.trimEnd() + '\\n\\n' + fallbackSection + '\\n' + entry + '\\n';\n }\n\n suppressPath(statePath);\n fs.writeFileSync(statePath, content, 'utf-8');\n }\n\n // ── Add Decision ──\n app.post('/api/state/decision', (req: Request, res: Response) => {\n try {\n const statePath = path.join(projectCwd, '.planning', 'STATE.md');\n ensureStateMd(statePath);\n\n const { phase, text } = req.body as { phase?: string; text?: string };\n if (!text?.trim()) return res.status(400).json({ error: 'text is required' });\n\n const phaseLabel = phase?.trim() || '?';\n const entry = `- [Phase ${phaseLabel}]: ${text.trim()}`;\n const sectionPattern = /(###?\\s*(?:Decisions|Decisions Made|Accumulated.*Decisions)\\s*\\n)([\\s\\S]*?)(?=\\n###?|\\n##[^#]|$)/i;\n\n appendToStateSection(statePath, sectionPattern, entry, '### Decisions');\n return res.json({ added: true, decision: entry });\n } catch (err) {\n log('ERROR', 'api', `POST /api/state/decision failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n // ── Add Blocker ──\n app.post('/api/state/blocker', (req: Request, res: Response) => {\n try {\n const statePath = path.join(projectCwd, '.planning', 'STATE.md');\n ensureStateMd(statePath);\n\n const { text } = req.body as { text?: string };\n if (!text?.trim()) return res.status(400).json({ error: 'text is required' });\n\n const entry = `- ${text.trim()}`;\n const sectionPattern = /(###?\\s*(?:Blockers|Blockers\\/Concerns|Concerns)\\s*\\n)([\\s\\S]*?)(?=\\n###?|\\n##[^#]|$)/i;\n\n appendToStateSection(statePath, sectionPattern, entry, '### Blockers/Concerns');\n return res.json({ added: true, blocker: text.trim() });\n } catch (err) {\n log('ERROR', 'api', `POST /api/state/blocker failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n // ── Phases ──\n app.get('/api/phases', (_req: Request, res: Response) => {\n try {\n return res.json(parsePhases(projectCwd));\n } catch (err) {\n log('ERROR', 'api', `GET /api/phases failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n app.get('/api/phase/:id', (req: Request, res: Response) => {\n try {\n const data = parsePhaseDetail(projectCwd, req.params.id);\n if (!data) return res.status(404).json({ error: `Phase ${req.params.id} not found` });\n return res.json(data);\n } catch (err) {\n log('ERROR', 'api', `GET /api/phase/:id failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n // ── Todos ──\n app.get('/api/todos', (_req: Request, res: Response) => {\n try {\n return res.json(parseTodos(projectCwd));\n } catch (err) {\n log('ERROR', 'api', `GET /api/todos failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n app.post('/api/todos', (req: Request, res: Response) => {\n try {\n const pendingDir = path.join(projectCwd, '.planning', 'todos', 'pending');\n const { text } = req.body as { text?: string };\n if (!text) return res.status(400).json({ error: 'text is required' });\n\n fs.mkdirSync(pendingDir, { recursive: true });\n\n const timestamp = new Date().toISOString().split('T')[0];\n const slug = text.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 40);\n const filename = `${timestamp}-${slug}.md`;\n const filePath = path.join(pendingDir, filename);\n const content = `title: ${text}\\ncreated: ${timestamp}\\narea: general\\n\\n${text}\\n`;\n\n suppressPath(filePath);\n fs.writeFileSync(filePath, content, 'utf-8');\n\n return res.json({ created: true, file: filename, text });\n } catch (err) {\n log('ERROR', 'api', `POST /api/todos failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n app.patch('/api/todos', (req: Request, res: Response) => {\n try {\n const pendingDir = path.join(projectCwd, '.planning', 'todos', 'pending');\n const completedDir = path.join(projectCwd, '.planning', 'todos', 'completed');\n const { file, completed } = req.body as { file?: string; completed?: boolean };\n\n if (!file) return res.status(400).json({ error: 'file is required' });\n if (file.includes('/') || file.includes('\\\\') || file.includes('..')) {\n return res.status(400).json({ error: 'Invalid filename' });\n }\n\n if (completed) {\n const sourcePath = path.join(pendingDir, file);\n if (!fs.existsSync(sourcePath)) return res.status(404).json({ error: 'Todo not found in pending' });\n\n fs.mkdirSync(completedDir, { recursive: true });\n const today = new Date().toISOString().split('T')[0];\n let content = fs.readFileSync(sourcePath, 'utf-8');\n content = `completed: ${today}\\n` + content;\n const destPath = path.join(completedDir, file);\n\n suppressPath(sourcePath);\n suppressPath(destPath);\n fs.writeFileSync(destPath, content, 'utf-8');\n fs.unlinkSync(sourcePath);\n\n return res.json({ completed: true, file, date: today });\n } else {\n const sourcePath = path.join(completedDir, file);\n if (!fs.existsSync(sourcePath)) return res.status(404).json({ error: 'Todo not found in completed' });\n\n fs.mkdirSync(pendingDir, { recursive: true });\n let content = fs.readFileSync(sourcePath, 'utf-8');\n content = content.replace(/^completed:\\s*.+\\n/m, '');\n const destPath = path.join(pendingDir, file);\n\n suppressPath(sourcePath);\n suppressPath(destPath);\n fs.writeFileSync(destPath, content, 'utf-8');\n fs.unlinkSync(sourcePath);\n\n return res.json({ completed: false, file });\n }\n } catch (err) {\n log('ERROR', 'api', `PATCH /api/todos failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n // ── Project ──\n app.get('/api/project', (_req: Request, res: Response) => {\n try {\n return res.json(parseProject(projectCwd));\n } catch (err) {\n log('ERROR', 'api', `GET /api/project failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n // ── Plan file (read) ──\n app.get('/api/plan/*', (req: Request, res: Response) => {\n try {\n const pathSegments = (req.params as Record<string, string>)['0'].split('/');\n const relativePath = path.join('.planning', ...pathSegments);\n\n if (!isWithinPlanning(projectCwd, relativePath)) {\n return res.status(403).json({ error: 'Path traversal not allowed' });\n }\n\n const fullPath = path.join(projectCwd, relativePath);\n if (!fs.existsSync(fullPath)) return res.status(404).json({ error: 'File not found' });\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n return res.json({ path: relativePath, content });\n } catch (err) {\n log('ERROR', 'api', `GET /api/plan/* failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n // ── Plan file (write) ──\n app.put('/api/plan/*', (req: Request, res: Response) => {\n try {\n const pathSegments = (req.params as Record<string, string>)['0'].split('/');\n const relativePath = path.join('.planning', ...pathSegments);\n\n if (!isWithinPlanning(projectCwd, relativePath)) {\n return res.status(403).json({ error: 'Path traversal not allowed' });\n }\n\n const { content } = req.body as { content?: string };\n if (content === undefined) return res.status(400).json({ error: 'content is required' });\n\n const fullPath = path.join(projectCwd, relativePath);\n const dir = path.dirname(fullPath);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n\n suppressPath(fullPath);\n fs.writeFileSync(fullPath, content, 'utf-8');\n\n return res.json({ written: true, path: relativePath });\n } catch (err) {\n log('ERROR', 'api', `PUT /api/plan/* failed: ${(err as Error).message}`);\n return res.status(500).json({ error: 'Internal server error' });\n }\n });\n\n // ── Server info ──\n app.get('/api/server-info', (_req: Request, res: Response) => {\n const localNetworkIp = getLocalNetworkIp();\n return res.json({\n localUrl: `http://127.0.0.1:${resolvedPort}`,\n networkUrl: localNetworkIp ? `http://${localNetworkIp}:${resolvedPort}` : null,\n projectName: path.basename(projectCwd),\n projectCwd,\n });\n });\n\n // ── Shutdown ──\n let shutdownFn: (() => void) | null = null;\n\n app.post('/api/shutdown', (_req: Request, res: Response) => {\n res.json({ shutdown: true });\n setTimeout(() => shutdownFn?.(), 100);\n });\n\n // ── MCP answer ──\n app.post('/api/mcp-answer', (req: Request, res: Response) => {\n const { questionId, answer } = req.body as { questionId: string; answer: string };\n if (!questionId || !answer) return res.status(400).json({ error: 'questionId and answer are required' });\n const resolve = pendingAnswers.get(questionId);\n if (!resolve) return res.status(404).json({ error: 'No pending question with that ID' });\n pendingAnswers.delete(questionId);\n resolve(answer);\n return res.json({ answered: true });\n });\n\n // ── MCP endpoint ──\n if (enableMcp) {\n app.post('/mcp', async (req: Request, res: Response) => {\n const mcpServer = new McpServer({ name: 'maxsim-backend', version: '1.0.0' });\n registerAllTools(mcpServer);\n try {\n const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });\n await mcpServer.connect(transport);\n await transport.handleRequest(req, res, req.body);\n res.on('close', () => {\n transport.close();\n mcpServer.close();\n });\n } catch (error) {\n log('ERROR', 'mcp', `Error handling MCP POST request: ${error}`);\n if (!res.headersSent) {\n res.status(500).json({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n });\n }\n }\n });\n\n app.get('/mcp', (_req: Request, res: Response) => {\n res.writeHead(405).end(JSON.stringify({\n jsonrpc: '2.0',\n error: { code: -32000, message: 'Method not allowed.' },\n id: null,\n }));\n });\n\n app.delete('/mcp', (_req: Request, res: Response) => {\n res.status(200).end();\n });\n }\n\n // ─── Terminal WebSocket ────────────────────────────────────────────────\n const terminalWss = new WebSocketServer({ noServer: true });\n const ptyManager = enableTerminal ? PtyManager.getInstance() : null;\n\n if (ptyManager && !ptyManager.isAvailable()) {\n log('WARN', 'server', 'node-pty not available — terminal features disabled');\n }\n\n terminalWss.on('connection', (ws: WebSocket) => {\n if (!ptyManager) return;\n log('INFO', 'terminal-ws', 'Client connected');\n ptyManager.addClient(ws);\n\n if (!ptyManager.isAvailable()) {\n ws.send(JSON.stringify({ type: 'unavailable', reason: 'node-pty is not installed' }));\n }\n\n ws.on('message', (raw: Buffer | string) => {\n try {\n const msg = JSON.parse(typeof raw === 'string' ? raw : raw.toString());\n switch (msg.type) {\n case 'input':\n ptyManager.write(msg.data);\n break;\n case 'resize':\n ptyManager.resize(msg.cols, msg.rows);\n break;\n case 'spawn':\n try {\n ptyManager.spawn({\n skipPermissions: !!msg.skipPermissions,\n cwd: projectCwd,\n cols: msg.cols,\n rows: msg.rows,\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n ws.send(JSON.stringify({ type: 'output', data: `\\r\\n\\x1b[31mFailed to start terminal: ${errMsg}\\x1b[0m\\r\\n` }));\n }\n break;\n case 'kill':\n ptyManager.kill();\n break;\n }\n } catch (err) {\n log('ERROR', 'terminal-ws', `Message handling error: ${(err as Error).message}`);\n }\n });\n\n ws.on('close', () => {\n log('INFO', 'terminal-ws', 'Client disconnected');\n ptyManager.removeClient(ws);\n });\n\n ws.on('error', (err) => {\n log('ERROR', 'terminal-ws', `Client error: ${err.message}`);\n });\n });\n\n // ─── HTTP Server ───────────────────────────────────────────────────────\n const server = createServer(app);\n\n // WebSocket upgrade routing\n server.on('upgrade', (req: IncomingMessage, socket: Duplex, head: Buffer) => {\n const url = req.url || '/';\n if (url === '/ws/terminal' || url.startsWith('/ws/terminal?')) {\n terminalWss.handleUpgrade(req, socket, head, (ws) => {\n terminalWss.emit('connection', ws, req);\n });\n } else if (url === '/api/ws' || url.startsWith('/api/ws?')) {\n wss.handleUpgrade(req, socket, head, (ws) => {\n wss.emit('connection', ws, req);\n });\n } else {\n socket.destroy();\n }\n });\n\n // ─── Lifecycle methods ─────────────────────────────────────────────────\n\n async function start(): Promise<void> {\n const port = await detectPort(config.port);\n resolvedPort = port;\n\n await setupWatcher();\n\n return new Promise<void>((resolve) => {\n server.listen(port, host, () => {\n serverReady = true;\n log('INFO', 'server', `Backend ready on ${host}:${port} for ${projectCwd}`);\n if (enableMcp) {\n log('INFO', 'mcp', `MCP endpoint available at http://127.0.0.1:${port}/mcp`);\n }\n resolve();\n });\n });\n }\n\n async function stop(): Promise<void> {\n log('INFO', 'server', 'Shutting down...');\n clearInterval(cleanupInterval);\n\n if (ptyManager) {\n ptyManager.kill();\n }\n\n if (watcher) {\n await watcher.close().catch(() => {});\n }\n\n terminalWss.close(() => {});\n wss.close(() => {});\n\n return new Promise<void>((resolve) => {\n server.close(() => {\n log('INFO', 'server', 'Server closed');\n resolve();\n });\n });\n }\n\n shutdownFn = () => {\n stop().then(() => process.exit(0)).catch(() => process.exit(1));\n };\n\n function getStatus(): BackendStatus {\n return {\n status: serverReady ? 'ok' : 'starting',\n ready: serverReady,\n port: resolvedPort,\n cwd: projectCwd,\n uptime: (Date.now() - startTime) / 1000,\n pid: process.pid,\n mcpEndpoint: enableMcp ? `http://127.0.0.1:${resolvedPort}/mcp` : null,\n terminalAvailable: ptyManager?.isAvailable() ?? false,\n connectedClients: clientCount,\n };\n }\n\n function getPort(): number {\n return resolvedPort;\n }\n\n return { start, stop, getStatus, getPort };\n}\n\n// ─── Utility ────────────────────────────────────────────────────────────────\n\nfunction getLocalNetworkIp(): string | null {\n const ifaces = os.networkInterfaces();\n for (const iface of Object.values(ifaces)) {\n for (const info of iface ?? []) {\n if (info.family === 'IPv4' && !info.internal) {\n return info.address;\n }\n }\n }\n return null;\n}\n"],"x_google_ignoreList":[8,9,10,11,12,13,14,15,16],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,IAAI;AAEJ,SAAgB,kBAAkB,UAAkC;AAElE,KAAI,aAAa,UAAa,gBAAgB,OA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