notioncode 0.1.1 → 0.1.3

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