@pixelbyte-software/pixcode 1.51.8 → 1.51.9

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 (307) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +155 -155
  3. package/LICENSE +718 -718
  4. package/README.de.md +169 -169
  5. package/README.ja.md +167 -167
  6. package/README.ko.md +167 -167
  7. package/README.md +419 -419
  8. package/README.ru.md +169 -169
  9. package/README.tr.md +298 -298
  10. package/README.zh-CN.md +167 -167
  11. package/SECURITY.md +46 -46
  12. package/dist/api-automation.html +110 -110
  13. package/dist/api-docs.html +548 -548
  14. package/dist/assets/{index--kNEhygZ.js → index-Gs7C4hZT.js} +69 -69
  15. package/dist/clear-cache.html +85 -85
  16. package/dist/convert-icons.md +52 -52
  17. package/dist/docs.html +308 -308
  18. package/dist/favicon.svg +8 -8
  19. package/dist/features.html +133 -133
  20. package/dist/generate-icons.js +48 -48
  21. package/dist/humans.txt +15 -15
  22. package/dist/icons/codex-white.svg +3 -3
  23. package/dist/icons/codex.svg +3 -3
  24. package/dist/icons/cursor-white.svg +11 -11
  25. package/dist/icons/icon-128x128.svg +9 -9
  26. package/dist/icons/icon-144x144.svg +9 -9
  27. package/dist/icons/icon-152x152.svg +9 -9
  28. package/dist/icons/icon-192x192.svg +9 -9
  29. package/dist/icons/icon-384x384.svg +9 -9
  30. package/dist/icons/icon-512x512.svg +9 -9
  31. package/dist/icons/icon-72x72.svg +9 -9
  32. package/dist/icons/icon-96x96.svg +9 -9
  33. package/dist/icons/icon-template.svg +9 -9
  34. package/dist/icons/qwen-logo.svg +14 -14
  35. package/dist/index.html +58 -58
  36. package/dist/landing.html +268 -268
  37. package/dist/llms-full.txt +119 -119
  38. package/dist/llms.txt +53 -53
  39. package/dist/logo.svg +12 -12
  40. package/dist/manifest.json +60 -60
  41. package/dist/openapi.yaml +1696 -1696
  42. package/dist/orchestration.html +125 -125
  43. package/dist/robots.txt +4 -4
  44. package/dist/site.css +692 -692
  45. package/dist/sitemap.xml +51 -51
  46. package/dist/sw.js +132 -132
  47. package/dist-server/server/cli.js +96 -96
  48. package/dist-server/server/daemon/manager.js +33 -33
  49. package/dist-server/server/daemon-manager.js +64 -64
  50. package/dist-server/server/index.js +91 -65
  51. package/dist-server/server/index.js.map +1 -1
  52. package/dist-server/server/routes/commands.js +25 -25
  53. package/dist-server/server/routes/git.js +17 -17
  54. package/dist-server/server/routes/live-view.js +46 -46
  55. package/dist-server/server/services/hermes-gateway.js +5 -5
  56. package/dist-server/server/services/public-api-manifest.js +51 -51
  57. package/package.json +222 -222
  58. package/scripts/fix-node-pty.js +67 -67
  59. package/scripts/github/create-v1.38-issues.mjs +351 -351
  60. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  61. package/scripts/hermes/configure-pixcode-mcp.mjs +165 -165
  62. package/scripts/hermes/pixcode-mcp-server.mjs +1009 -1009
  63. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  64. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  65. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  66. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  67. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  68. package/scripts/smoke/chat-session-state.mjs +19 -19
  69. package/scripts/smoke/code-editor-theme.mjs +55 -55
  70. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  71. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  72. package/scripts/smoke/command-center-non-git.mjs +46 -46
  73. package/scripts/smoke/context-packet.mjs +43 -43
  74. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  75. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  76. package/scripts/smoke/default-landing-routing.mjs +33 -33
  77. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  78. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  79. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  80. package/scripts/smoke/git-install-update.mjs +255 -255
  81. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  82. package/scripts/smoke/hermes-api-install.mjs +56 -56
  83. package/scripts/smoke/hermes-gateway-persistence.mjs +104 -104
  84. package/scripts/smoke/hermes-mcp-pixcode-roundtrip.mjs +426 -426
  85. package/scripts/smoke/hermes-rest-chat-api.mjs +162 -162
  86. package/scripts/smoke/hermes-rest-chat-live.mjs +45 -45
  87. package/scripts/smoke/hermes-rest-codex-launch.mjs +209 -209
  88. package/scripts/smoke/hermes-rest-gateway.mjs +79 -79
  89. package/scripts/smoke/hermes-rest-live.mjs +42 -42
  90. package/scripts/smoke/hermes-roundtrip.mjs +167 -167
  91. package/scripts/smoke/hermes-settings-commands.mjs +349 -349
  92. package/scripts/smoke/hermes-smoke-launcher-guard.mjs +34 -34
  93. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  94. package/scripts/smoke/live-view-environment.mjs +92 -92
  95. package/scripts/smoke/live-view-integration.mjs +450 -450
  96. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  97. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  98. package/scripts/smoke/model-registry.mjs +36 -36
  99. package/scripts/smoke/multi-project-ui.mjs +45 -45
  100. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  101. package/scripts/smoke/notification-center.mjs +87 -87
  102. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  103. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  104. package/scripts/smoke/orchestration-api.mjs +172 -172
  105. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  106. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  107. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  108. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  109. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  110. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  111. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  112. package/scripts/smoke/permission-policy.mjs +50 -50
  113. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  114. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  115. package/scripts/smoke/provider-rest-api.mjs +124 -124
  116. package/scripts/smoke/provider-selection-status.mjs +52 -52
  117. package/scripts/smoke/run-state-refresh.mjs +52 -52
  118. package/scripts/smoke/runtime-manager.mjs +99 -99
  119. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  120. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  121. package/scripts/smoke/static-root-routing.mjs +21 -21
  122. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  123. package/scripts/smoke/taskmaster-config.mjs +24 -24
  124. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  125. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  126. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  127. package/scripts/smoke/telegram-control.mjs +242 -242
  128. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  129. package/scripts/smoke/update-issue-progress.mjs +69 -69
  130. package/scripts/smoke/update-ux.mjs +55 -55
  131. package/scripts/smoke/v138-completion.mjs +132 -132
  132. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  133. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  134. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  135. package/scripts/smoke/v143-remote-control.mjs +76 -76
  136. package/scripts/smoke/v144-production-loop.mjs +47 -47
  137. package/scripts/smoke/v145-platformization.mjs +46 -46
  138. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  139. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  140. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  141. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  142. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  143. package/scripts/smoke/workflow-templates.mjs +43 -43
  144. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  145. package/scripts/update-git-install.mjs +283 -283
  146. package/server/claude-sdk.js +920 -920
  147. package/server/cli.js +1035 -1035
  148. package/server/constants/config.js +4 -4
  149. package/server/cursor-cli.js +344 -344
  150. package/server/daemon/manager.js +563 -563
  151. package/server/daemon-manager.js +964 -964
  152. package/server/database/db.js +895 -895
  153. package/server/database/json-store.js +197 -197
  154. package/server/gemini-cli.js +550 -550
  155. package/server/gemini-response-handler.js +79 -79
  156. package/server/index.js +111 -81
  157. package/server/load-env.js +35 -35
  158. package/server/middleware/auth.js +155 -155
  159. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  160. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
  161. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
  162. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  163. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  164. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  165. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +100 -100
  166. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  167. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  168. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  169. package/server/modules/orchestration/a2a/routes.ts +590 -590
  170. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  171. package/server/modules/orchestration/a2a/types.ts +126 -126
  172. package/server/modules/orchestration/a2a/validator.ts +113 -113
  173. package/server/modules/orchestration/hermes/hermes.routes.ts +642 -642
  174. package/server/modules/orchestration/index.ts +101 -101
  175. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  176. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  177. package/server/modules/orchestration/preview/types.ts +19 -19
  178. package/server/modules/orchestration/security/permission-policy.ts +401 -401
  179. package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
  180. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +64 -64
  181. package/server/modules/orchestration/tasks/orchestration-task.service.ts +209 -209
  182. package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
  183. package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
  184. package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
  185. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  186. package/server/modules/orchestration/workflows/context-packet.ts +186 -186
  187. package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
  188. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
  189. package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
  190. package/server/modules/orchestration/workflows/workflow-runner.ts +2070 -2070
  191. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  192. package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
  193. package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
  194. package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
  195. package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
  196. package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
  197. package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
  198. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  199. package/server/modules/orchestration/workspace/types.ts +52 -52
  200. package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
  201. package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
  202. package/server/modules/providers/index.ts +2 -2
  203. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  204. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  205. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  206. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  207. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  208. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  209. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  210. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  211. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  212. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  213. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  214. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  215. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  216. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  217. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  218. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  219. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  220. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  221. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  222. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  223. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  224. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  225. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  226. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  227. package/server/modules/providers/provider.registry.ts +40 -40
  228. package/server/modules/providers/provider.routes.ts +891 -891
  229. package/server/modules/providers/services/mcp.service.ts +86 -86
  230. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  231. package/server/modules/providers/services/sessions.service.ts +45 -45
  232. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  233. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  234. package/server/modules/providers/shared/provider-configs.ts +142 -142
  235. package/server/modules/providers/tests/mcp.test.ts +293 -293
  236. package/server/openai-codex.js +462 -462
  237. package/server/opencode-cli.js +491 -491
  238. package/server/opencode-response-handler.js +111 -111
  239. package/server/projects.js +3008 -3008
  240. package/server/qwen-code-cli.js +410 -410
  241. package/server/qwen-response-handler.js +73 -73
  242. package/server/routes/agent.js +1435 -1435
  243. package/server/routes/auth.js +142 -142
  244. package/server/routes/codex.js +20 -20
  245. package/server/routes/commands.js +538 -538
  246. package/server/routes/cursor.js +61 -61
  247. package/server/routes/diagnostics.js +41 -41
  248. package/server/routes/gemini.js +25 -25
  249. package/server/routes/git.js +1641 -1641
  250. package/server/routes/live-view.js +387 -387
  251. package/server/routes/mcp-utils.js +13 -13
  252. package/server/routes/messages.js +50 -50
  253. package/server/routes/network.js +117 -117
  254. package/server/routes/platformization.js +182 -182
  255. package/server/routes/plugins.js +320 -320
  256. package/server/routes/production-agent-loop.js +90 -90
  257. package/server/routes/projects.js +911 -911
  258. package/server/routes/public-api.js +34 -34
  259. package/server/routes/qwen.js +27 -27
  260. package/server/routes/remote.js +50 -50
  261. package/server/routes/settings.js +321 -321
  262. package/server/routes/telegram.js +140 -140
  263. package/server/routes/user.js +125 -125
  264. package/server/routes/webhooks.js +63 -63
  265. package/server/services/control-room.js +102 -102
  266. package/server/services/diagnostics.js +165 -165
  267. package/server/services/external-access.js +375 -375
  268. package/server/services/hermes-gateway.js +1562 -1562
  269. package/server/services/hermes-install-jobs.js +729 -729
  270. package/server/services/install-jobs.js +715 -715
  271. package/server/services/live-view.js +956 -956
  272. package/server/services/managed-runtimes.js +493 -493
  273. package/server/services/model-registry.js +144 -144
  274. package/server/services/notification-orchestrator.js +365 -365
  275. package/server/services/notification-taxonomy.js +204 -204
  276. package/server/services/platformization.js +773 -773
  277. package/server/services/production-agent-loop.js +248 -248
  278. package/server/services/provider-cli-versions.js +149 -149
  279. package/server/services/provider-credentials.js +189 -189
  280. package/server/services/provider-models.js +396 -396
  281. package/server/services/public-api-manifest.js +190 -190
  282. package/server/services/remote-connection.js +127 -127
  283. package/server/services/runtime-manager.js +323 -323
  284. package/server/services/startup-update.js +234 -234
  285. package/server/services/telegram/bot.js +331 -331
  286. package/server/services/telegram/control-center.js +979 -979
  287. package/server/services/telegram/telegram-http-client.js +151 -151
  288. package/server/services/telegram/translations.js +340 -340
  289. package/server/services/vapid-keys.js +36 -36
  290. package/server/services/webhooks.js +216 -216
  291. package/server/sessionManager.js +225 -225
  292. package/server/shared/interfaces.ts +54 -54
  293. package/server/shared/types.ts +172 -172
  294. package/server/shared/utils.ts +193 -193
  295. package/server/tsconfig.json +36 -36
  296. package/server/utils/colors.js +21 -21
  297. package/server/utils/commandParser.js +305 -305
  298. package/server/utils/frontmatter.js +18 -18
  299. package/server/utils/gitConfig.js +34 -34
  300. package/server/utils/plugin-loader.js +457 -457
  301. package/server/utils/plugin-process-manager.js +185 -185
  302. package/server/utils/port-access.js +209 -209
  303. package/server/utils/runtime-paths.js +37 -37
  304. package/server/utils/url-detection.js +71 -71
  305. package/server/vite-daemon.js +79 -79
  306. package/shared/modelConstants.js +161 -161
  307. package/shared/networkHosts.js +22 -22
@@ -1,34 +1,34 @@
1
- import { spawn } from 'child_process';
2
- import path from 'path';
3
- import { promises as fs } from 'fs';
4
-
5
- import express from 'express';
6
-
1
+ import { spawn } from 'child_process';
2
+ import path from 'path';
3
+ import { promises as fs } from 'fs';
4
+
5
+ import express from 'express';
6
+
7
7
  import { extractProjectDirectory } from '../projects.js';
8
8
  import { queryClaudeSDK } from '../claude-sdk.js';
9
9
  import { spawnCursor } from '../cursor-cli.js';
10
10
  import { userHasProjectAccess } from '../services/platformization.js';
11
-
11
+
12
12
  const router = express.Router();
13
- const COMMIT_DIFF_CHARACTER_LIMIT = 500_000;
14
- const FILESYSTEM_SCAN_MAX_FILES = 5_000;
15
- const FILESYSTEM_SCAN_MAX_DEPTH = 10;
13
+ const COMMIT_DIFF_CHARACTER_LIMIT = 500_000;
14
+ const FILESYSTEM_SCAN_MAX_FILES = 5_000;
15
+ const FILESYSTEM_SCAN_MAX_DEPTH = 10;
16
16
  const filesystemChangeSnapshots = new Map();
17
17
  const FILESYSTEM_SCAN_EXCLUDED_DIRS = new Set([
18
- '.git',
19
- '.hg',
20
- '.svn',
21
- 'node_modules',
22
- 'dist',
23
- 'dist-server',
24
- 'build',
25
- '.next',
26
- '.nuxt',
27
- '.svelte-kit',
28
- 'coverage',
29
- '.turbo',
30
- '.cache',
31
- '.pixcode-dev',
18
+ '.git',
19
+ '.hg',
20
+ '.svn',
21
+ 'node_modules',
22
+ 'dist',
23
+ 'dist-server',
24
+ 'build',
25
+ '.next',
26
+ '.nuxt',
27
+ '.svelte-kit',
28
+ 'coverage',
29
+ '.turbo',
30
+ '.cache',
31
+ '.pixcode-dev',
32
32
  ]);
33
33
 
34
34
  router.use((req, res, next) => {
@@ -46,1620 +46,1620 @@ router.use((req, res, next) => {
46
46
  });
47
47
 
48
48
  function isNotGitRepositoryMessage(message = '') {
49
- return message.includes('Not a git repository')
50
- || message.includes('not a git repository')
51
- || message.includes('Project directory is not a git repository');
52
- }
53
-
54
- function shouldSkipFilesystemEntry(entryName) {
55
- return FILESYSTEM_SCAN_EXCLUDED_DIRS.has(entryName)
56
- || entryName.endsWith('.log')
57
- || entryName === '.DS_Store';
58
- }
59
-
60
- function toProjectRelativePath(projectPath, filePath) {
61
- return path.relative(projectPath, filePath).replace(/\\/g, '/');
62
- }
63
-
64
- async function collectFilesystemSnapshot(projectPath) {
65
- const snapshot = new Map();
66
- let limitReached = false;
67
-
68
- async function walk(directoryPath, depth) {
69
- if (limitReached || depth > FILESYSTEM_SCAN_MAX_DEPTH) {
70
- return;
71
- }
72
-
73
- let entries = [];
74
- try {
75
- entries = await fs.readdir(directoryPath, { withFileTypes: true });
76
- } catch {
77
- return;
78
- }
79
-
80
- for (const entry of entries) {
81
- if (limitReached || shouldSkipFilesystemEntry(entry.name)) {
82
- continue;
83
- }
84
-
85
- const absolutePath = path.join(directoryPath, entry.name);
86
-
87
- if (entry.isDirectory()) {
88
- await walk(absolutePath, depth + 1);
89
- continue;
90
- }
91
-
92
- if (!entry.isFile()) {
93
- continue;
94
- }
95
-
96
- try {
97
- const stat = await fs.stat(absolutePath);
98
- snapshot.set(toProjectRelativePath(projectPath, absolutePath), {
99
- mtimeMs: Math.round(stat.mtimeMs),
100
- size: stat.size,
101
- });
102
- } catch {
103
- continue;
104
- }
105
-
106
- if (snapshot.size >= FILESYSTEM_SCAN_MAX_FILES) {
107
- limitReached = true;
108
- break;
109
- }
110
- }
111
- }
112
-
113
- await walk(projectPath, 0);
114
- return { snapshot, limitReached };
115
- }
116
-
117
- function diffFilesystemSnapshots(previousSnapshot, nextSnapshot) {
118
- if (!previousSnapshot) {
119
- return { modified: [], added: [], deleted: [] };
120
- }
121
-
122
- const modified = [];
123
- const added = [];
124
- const deleted = [];
125
-
126
- for (const [filePath, nextMeta] of nextSnapshot.entries()) {
127
- const previousMeta = previousSnapshot.get(filePath);
128
- if (!previousMeta) {
129
- added.push(filePath);
130
- continue;
131
- }
132
-
133
- if (previousMeta.mtimeMs !== nextMeta.mtimeMs || previousMeta.size !== nextMeta.size) {
134
- modified.push(filePath);
135
- }
136
- }
137
-
138
- for (const filePath of previousSnapshot.keys()) {
139
- if (!nextSnapshot.has(filePath)) {
140
- deleted.push(filePath);
141
- }
142
- }
143
-
144
- return {
145
- modified: modified.sort(),
146
- added: added.sort(),
147
- deleted: deleted.sort(),
148
- };
149
- }
150
-
151
- async function buildFilesystemStatus(projectPath) {
152
- const normalizedProjectPath = path.resolve(projectPath);
153
- const previousSnapshot = filesystemChangeSnapshots.get(normalizedProjectPath) ?? null;
154
- const { snapshot, limitReached } = await collectFilesystemSnapshot(normalizedProjectPath);
155
- filesystemChangeSnapshots.set(normalizedProjectPath, snapshot);
156
- const { modified, added, deleted } = diffFilesystemSnapshots(previousSnapshot, snapshot);
157
-
158
- return {
159
- isGitRepository: false,
160
- trackingMode: 'filesystem',
161
- branch: null,
162
- hasCommits: false,
163
- modified,
164
- added,
165
- deleted,
166
- untracked: [],
167
- snapshotReady: Boolean(previousSnapshot),
168
- fileCount: snapshot.size,
169
- scanLimitReached: limitReached,
170
- };
171
- }
172
-
173
- function spawnAsync(command, args, options = {}) {
174
- return new Promise((resolve, reject) => {
175
- const child = spawn(command, args, {
176
- ...options,
177
- shell: false,
178
- });
179
-
180
- let stdout = '';
181
- let stderr = '';
182
-
183
- child.stdout.on('data', (data) => {
184
- stdout += data.toString();
185
- });
186
-
187
- child.stderr.on('data', (data) => {
188
- stderr += data.toString();
189
- });
190
-
191
- child.on('error', (error) => {
192
- reject(error);
193
- });
194
-
195
- child.on('close', (code) => {
196
- if (code === 0) {
197
- resolve({ stdout, stderr });
198
- return;
199
- }
200
-
201
- const error = new Error(`Command failed: ${command} ${args.join(' ')}`);
202
- error.code = code;
203
- error.stdout = stdout;
204
- error.stderr = stderr;
205
- reject(error);
206
- });
207
- });
208
- }
209
-
210
- // Input validation helpers (defense-in-depth)
211
- function validateCommitRef(commit) {
212
- // Allow hex hashes, HEAD, HEAD~N, HEAD^N, tag names, branch names
213
- if (!/^[a-zA-Z0-9._~^{}@\/-]+$/.test(commit)) {
214
- throw new Error('Invalid commit reference');
215
- }
216
- return commit;
217
- }
218
-
219
- function validateBranchName(branch) {
220
- if (!/^[a-zA-Z0-9._\/-]+$/.test(branch)) {
221
- throw new Error('Invalid branch name');
222
- }
223
- return branch;
224
- }
225
-
226
- function validateFilePath(file, projectPath) {
227
- if (!file || file.includes('\0')) {
228
- throw new Error('Invalid file path');
229
- }
230
- // Prevent path traversal: resolve the file relative to the project root
231
- // and ensure the result stays within the project directory
232
- if (projectPath) {
233
- const resolved = path.resolve(projectPath, file);
234
- const normalizedRoot = path.resolve(projectPath) + path.sep;
235
- if (!resolved.startsWith(normalizedRoot) && resolved !== path.resolve(projectPath)) {
236
- throw new Error('Invalid file path: path traversal detected');
237
- }
238
- }
239
- return file;
240
- }
241
-
242
- function validateRemoteName(remote) {
243
- if (!/^[a-zA-Z0-9._-]+$/.test(remote)) {
244
- throw new Error('Invalid remote name');
245
- }
246
- return remote;
247
- }
248
-
249
- function validateProjectPath(projectPath) {
250
- if (!projectPath || projectPath.includes('\0')) {
251
- throw new Error('Invalid project path');
252
- }
253
- const resolved = path.resolve(projectPath);
254
- // Must be an absolute path after resolution
255
- if (!path.isAbsolute(resolved)) {
256
- throw new Error('Invalid project path: must be absolute');
257
- }
258
- // Block obviously dangerous paths
259
- if (resolved === '/' || resolved === path.sep) {
260
- throw new Error('Invalid project path: root directory not allowed');
261
- }
262
- return resolved;
263
- }
264
-
265
- // Helper function to get the actual project path from the encoded project name
266
- async function getActualProjectPath(projectName) {
267
- let projectPath;
268
- try {
269
- projectPath = await extractProjectDirectory(projectName);
270
- } catch (error) {
271
- console.error(`Error extracting project directory for ${projectName}:`, error);
272
- throw new Error(`Unable to resolve project path for "${projectName}"`);
273
- }
274
- return validateProjectPath(projectPath);
275
- }
276
-
277
- // Helper function to strip git diff headers
278
- function stripDiffHeaders(diff) {
279
- if (!diff) return '';
280
-
281
- const lines = diff.split('\n');
282
- const filteredLines = [];
283
- let startIncluding = false;
284
-
285
- for (const line of lines) {
286
- // Skip all header lines including diff --git, index, file mode, and --- / +++ file paths
287
- if (line.startsWith('diff --git') ||
288
- line.startsWith('index ') ||
289
- line.startsWith('new file mode') ||
290
- line.startsWith('deleted file mode') ||
291
- line.startsWith('---') ||
292
- line.startsWith('+++')) {
293
- continue;
294
- }
295
-
296
- // Start including lines from @@ hunk headers onwards
297
- if (line.startsWith('@@') || startIncluding) {
298
- startIncluding = true;
299
- filteredLines.push(line);
300
- }
301
- }
302
-
303
- return filteredLines.join('\n');
304
- }
305
-
306
- // Helper function to validate git repository
307
- async function validateGitRepository(projectPath) {
308
- try {
309
- // Check if directory exists
310
- await fs.access(projectPath);
311
- } catch {
312
- throw new Error(`Project path not found: ${projectPath}`);
313
- }
314
-
315
- try {
316
- // Allow any directory that is inside a work tree (repo root or nested folder).
317
- const { stdout: insideWorkTreeOutput } = await spawnAsync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: projectPath });
318
- const isInsideWorkTree = insideWorkTreeOutput.trim() === 'true';
319
- if (!isInsideWorkTree) {
320
- throw new Error('Not inside a git work tree');
321
- }
322
-
323
- // Ensure git can resolve the repository root for this directory.
324
- await spawnAsync('git', ['rev-parse', '--show-toplevel'], { cwd: projectPath });
325
- } catch {
326
- throw new Error('Not a git repository. This directory does not contain a .git folder. Initialize a git repository with "git init" to use source control features.');
327
- }
328
- }
329
-
330
- function getGitErrorDetails(error) {
331
- return `${error?.message || ''} ${error?.stderr || ''} ${error?.stdout || ''}`;
332
- }
333
-
334
- function isMissingHeadRevisionError(error) {
335
- const errorDetails = getGitErrorDetails(error).toLowerCase();
336
- return errorDetails.includes('unknown revision')
337
- || errorDetails.includes('ambiguous argument')
338
- || errorDetails.includes('needed a single revision')
339
- || errorDetails.includes('bad revision');
340
- }
341
-
342
- async function getCurrentBranchName(projectPath) {
343
- try {
344
- // symbolic-ref works even when the repository has no commits.
345
- const { stdout } = await spawnAsync('git', ['symbolic-ref', '--short', 'HEAD'], { cwd: projectPath });
346
- const branchName = stdout.trim();
347
- if (branchName) {
348
- return branchName;
349
- }
350
- } catch (error) {
351
- // Fall back to rev-parse for detached HEAD and older git edge cases.
352
- }
353
-
354
- const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: projectPath });
355
- return stdout.trim();
356
- }
357
-
358
- async function repositoryHasCommits(projectPath) {
359
- try {
360
- await spawnAsync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: projectPath });
361
- return true;
362
- } catch (error) {
363
- if (isMissingHeadRevisionError(error)) {
364
- return false;
365
- }
366
- throw error;
367
- }
368
- }
369
-
370
- async function getRepositoryRootPath(projectPath) {
371
- const { stdout } = await spawnAsync('git', ['rev-parse', '--show-toplevel'], { cwd: projectPath });
372
- return stdout.trim();
373
- }
374
-
375
- function normalizeRepositoryRelativeFilePath(filePath) {
376
- return String(filePath)
377
- .replace(/\\/g, '/')
378
- .replace(/^\.\/+/, '')
379
- .replace(/^\/+/, '')
380
- .trim();
381
- }
382
-
383
- function parseStatusFilePaths(statusOutput) {
384
- return statusOutput
385
- .split('\n')
386
- .map((line) => line.trimEnd())
387
- .filter((line) => line.trim())
388
- .map((line) => {
389
- const statusPath = line.substring(3);
390
- const renamedFilePath = statusPath.split(' -> ')[1];
391
- return normalizeRepositoryRelativeFilePath(renamedFilePath || statusPath);
392
- })
393
- .filter(Boolean);
394
- }
395
-
396
- function buildFilePathCandidates(projectPath, repositoryRootPath, filePath) {
397
- const normalizedFilePath = normalizeRepositoryRelativeFilePath(filePath);
398
- const projectRelativePath = normalizeRepositoryRelativeFilePath(path.relative(repositoryRootPath, projectPath));
399
- const candidates = [normalizedFilePath];
400
-
401
- if (
402
- projectRelativePath
403
- && projectRelativePath !== '.'
404
- && !normalizedFilePath.startsWith(`${projectRelativePath}/`)
405
- ) {
406
- candidates.push(`${projectRelativePath}/${normalizedFilePath}`);
407
- }
408
-
409
- return Array.from(new Set(candidates.filter(Boolean)));
410
- }
411
-
412
- async function resolveRepositoryFilePath(projectPath, filePath) {
413
- validateFilePath(filePath);
414
-
415
- const repositoryRootPath = await getRepositoryRootPath(projectPath);
416
- const candidateFilePaths = buildFilePathCandidates(projectPath, repositoryRootPath, filePath);
417
-
418
- for (const candidateFilePath of candidateFilePaths) {
419
- const { stdout } = await spawnAsync('git', ['status', '--porcelain', '--', candidateFilePath], { cwd: repositoryRootPath });
420
- if (stdout.trim()) {
421
- return {
422
- repositoryRootPath,
423
- repositoryRelativeFilePath: candidateFilePath,
424
- };
425
- }
426
- }
427
-
428
- // If the caller sent a bare filename (e.g. "hello.ts"), recover it from changed files.
429
- const normalizedFilePath = normalizeRepositoryRelativeFilePath(filePath);
430
- if (!normalizedFilePath.includes('/')) {
431
- const { stdout: repositoryStatusOutput } = await spawnAsync('git', ['status', '--porcelain'], { cwd: repositoryRootPath });
432
- const changedFilePaths = parseStatusFilePaths(repositoryStatusOutput);
433
- const suffixMatches = changedFilePaths.filter(
434
- (changedFilePath) => changedFilePath === normalizedFilePath || changedFilePath.endsWith(`/${normalizedFilePath}`),
435
- );
436
-
437
- if (suffixMatches.length === 1) {
438
- return {
439
- repositoryRootPath,
440
- repositoryRelativeFilePath: suffixMatches[0],
441
- };
442
- }
443
- }
444
-
445
- return {
446
- repositoryRootPath,
447
- repositoryRelativeFilePath: candidateFilePaths[0],
448
- };
449
- }
450
-
451
- // Get git status for a project
452
- router.get('/status', async (req, res) => {
453
- const { project } = req.query;
454
- const requestedTrackingMode = String(req.query.mode || req.query.trackingMode || '').toLowerCase();
455
- const gitOnly = requestedTrackingMode === 'git';
456
-
457
- if (!project) {
458
- return res.status(400).json({ error: 'Project name is required' });
459
- }
460
-
461
- let projectPath;
462
- try {
463
- projectPath = await getActualProjectPath(project);
464
-
465
- // Validate git repository
466
- await validateGitRepository(projectPath);
467
-
468
- const branch = await getCurrentBranchName(projectPath);
469
- const hasCommits = await repositoryHasCommits(projectPath);
470
-
471
- // Get git status
472
- const { stdout: statusOutput } = await spawnAsync('git', ['status', '--porcelain'], { cwd: projectPath });
473
-
474
- const modified = [];
475
- const added = [];
476
- const deleted = [];
477
- const untracked = [];
478
-
479
- statusOutput.split('\n').forEach(line => {
480
- if (!line.trim()) return;
481
-
482
- const status = line.substring(0, 2);
483
- const file = line.substring(3);
484
-
485
- if (status === 'M ' || status === ' M' || status === 'MM') {
486
- modified.push(file);
487
- } else if (status === 'A ' || status === 'AM') {
488
- added.push(file);
489
- } else if (status === 'D ' || status === ' D') {
490
- deleted.push(file);
491
- } else if (status === '??') {
492
- untracked.push(file);
493
- }
494
- });
495
-
496
- res.json({
497
- isGitRepository: true,
498
- trackingMode: 'git',
499
- branch,
500
- hasCommits,
501
- modified,
502
- added,
503
- deleted,
504
- untracked
505
- });
506
- } catch (error) {
507
- if (projectPath && !gitOnly && isNotGitRepositoryMessage(error.message)) {
508
- try {
509
- res.json(await buildFilesystemStatus(projectPath));
510
- return;
511
- } catch (fallbackError) {
512
- console.error('Filesystem status fallback error:', fallbackError);
513
- }
514
- }
515
-
516
- console.error('Git status error:', error);
517
- res.json({
518
- isGitRepository: false,
519
- trackingMode: gitOnly ? 'git' : undefined,
520
- error: error.message.includes('not a git repository') || error.message.includes('Project directory is not a git repository')
521
- ? error.message
522
- : 'Git operation failed',
523
- details: error.message.includes('not a git repository') || error.message.includes('Project directory is not a git repository')
524
- ? error.message
525
- : `Failed to get git status: ${error.message}`
526
- });
527
- }
528
- });
529
-
530
- // Get diff for a specific file
531
- router.get('/diff', async (req, res) => {
532
- const { project, file } = req.query;
533
-
534
- if (!project || !file) {
535
- return res.status(400).json({ error: 'Project name and file path are required' });
536
- }
537
-
538
- try {
539
- const projectPath = await getActualProjectPath(project);
540
-
541
- // Validate git repository
542
- await validateGitRepository(projectPath);
543
-
544
- const {
545
- repositoryRootPath,
546
- repositoryRelativeFilePath,
547
- } = await resolveRepositoryFilePath(projectPath, file);
548
-
549
- // Check if file is untracked or deleted
550
- const { stdout: statusOutput } = await spawnAsync(
551
- 'git',
552
- ['status', '--porcelain', '--', repositoryRelativeFilePath],
553
- { cwd: repositoryRootPath },
554
- );
555
- const isUntracked = statusOutput.startsWith('??');
556
- const isDeleted = statusOutput.trim().startsWith('D ') || statusOutput.trim().startsWith(' D');
557
-
558
- let diff;
559
- if (isUntracked) {
560
- // For untracked files, show the entire file content as additions
561
- const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
562
- const stats = await fs.stat(filePath);
563
-
564
- if (stats.isDirectory()) {
565
- // For directories, show a simple message
566
- diff = `Directory: ${repositoryRelativeFilePath}\n(Cannot show diff for directories)`;
567
- } else {
568
- const fileContent = await fs.readFile(filePath, 'utf-8');
569
- const lines = fileContent.split('\n');
570
- diff = `--- /dev/null\n+++ b/${repositoryRelativeFilePath}\n@@ -0,0 +1,${lines.length} @@\n` +
571
- lines.map(line => `+${line}`).join('\n');
572
- }
573
- } else if (isDeleted) {
574
- // For deleted files, show the entire file content from HEAD as deletions
575
- const { stdout: fileContent } = await spawnAsync(
576
- 'git',
577
- ['show', `HEAD:${repositoryRelativeFilePath}`],
578
- { cwd: repositoryRootPath },
579
- );
580
- const lines = fileContent.split('\n');
581
- diff = `--- a/${repositoryRelativeFilePath}\n+++ /dev/null\n@@ -1,${lines.length} +0,0 @@\n` +
582
- lines.map(line => `-${line}`).join('\n');
583
- } else {
584
- // Get diff for tracked files
585
- // First check for unstaged changes (working tree vs index)
586
- const { stdout: unstagedDiff } = await spawnAsync(
587
- 'git',
588
- ['diff', '--', repositoryRelativeFilePath],
589
- { cwd: repositoryRootPath },
590
- );
591
-
592
- if (unstagedDiff) {
593
- // Show unstaged changes if they exist
594
- diff = stripDiffHeaders(unstagedDiff);
595
- } else {
596
- // If no unstaged changes, check for staged changes (index vs HEAD)
597
- const { stdout: stagedDiff } = await spawnAsync(
598
- 'git',
599
- ['diff', '--cached', '--', repositoryRelativeFilePath],
600
- { cwd: repositoryRootPath },
601
- );
602
- diff = stripDiffHeaders(stagedDiff) || '';
603
- }
604
- }
605
-
606
- res.json({ diff });
607
- } catch (error) {
608
- console.error('Git diff error:', error);
609
- res.json({ error: error.message });
610
- }
611
- });
612
-
613
- // Get file content with diff information for CodeEditor
614
- router.get('/file-with-diff', async (req, res) => {
615
- const { project, file } = req.query;
616
-
617
- if (!project || !file) {
618
- return res.status(400).json({ error: 'Project name and file path are required' });
619
- }
620
-
621
- try {
622
- const projectPath = await getActualProjectPath(project);
623
-
624
- // Validate git repository
625
- await validateGitRepository(projectPath);
626
-
627
- const {
628
- repositoryRootPath,
629
- repositoryRelativeFilePath,
630
- } = await resolveRepositoryFilePath(projectPath, file);
631
-
632
- // Check file status
633
- const { stdout: statusOutput } = await spawnAsync(
634
- 'git',
635
- ['status', '--porcelain', '--', repositoryRelativeFilePath],
636
- { cwd: repositoryRootPath },
637
- );
638
- const isUntracked = statusOutput.startsWith('??');
639
- const isDeleted = statusOutput.trim().startsWith('D ') || statusOutput.trim().startsWith(' D');
640
-
641
- let currentContent = '';
642
- let oldContent = '';
643
-
644
- if (isDeleted) {
645
- // For deleted files, get content from HEAD
646
- const { stdout: headContent } = await spawnAsync(
647
- 'git',
648
- ['show', `HEAD:${repositoryRelativeFilePath}`],
649
- { cwd: repositoryRootPath },
650
- );
651
- oldContent = headContent;
652
- currentContent = headContent; // Show the deleted content in editor
653
- } else {
654
- // Get current file content
655
- const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
656
- const stats = await fs.stat(filePath);
657
-
658
- if (stats.isDirectory()) {
659
- // Cannot show content for directories
660
- return res.status(400).json({ error: 'Cannot show diff for directories' });
661
- }
662
-
663
- currentContent = await fs.readFile(filePath, 'utf-8');
664
-
665
- if (!isUntracked) {
666
- // Get the old content from HEAD for tracked files
667
- try {
668
- const { stdout: headContent } = await spawnAsync(
669
- 'git',
670
- ['show', `HEAD:${repositoryRelativeFilePath}`],
671
- { cwd: repositoryRootPath },
672
- );
673
- oldContent = headContent;
674
- } catch (error) {
675
- // File might be newly added to git (staged but not committed)
676
- oldContent = '';
677
- }
678
- }
679
- }
680
-
681
- res.json({
682
- currentContent,
683
- oldContent,
684
- isDeleted,
685
- isUntracked
686
- });
687
- } catch (error) {
688
- console.error('Git file-with-diff error:', error);
689
- res.json({ error: error.message });
690
- }
691
- });
692
-
693
- // Create initial commit
694
- router.post('/initial-commit', async (req, res) => {
695
- const { project } = req.body;
696
-
697
- if (!project) {
698
- return res.status(400).json({ error: 'Project name is required' });
699
- }
700
-
701
- try {
702
- const projectPath = await getActualProjectPath(project);
703
-
704
- // Validate git repository
705
- await validateGitRepository(projectPath);
706
-
707
- // Check if there are already commits
708
- try {
709
- await spawnAsync('git', ['rev-parse', 'HEAD'], { cwd: projectPath });
710
- return res.status(400).json({ error: 'Repository already has commits. Use regular commit instead.' });
711
- } catch (error) {
712
- // No HEAD - this is good, we can create initial commit
713
- }
714
-
715
- // Add all files
716
- await spawnAsync('git', ['add', '.'], { cwd: projectPath });
717
-
718
- // Create initial commit
719
- const { stdout } = await spawnAsync('git', ['commit', '-m', 'Initial commit'], { cwd: projectPath });
720
-
721
- res.json({ success: true, output: stdout, message: 'Initial commit created successfully' });
722
- } catch (error) {
723
- console.error('Git initial commit error:', error);
724
-
725
- // Handle the case where there's nothing to commit
726
- if (error.message.includes('nothing to commit')) {
727
- return res.status(400).json({
728
- error: 'Nothing to commit',
729
- details: 'No files found in the repository. Add some files first.'
730
- });
731
- }
732
-
733
- res.status(500).json({ error: error.message });
734
- }
735
- });
736
-
737
- // Commit changes
738
- router.post('/commit', async (req, res) => {
739
- const { project, message, files } = req.body;
740
-
741
- if (!project || !message || !files || files.length === 0) {
742
- return res.status(400).json({ error: 'Project name, commit message, and files are required' });
743
- }
744
-
745
- try {
746
- const projectPath = await getActualProjectPath(project);
747
-
748
- // Validate git repository
749
- await validateGitRepository(projectPath);
750
- const repositoryRootPath = await getRepositoryRootPath(projectPath);
751
-
752
- // Stage selected files
753
- for (const file of files) {
754
- const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
755
- await spawnAsync('git', ['add', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
756
- }
757
-
758
- // Commit with message
759
- const { stdout } = await spawnAsync('git', ['commit', '-m', message], { cwd: repositoryRootPath });
760
-
761
- res.json({ success: true, output: stdout });
762
- } catch (error) {
763
- console.error('Git commit error:', error);
764
- res.status(500).json({ error: error.message });
765
- }
766
- });
767
-
768
- // Revert latest local commit (keeps changes staged)
769
- router.post('/revert-local-commit', async (req, res) => {
770
- const { project } = req.body;
771
-
772
- if (!project) {
773
- return res.status(400).json({ error: 'Project name is required' });
774
- }
775
-
776
- try {
777
- const projectPath = await getActualProjectPath(project);
778
- await validateGitRepository(projectPath);
779
-
780
- try {
781
- await spawnAsync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: projectPath });
782
- } catch (error) {
783
- return res.status(400).json({
784
- error: 'No local commit to revert',
785
- details: 'This repository has no commit yet.',
786
- });
787
- }
788
-
789
- try {
790
- // Soft reset rewinds one commit while preserving all file changes in the index.
791
- await spawnAsync('git', ['reset', '--soft', 'HEAD~1'], { cwd: projectPath });
792
- } catch (error) {
793
- const errorDetails = `${error.stderr || ''} ${error.message || ''}`;
794
- const isInitialCommit = errorDetails.includes('HEAD~1') &&
795
- (errorDetails.includes('unknown revision') || errorDetails.includes('ambiguous argument'));
796
-
797
- if (!isInitialCommit) {
798
- throw error;
799
- }
800
-
801
- // Initial commit has no parent; deleting HEAD uncommits it and keeps files staged.
802
- await spawnAsync('git', ['update-ref', '-d', 'HEAD'], { cwd: projectPath });
803
- }
804
-
805
- res.json({
806
- success: true,
807
- output: 'Latest local commit reverted successfully. Changes were kept staged.',
808
- });
809
- } catch (error) {
810
- console.error('Git revert local commit error:', error);
811
- res.status(500).json({ error: error.message });
812
- }
813
- });
814
-
815
- // Get list of branches
816
- router.get('/branches', async (req, res) => {
817
- const { project } = req.query;
818
-
819
- if (!project) {
820
- return res.status(400).json({ error: 'Project name is required' });
821
- }
822
-
823
- try {
824
- const projectPath = await getActualProjectPath(project);
825
-
826
- // Validate git repository
827
- await validateGitRepository(projectPath);
828
-
829
- // Get all branches
830
- const { stdout } = await spawnAsync('git', ['branch', '-a'], { cwd: projectPath });
831
-
832
- const rawLines = stdout
833
- .split('\n')
834
- .map(b => b.trim())
835
- .filter(b => b && !b.includes('->'));
836
-
837
- // Local branches (may start with '* ' for current)
838
- const localBranches = rawLines
839
- .filter(b => !b.startsWith('remotes/'))
840
- .map(b => (b.startsWith('* ') ? b.substring(2) : b));
841
-
842
- // Remote branches — strip 'remotes/<remote>/' prefix
843
- const remoteBranches = rawLines
844
- .filter(b => b.startsWith('remotes/'))
845
- .map(b => b.replace(/^remotes\/[^/]+\//, ''))
846
- .filter(name => !localBranches.includes(name)); // skip if already a local branch
847
-
848
- // Backward-compat flat list (local + unique remotes, deduplicated)
849
- const branches = [...localBranches, ...remoteBranches]
850
- .filter((b, i, arr) => arr.indexOf(b) === i);
851
-
852
- res.json({ branches, localBranches, remoteBranches });
853
- } catch (error) {
854
- console.error('Git branches error:', error);
855
- res.json({ error: error.message });
856
- }
857
- });
858
-
859
- // Checkout branch
860
- router.post('/checkout', async (req, res) => {
861
- const { project, branch } = req.body;
862
-
863
- if (!project || !branch) {
864
- return res.status(400).json({ error: 'Project name and branch are required' });
865
- }
866
-
867
- try {
868
- const projectPath = await getActualProjectPath(project);
869
-
870
- // Checkout the branch
871
- validateBranchName(branch);
872
- const { stdout } = await spawnAsync('git', ['checkout', branch], { cwd: projectPath });
873
-
874
- res.json({ success: true, output: stdout });
875
- } catch (error) {
876
- console.error('Git checkout error:', error);
877
- res.status(500).json({ error: error.message });
878
- }
879
- });
880
-
881
- // Create new branch
882
- router.post('/create-branch', async (req, res) => {
883
- const { project, branch } = req.body;
884
-
885
- if (!project || !branch) {
886
- return res.status(400).json({ error: 'Project name and branch name are required' });
887
- }
888
-
889
- try {
890
- const projectPath = await getActualProjectPath(project);
891
-
892
- // Create and checkout new branch
893
- validateBranchName(branch);
894
- const { stdout } = await spawnAsync('git', ['checkout', '-b', branch], { cwd: projectPath });
895
-
896
- res.json({ success: true, output: stdout });
897
- } catch (error) {
898
- console.error('Git create branch error:', error);
899
- res.status(500).json({ error: error.message });
900
- }
901
- });
902
-
903
- // Delete a local branch
904
- router.post('/delete-branch', async (req, res) => {
905
- const { project, branch } = req.body;
906
-
907
- if (!project || !branch) {
908
- return res.status(400).json({ error: 'Project name and branch name are required' });
909
- }
910
-
911
- try {
912
- const projectPath = await getActualProjectPath(project);
913
- await validateGitRepository(projectPath);
914
-
915
- // Safety: cannot delete the currently checked-out branch
916
- const { stdout: currentBranch } = await spawnAsync('git', ['branch', '--show-current'], { cwd: projectPath });
917
- if (currentBranch.trim() === branch) {
918
- return res.status(400).json({ error: 'Cannot delete the currently checked-out branch' });
919
- }
920
-
921
- const { stdout } = await spawnAsync('git', ['branch', '-d', branch], { cwd: projectPath });
922
- res.json({ success: true, output: stdout });
923
- } catch (error) {
924
- console.error('Git delete branch error:', error);
925
- res.status(500).json({ error: error.message });
926
- }
927
- });
928
-
929
- // Get recent commits
930
- router.get('/commits', async (req, res) => {
931
- const { project, limit = 10 } = req.query;
932
-
933
- if (!project) {
934
- return res.status(400).json({ error: 'Project name is required' });
935
- }
936
-
937
- try {
938
- const projectPath = await getActualProjectPath(project);
939
- await validateGitRepository(projectPath);
940
- const parsedLimit = Number.parseInt(String(limit), 10);
941
- const safeLimit = Number.isFinite(parsedLimit) && parsedLimit > 0
942
- ? Math.min(parsedLimit, 100)
943
- : 10;
944
-
945
- // Get commit log with stats
946
- const { stdout } = await spawnAsync(
947
- 'git',
948
- ['log', '--pretty=format:%H|%an|%ae|%ad|%s', '--date=iso-strict', '-n', String(safeLimit)],
949
- { cwd: projectPath },
950
- );
951
-
952
- const commits = stdout
953
- .split('\n')
954
- .filter(line => line.trim())
955
- .map(line => {
956
- const [hash, author, email, date, ...messageParts] = line.split('|');
957
- return {
958
- hash,
959
- author,
960
- email,
961
- date,
962
- message: messageParts.join('|')
963
- };
964
- });
965
-
966
- // Get stats for each commit
967
- for (const commit of commits) {
968
- try {
969
- const { stdout: stats } = await spawnAsync(
970
- 'git', ['show', '--stat', '--format=', commit.hash],
971
- { cwd: projectPath }
972
- );
973
- commit.stats = stats.trim().split('\n').pop(); // Get the summary line
974
- } catch (error) {
975
- commit.stats = '';
976
- }
977
- }
978
-
979
- res.json({ commits });
980
- } catch (error) {
981
- console.error('Git commits error:', error);
982
- res.json({ error: error.message });
983
- }
984
- });
985
-
986
- // Get diff for a specific commit
987
- router.get('/commit-diff', async (req, res) => {
988
- const { project, commit } = req.query;
989
-
990
- if (!project || !commit) {
991
- return res.status(400).json({ error: 'Project name and commit hash are required' });
992
- }
993
-
994
- try {
995
- const projectPath = await getActualProjectPath(project);
996
-
997
- // Validate commit reference (defense-in-depth)
998
- validateCommitRef(commit);
999
-
1000
- // Get diff for the commit
1001
- const { stdout } = await spawnAsync(
1002
- 'git', ['show', commit],
1003
- { cwd: projectPath }
1004
- );
1005
-
1006
- const isTruncated = stdout.length > COMMIT_DIFF_CHARACTER_LIMIT;
1007
- const diff = isTruncated
1008
- ? `${stdout.slice(0, COMMIT_DIFF_CHARACTER_LIMIT)}\n\n... Diff truncated to keep the UI responsive ...`
1009
- : stdout;
1010
-
1011
- res.json({ diff, isTruncated });
1012
- } catch (error) {
1013
- console.error('Git commit diff error:', error);
1014
- res.json({ error: error.message });
1015
- }
1016
- });
1017
-
1018
- // Generate commit message based on staged changes using AI
1019
- router.post('/generate-commit-message', async (req, res) => {
1020
- const { project, files, provider = 'claude' } = req.body;
1021
-
1022
- if (!project || !files || files.length === 0) {
1023
- return res.status(400).json({ error: 'Project name and files are required' });
1024
- }
1025
-
1026
- // Validate provider
1027
- if (!['claude', 'cursor'].includes(provider)) {
1028
- return res.status(400).json({ error: 'provider must be "claude" or "cursor"' });
1029
- }
1030
-
1031
- try {
1032
- const projectPath = await getActualProjectPath(project);
1033
- await validateGitRepository(projectPath);
1034
- const repositoryRootPath = await getRepositoryRootPath(projectPath);
1035
-
1036
- // Get diff for selected files
1037
- let diffContext = '';
1038
- for (const file of files) {
1039
- try {
1040
- const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
1041
- const { stdout } = await spawnAsync(
1042
- 'git', ['diff', 'HEAD', '--', repositoryRelativeFilePath],
1043
- { cwd: repositoryRootPath }
1044
- );
1045
- if (stdout) {
1046
- diffContext += `\n--- ${repositoryRelativeFilePath} ---\n${stdout}`;
1047
- }
1048
- } catch (error) {
1049
- console.error(`Error getting diff for ${file}:`, error);
1050
- }
1051
- }
1052
-
1053
- // If no diff found, might be untracked files
1054
- if (!diffContext.trim()) {
1055
- // Try to get content of untracked files
1056
- for (const file of files) {
1057
- try {
1058
- const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
1059
- const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
1060
- const stats = await fs.stat(filePath);
1061
-
1062
- if (!stats.isDirectory()) {
1063
- const content = await fs.readFile(filePath, 'utf-8');
1064
- diffContext += `\n--- ${repositoryRelativeFilePath} (new file) ---\n${content.substring(0, 1000)}\n`;
1065
- } else {
1066
- diffContext += `\n--- ${repositoryRelativeFilePath} (new directory) ---\n`;
1067
- }
1068
- } catch (error) {
1069
- console.error(`Error reading file ${file}:`, error);
1070
- }
1071
- }
1072
- }
1073
-
1074
- // Generate commit message using AI
1075
- const message = await generateCommitMessageWithAI(files, diffContext, provider, projectPath);
1076
-
1077
- res.json({ message });
1078
- } catch (error) {
1079
- console.error('Generate commit message error:', error);
1080
- res.status(500).json({ error: error.message });
1081
- }
1082
- });
1083
-
1084
- /**
1085
- * Generates a commit message using AI (Claude SDK or Cursor CLI)
1086
- * @param {Array<string>} files - List of changed files
1087
- * @param {string} diffContext - Git diff content
1088
- * @param {string} provider - 'claude' or 'cursor'
1089
- * @param {string} projectPath - Project directory path
1090
- * @returns {Promise<string>} Generated commit message
1091
- */
1092
- async function generateCommitMessageWithAI(files, diffContext, provider, projectPath) {
1093
- // Create the prompt
1094
- const prompt = `Generate a conventional commit message for these changes.
1095
-
1096
- REQUIREMENTS:
1097
- - Format: type(scope): subject
1098
- - Include body explaining what changed and why
1099
- - Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
1100
- - Subject under 50 chars, body wrapped at 72 chars
1101
- - Focus on user-facing changes, not implementation details
1102
- - Consider what's being added AND removed
1103
- - Return ONLY the commit message (no markdown, explanations, or code blocks)
1104
-
1105
- FILES CHANGED:
1106
- ${files.map(f => `- ${f}`).join('\n')}
1107
-
1108
- DIFFS:
1109
- ${diffContext.substring(0, 4000)}
1110
-
1111
- Generate the commit message:`;
1112
-
1113
- try {
1114
- // Create a simple writer that collects the response
1115
- let responseText = '';
1116
- const writer = {
1117
- send: (data) => {
1118
- try {
1119
- const parsed = typeof data === 'string' ? JSON.parse(data) : data;
1120
- console.log('🔍 Writer received message type:', parsed.type);
1121
-
1122
- // Handle different message formats from Claude SDK and Cursor CLI
1123
- // Claude SDK sends: {type: 'claude-response', data: {message: {content: [...]}}}
1124
- if (parsed.type === 'claude-response' && parsed.data) {
1125
- const message = parsed.data.message || parsed.data;
1126
- console.log('📦 Claude response message:', JSON.stringify(message, null, 2).substring(0, 500));
1127
- if (message.content && Array.isArray(message.content)) {
1128
- // Extract text from content array
1129
- for (const item of message.content) {
1130
- if (item.type === 'text' && item.text) {
1131
- console.log('✅ Extracted text chunk:', item.text.substring(0, 100));
1132
- responseText += item.text;
1133
- }
1134
- }
1135
- }
1136
- }
1137
- // Cursor CLI sends: {type: 'cursor-output', output: '...'}
1138
- else if (parsed.type === 'cursor-output' && parsed.output) {
1139
- console.log('✅ Cursor output:', parsed.output.substring(0, 100));
1140
- responseText += parsed.output;
1141
- }
1142
- // Also handle direct text messages
1143
- else if (parsed.type === 'text' && parsed.text) {
1144
- console.log('✅ Direct text:', parsed.text.substring(0, 100));
1145
- responseText += parsed.text;
1146
- }
1147
- } catch (e) {
1148
- // Ignore parse errors
1149
- console.error('Error parsing writer data:', e);
1150
- }
1151
- },
1152
- setSessionId: () => {}, // No-op for this use case
1153
- };
1154
-
1155
- console.log('🚀 Calling AI agent with provider:', provider);
1156
- console.log('📝 Prompt length:', prompt.length);
1157
-
1158
- // Call the appropriate agent
1159
- if (provider === 'claude') {
1160
- await queryClaudeSDK(prompt, {
1161
- cwd: projectPath,
1162
- permissionMode: 'bypassPermissions',
1163
- model: 'sonnet'
1164
- }, writer);
1165
- } else if (provider === 'cursor') {
1166
- await spawnCursor(prompt, {
1167
- cwd: projectPath,
1168
- skipPermissions: true
1169
- }, writer);
1170
- }
1171
-
1172
- console.log('📊 Total response text collected:', responseText.length, 'characters');
1173
- console.log('📄 Response preview:', responseText.substring(0, 200));
1174
-
1175
- // Clean up the response
1176
- const cleanedMessage = cleanCommitMessage(responseText);
1177
- console.log('🧹 Cleaned message:', cleanedMessage.substring(0, 200));
1178
-
1179
- return cleanedMessage || 'chore: update files';
1180
- } catch (error) {
1181
- console.error('Error generating commit message with AI:', error);
1182
- // Fallback to simple message
1183
- return `chore: update ${files.length} file${files.length !== 1 ? 's' : ''}`;
1184
- }
1185
- }
1186
-
1187
- /**
1188
- * Cleans the AI-generated commit message by removing markdown, code blocks, and extra formatting
1189
- * @param {string} text - Raw AI response
1190
- * @returns {string} Clean commit message
1191
- */
1192
- function cleanCommitMessage(text) {
1193
- if (!text || !text.trim()) {
1194
- return '';
1195
- }
1196
-
1197
- let cleaned = text.trim();
1198
-
1199
- // Remove markdown code blocks
1200
- cleaned = cleaned.replace(/```[a-z]*\n/g, '');
1201
- cleaned = cleaned.replace(/```/g, '');
1202
-
1203
- // Remove markdown headers
1204
- cleaned = cleaned.replace(/^#+\s*/gm, '');
1205
-
1206
- // Remove leading/trailing quotes
1207
- cleaned = cleaned.replace(/^["']|["']$/g, '');
1208
-
1209
- // If there are multiple lines, take everything (subject + body)
1210
- // Just clean up extra blank lines
1211
- cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
1212
-
1213
- // Remove any explanatory text before the actual commit message
1214
- // Look for conventional commit pattern and start from there
1215
- const conventionalCommitMatch = cleaned.match(/(feat|fix|docs|style|refactor|perf|test|build|ci|chore)(\(.+?\))?:.+/s);
1216
- if (conventionalCommitMatch) {
1217
- cleaned = cleaned.substring(cleaned.indexOf(conventionalCommitMatch[0]));
1218
- }
1219
-
1220
- return cleaned.trim();
1221
- }
1222
-
1223
- // Get remote status (ahead/behind commits with smart remote detection)
1224
- router.get('/remote-status', async (req, res) => {
1225
- const { project } = req.query;
1226
-
1227
- if (!project) {
1228
- return res.status(400).json({ error: 'Project name is required' });
1229
- }
1230
-
1231
- try {
1232
- const projectPath = await getActualProjectPath(project);
1233
- await validateGitRepository(projectPath);
1234
-
1235
- const branch = await getCurrentBranchName(projectPath);
1236
- const hasCommits = await repositoryHasCommits(projectPath);
1237
-
1238
- const { stdout: remoteOutput } = await spawnAsync('git', ['remote'], { cwd: projectPath });
1239
- const remotes = remoteOutput.trim().split('\n').filter(r => r.trim());
1240
- const hasRemote = remotes.length > 0;
1241
- const fallbackRemoteName = hasRemote
1242
- ? (remotes.includes('origin') ? 'origin' : remotes[0])
1243
- : null;
1244
-
1245
- // Repositories initialized with `git init` can have a branch but no commits.
1246
- // Return a non-error state so the UI can show the initial-commit workflow.
1247
- if (!hasCommits) {
1248
- return res.json({
1249
- hasRemote,
1250
- hasUpstream: false,
1251
- branch,
1252
- remoteName: fallbackRemoteName,
1253
- ahead: 0,
1254
- behind: 0,
1255
- isUpToDate: false,
1256
- message: 'Repository has no commits yet'
1257
- });
1258
- }
1259
-
1260
- // Check if there's a remote tracking branch (smart detection)
1261
- let trackingBranch;
1262
- let remoteName;
1263
- try {
1264
- const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
1265
- trackingBranch = stdout.trim();
1266
- remoteName = trackingBranch.split('/')[0]; // Extract remote name (e.g., "origin/main" -> "origin")
1267
- } catch (error) {
1268
- return res.json({
1269
- hasRemote,
1270
- hasUpstream: false,
1271
- branch,
1272
- remoteName: fallbackRemoteName,
1273
- message: 'No remote tracking branch configured'
1274
- });
1275
- }
1276
-
1277
- // Get ahead/behind counts
1278
- const { stdout: countOutput } = await spawnAsync(
1279
- 'git', ['rev-list', '--count', '--left-right', `${trackingBranch}...HEAD`],
1280
- { cwd: projectPath }
1281
- );
1282
-
1283
- const [behind, ahead] = countOutput.trim().split('\t').map(Number);
1284
-
1285
- res.json({
1286
- hasRemote: true,
1287
- hasUpstream: true,
1288
- branch,
1289
- remoteBranch: trackingBranch,
1290
- remoteName,
1291
- ahead: ahead || 0,
1292
- behind: behind || 0,
1293
- isUpToDate: ahead === 0 && behind === 0
1294
- });
1295
- } catch (error) {
1296
- console.error('Git remote status error:', error);
1297
- res.json({ error: error.message });
1298
- }
1299
- });
1300
-
1301
- // Fetch from remote (using smart remote detection)
1302
- router.post('/fetch', async (req, res) => {
1303
- const { project } = req.body;
1304
-
1305
- if (!project) {
1306
- return res.status(400).json({ error: 'Project name is required' });
1307
- }
1308
-
1309
- try {
1310
- const projectPath = await getActualProjectPath(project);
1311
- await validateGitRepository(projectPath);
1312
-
1313
- // Get current branch and its upstream remote
1314
- const branch = await getCurrentBranchName(projectPath);
1315
-
1316
- let remoteName = 'origin'; // fallback
1317
- try {
1318
- const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
1319
- remoteName = stdout.trim().split('/')[0]; // Extract remote name
1320
- } catch (error) {
1321
- // No upstream, try to fetch from origin anyway
1322
- console.log('No upstream configured, using origin as fallback');
1323
- }
1324
-
1325
- validateRemoteName(remoteName);
1326
- const { stdout } = await spawnAsync('git', ['fetch', remoteName], { cwd: projectPath });
1327
-
1328
- res.json({ success: true, output: stdout || 'Fetch completed successfully', remoteName });
1329
- } catch (error) {
1330
- console.error('Git fetch error:', error);
1331
- res.status(500).json({
1332
- error: 'Fetch failed',
1333
- details: error.message.includes('Could not resolve hostname')
1334
- ? 'Unable to connect to remote repository. Check your internet connection.'
1335
- : error.message.includes('fatal: \'origin\' does not appear to be a git repository')
1336
- ? 'No remote repository configured. Add a remote with: git remote add origin <url>'
1337
- : error.message
1338
- });
1339
- }
1340
- });
1341
-
1342
- // Pull from remote (fetch + merge using smart remote detection)
1343
- router.post('/pull', async (req, res) => {
1344
- const { project } = req.body;
1345
-
1346
- if (!project) {
1347
- return res.status(400).json({ error: 'Project name is required' });
1348
- }
1349
-
1350
- try {
1351
- const projectPath = await getActualProjectPath(project);
1352
- await validateGitRepository(projectPath);
1353
-
1354
- // Get current branch and its upstream remote
1355
- const branch = await getCurrentBranchName(projectPath);
1356
-
1357
- let remoteName = 'origin'; // fallback
1358
- let remoteBranch = branch; // fallback
1359
- try {
1360
- const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
1361
- const tracking = stdout.trim();
1362
- remoteName = tracking.split('/')[0]; // Extract remote name
1363
- remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
1364
- } catch (error) {
1365
- // No upstream, use fallback
1366
- console.log('No upstream configured, using origin/branch as fallback');
1367
- }
1368
-
1369
- validateRemoteName(remoteName);
1370
- validateBranchName(remoteBranch);
1371
- const { stdout } = await spawnAsync('git', ['pull', remoteName, remoteBranch], { cwd: projectPath });
1372
-
1373
- res.json({
1374
- success: true,
1375
- output: stdout || 'Pull completed successfully',
1376
- remoteName,
1377
- remoteBranch
1378
- });
1379
- } catch (error) {
1380
- console.error('Git pull error:', error);
1381
-
1382
- // Enhanced error handling for common pull scenarios
1383
- let errorMessage = 'Pull failed';
1384
- let details = error.message;
1385
-
1386
- if (error.message.includes('CONFLICT')) {
1387
- errorMessage = 'Merge conflicts detected';
1388
- details = 'Pull created merge conflicts. Please resolve conflicts manually in the editor, then commit the changes.';
1389
- } else if (error.message.includes('Please commit your changes or stash them')) {
1390
- errorMessage = 'Uncommitted changes detected';
1391
- details = 'Please commit or stash your local changes before pulling.';
1392
- } else if (error.message.includes('Could not resolve hostname')) {
1393
- errorMessage = 'Network error';
1394
- details = 'Unable to connect to remote repository. Check your internet connection.';
1395
- } else if (error.message.includes('fatal: \'origin\' does not appear to be a git repository')) {
1396
- errorMessage = 'Remote not configured';
1397
- details = 'No remote repository configured. Add a remote with: git remote add origin <url>';
1398
- } else if (error.message.includes('diverged')) {
1399
- errorMessage = 'Branches have diverged';
1400
- details = 'Your local branch and remote branch have diverged. Consider fetching first to review changes.';
1401
- }
1402
-
1403
- res.status(500).json({
1404
- error: errorMessage,
1405
- details: details
1406
- });
1407
- }
1408
- });
1409
-
1410
- // Push commits to remote repository
1411
- router.post('/push', async (req, res) => {
1412
- const { project } = req.body;
1413
-
1414
- if (!project) {
1415
- return res.status(400).json({ error: 'Project name is required' });
1416
- }
1417
-
1418
- try {
1419
- const projectPath = await getActualProjectPath(project);
1420
- await validateGitRepository(projectPath);
1421
-
1422
- // Get current branch and its upstream remote
1423
- const branch = await getCurrentBranchName(projectPath);
1424
-
1425
- let remoteName = 'origin'; // fallback
1426
- let remoteBranch = branch; // fallback
1427
- try {
1428
- const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
1429
- const tracking = stdout.trim();
1430
- remoteName = tracking.split('/')[0]; // Extract remote name
1431
- remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
1432
- } catch (error) {
1433
- // No upstream, use fallback
1434
- console.log('No upstream configured, using origin/branch as fallback');
1435
- }
1436
-
1437
- validateRemoteName(remoteName);
1438
- validateBranchName(remoteBranch);
1439
- const { stdout } = await spawnAsync('git', ['push', remoteName, remoteBranch], { cwd: projectPath });
1440
-
1441
- res.json({
1442
- success: true,
1443
- output: stdout || 'Push completed successfully',
1444
- remoteName,
1445
- remoteBranch
1446
- });
1447
- } catch (error) {
1448
- console.error('Git push error:', error);
1449
-
1450
- // Enhanced error handling for common push scenarios
1451
- let errorMessage = 'Push failed';
1452
- let details = error.message;
1453
-
1454
- if (error.message.includes('rejected')) {
1455
- errorMessage = 'Push rejected';
1456
- details = 'The remote has newer commits. Pull first to merge changes before pushing.';
1457
- } else if (error.message.includes('non-fast-forward')) {
1458
- errorMessage = 'Non-fast-forward push';
1459
- details = 'Your branch is behind the remote. Pull the latest changes first.';
1460
- } else if (error.message.includes('Could not resolve hostname')) {
1461
- errorMessage = 'Network error';
1462
- details = 'Unable to connect to remote repository. Check your internet connection.';
1463
- } else if (error.message.includes('fatal: \'origin\' does not appear to be a git repository')) {
1464
- errorMessage = 'Remote not configured';
1465
- details = 'No remote repository configured. Add a remote with: git remote add origin <url>';
1466
- } else if (error.message.includes('Permission denied')) {
1467
- errorMessage = 'Authentication failed';
1468
- details = 'Permission denied. Check your credentials or SSH keys.';
1469
- } else if (error.message.includes('no upstream branch')) {
1470
- errorMessage = 'No upstream branch';
1471
- details = 'No upstream branch configured. Use: git push --set-upstream origin <branch>';
1472
- }
1473
-
1474
- res.status(500).json({
1475
- error: errorMessage,
1476
- details: details
1477
- });
1478
- }
1479
- });
1480
-
1481
- // Publish branch to remote (set upstream and push)
1482
- router.post('/publish', async (req, res) => {
1483
- const { project, branch } = req.body;
1484
-
1485
- if (!project || !branch) {
1486
- return res.status(400).json({ error: 'Project name and branch are required' });
1487
- }
1488
-
1489
- try {
1490
- const projectPath = await getActualProjectPath(project);
1491
- await validateGitRepository(projectPath);
1492
-
1493
- // Validate branch name
1494
- validateBranchName(branch);
1495
-
1496
- // Get current branch to verify it matches the requested branch
1497
- const currentBranchName = await getCurrentBranchName(projectPath);
1498
-
1499
- if (currentBranchName !== branch) {
1500
- return res.status(400).json({
1501
- error: `Branch mismatch. Current branch is ${currentBranchName}, but trying to publish ${branch}`
1502
- });
1503
- }
1504
-
1505
- // Check if remote exists
1506
- let remoteName = 'origin';
1507
- try {
1508
- const { stdout } = await spawnAsync('git', ['remote'], { cwd: projectPath });
1509
- const remotes = stdout.trim().split('\n').filter(r => r.trim());
1510
- if (remotes.length === 0) {
1511
- return res.status(400).json({
1512
- error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
1513
- });
1514
- }
1515
- remoteName = remotes.includes('origin') ? 'origin' : remotes[0];
1516
- } catch (error) {
1517
- return res.status(400).json({
1518
- error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
1519
- });
1520
- }
1521
-
1522
- // Publish the branch (set upstream and push)
1523
- validateRemoteName(remoteName);
1524
- const { stdout } = await spawnAsync('git', ['push', '--set-upstream', remoteName, branch], { cwd: projectPath });
1525
-
1526
- res.json({
1527
- success: true,
1528
- output: stdout || 'Branch published successfully',
1529
- remoteName,
1530
- branch
1531
- });
1532
- } catch (error) {
1533
- console.error('Git publish error:', error);
1534
-
1535
- // Enhanced error handling for common publish scenarios
1536
- let errorMessage = 'Publish failed';
1537
- let details = error.message;
1538
-
1539
- if (error.message.includes('rejected')) {
1540
- errorMessage = 'Publish rejected';
1541
- details = 'The remote branch already exists and has different commits. Use push instead.';
1542
- } else if (error.message.includes('Could not resolve hostname')) {
1543
- errorMessage = 'Network error';
1544
- details = 'Unable to connect to remote repository. Check your internet connection.';
1545
- } else if (error.message.includes('Permission denied')) {
1546
- errorMessage = 'Authentication failed';
1547
- details = 'Permission denied. Check your credentials or SSH keys.';
1548
- } else if (error.message.includes('fatal:') && error.message.includes('does not appear to be a git repository')) {
1549
- errorMessage = 'Remote not configured';
1550
- details = 'Remote repository not properly configured. Check your remote URL.';
1551
- }
1552
-
1553
- res.status(500).json({
1554
- error: errorMessage,
1555
- details: details
1556
- });
1557
- }
1558
- });
1559
-
1560
- // Discard changes for a specific file
1561
- router.post('/discard', async (req, res) => {
1562
- const { project, file } = req.body;
1563
-
1564
- if (!project || !file) {
1565
- return res.status(400).json({ error: 'Project name and file path are required' });
1566
- }
1567
-
1568
- try {
1569
- const projectPath = await getActualProjectPath(project);
1570
- await validateGitRepository(projectPath);
1571
- const {
1572
- repositoryRootPath,
1573
- repositoryRelativeFilePath,
1574
- } = await resolveRepositoryFilePath(projectPath, file);
1575
-
1576
- // Check file status to determine correct discard command
1577
- const { stdout: statusOutput } = await spawnAsync(
1578
- 'git',
1579
- ['status', '--porcelain', '--', repositoryRelativeFilePath],
1580
- { cwd: repositoryRootPath },
1581
- );
1582
-
1583
- if (!statusOutput.trim()) {
1584
- return res.status(400).json({ error: 'No changes to discard for this file' });
1585
- }
1586
-
1587
- const status = statusOutput.substring(0, 2);
1588
-
1589
- if (status === '??') {
1590
- // Untracked file or directory - delete it
1591
- const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
1592
- const stats = await fs.stat(filePath);
1593
-
1594
- if (stats.isDirectory()) {
1595
- await fs.rm(filePath, { recursive: true, force: true });
1596
- } else {
1597
- await fs.unlink(filePath);
1598
- }
1599
- } else if (status.includes('M') || status.includes('D')) {
1600
- // Modified or deleted file - restore from HEAD
1601
- await spawnAsync('git', ['restore', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
1602
- } else if (status.includes('A')) {
1603
- // Added file - unstage it
1604
- await spawnAsync('git', ['reset', 'HEAD', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
1605
- }
1606
-
1607
- res.json({ success: true, message: `Changes discarded for ${repositoryRelativeFilePath}` });
1608
- } catch (error) {
1609
- console.error('Git discard error:', error);
1610
- res.status(500).json({ error: error.message });
1611
- }
1612
- });
1613
-
1614
- // Delete untracked file
1615
- router.post('/delete-untracked', async (req, res) => {
1616
- const { project, file } = req.body;
1617
-
1618
- if (!project || !file) {
1619
- return res.status(400).json({ error: 'Project name and file path are required' });
1620
- }
1621
-
1622
- try {
1623
- const projectPath = await getActualProjectPath(project);
1624
- await validateGitRepository(projectPath);
1625
- const {
1626
- repositoryRootPath,
1627
- repositoryRelativeFilePath,
1628
- } = await resolveRepositoryFilePath(projectPath, file);
1629
-
1630
- // Check if file is actually untracked
1631
- const { stdout: statusOutput } = await spawnAsync(
1632
- 'git',
1633
- ['status', '--porcelain', '--', repositoryRelativeFilePath],
1634
- { cwd: repositoryRootPath },
1635
- );
1636
-
1637
- if (!statusOutput.trim()) {
1638
- return res.status(400).json({ error: 'File is not untracked or does not exist' });
1639
- }
1640
-
1641
- const status = statusOutput.substring(0, 2);
1642
-
1643
- if (status !== '??') {
1644
- return res.status(400).json({ error: 'File is not untracked. Use discard for tracked files.' });
1645
- }
1646
-
1647
- // Delete the untracked file or directory
1648
- const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
1649
- const stats = await fs.stat(filePath);
1650
-
1651
- if (stats.isDirectory()) {
1652
- // Use rm with recursive option for directories
1653
- await fs.rm(filePath, { recursive: true, force: true });
1654
- res.json({ success: true, message: `Untracked directory ${repositoryRelativeFilePath} deleted successfully` });
1655
- } else {
1656
- await fs.unlink(filePath);
1657
- res.json({ success: true, message: `Untracked file ${repositoryRelativeFilePath} deleted successfully` });
1658
- }
1659
- } catch (error) {
1660
- console.error('Git delete untracked error:', error);
1661
- res.status(500).json({ error: error.message });
1662
- }
1663
- });
1664
-
1665
- export default router;
49
+ return message.includes('Not a git repository')
50
+ || message.includes('not a git repository')
51
+ || message.includes('Project directory is not a git repository');
52
+ }
53
+
54
+ function shouldSkipFilesystemEntry(entryName) {
55
+ return FILESYSTEM_SCAN_EXCLUDED_DIRS.has(entryName)
56
+ || entryName.endsWith('.log')
57
+ || entryName === '.DS_Store';
58
+ }
59
+
60
+ function toProjectRelativePath(projectPath, filePath) {
61
+ return path.relative(projectPath, filePath).replace(/\\/g, '/');
62
+ }
63
+
64
+ async function collectFilesystemSnapshot(projectPath) {
65
+ const snapshot = new Map();
66
+ let limitReached = false;
67
+
68
+ async function walk(directoryPath, depth) {
69
+ if (limitReached || depth > FILESYSTEM_SCAN_MAX_DEPTH) {
70
+ return;
71
+ }
72
+
73
+ let entries = [];
74
+ try {
75
+ entries = await fs.readdir(directoryPath, { withFileTypes: true });
76
+ } catch {
77
+ return;
78
+ }
79
+
80
+ for (const entry of entries) {
81
+ if (limitReached || shouldSkipFilesystemEntry(entry.name)) {
82
+ continue;
83
+ }
84
+
85
+ const absolutePath = path.join(directoryPath, entry.name);
86
+
87
+ if (entry.isDirectory()) {
88
+ await walk(absolutePath, depth + 1);
89
+ continue;
90
+ }
91
+
92
+ if (!entry.isFile()) {
93
+ continue;
94
+ }
95
+
96
+ try {
97
+ const stat = await fs.stat(absolutePath);
98
+ snapshot.set(toProjectRelativePath(projectPath, absolutePath), {
99
+ mtimeMs: Math.round(stat.mtimeMs),
100
+ size: stat.size,
101
+ });
102
+ } catch {
103
+ continue;
104
+ }
105
+
106
+ if (snapshot.size >= FILESYSTEM_SCAN_MAX_FILES) {
107
+ limitReached = true;
108
+ break;
109
+ }
110
+ }
111
+ }
112
+
113
+ await walk(projectPath, 0);
114
+ return { snapshot, limitReached };
115
+ }
116
+
117
+ function diffFilesystemSnapshots(previousSnapshot, nextSnapshot) {
118
+ if (!previousSnapshot) {
119
+ return { modified: [], added: [], deleted: [] };
120
+ }
121
+
122
+ const modified = [];
123
+ const added = [];
124
+ const deleted = [];
125
+
126
+ for (const [filePath, nextMeta] of nextSnapshot.entries()) {
127
+ const previousMeta = previousSnapshot.get(filePath);
128
+ if (!previousMeta) {
129
+ added.push(filePath);
130
+ continue;
131
+ }
132
+
133
+ if (previousMeta.mtimeMs !== nextMeta.mtimeMs || previousMeta.size !== nextMeta.size) {
134
+ modified.push(filePath);
135
+ }
136
+ }
137
+
138
+ for (const filePath of previousSnapshot.keys()) {
139
+ if (!nextSnapshot.has(filePath)) {
140
+ deleted.push(filePath);
141
+ }
142
+ }
143
+
144
+ return {
145
+ modified: modified.sort(),
146
+ added: added.sort(),
147
+ deleted: deleted.sort(),
148
+ };
149
+ }
150
+
151
+ async function buildFilesystemStatus(projectPath) {
152
+ const normalizedProjectPath = path.resolve(projectPath);
153
+ const previousSnapshot = filesystemChangeSnapshots.get(normalizedProjectPath) ?? null;
154
+ const { snapshot, limitReached } = await collectFilesystemSnapshot(normalizedProjectPath);
155
+ filesystemChangeSnapshots.set(normalizedProjectPath, snapshot);
156
+ const { modified, added, deleted } = diffFilesystemSnapshots(previousSnapshot, snapshot);
157
+
158
+ return {
159
+ isGitRepository: false,
160
+ trackingMode: 'filesystem',
161
+ branch: null,
162
+ hasCommits: false,
163
+ modified,
164
+ added,
165
+ deleted,
166
+ untracked: [],
167
+ snapshotReady: Boolean(previousSnapshot),
168
+ fileCount: snapshot.size,
169
+ scanLimitReached: limitReached,
170
+ };
171
+ }
172
+
173
+ function spawnAsync(command, args, options = {}) {
174
+ return new Promise((resolve, reject) => {
175
+ const child = spawn(command, args, {
176
+ ...options,
177
+ shell: false,
178
+ });
179
+
180
+ let stdout = '';
181
+ let stderr = '';
182
+
183
+ child.stdout.on('data', (data) => {
184
+ stdout += data.toString();
185
+ });
186
+
187
+ child.stderr.on('data', (data) => {
188
+ stderr += data.toString();
189
+ });
190
+
191
+ child.on('error', (error) => {
192
+ reject(error);
193
+ });
194
+
195
+ child.on('close', (code) => {
196
+ if (code === 0) {
197
+ resolve({ stdout, stderr });
198
+ return;
199
+ }
200
+
201
+ const error = new Error(`Command failed: ${command} ${args.join(' ')}`);
202
+ error.code = code;
203
+ error.stdout = stdout;
204
+ error.stderr = stderr;
205
+ reject(error);
206
+ });
207
+ });
208
+ }
209
+
210
+ // Input validation helpers (defense-in-depth)
211
+ function validateCommitRef(commit) {
212
+ // Allow hex hashes, HEAD, HEAD~N, HEAD^N, tag names, branch names
213
+ if (!/^[a-zA-Z0-9._~^{}@\/-]+$/.test(commit)) {
214
+ throw new Error('Invalid commit reference');
215
+ }
216
+ return commit;
217
+ }
218
+
219
+ function validateBranchName(branch) {
220
+ if (!/^[a-zA-Z0-9._\/-]+$/.test(branch)) {
221
+ throw new Error('Invalid branch name');
222
+ }
223
+ return branch;
224
+ }
225
+
226
+ function validateFilePath(file, projectPath) {
227
+ if (!file || file.includes('\0')) {
228
+ throw new Error('Invalid file path');
229
+ }
230
+ // Prevent path traversal: resolve the file relative to the project root
231
+ // and ensure the result stays within the project directory
232
+ if (projectPath) {
233
+ const resolved = path.resolve(projectPath, file);
234
+ const normalizedRoot = path.resolve(projectPath) + path.sep;
235
+ if (!resolved.startsWith(normalizedRoot) && resolved !== path.resolve(projectPath)) {
236
+ throw new Error('Invalid file path: path traversal detected');
237
+ }
238
+ }
239
+ return file;
240
+ }
241
+
242
+ function validateRemoteName(remote) {
243
+ if (!/^[a-zA-Z0-9._-]+$/.test(remote)) {
244
+ throw new Error('Invalid remote name');
245
+ }
246
+ return remote;
247
+ }
248
+
249
+ function validateProjectPath(projectPath) {
250
+ if (!projectPath || projectPath.includes('\0')) {
251
+ throw new Error('Invalid project path');
252
+ }
253
+ const resolved = path.resolve(projectPath);
254
+ // Must be an absolute path after resolution
255
+ if (!path.isAbsolute(resolved)) {
256
+ throw new Error('Invalid project path: must be absolute');
257
+ }
258
+ // Block obviously dangerous paths
259
+ if (resolved === '/' || resolved === path.sep) {
260
+ throw new Error('Invalid project path: root directory not allowed');
261
+ }
262
+ return resolved;
263
+ }
264
+
265
+ // Helper function to get the actual project path from the encoded project name
266
+ async function getActualProjectPath(projectName) {
267
+ let projectPath;
268
+ try {
269
+ projectPath = await extractProjectDirectory(projectName);
270
+ } catch (error) {
271
+ console.error(`Error extracting project directory for ${projectName}:`, error);
272
+ throw new Error(`Unable to resolve project path for "${projectName}"`);
273
+ }
274
+ return validateProjectPath(projectPath);
275
+ }
276
+
277
+ // Helper function to strip git diff headers
278
+ function stripDiffHeaders(diff) {
279
+ if (!diff) return '';
280
+
281
+ const lines = diff.split('\n');
282
+ const filteredLines = [];
283
+ let startIncluding = false;
284
+
285
+ for (const line of lines) {
286
+ // Skip all header lines including diff --git, index, file mode, and --- / +++ file paths
287
+ if (line.startsWith('diff --git') ||
288
+ line.startsWith('index ') ||
289
+ line.startsWith('new file mode') ||
290
+ line.startsWith('deleted file mode') ||
291
+ line.startsWith('---') ||
292
+ line.startsWith('+++')) {
293
+ continue;
294
+ }
295
+
296
+ // Start including lines from @@ hunk headers onwards
297
+ if (line.startsWith('@@') || startIncluding) {
298
+ startIncluding = true;
299
+ filteredLines.push(line);
300
+ }
301
+ }
302
+
303
+ return filteredLines.join('\n');
304
+ }
305
+
306
+ // Helper function to validate git repository
307
+ async function validateGitRepository(projectPath) {
308
+ try {
309
+ // Check if directory exists
310
+ await fs.access(projectPath);
311
+ } catch {
312
+ throw new Error(`Project path not found: ${projectPath}`);
313
+ }
314
+
315
+ try {
316
+ // Allow any directory that is inside a work tree (repo root or nested folder).
317
+ const { stdout: insideWorkTreeOutput } = await spawnAsync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: projectPath });
318
+ const isInsideWorkTree = insideWorkTreeOutput.trim() === 'true';
319
+ if (!isInsideWorkTree) {
320
+ throw new Error('Not inside a git work tree');
321
+ }
322
+
323
+ // Ensure git can resolve the repository root for this directory.
324
+ await spawnAsync('git', ['rev-parse', '--show-toplevel'], { cwd: projectPath });
325
+ } catch {
326
+ throw new Error('Not a git repository. This directory does not contain a .git folder. Initialize a git repository with "git init" to use source control features.');
327
+ }
328
+ }
329
+
330
+ function getGitErrorDetails(error) {
331
+ return `${error?.message || ''} ${error?.stderr || ''} ${error?.stdout || ''}`;
332
+ }
333
+
334
+ function isMissingHeadRevisionError(error) {
335
+ const errorDetails = getGitErrorDetails(error).toLowerCase();
336
+ return errorDetails.includes('unknown revision')
337
+ || errorDetails.includes('ambiguous argument')
338
+ || errorDetails.includes('needed a single revision')
339
+ || errorDetails.includes('bad revision');
340
+ }
341
+
342
+ async function getCurrentBranchName(projectPath) {
343
+ try {
344
+ // symbolic-ref works even when the repository has no commits.
345
+ const { stdout } = await spawnAsync('git', ['symbolic-ref', '--short', 'HEAD'], { cwd: projectPath });
346
+ const branchName = stdout.trim();
347
+ if (branchName) {
348
+ return branchName;
349
+ }
350
+ } catch (error) {
351
+ // Fall back to rev-parse for detached HEAD and older git edge cases.
352
+ }
353
+
354
+ const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: projectPath });
355
+ return stdout.trim();
356
+ }
357
+
358
+ async function repositoryHasCommits(projectPath) {
359
+ try {
360
+ await spawnAsync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: projectPath });
361
+ return true;
362
+ } catch (error) {
363
+ if (isMissingHeadRevisionError(error)) {
364
+ return false;
365
+ }
366
+ throw error;
367
+ }
368
+ }
369
+
370
+ async function getRepositoryRootPath(projectPath) {
371
+ const { stdout } = await spawnAsync('git', ['rev-parse', '--show-toplevel'], { cwd: projectPath });
372
+ return stdout.trim();
373
+ }
374
+
375
+ function normalizeRepositoryRelativeFilePath(filePath) {
376
+ return String(filePath)
377
+ .replace(/\\/g, '/')
378
+ .replace(/^\.\/+/, '')
379
+ .replace(/^\/+/, '')
380
+ .trim();
381
+ }
382
+
383
+ function parseStatusFilePaths(statusOutput) {
384
+ return statusOutput
385
+ .split('\n')
386
+ .map((line) => line.trimEnd())
387
+ .filter((line) => line.trim())
388
+ .map((line) => {
389
+ const statusPath = line.substring(3);
390
+ const renamedFilePath = statusPath.split(' -> ')[1];
391
+ return normalizeRepositoryRelativeFilePath(renamedFilePath || statusPath);
392
+ })
393
+ .filter(Boolean);
394
+ }
395
+
396
+ function buildFilePathCandidates(projectPath, repositoryRootPath, filePath) {
397
+ const normalizedFilePath = normalizeRepositoryRelativeFilePath(filePath);
398
+ const projectRelativePath = normalizeRepositoryRelativeFilePath(path.relative(repositoryRootPath, projectPath));
399
+ const candidates = [normalizedFilePath];
400
+
401
+ if (
402
+ projectRelativePath
403
+ && projectRelativePath !== '.'
404
+ && !normalizedFilePath.startsWith(`${projectRelativePath}/`)
405
+ ) {
406
+ candidates.push(`${projectRelativePath}/${normalizedFilePath}`);
407
+ }
408
+
409
+ return Array.from(new Set(candidates.filter(Boolean)));
410
+ }
411
+
412
+ async function resolveRepositoryFilePath(projectPath, filePath) {
413
+ validateFilePath(filePath);
414
+
415
+ const repositoryRootPath = await getRepositoryRootPath(projectPath);
416
+ const candidateFilePaths = buildFilePathCandidates(projectPath, repositoryRootPath, filePath);
417
+
418
+ for (const candidateFilePath of candidateFilePaths) {
419
+ const { stdout } = await spawnAsync('git', ['status', '--porcelain', '--', candidateFilePath], { cwd: repositoryRootPath });
420
+ if (stdout.trim()) {
421
+ return {
422
+ repositoryRootPath,
423
+ repositoryRelativeFilePath: candidateFilePath,
424
+ };
425
+ }
426
+ }
427
+
428
+ // If the caller sent a bare filename (e.g. "hello.ts"), recover it from changed files.
429
+ const normalizedFilePath = normalizeRepositoryRelativeFilePath(filePath);
430
+ if (!normalizedFilePath.includes('/')) {
431
+ const { stdout: repositoryStatusOutput } = await spawnAsync('git', ['status', '--porcelain'], { cwd: repositoryRootPath });
432
+ const changedFilePaths = parseStatusFilePaths(repositoryStatusOutput);
433
+ const suffixMatches = changedFilePaths.filter(
434
+ (changedFilePath) => changedFilePath === normalizedFilePath || changedFilePath.endsWith(`/${normalizedFilePath}`),
435
+ );
436
+
437
+ if (suffixMatches.length === 1) {
438
+ return {
439
+ repositoryRootPath,
440
+ repositoryRelativeFilePath: suffixMatches[0],
441
+ };
442
+ }
443
+ }
444
+
445
+ return {
446
+ repositoryRootPath,
447
+ repositoryRelativeFilePath: candidateFilePaths[0],
448
+ };
449
+ }
450
+
451
+ // Get git status for a project
452
+ router.get('/status', async (req, res) => {
453
+ const { project } = req.query;
454
+ const requestedTrackingMode = String(req.query.mode || req.query.trackingMode || '').toLowerCase();
455
+ const gitOnly = requestedTrackingMode === 'git';
456
+
457
+ if (!project) {
458
+ return res.status(400).json({ error: 'Project name is required' });
459
+ }
460
+
461
+ let projectPath;
462
+ try {
463
+ projectPath = await getActualProjectPath(project);
464
+
465
+ // Validate git repository
466
+ await validateGitRepository(projectPath);
467
+
468
+ const branch = await getCurrentBranchName(projectPath);
469
+ const hasCommits = await repositoryHasCommits(projectPath);
470
+
471
+ // Get git status
472
+ const { stdout: statusOutput } = await spawnAsync('git', ['status', '--porcelain'], { cwd: projectPath });
473
+
474
+ const modified = [];
475
+ const added = [];
476
+ const deleted = [];
477
+ const untracked = [];
478
+
479
+ statusOutput.split('\n').forEach(line => {
480
+ if (!line.trim()) return;
481
+
482
+ const status = line.substring(0, 2);
483
+ const file = line.substring(3);
484
+
485
+ if (status === 'M ' || status === ' M' || status === 'MM') {
486
+ modified.push(file);
487
+ } else if (status === 'A ' || status === 'AM') {
488
+ added.push(file);
489
+ } else if (status === 'D ' || status === ' D') {
490
+ deleted.push(file);
491
+ } else if (status === '??') {
492
+ untracked.push(file);
493
+ }
494
+ });
495
+
496
+ res.json({
497
+ isGitRepository: true,
498
+ trackingMode: 'git',
499
+ branch,
500
+ hasCommits,
501
+ modified,
502
+ added,
503
+ deleted,
504
+ untracked
505
+ });
506
+ } catch (error) {
507
+ if (projectPath && !gitOnly && isNotGitRepositoryMessage(error.message)) {
508
+ try {
509
+ res.json(await buildFilesystemStatus(projectPath));
510
+ return;
511
+ } catch (fallbackError) {
512
+ console.error('Filesystem status fallback error:', fallbackError);
513
+ }
514
+ }
515
+
516
+ console.error('Git status error:', error);
517
+ res.json({
518
+ isGitRepository: false,
519
+ trackingMode: gitOnly ? 'git' : undefined,
520
+ error: error.message.includes('not a git repository') || error.message.includes('Project directory is not a git repository')
521
+ ? error.message
522
+ : 'Git operation failed',
523
+ details: error.message.includes('not a git repository') || error.message.includes('Project directory is not a git repository')
524
+ ? error.message
525
+ : `Failed to get git status: ${error.message}`
526
+ });
527
+ }
528
+ });
529
+
530
+ // Get diff for a specific file
531
+ router.get('/diff', async (req, res) => {
532
+ const { project, file } = req.query;
533
+
534
+ if (!project || !file) {
535
+ return res.status(400).json({ error: 'Project name and file path are required' });
536
+ }
537
+
538
+ try {
539
+ const projectPath = await getActualProjectPath(project);
540
+
541
+ // Validate git repository
542
+ await validateGitRepository(projectPath);
543
+
544
+ const {
545
+ repositoryRootPath,
546
+ repositoryRelativeFilePath,
547
+ } = await resolveRepositoryFilePath(projectPath, file);
548
+
549
+ // Check if file is untracked or deleted
550
+ const { stdout: statusOutput } = await spawnAsync(
551
+ 'git',
552
+ ['status', '--porcelain', '--', repositoryRelativeFilePath],
553
+ { cwd: repositoryRootPath },
554
+ );
555
+ const isUntracked = statusOutput.startsWith('??');
556
+ const isDeleted = statusOutput.trim().startsWith('D ') || statusOutput.trim().startsWith(' D');
557
+
558
+ let diff;
559
+ if (isUntracked) {
560
+ // For untracked files, show the entire file content as additions
561
+ const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
562
+ const stats = await fs.stat(filePath);
563
+
564
+ if (stats.isDirectory()) {
565
+ // For directories, show a simple message
566
+ diff = `Directory: ${repositoryRelativeFilePath}\n(Cannot show diff for directories)`;
567
+ } else {
568
+ const fileContent = await fs.readFile(filePath, 'utf-8');
569
+ const lines = fileContent.split('\n');
570
+ diff = `--- /dev/null\n+++ b/${repositoryRelativeFilePath}\n@@ -0,0 +1,${lines.length} @@\n` +
571
+ lines.map(line => `+${line}`).join('\n');
572
+ }
573
+ } else if (isDeleted) {
574
+ // For deleted files, show the entire file content from HEAD as deletions
575
+ const { stdout: fileContent } = await spawnAsync(
576
+ 'git',
577
+ ['show', `HEAD:${repositoryRelativeFilePath}`],
578
+ { cwd: repositoryRootPath },
579
+ );
580
+ const lines = fileContent.split('\n');
581
+ diff = `--- a/${repositoryRelativeFilePath}\n+++ /dev/null\n@@ -1,${lines.length} +0,0 @@\n` +
582
+ lines.map(line => `-${line}`).join('\n');
583
+ } else {
584
+ // Get diff for tracked files
585
+ // First check for unstaged changes (working tree vs index)
586
+ const { stdout: unstagedDiff } = await spawnAsync(
587
+ 'git',
588
+ ['diff', '--', repositoryRelativeFilePath],
589
+ { cwd: repositoryRootPath },
590
+ );
591
+
592
+ if (unstagedDiff) {
593
+ // Show unstaged changes if they exist
594
+ diff = stripDiffHeaders(unstagedDiff);
595
+ } else {
596
+ // If no unstaged changes, check for staged changes (index vs HEAD)
597
+ const { stdout: stagedDiff } = await spawnAsync(
598
+ 'git',
599
+ ['diff', '--cached', '--', repositoryRelativeFilePath],
600
+ { cwd: repositoryRootPath },
601
+ );
602
+ diff = stripDiffHeaders(stagedDiff) || '';
603
+ }
604
+ }
605
+
606
+ res.json({ diff });
607
+ } catch (error) {
608
+ console.error('Git diff error:', error);
609
+ res.json({ error: error.message });
610
+ }
611
+ });
612
+
613
+ // Get file content with diff information for CodeEditor
614
+ router.get('/file-with-diff', async (req, res) => {
615
+ const { project, file } = req.query;
616
+
617
+ if (!project || !file) {
618
+ return res.status(400).json({ error: 'Project name and file path are required' });
619
+ }
620
+
621
+ try {
622
+ const projectPath = await getActualProjectPath(project);
623
+
624
+ // Validate git repository
625
+ await validateGitRepository(projectPath);
626
+
627
+ const {
628
+ repositoryRootPath,
629
+ repositoryRelativeFilePath,
630
+ } = await resolveRepositoryFilePath(projectPath, file);
631
+
632
+ // Check file status
633
+ const { stdout: statusOutput } = await spawnAsync(
634
+ 'git',
635
+ ['status', '--porcelain', '--', repositoryRelativeFilePath],
636
+ { cwd: repositoryRootPath },
637
+ );
638
+ const isUntracked = statusOutput.startsWith('??');
639
+ const isDeleted = statusOutput.trim().startsWith('D ') || statusOutput.trim().startsWith(' D');
640
+
641
+ let currentContent = '';
642
+ let oldContent = '';
643
+
644
+ if (isDeleted) {
645
+ // For deleted files, get content from HEAD
646
+ const { stdout: headContent } = await spawnAsync(
647
+ 'git',
648
+ ['show', `HEAD:${repositoryRelativeFilePath}`],
649
+ { cwd: repositoryRootPath },
650
+ );
651
+ oldContent = headContent;
652
+ currentContent = headContent; // Show the deleted content in editor
653
+ } else {
654
+ // Get current file content
655
+ const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
656
+ const stats = await fs.stat(filePath);
657
+
658
+ if (stats.isDirectory()) {
659
+ // Cannot show content for directories
660
+ return res.status(400).json({ error: 'Cannot show diff for directories' });
661
+ }
662
+
663
+ currentContent = await fs.readFile(filePath, 'utf-8');
664
+
665
+ if (!isUntracked) {
666
+ // Get the old content from HEAD for tracked files
667
+ try {
668
+ const { stdout: headContent } = await spawnAsync(
669
+ 'git',
670
+ ['show', `HEAD:${repositoryRelativeFilePath}`],
671
+ { cwd: repositoryRootPath },
672
+ );
673
+ oldContent = headContent;
674
+ } catch (error) {
675
+ // File might be newly added to git (staged but not committed)
676
+ oldContent = '';
677
+ }
678
+ }
679
+ }
680
+
681
+ res.json({
682
+ currentContent,
683
+ oldContent,
684
+ isDeleted,
685
+ isUntracked
686
+ });
687
+ } catch (error) {
688
+ console.error('Git file-with-diff error:', error);
689
+ res.json({ error: error.message });
690
+ }
691
+ });
692
+
693
+ // Create initial commit
694
+ router.post('/initial-commit', async (req, res) => {
695
+ const { project } = req.body;
696
+
697
+ if (!project) {
698
+ return res.status(400).json({ error: 'Project name is required' });
699
+ }
700
+
701
+ try {
702
+ const projectPath = await getActualProjectPath(project);
703
+
704
+ // Validate git repository
705
+ await validateGitRepository(projectPath);
706
+
707
+ // Check if there are already commits
708
+ try {
709
+ await spawnAsync('git', ['rev-parse', 'HEAD'], { cwd: projectPath });
710
+ return res.status(400).json({ error: 'Repository already has commits. Use regular commit instead.' });
711
+ } catch (error) {
712
+ // No HEAD - this is good, we can create initial commit
713
+ }
714
+
715
+ // Add all files
716
+ await spawnAsync('git', ['add', '.'], { cwd: projectPath });
717
+
718
+ // Create initial commit
719
+ const { stdout } = await spawnAsync('git', ['commit', '-m', 'Initial commit'], { cwd: projectPath });
720
+
721
+ res.json({ success: true, output: stdout, message: 'Initial commit created successfully' });
722
+ } catch (error) {
723
+ console.error('Git initial commit error:', error);
724
+
725
+ // Handle the case where there's nothing to commit
726
+ if (error.message.includes('nothing to commit')) {
727
+ return res.status(400).json({
728
+ error: 'Nothing to commit',
729
+ details: 'No files found in the repository. Add some files first.'
730
+ });
731
+ }
732
+
733
+ res.status(500).json({ error: error.message });
734
+ }
735
+ });
736
+
737
+ // Commit changes
738
+ router.post('/commit', async (req, res) => {
739
+ const { project, message, files } = req.body;
740
+
741
+ if (!project || !message || !files || files.length === 0) {
742
+ return res.status(400).json({ error: 'Project name, commit message, and files are required' });
743
+ }
744
+
745
+ try {
746
+ const projectPath = await getActualProjectPath(project);
747
+
748
+ // Validate git repository
749
+ await validateGitRepository(projectPath);
750
+ const repositoryRootPath = await getRepositoryRootPath(projectPath);
751
+
752
+ // Stage selected files
753
+ for (const file of files) {
754
+ const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
755
+ await spawnAsync('git', ['add', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
756
+ }
757
+
758
+ // Commit with message
759
+ const { stdout } = await spawnAsync('git', ['commit', '-m', message], { cwd: repositoryRootPath });
760
+
761
+ res.json({ success: true, output: stdout });
762
+ } catch (error) {
763
+ console.error('Git commit error:', error);
764
+ res.status(500).json({ error: error.message });
765
+ }
766
+ });
767
+
768
+ // Revert latest local commit (keeps changes staged)
769
+ router.post('/revert-local-commit', async (req, res) => {
770
+ const { project } = req.body;
771
+
772
+ if (!project) {
773
+ return res.status(400).json({ error: 'Project name is required' });
774
+ }
775
+
776
+ try {
777
+ const projectPath = await getActualProjectPath(project);
778
+ await validateGitRepository(projectPath);
779
+
780
+ try {
781
+ await spawnAsync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: projectPath });
782
+ } catch (error) {
783
+ return res.status(400).json({
784
+ error: 'No local commit to revert',
785
+ details: 'This repository has no commit yet.',
786
+ });
787
+ }
788
+
789
+ try {
790
+ // Soft reset rewinds one commit while preserving all file changes in the index.
791
+ await spawnAsync('git', ['reset', '--soft', 'HEAD~1'], { cwd: projectPath });
792
+ } catch (error) {
793
+ const errorDetails = `${error.stderr || ''} ${error.message || ''}`;
794
+ const isInitialCommit = errorDetails.includes('HEAD~1') &&
795
+ (errorDetails.includes('unknown revision') || errorDetails.includes('ambiguous argument'));
796
+
797
+ if (!isInitialCommit) {
798
+ throw error;
799
+ }
800
+
801
+ // Initial commit has no parent; deleting HEAD uncommits it and keeps files staged.
802
+ await spawnAsync('git', ['update-ref', '-d', 'HEAD'], { cwd: projectPath });
803
+ }
804
+
805
+ res.json({
806
+ success: true,
807
+ output: 'Latest local commit reverted successfully. Changes were kept staged.',
808
+ });
809
+ } catch (error) {
810
+ console.error('Git revert local commit error:', error);
811
+ res.status(500).json({ error: error.message });
812
+ }
813
+ });
814
+
815
+ // Get list of branches
816
+ router.get('/branches', async (req, res) => {
817
+ const { project } = req.query;
818
+
819
+ if (!project) {
820
+ return res.status(400).json({ error: 'Project name is required' });
821
+ }
822
+
823
+ try {
824
+ const projectPath = await getActualProjectPath(project);
825
+
826
+ // Validate git repository
827
+ await validateGitRepository(projectPath);
828
+
829
+ // Get all branches
830
+ const { stdout } = await spawnAsync('git', ['branch', '-a'], { cwd: projectPath });
831
+
832
+ const rawLines = stdout
833
+ .split('\n')
834
+ .map(b => b.trim())
835
+ .filter(b => b && !b.includes('->'));
836
+
837
+ // Local branches (may start with '* ' for current)
838
+ const localBranches = rawLines
839
+ .filter(b => !b.startsWith('remotes/'))
840
+ .map(b => (b.startsWith('* ') ? b.substring(2) : b));
841
+
842
+ // Remote branches — strip 'remotes/<remote>/' prefix
843
+ const remoteBranches = rawLines
844
+ .filter(b => b.startsWith('remotes/'))
845
+ .map(b => b.replace(/^remotes\/[^/]+\//, ''))
846
+ .filter(name => !localBranches.includes(name)); // skip if already a local branch
847
+
848
+ // Backward-compat flat list (local + unique remotes, deduplicated)
849
+ const branches = [...localBranches, ...remoteBranches]
850
+ .filter((b, i, arr) => arr.indexOf(b) === i);
851
+
852
+ res.json({ branches, localBranches, remoteBranches });
853
+ } catch (error) {
854
+ console.error('Git branches error:', error);
855
+ res.json({ error: error.message });
856
+ }
857
+ });
858
+
859
+ // Checkout branch
860
+ router.post('/checkout', async (req, res) => {
861
+ const { project, branch } = req.body;
862
+
863
+ if (!project || !branch) {
864
+ return res.status(400).json({ error: 'Project name and branch are required' });
865
+ }
866
+
867
+ try {
868
+ const projectPath = await getActualProjectPath(project);
869
+
870
+ // Checkout the branch
871
+ validateBranchName(branch);
872
+ const { stdout } = await spawnAsync('git', ['checkout', branch], { cwd: projectPath });
873
+
874
+ res.json({ success: true, output: stdout });
875
+ } catch (error) {
876
+ console.error('Git checkout error:', error);
877
+ res.status(500).json({ error: error.message });
878
+ }
879
+ });
880
+
881
+ // Create new branch
882
+ router.post('/create-branch', async (req, res) => {
883
+ const { project, branch } = req.body;
884
+
885
+ if (!project || !branch) {
886
+ return res.status(400).json({ error: 'Project name and branch name are required' });
887
+ }
888
+
889
+ try {
890
+ const projectPath = await getActualProjectPath(project);
891
+
892
+ // Create and checkout new branch
893
+ validateBranchName(branch);
894
+ const { stdout } = await spawnAsync('git', ['checkout', '-b', branch], { cwd: projectPath });
895
+
896
+ res.json({ success: true, output: stdout });
897
+ } catch (error) {
898
+ console.error('Git create branch error:', error);
899
+ res.status(500).json({ error: error.message });
900
+ }
901
+ });
902
+
903
+ // Delete a local branch
904
+ router.post('/delete-branch', async (req, res) => {
905
+ const { project, branch } = req.body;
906
+
907
+ if (!project || !branch) {
908
+ return res.status(400).json({ error: 'Project name and branch name are required' });
909
+ }
910
+
911
+ try {
912
+ const projectPath = await getActualProjectPath(project);
913
+ await validateGitRepository(projectPath);
914
+
915
+ // Safety: cannot delete the currently checked-out branch
916
+ const { stdout: currentBranch } = await spawnAsync('git', ['branch', '--show-current'], { cwd: projectPath });
917
+ if (currentBranch.trim() === branch) {
918
+ return res.status(400).json({ error: 'Cannot delete the currently checked-out branch' });
919
+ }
920
+
921
+ const { stdout } = await spawnAsync('git', ['branch', '-d', branch], { cwd: projectPath });
922
+ res.json({ success: true, output: stdout });
923
+ } catch (error) {
924
+ console.error('Git delete branch error:', error);
925
+ res.status(500).json({ error: error.message });
926
+ }
927
+ });
928
+
929
+ // Get recent commits
930
+ router.get('/commits', async (req, res) => {
931
+ const { project, limit = 10 } = req.query;
932
+
933
+ if (!project) {
934
+ return res.status(400).json({ error: 'Project name is required' });
935
+ }
936
+
937
+ try {
938
+ const projectPath = await getActualProjectPath(project);
939
+ await validateGitRepository(projectPath);
940
+ const parsedLimit = Number.parseInt(String(limit), 10);
941
+ const safeLimit = Number.isFinite(parsedLimit) && parsedLimit > 0
942
+ ? Math.min(parsedLimit, 100)
943
+ : 10;
944
+
945
+ // Get commit log with stats
946
+ const { stdout } = await spawnAsync(
947
+ 'git',
948
+ ['log', '--pretty=format:%H|%an|%ae|%ad|%s', '--date=iso-strict', '-n', String(safeLimit)],
949
+ { cwd: projectPath },
950
+ );
951
+
952
+ const commits = stdout
953
+ .split('\n')
954
+ .filter(line => line.trim())
955
+ .map(line => {
956
+ const [hash, author, email, date, ...messageParts] = line.split('|');
957
+ return {
958
+ hash,
959
+ author,
960
+ email,
961
+ date,
962
+ message: messageParts.join('|')
963
+ };
964
+ });
965
+
966
+ // Get stats for each commit
967
+ for (const commit of commits) {
968
+ try {
969
+ const { stdout: stats } = await spawnAsync(
970
+ 'git', ['show', '--stat', '--format=', commit.hash],
971
+ { cwd: projectPath }
972
+ );
973
+ commit.stats = stats.trim().split('\n').pop(); // Get the summary line
974
+ } catch (error) {
975
+ commit.stats = '';
976
+ }
977
+ }
978
+
979
+ res.json({ commits });
980
+ } catch (error) {
981
+ console.error('Git commits error:', error);
982
+ res.json({ error: error.message });
983
+ }
984
+ });
985
+
986
+ // Get diff for a specific commit
987
+ router.get('/commit-diff', async (req, res) => {
988
+ const { project, commit } = req.query;
989
+
990
+ if (!project || !commit) {
991
+ return res.status(400).json({ error: 'Project name and commit hash are required' });
992
+ }
993
+
994
+ try {
995
+ const projectPath = await getActualProjectPath(project);
996
+
997
+ // Validate commit reference (defense-in-depth)
998
+ validateCommitRef(commit);
999
+
1000
+ // Get diff for the commit
1001
+ const { stdout } = await spawnAsync(
1002
+ 'git', ['show', commit],
1003
+ { cwd: projectPath }
1004
+ );
1005
+
1006
+ const isTruncated = stdout.length > COMMIT_DIFF_CHARACTER_LIMIT;
1007
+ const diff = isTruncated
1008
+ ? `${stdout.slice(0, COMMIT_DIFF_CHARACTER_LIMIT)}\n\n... Diff truncated to keep the UI responsive ...`
1009
+ : stdout;
1010
+
1011
+ res.json({ diff, isTruncated });
1012
+ } catch (error) {
1013
+ console.error('Git commit diff error:', error);
1014
+ res.json({ error: error.message });
1015
+ }
1016
+ });
1017
+
1018
+ // Generate commit message based on staged changes using AI
1019
+ router.post('/generate-commit-message', async (req, res) => {
1020
+ const { project, files, provider = 'claude' } = req.body;
1021
+
1022
+ if (!project || !files || files.length === 0) {
1023
+ return res.status(400).json({ error: 'Project name and files are required' });
1024
+ }
1025
+
1026
+ // Validate provider
1027
+ if (!['claude', 'cursor'].includes(provider)) {
1028
+ return res.status(400).json({ error: 'provider must be "claude" or "cursor"' });
1029
+ }
1030
+
1031
+ try {
1032
+ const projectPath = await getActualProjectPath(project);
1033
+ await validateGitRepository(projectPath);
1034
+ const repositoryRootPath = await getRepositoryRootPath(projectPath);
1035
+
1036
+ // Get diff for selected files
1037
+ let diffContext = '';
1038
+ for (const file of files) {
1039
+ try {
1040
+ const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
1041
+ const { stdout } = await spawnAsync(
1042
+ 'git', ['diff', 'HEAD', '--', repositoryRelativeFilePath],
1043
+ { cwd: repositoryRootPath }
1044
+ );
1045
+ if (stdout) {
1046
+ diffContext += `\n--- ${repositoryRelativeFilePath} ---\n${stdout}`;
1047
+ }
1048
+ } catch (error) {
1049
+ console.error(`Error getting diff for ${file}:`, error);
1050
+ }
1051
+ }
1052
+
1053
+ // If no diff found, might be untracked files
1054
+ if (!diffContext.trim()) {
1055
+ // Try to get content of untracked files
1056
+ for (const file of files) {
1057
+ try {
1058
+ const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
1059
+ const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
1060
+ const stats = await fs.stat(filePath);
1061
+
1062
+ if (!stats.isDirectory()) {
1063
+ const content = await fs.readFile(filePath, 'utf-8');
1064
+ diffContext += `\n--- ${repositoryRelativeFilePath} (new file) ---\n${content.substring(0, 1000)}\n`;
1065
+ } else {
1066
+ diffContext += `\n--- ${repositoryRelativeFilePath} (new directory) ---\n`;
1067
+ }
1068
+ } catch (error) {
1069
+ console.error(`Error reading file ${file}:`, error);
1070
+ }
1071
+ }
1072
+ }
1073
+
1074
+ // Generate commit message using AI
1075
+ const message = await generateCommitMessageWithAI(files, diffContext, provider, projectPath);
1076
+
1077
+ res.json({ message });
1078
+ } catch (error) {
1079
+ console.error('Generate commit message error:', error);
1080
+ res.status(500).json({ error: error.message });
1081
+ }
1082
+ });
1083
+
1084
+ /**
1085
+ * Generates a commit message using AI (Claude SDK or Cursor CLI)
1086
+ * @param {Array<string>} files - List of changed files
1087
+ * @param {string} diffContext - Git diff content
1088
+ * @param {string} provider - 'claude' or 'cursor'
1089
+ * @param {string} projectPath - Project directory path
1090
+ * @returns {Promise<string>} Generated commit message
1091
+ */
1092
+ async function generateCommitMessageWithAI(files, diffContext, provider, projectPath) {
1093
+ // Create the prompt
1094
+ const prompt = `Generate a conventional commit message for these changes.
1095
+
1096
+ REQUIREMENTS:
1097
+ - Format: type(scope): subject
1098
+ - Include body explaining what changed and why
1099
+ - Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
1100
+ - Subject under 50 chars, body wrapped at 72 chars
1101
+ - Focus on user-facing changes, not implementation details
1102
+ - Consider what's being added AND removed
1103
+ - Return ONLY the commit message (no markdown, explanations, or code blocks)
1104
+
1105
+ FILES CHANGED:
1106
+ ${files.map(f => `- ${f}`).join('\n')}
1107
+
1108
+ DIFFS:
1109
+ ${diffContext.substring(0, 4000)}
1110
+
1111
+ Generate the commit message:`;
1112
+
1113
+ try {
1114
+ // Create a simple writer that collects the response
1115
+ let responseText = '';
1116
+ const writer = {
1117
+ send: (data) => {
1118
+ try {
1119
+ const parsed = typeof data === 'string' ? JSON.parse(data) : data;
1120
+ console.log('🔍 Writer received message type:', parsed.type);
1121
+
1122
+ // Handle different message formats from Claude SDK and Cursor CLI
1123
+ // Claude SDK sends: {type: 'claude-response', data: {message: {content: [...]}}}
1124
+ if (parsed.type === 'claude-response' && parsed.data) {
1125
+ const message = parsed.data.message || parsed.data;
1126
+ console.log('📦 Claude response message:', JSON.stringify(message, null, 2).substring(0, 500));
1127
+ if (message.content && Array.isArray(message.content)) {
1128
+ // Extract text from content array
1129
+ for (const item of message.content) {
1130
+ if (item.type === 'text' && item.text) {
1131
+ console.log('✅ Extracted text chunk:', item.text.substring(0, 100));
1132
+ responseText += item.text;
1133
+ }
1134
+ }
1135
+ }
1136
+ }
1137
+ // Cursor CLI sends: {type: 'cursor-output', output: '...'}
1138
+ else if (parsed.type === 'cursor-output' && parsed.output) {
1139
+ console.log('✅ Cursor output:', parsed.output.substring(0, 100));
1140
+ responseText += parsed.output;
1141
+ }
1142
+ // Also handle direct text messages
1143
+ else if (parsed.type === 'text' && parsed.text) {
1144
+ console.log('✅ Direct text:', parsed.text.substring(0, 100));
1145
+ responseText += parsed.text;
1146
+ }
1147
+ } catch (e) {
1148
+ // Ignore parse errors
1149
+ console.error('Error parsing writer data:', e);
1150
+ }
1151
+ },
1152
+ setSessionId: () => {}, // No-op for this use case
1153
+ };
1154
+
1155
+ console.log('🚀 Calling AI agent with provider:', provider);
1156
+ console.log('📝 Prompt length:', prompt.length);
1157
+
1158
+ // Call the appropriate agent
1159
+ if (provider === 'claude') {
1160
+ await queryClaudeSDK(prompt, {
1161
+ cwd: projectPath,
1162
+ permissionMode: 'bypassPermissions',
1163
+ model: 'sonnet'
1164
+ }, writer);
1165
+ } else if (provider === 'cursor') {
1166
+ await spawnCursor(prompt, {
1167
+ cwd: projectPath,
1168
+ skipPermissions: true
1169
+ }, writer);
1170
+ }
1171
+
1172
+ console.log('📊 Total response text collected:', responseText.length, 'characters');
1173
+ console.log('📄 Response preview:', responseText.substring(0, 200));
1174
+
1175
+ // Clean up the response
1176
+ const cleanedMessage = cleanCommitMessage(responseText);
1177
+ console.log('🧹 Cleaned message:', cleanedMessage.substring(0, 200));
1178
+
1179
+ return cleanedMessage || 'chore: update files';
1180
+ } catch (error) {
1181
+ console.error('Error generating commit message with AI:', error);
1182
+ // Fallback to simple message
1183
+ return `chore: update ${files.length} file${files.length !== 1 ? 's' : ''}`;
1184
+ }
1185
+ }
1186
+
1187
+ /**
1188
+ * Cleans the AI-generated commit message by removing markdown, code blocks, and extra formatting
1189
+ * @param {string} text - Raw AI response
1190
+ * @returns {string} Clean commit message
1191
+ */
1192
+ function cleanCommitMessage(text) {
1193
+ if (!text || !text.trim()) {
1194
+ return '';
1195
+ }
1196
+
1197
+ let cleaned = text.trim();
1198
+
1199
+ // Remove markdown code blocks
1200
+ cleaned = cleaned.replace(/```[a-z]*\n/g, '');
1201
+ cleaned = cleaned.replace(/```/g, '');
1202
+
1203
+ // Remove markdown headers
1204
+ cleaned = cleaned.replace(/^#+\s*/gm, '');
1205
+
1206
+ // Remove leading/trailing quotes
1207
+ cleaned = cleaned.replace(/^["']|["']$/g, '');
1208
+
1209
+ // If there are multiple lines, take everything (subject + body)
1210
+ // Just clean up extra blank lines
1211
+ cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
1212
+
1213
+ // Remove any explanatory text before the actual commit message
1214
+ // Look for conventional commit pattern and start from there
1215
+ const conventionalCommitMatch = cleaned.match(/(feat|fix|docs|style|refactor|perf|test|build|ci|chore)(\(.+?\))?:.+/s);
1216
+ if (conventionalCommitMatch) {
1217
+ cleaned = cleaned.substring(cleaned.indexOf(conventionalCommitMatch[0]));
1218
+ }
1219
+
1220
+ return cleaned.trim();
1221
+ }
1222
+
1223
+ // Get remote status (ahead/behind commits with smart remote detection)
1224
+ router.get('/remote-status', async (req, res) => {
1225
+ const { project } = req.query;
1226
+
1227
+ if (!project) {
1228
+ return res.status(400).json({ error: 'Project name is required' });
1229
+ }
1230
+
1231
+ try {
1232
+ const projectPath = await getActualProjectPath(project);
1233
+ await validateGitRepository(projectPath);
1234
+
1235
+ const branch = await getCurrentBranchName(projectPath);
1236
+ const hasCommits = await repositoryHasCommits(projectPath);
1237
+
1238
+ const { stdout: remoteOutput } = await spawnAsync('git', ['remote'], { cwd: projectPath });
1239
+ const remotes = remoteOutput.trim().split('\n').filter(r => r.trim());
1240
+ const hasRemote = remotes.length > 0;
1241
+ const fallbackRemoteName = hasRemote
1242
+ ? (remotes.includes('origin') ? 'origin' : remotes[0])
1243
+ : null;
1244
+
1245
+ // Repositories initialized with `git init` can have a branch but no commits.
1246
+ // Return a non-error state so the UI can show the initial-commit workflow.
1247
+ if (!hasCommits) {
1248
+ return res.json({
1249
+ hasRemote,
1250
+ hasUpstream: false,
1251
+ branch,
1252
+ remoteName: fallbackRemoteName,
1253
+ ahead: 0,
1254
+ behind: 0,
1255
+ isUpToDate: false,
1256
+ message: 'Repository has no commits yet'
1257
+ });
1258
+ }
1259
+
1260
+ // Check if there's a remote tracking branch (smart detection)
1261
+ let trackingBranch;
1262
+ let remoteName;
1263
+ try {
1264
+ const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
1265
+ trackingBranch = stdout.trim();
1266
+ remoteName = trackingBranch.split('/')[0]; // Extract remote name (e.g., "origin/main" -> "origin")
1267
+ } catch (error) {
1268
+ return res.json({
1269
+ hasRemote,
1270
+ hasUpstream: false,
1271
+ branch,
1272
+ remoteName: fallbackRemoteName,
1273
+ message: 'No remote tracking branch configured'
1274
+ });
1275
+ }
1276
+
1277
+ // Get ahead/behind counts
1278
+ const { stdout: countOutput } = await spawnAsync(
1279
+ 'git', ['rev-list', '--count', '--left-right', `${trackingBranch}...HEAD`],
1280
+ { cwd: projectPath }
1281
+ );
1282
+
1283
+ const [behind, ahead] = countOutput.trim().split('\t').map(Number);
1284
+
1285
+ res.json({
1286
+ hasRemote: true,
1287
+ hasUpstream: true,
1288
+ branch,
1289
+ remoteBranch: trackingBranch,
1290
+ remoteName,
1291
+ ahead: ahead || 0,
1292
+ behind: behind || 0,
1293
+ isUpToDate: ahead === 0 && behind === 0
1294
+ });
1295
+ } catch (error) {
1296
+ console.error('Git remote status error:', error);
1297
+ res.json({ error: error.message });
1298
+ }
1299
+ });
1300
+
1301
+ // Fetch from remote (using smart remote detection)
1302
+ router.post('/fetch', async (req, res) => {
1303
+ const { project } = req.body;
1304
+
1305
+ if (!project) {
1306
+ return res.status(400).json({ error: 'Project name is required' });
1307
+ }
1308
+
1309
+ try {
1310
+ const projectPath = await getActualProjectPath(project);
1311
+ await validateGitRepository(projectPath);
1312
+
1313
+ // Get current branch and its upstream remote
1314
+ const branch = await getCurrentBranchName(projectPath);
1315
+
1316
+ let remoteName = 'origin'; // fallback
1317
+ try {
1318
+ const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
1319
+ remoteName = stdout.trim().split('/')[0]; // Extract remote name
1320
+ } catch (error) {
1321
+ // No upstream, try to fetch from origin anyway
1322
+ console.log('No upstream configured, using origin as fallback');
1323
+ }
1324
+
1325
+ validateRemoteName(remoteName);
1326
+ const { stdout } = await spawnAsync('git', ['fetch', remoteName], { cwd: projectPath });
1327
+
1328
+ res.json({ success: true, output: stdout || 'Fetch completed successfully', remoteName });
1329
+ } catch (error) {
1330
+ console.error('Git fetch error:', error);
1331
+ res.status(500).json({
1332
+ error: 'Fetch failed',
1333
+ details: error.message.includes('Could not resolve hostname')
1334
+ ? 'Unable to connect to remote repository. Check your internet connection.'
1335
+ : error.message.includes('fatal: \'origin\' does not appear to be a git repository')
1336
+ ? 'No remote repository configured. Add a remote with: git remote add origin <url>'
1337
+ : error.message
1338
+ });
1339
+ }
1340
+ });
1341
+
1342
+ // Pull from remote (fetch + merge using smart remote detection)
1343
+ router.post('/pull', async (req, res) => {
1344
+ const { project } = req.body;
1345
+
1346
+ if (!project) {
1347
+ return res.status(400).json({ error: 'Project name is required' });
1348
+ }
1349
+
1350
+ try {
1351
+ const projectPath = await getActualProjectPath(project);
1352
+ await validateGitRepository(projectPath);
1353
+
1354
+ // Get current branch and its upstream remote
1355
+ const branch = await getCurrentBranchName(projectPath);
1356
+
1357
+ let remoteName = 'origin'; // fallback
1358
+ let remoteBranch = branch; // fallback
1359
+ try {
1360
+ const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
1361
+ const tracking = stdout.trim();
1362
+ remoteName = tracking.split('/')[0]; // Extract remote name
1363
+ remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
1364
+ } catch (error) {
1365
+ // No upstream, use fallback
1366
+ console.log('No upstream configured, using origin/branch as fallback');
1367
+ }
1368
+
1369
+ validateRemoteName(remoteName);
1370
+ validateBranchName(remoteBranch);
1371
+ const { stdout } = await spawnAsync('git', ['pull', remoteName, remoteBranch], { cwd: projectPath });
1372
+
1373
+ res.json({
1374
+ success: true,
1375
+ output: stdout || 'Pull completed successfully',
1376
+ remoteName,
1377
+ remoteBranch
1378
+ });
1379
+ } catch (error) {
1380
+ console.error('Git pull error:', error);
1381
+
1382
+ // Enhanced error handling for common pull scenarios
1383
+ let errorMessage = 'Pull failed';
1384
+ let details = error.message;
1385
+
1386
+ if (error.message.includes('CONFLICT')) {
1387
+ errorMessage = 'Merge conflicts detected';
1388
+ details = 'Pull created merge conflicts. Please resolve conflicts manually in the editor, then commit the changes.';
1389
+ } else if (error.message.includes('Please commit your changes or stash them')) {
1390
+ errorMessage = 'Uncommitted changes detected';
1391
+ details = 'Please commit or stash your local changes before pulling.';
1392
+ } else if (error.message.includes('Could not resolve hostname')) {
1393
+ errorMessage = 'Network error';
1394
+ details = 'Unable to connect to remote repository. Check your internet connection.';
1395
+ } else if (error.message.includes('fatal: \'origin\' does not appear to be a git repository')) {
1396
+ errorMessage = 'Remote not configured';
1397
+ details = 'No remote repository configured. Add a remote with: git remote add origin <url>';
1398
+ } else if (error.message.includes('diverged')) {
1399
+ errorMessage = 'Branches have diverged';
1400
+ details = 'Your local branch and remote branch have diverged. Consider fetching first to review changes.';
1401
+ }
1402
+
1403
+ res.status(500).json({
1404
+ error: errorMessage,
1405
+ details: details
1406
+ });
1407
+ }
1408
+ });
1409
+
1410
+ // Push commits to remote repository
1411
+ router.post('/push', async (req, res) => {
1412
+ const { project } = req.body;
1413
+
1414
+ if (!project) {
1415
+ return res.status(400).json({ error: 'Project name is required' });
1416
+ }
1417
+
1418
+ try {
1419
+ const projectPath = await getActualProjectPath(project);
1420
+ await validateGitRepository(projectPath);
1421
+
1422
+ // Get current branch and its upstream remote
1423
+ const branch = await getCurrentBranchName(projectPath);
1424
+
1425
+ let remoteName = 'origin'; // fallback
1426
+ let remoteBranch = branch; // fallback
1427
+ try {
1428
+ const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
1429
+ const tracking = stdout.trim();
1430
+ remoteName = tracking.split('/')[0]; // Extract remote name
1431
+ remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
1432
+ } catch (error) {
1433
+ // No upstream, use fallback
1434
+ console.log('No upstream configured, using origin/branch as fallback');
1435
+ }
1436
+
1437
+ validateRemoteName(remoteName);
1438
+ validateBranchName(remoteBranch);
1439
+ const { stdout } = await spawnAsync('git', ['push', remoteName, remoteBranch], { cwd: projectPath });
1440
+
1441
+ res.json({
1442
+ success: true,
1443
+ output: stdout || 'Push completed successfully',
1444
+ remoteName,
1445
+ remoteBranch
1446
+ });
1447
+ } catch (error) {
1448
+ console.error('Git push error:', error);
1449
+
1450
+ // Enhanced error handling for common push scenarios
1451
+ let errorMessage = 'Push failed';
1452
+ let details = error.message;
1453
+
1454
+ if (error.message.includes('rejected')) {
1455
+ errorMessage = 'Push rejected';
1456
+ details = 'The remote has newer commits. Pull first to merge changes before pushing.';
1457
+ } else if (error.message.includes('non-fast-forward')) {
1458
+ errorMessage = 'Non-fast-forward push';
1459
+ details = 'Your branch is behind the remote. Pull the latest changes first.';
1460
+ } else if (error.message.includes('Could not resolve hostname')) {
1461
+ errorMessage = 'Network error';
1462
+ details = 'Unable to connect to remote repository. Check your internet connection.';
1463
+ } else if (error.message.includes('fatal: \'origin\' does not appear to be a git repository')) {
1464
+ errorMessage = 'Remote not configured';
1465
+ details = 'No remote repository configured. Add a remote with: git remote add origin <url>';
1466
+ } else if (error.message.includes('Permission denied')) {
1467
+ errorMessage = 'Authentication failed';
1468
+ details = 'Permission denied. Check your credentials or SSH keys.';
1469
+ } else if (error.message.includes('no upstream branch')) {
1470
+ errorMessage = 'No upstream branch';
1471
+ details = 'No upstream branch configured. Use: git push --set-upstream origin <branch>';
1472
+ }
1473
+
1474
+ res.status(500).json({
1475
+ error: errorMessage,
1476
+ details: details
1477
+ });
1478
+ }
1479
+ });
1480
+
1481
+ // Publish branch to remote (set upstream and push)
1482
+ router.post('/publish', async (req, res) => {
1483
+ const { project, branch } = req.body;
1484
+
1485
+ if (!project || !branch) {
1486
+ return res.status(400).json({ error: 'Project name and branch are required' });
1487
+ }
1488
+
1489
+ try {
1490
+ const projectPath = await getActualProjectPath(project);
1491
+ await validateGitRepository(projectPath);
1492
+
1493
+ // Validate branch name
1494
+ validateBranchName(branch);
1495
+
1496
+ // Get current branch to verify it matches the requested branch
1497
+ const currentBranchName = await getCurrentBranchName(projectPath);
1498
+
1499
+ if (currentBranchName !== branch) {
1500
+ return res.status(400).json({
1501
+ error: `Branch mismatch. Current branch is ${currentBranchName}, but trying to publish ${branch}`
1502
+ });
1503
+ }
1504
+
1505
+ // Check if remote exists
1506
+ let remoteName = 'origin';
1507
+ try {
1508
+ const { stdout } = await spawnAsync('git', ['remote'], { cwd: projectPath });
1509
+ const remotes = stdout.trim().split('\n').filter(r => r.trim());
1510
+ if (remotes.length === 0) {
1511
+ return res.status(400).json({
1512
+ error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
1513
+ });
1514
+ }
1515
+ remoteName = remotes.includes('origin') ? 'origin' : remotes[0];
1516
+ } catch (error) {
1517
+ return res.status(400).json({
1518
+ error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
1519
+ });
1520
+ }
1521
+
1522
+ // Publish the branch (set upstream and push)
1523
+ validateRemoteName(remoteName);
1524
+ const { stdout } = await spawnAsync('git', ['push', '--set-upstream', remoteName, branch], { cwd: projectPath });
1525
+
1526
+ res.json({
1527
+ success: true,
1528
+ output: stdout || 'Branch published successfully',
1529
+ remoteName,
1530
+ branch
1531
+ });
1532
+ } catch (error) {
1533
+ console.error('Git publish error:', error);
1534
+
1535
+ // Enhanced error handling for common publish scenarios
1536
+ let errorMessage = 'Publish failed';
1537
+ let details = error.message;
1538
+
1539
+ if (error.message.includes('rejected')) {
1540
+ errorMessage = 'Publish rejected';
1541
+ details = 'The remote branch already exists and has different commits. Use push instead.';
1542
+ } else if (error.message.includes('Could not resolve hostname')) {
1543
+ errorMessage = 'Network error';
1544
+ details = 'Unable to connect to remote repository. Check your internet connection.';
1545
+ } else if (error.message.includes('Permission denied')) {
1546
+ errorMessage = 'Authentication failed';
1547
+ details = 'Permission denied. Check your credentials or SSH keys.';
1548
+ } else if (error.message.includes('fatal:') && error.message.includes('does not appear to be a git repository')) {
1549
+ errorMessage = 'Remote not configured';
1550
+ details = 'Remote repository not properly configured. Check your remote URL.';
1551
+ }
1552
+
1553
+ res.status(500).json({
1554
+ error: errorMessage,
1555
+ details: details
1556
+ });
1557
+ }
1558
+ });
1559
+
1560
+ // Discard changes for a specific file
1561
+ router.post('/discard', async (req, res) => {
1562
+ const { project, file } = req.body;
1563
+
1564
+ if (!project || !file) {
1565
+ return res.status(400).json({ error: 'Project name and file path are required' });
1566
+ }
1567
+
1568
+ try {
1569
+ const projectPath = await getActualProjectPath(project);
1570
+ await validateGitRepository(projectPath);
1571
+ const {
1572
+ repositoryRootPath,
1573
+ repositoryRelativeFilePath,
1574
+ } = await resolveRepositoryFilePath(projectPath, file);
1575
+
1576
+ // Check file status to determine correct discard command
1577
+ const { stdout: statusOutput } = await spawnAsync(
1578
+ 'git',
1579
+ ['status', '--porcelain', '--', repositoryRelativeFilePath],
1580
+ { cwd: repositoryRootPath },
1581
+ );
1582
+
1583
+ if (!statusOutput.trim()) {
1584
+ return res.status(400).json({ error: 'No changes to discard for this file' });
1585
+ }
1586
+
1587
+ const status = statusOutput.substring(0, 2);
1588
+
1589
+ if (status === '??') {
1590
+ // Untracked file or directory - delete it
1591
+ const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
1592
+ const stats = await fs.stat(filePath);
1593
+
1594
+ if (stats.isDirectory()) {
1595
+ await fs.rm(filePath, { recursive: true, force: true });
1596
+ } else {
1597
+ await fs.unlink(filePath);
1598
+ }
1599
+ } else if (status.includes('M') || status.includes('D')) {
1600
+ // Modified or deleted file - restore from HEAD
1601
+ await spawnAsync('git', ['restore', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
1602
+ } else if (status.includes('A')) {
1603
+ // Added file - unstage it
1604
+ await spawnAsync('git', ['reset', 'HEAD', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
1605
+ }
1606
+
1607
+ res.json({ success: true, message: `Changes discarded for ${repositoryRelativeFilePath}` });
1608
+ } catch (error) {
1609
+ console.error('Git discard error:', error);
1610
+ res.status(500).json({ error: error.message });
1611
+ }
1612
+ });
1613
+
1614
+ // Delete untracked file
1615
+ router.post('/delete-untracked', async (req, res) => {
1616
+ const { project, file } = req.body;
1617
+
1618
+ if (!project || !file) {
1619
+ return res.status(400).json({ error: 'Project name and file path are required' });
1620
+ }
1621
+
1622
+ try {
1623
+ const projectPath = await getActualProjectPath(project);
1624
+ await validateGitRepository(projectPath);
1625
+ const {
1626
+ repositoryRootPath,
1627
+ repositoryRelativeFilePath,
1628
+ } = await resolveRepositoryFilePath(projectPath, file);
1629
+
1630
+ // Check if file is actually untracked
1631
+ const { stdout: statusOutput } = await spawnAsync(
1632
+ 'git',
1633
+ ['status', '--porcelain', '--', repositoryRelativeFilePath],
1634
+ { cwd: repositoryRootPath },
1635
+ );
1636
+
1637
+ if (!statusOutput.trim()) {
1638
+ return res.status(400).json({ error: 'File is not untracked or does not exist' });
1639
+ }
1640
+
1641
+ const status = statusOutput.substring(0, 2);
1642
+
1643
+ if (status !== '??') {
1644
+ return res.status(400).json({ error: 'File is not untracked. Use discard for tracked files.' });
1645
+ }
1646
+
1647
+ // Delete the untracked file or directory
1648
+ const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
1649
+ const stats = await fs.stat(filePath);
1650
+
1651
+ if (stats.isDirectory()) {
1652
+ // Use rm with recursive option for directories
1653
+ await fs.rm(filePath, { recursive: true, force: true });
1654
+ res.json({ success: true, message: `Untracked directory ${repositoryRelativeFilePath} deleted successfully` });
1655
+ } else {
1656
+ await fs.unlink(filePath);
1657
+ res.json({ success: true, message: `Untracked file ${repositoryRelativeFilePath} deleted successfully` });
1658
+ }
1659
+ } catch (error) {
1660
+ console.error('Git delete untracked error:', error);
1661
+ res.status(500).json({ error: error.message });
1662
+ }
1663
+ });
1664
+
1665
+ export default router;