plugin-git-manager 1.3.3 → 1.4.1

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 (71) hide show
  1. package/dist/client/{156.c27c2392746e7866.js → 156.8e36af3e2cee173e.js} +1 -1
  2. package/dist/client/317.e7b1d59371812c30.js +10 -0
  3. package/dist/client/434.05d0ba2b821105dc.js +10 -0
  4. package/dist/client/453.cdcba6d2d0c9522b.js +10 -0
  5. package/dist/client/454.625da741a7e1161f.js +10 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/317.4e116f84ed9081b6.js +10 -0
  8. package/dist/client-v2/434.764113d20743a45b.js +10 -0
  9. package/dist/client-v2/453.5ab80c06d8e61a7e.js +10 -0
  10. package/dist/client-v2/454.b885b1d35ef7ff72.js +10 -0
  11. package/dist/client-v2/index.js +1 -1
  12. package/dist/externalVersion.js +10 -9
  13. package/dist/locale/en-US.json +38 -1
  14. package/dist/locale/vi-VN.json +38 -1
  15. package/dist/locale/zh-CN.json +41 -1
  16. package/dist/node_modules/simple-git/package.json +1 -1
  17. package/dist/node_modules/zod/package.json +1 -1
  18. package/dist/server/actions/chat-context.js +282 -0
  19. package/dist/server/actions/git-actions.js +387 -80
  20. package/dist/server/actions/gitlab-api.js +101 -15
  21. package/dist/server/actions/subtree.js +20 -10
  22. package/dist/server/chat-context-admission.js +187 -0
  23. package/dist/server/plugin.js +142 -10
  24. package/dist/server/repository-access.js +2 -2
  25. package/dist/server/request-method-policy.js +4 -1
  26. package/dist/server/services/review-source.js +2 -1
  27. package/dist/server/utils/cluster-git.js +181 -0
  28. package/package.json +2 -2
  29. package/src/client/__tests__/FileExplorerAndManage.test.tsx +236 -0
  30. package/src/client/__tests__/GitContextPicker.test.tsx +120 -0
  31. package/src/client/__tests__/ai-context.test.tsx +119 -0
  32. package/src/client/__tests__/workflowRoutes.test.ts +3 -1
  33. package/src/client/ai-context.tsx +3 -113
  34. package/src/client/components/CommitHistory.tsx +19 -7
  35. package/src/client/components/FileExplorer.tsx +80 -34
  36. package/src/client/components/GitManagerSettings.tsx +21 -5
  37. package/src/client/components/GitOperations.tsx +25 -4
  38. package/src/client/components/GitRuntimeBanner.tsx +97 -0
  39. package/src/client/components/RepositoryConfig.tsx +28 -6
  40. package/src/client/context/GitManagerContext.tsx +174 -15
  41. package/src/client/index.tsx +3 -5
  42. package/src/client/workflowRoutes.ts +11 -0
  43. package/src/client-v2/ai-context.tsx +135 -72
  44. package/src/client-v2/components/GitContextPicker.tsx +418 -0
  45. package/src/client-v2/git-context-api.ts +59 -0
  46. package/src/client-v2/plugin.tsx +2 -4
  47. package/src/locale/en-US.json +38 -1
  48. package/src/locale/vi-VN.json +38 -1
  49. package/src/locale/zh-CN.json +41 -1
  50. package/src/server/__tests__/chat-context-admission.test.ts +276 -0
  51. package/src/server/__tests__/chat-context-options.test.ts +144 -0
  52. package/src/server/__tests__/git-actions.test.ts +329 -4
  53. package/src/server/__tests__/git-chat-context.test.ts +138 -0
  54. package/src/server/__tests__/git-security.test.ts +52 -0
  55. package/src/server/__tests__/smoke.test.ts +232 -1
  56. package/src/server/actions/chat-context.ts +302 -0
  57. package/src/server/actions/git-actions.ts +428 -89
  58. package/src/server/actions/gitlab-api.ts +113 -14
  59. package/src/server/actions/subtree.ts +23 -6
  60. package/src/server/chat-context-admission.ts +182 -0
  61. package/src/server/plugin.ts +163 -3
  62. package/src/server/repository-access.ts +2 -2
  63. package/src/server/request-method-policy.ts +3 -0
  64. package/src/server/services/review-source.ts +3 -2
  65. package/src/server/utils/cluster-git.ts +209 -0
  66. package/dist/client/317.17ed0018e3e7db00.js +0 -10
  67. package/dist/client/434.b2eeaaef33aae6e0.js +0 -10
  68. package/dist/client/453.fc3042c9740d8fab.js +0 -10
  69. package/dist/client-v2/317.d2466574d00f94d0.js +0 -10
  70. package/dist/client-v2/434.19c7579c06b9077c.js +0 -10
  71. package/dist/client-v2/453.5e507c94c59277b1.js +0 -10
@@ -2,22 +2,34 @@
2
2
 
3
3
  import simpleGit, { SimpleGit } from 'simple-git';
4
4
  import { Context } from '@nocobase/actions';
5
+ import { createHash } from 'crypto';
5
6
  import * as path from 'path';
6
7
  import * as fs from 'fs';
7
- import { spawnSync } from 'child_process';
8
+ import { spawn, spawnSync } from 'child_process';
8
9
  import { getEffectiveActionParams } from '../repository-access';
9
10
  import { redactError } from '../utils/redact';
10
11
  import { getRepoAccount } from '../utils/get-repo-account';
11
12
  import { assertUrlHasNoUserInfo } from '../utils/url-security';
13
+ import {
14
+ dispatchClusterGitInstall,
15
+ readClusterGitStatus,
16
+ type ClusterGitApp,
17
+ type ClusterGitStatus,
18
+ } from '../utils/cluster-git';
12
19
 
13
20
  // Disallow leading `-` to prevent argument-injection (e.g. `--upload-pack=...`)
14
21
  // when refs are passed as positional args to git.
15
22
  const REF_PATTERN = /^(?!-)[a-zA-Z0-9._/-]+$/;
23
+ const FALLBACK_GIT_PATHS = ['git', '/usr/bin/git', '/usr/local/bin/git', '/bin/git'];
24
+ const REPO_LOCK_TTL_MS = 5 * 60 * 1000;
16
25
 
17
- // Per-repo mutex to prevent PAT race conditions in withAuth
26
+ export interface RepoLockManager {
27
+ runExclusive<T>(key: string, fn: () => Promise<T>, ttl?: number): Promise<T>;
28
+ }
29
+
30
+ // Per-repo in-process mutex paired with app.lockManager (when available) for HA clusters
18
31
  const repoLocks = new Map<string, Promise<void>>();
19
- const GIT_BINARY = process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || 'git';
20
- let gitAvailabilityChecked = false;
32
+ let cachedGitBinary: { envValue: string; binary: string } | null = null;
21
33
 
22
34
  interface GitActionParams {
23
35
  repositoryId?: number | string;
@@ -25,6 +37,7 @@ interface GitActionParams {
25
37
  commitHash?: string;
26
38
  compareHash?: string;
27
39
  maxCount?: number | string;
40
+ skip?: number | string;
28
41
  branch?: string;
29
42
  ref?: string;
30
43
  treePath?: string;
@@ -91,34 +104,85 @@ export function validateRepoUrl(repoUrl: string): void {
91
104
  }
92
105
  }
93
106
 
94
- export async function withAuth<T>(
95
- git: ReturnType<typeof simpleGit>,
107
+ export async function withRepoLock<T>(
96
108
  localPath: string,
109
+ fn: () => Promise<T>,
110
+ lockManager?: RepoLockManager,
111
+ ): Promise<T> {
112
+ const runLocal = async () => {
113
+ const lock = acquireLock(localPath);
114
+ await lock.promise;
115
+ try {
116
+ return await fn();
117
+ } finally {
118
+ lock.release();
119
+ }
120
+ };
121
+ if (lockManager?.runExclusive) {
122
+ const lockKey = `git-repo:${createHash('sha256').update(localPath).digest('hex')}`;
123
+ return lockManager.runExclusive(lockKey, runLocal, REPO_LOCK_TTL_MS);
124
+ }
125
+ return runLocal();
126
+ }
127
+
128
+ export function validateRepoRelativePath(rawPath: string, label = 'file path'): string {
129
+ if (rawPath.includes('\0')) {
130
+ throw new Error(`Invalid ${label}`);
131
+ }
132
+ const normalized = rawPath.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
133
+ if (!normalized || /^[a-zA-Z]:\//.test(normalized)) {
134
+ throw new Error(`Invalid ${label}`);
135
+ }
136
+ if (normalized.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
137
+ throw new Error(`Invalid ${label}`);
138
+ }
139
+ return normalized;
140
+ }
141
+
142
+ async function runAuthenticatedGitUnlocked<T>(
143
+ git: ReturnType<typeof simpleGit>,
97
144
  repoUrl: string,
98
145
  pat: string,
99
146
  fn: () => Promise<T>,
100
147
  username?: string,
101
148
  remoteName = 'origin',
102
149
  ): Promise<T> {
103
- validateRepoUrl(repoUrl);
104
- const lock = acquireLock(localPath);
105
- await lock.promise;
106
150
  try {
107
151
  git.env(credentialEnvironment(repoUrl, pat, username));
108
- // Persist only the clean URL. Authentication is scoped to this URL in the child process environment.
109
- await git.remote(['set-url', remoteName, repoUrl]);
152
+ // Persist only the clean URL when it differs from .git/config to avoid unnecessary lock contention across HA nodes.
153
+ const currentUrl =
154
+ typeof git.raw === 'function'
155
+ ? (await git.raw(['config', '--get', `remote.${remoteName}.url`]).catch(() => '')).trim()
156
+ : '';
157
+ if (currentUrl !== repoUrl) {
158
+ await git.remote(['set-url', remoteName, repoUrl]);
159
+ }
110
160
  return await fn();
111
161
  } catch (error) {
112
162
  throw redactGitCredentialError(error, pat, username);
113
163
  } finally {
114
- try {
115
- git.env(gitProcessEnvironment());
116
- } finally {
117
- lock.release();
118
- }
164
+ git.env(gitProcessEnvironment());
119
165
  }
120
166
  }
121
167
 
168
+ export async function withAuth<T>(
169
+ git: ReturnType<typeof simpleGit>,
170
+ localPath: string,
171
+ repoUrl: string,
172
+ pat: string,
173
+ fn: () => Promise<T>,
174
+ username?: string,
175
+ remoteName = 'origin',
176
+ lockManager?: RepoLockManager,
177
+ ): Promise<T> {
178
+ validateRepoUrl(repoUrl);
179
+ return withRepoLock(
180
+ localPath,
181
+ () => runAuthenticatedGitUnlocked(git, repoUrl, pat, fn, username, remoteName),
182
+ lockManager,
183
+ );
184
+ }
185
+
122
186
  function gitProcessEnvironment(): NodeJS.ProcessEnv {
123
187
  const env = { ...process.env };
124
188
  for (const key of Object.keys(env)) {
@@ -164,18 +228,94 @@ function redactGitCredentialError(error: unknown, pat: string, username?: string
164
228
  return redactError(new Error(safeMessage));
165
229
  }
166
230
 
167
- function getGitMissingMessage() {
168
- return `Git executable "${GIT_BINARY}" was not found on the server. Install git in the app/worker container, or set GIT_BINARY_PATH to the absolute git binary path.`;
231
+ function configuredGitBinary(): string {
232
+ return (process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || '').trim();
233
+ }
234
+
235
+ function canExecuteGit(binary: string): boolean {
236
+ if (path.isAbsolute(binary) && !fs.existsSync(binary)) {
237
+ return false;
238
+ }
239
+ const check = spawnSync(binary, ['--version'], { stdio: 'ignore' });
240
+ return !check.error && check.status === 0;
169
241
  }
170
242
 
171
- function assertGitAvailable(ctx: Context) {
172
- if (gitAvailabilityChecked) return;
243
+ export function resolveGitBinary(): string | null {
244
+ const configured = configuredGitBinary();
245
+ if (
246
+ cachedGitBinary &&
247
+ cachedGitBinary.envValue === configured &&
248
+ (!path.isAbsolute(cachedGitBinary.binary) || fs.existsSync(cachedGitBinary.binary)) &&
249
+ canExecuteGit(cachedGitBinary.binary)
250
+ ) {
251
+ return cachedGitBinary.binary;
252
+ }
253
+ cachedGitBinary = null;
254
+
255
+ const candidates = configured ? [configured] : FALLBACK_GIT_PATHS;
256
+ for (const candidate of candidates) {
257
+ if (canExecuteGit(candidate)) {
258
+ cachedGitBinary = { envValue: configured, binary: candidate };
259
+ return candidate;
260
+ }
261
+ }
262
+ return null;
263
+ }
264
+
265
+ export function resetGitBinaryCacheForTests(): void {
266
+ cachedGitBinary = null;
267
+ }
268
+
269
+ export function isGitAvailable(): boolean {
270
+ return resolveGitBinary() !== null;
271
+ }
272
+
273
+ export function getGitMissingMessage(clusterStatus?: ClusterGitStatus): string {
274
+ const binary = configuredGitBinary() || 'git';
275
+ if (clusterStatus?.available && clusterStatus.status === 'running') {
276
+ return `Git executable "${binary}" is currently being installed via Cluster Manager. Please wait a moment and retry.`;
277
+ }
278
+ if (clusterStatus?.available) {
279
+ return `Git executable "${binary}" was not found on the server. Install git via Cluster Manager (Package Installer), or set GIT_BINARY_PATH to the absolute git binary path.`;
280
+ }
281
+ return `Git executable "${binary}" was not found on the server. Install git in the app/worker container, or set GIT_BINARY_PATH to the absolute git binary path.`;
282
+ }
283
+
284
+ export async function assertGitAvailable(ctx: Context): Promise<string> {
285
+ const binary = resolveGitBinary();
286
+ if (binary) return binary;
287
+
288
+ const app = (ctx as Context & { app?: ClusterGitApp }).app;
289
+ const clusterStatus = await readClusterGitStatus(app).catch(() => undefined);
290
+ if (clusterStatus?.available && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
291
+ dispatchClusterGitInstall(app).catch((err) => {
292
+ app?.log?.warn?.('plugin-git-manager: background git restore via Cluster Manager failed', err);
293
+ });
294
+ const refreshedStatus: ClusterGitStatus = { ...clusterStatus, status: 'running' };
295
+ return ctx.throw(503, getGitMissingMessage(refreshedStatus));
296
+ }
297
+ return ctx.throw(503, getGitMissingMessage(clusterStatus));
298
+ }
173
299
 
174
- const check = spawnSync(GIT_BINARY, ['--version'], { stdio: 'ignore' });
175
- if (check.error || check.status !== 0) {
176
- ctx.throw(503, getGitMissingMessage());
300
+ export async function assertLocalGitReady(localPath: string, app?: ClusterGitApp): Promise<SimpleGit> {
301
+ if (!fs.existsSync(localPath)) {
302
+ const missingDirError = Object.assign(
303
+ new Error('Repository directory does not exist. Please clone the repository first.'),
304
+ { status: 400 },
305
+ );
306
+ throw missingDirError;
177
307
  }
178
- gitAvailabilityChecked = true;
308
+ const binary = resolveGitBinary();
309
+ if (!binary) {
310
+ const clusterStatus = await readClusterGitStatus(app).catch(() => undefined);
311
+ if (clusterStatus?.available && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
312
+ dispatchClusterGitInstall(app).catch((err) => {
313
+ app?.log?.warn?.('plugin-git-manager: background git restore via Cluster Manager failed', err);
314
+ });
315
+ }
316
+ throw Object.assign(new Error(getGitMissingMessage(clusterStatus)), { status: 503 });
317
+ }
318
+ return createGit(localPath);
179
319
  }
180
320
 
181
321
  function isMissingGitError(error: unknown) {
@@ -188,25 +328,67 @@ export function createGit(baseDir?: string): SimpleGit {
188
328
  // All config keys and values come from credentialEnvironment, never from request parameters.
189
329
  return simpleGit({
190
330
  baseDir,
191
- binary: GIT_BINARY,
331
+ binary: getGitBinaryPath(),
192
332
  unsafe: { allowUnsafeConfigEnvCount: true, allowUnsafeCredentialHelper: true },
193
333
  }).env(gitProcessEnvironment());
194
334
  }
195
335
 
196
336
  export function getGitBinaryPath(): string {
197
- return GIT_BINARY;
337
+ return resolveGitBinary() || configuredGitBinary() || 'git';
198
338
  }
199
339
 
200
- function getGit(ctx: Context, localPath: string): SimpleGit {
340
+ export async function getGit(ctx: Context, localPath: string): Promise<SimpleGit> {
201
341
  if (!fs.existsSync(localPath)) {
202
342
  ctx.throw(400, 'Repository directory does not exist. Please clone the repository first.');
203
343
  }
204
- assertGitAvailable(ctx);
344
+ await assertGitAvailable(ctx);
205
345
  return createGit(localPath);
206
346
  }
207
347
 
208
- export async function getRepo(ctx: Context) {
209
- const { repositoryId } = getGitActionParams(ctx);
348
+ export async function runtimeStatus(ctx: Context, next: () => Promise<void>) {
349
+ const binary = resolveGitBinary();
350
+ const app = (ctx as Context & { app?: ClusterGitApp }).app;
351
+ const clusterStatus = await readClusterGitStatus(app);
352
+ if (!binary && clusterStatus.available && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
353
+ const restore = await dispatchClusterGitInstall(app).catch(() => ({ dispatched: false }));
354
+ if (restore.dispatched) {
355
+ clusterStatus.status = 'running';
356
+ }
357
+ }
358
+ ctx.body = {
359
+ success: true,
360
+ data: {
361
+ gitAvailable: binary !== null,
362
+ gitBinary: binary || configuredGitBinary() || 'git',
363
+ clusterManager: {
364
+ available: clusterStatus.available,
365
+ gitConfigured: clusterStatus.gitConfigured,
366
+ status: clusterStatus.status,
367
+ progressPercent: clusterStatus.progressPercent,
368
+ },
369
+ },
370
+ };
371
+ await next();
372
+ }
373
+
374
+ export async function installGit(ctx: Context, next: () => Promise<void>) {
375
+ const binary = resolveGitBinary();
376
+ if (binary) {
377
+ ctx.body = { success: true, data: { alreadyInstalled: true, gitBinary: binary } };
378
+ await next();
379
+ return;
380
+ }
381
+ const app = (ctx as Context & { app?: ClusterGitApp }).app;
382
+ const result = await dispatchClusterGitInstall(app, { ensureGitInConfig: true });
383
+ if (!result.dispatched && result.reason !== 'Cluster package installation is already running') {
384
+ ctx.throw(400, result.reason || 'Unable to dispatch git installation via Cluster Manager');
385
+ }
386
+ ctx.body = { success: true, data: { dispatched: true } };
387
+ await next();
388
+ }
389
+
390
+ export async function getRepo(ctx: Context, requestedRepositoryId?: number | string) {
391
+ const repositoryId = requestedRepositoryId ?? getGitActionParams(ctx).repositoryId;
210
392
  const repo = await ctx.db.getRepository('gitRepositories').findOne({
211
393
  filterByTk: repositoryId,
212
394
  });
@@ -264,37 +446,60 @@ export async function clone(ctx: Context, next: () => Promise<void>) {
264
446
  validateRepoUrl(repoUrl);
265
447
  // Prevent argument-injection through `defaultBranch` (e.g. `--upload-pack=...`)
266
448
  validateBranch(defaultBranch);
267
-
268
- // Check if directory already exists
269
- if (fs.existsSync(localPath)) {
270
- ctx.throw(400, 'Directory already exists. Remove it before cloning again.');
271
- }
272
-
273
- if (!fs.existsSync(path.dirname(localPath))) {
274
- fs.mkdirSync(path.dirname(localPath), { recursive: true });
275
- }
276
-
277
- assertGitAvailable(ctx);
278
- try {
279
- await createGit()
280
- .env(credentialEnvironment(repoUrl, pat, username))
281
- .clone(repoUrl, localPath, ['--branch', defaultBranch]);
282
- await ctx.db.getRepository('gitRepositories').update({
283
- filterByTk: repo.get('id'),
284
- values: { status: 'connected' },
285
- });
286
- ctx.body = { success: true, message: 'Repository cloned successfully' };
287
- } catch (err) {
288
- await ctx.db.getRepository('gitRepositories').update({
289
- filterByTk: repo.get('id'),
290
- values: { status: 'error' },
291
- });
292
- // Redact embedded PAT before the error reaches the client / log
293
- if (isMissingGitError(err)) {
294
- ctx.throw(503, getGitMissingMessage());
295
- }
296
- throw redactGitCredentialError(err, pat, username);
297
- }
449
+ await assertGitAvailable(ctx);
450
+
451
+ const app = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app;
452
+ await withRepoLock(
453
+ localPath,
454
+ async () => {
455
+ if (fs.existsSync(localPath)) {
456
+ const entries = fs.readdirSync(localPath);
457
+ if (entries.length > 0) {
458
+ if (fs.existsSync(path.join(localPath, '.git'))) {
459
+ const existingGit = createGit(localPath);
460
+ const existingOrigin = (
461
+ await existingGit.raw(['config', '--get', 'remote.origin.url']).catch(() => '')
462
+ ).trim();
463
+ if (existingOrigin === repoUrl) {
464
+ await runAuthenticatedGitUnlocked(existingGit, repoUrl, pat, () => existingGit.fetch(), username);
465
+ await ctx.db.getRepository('gitRepositories').update({
466
+ filterByTk: repo.get('id'),
467
+ values: { status: 'connected' },
468
+ });
469
+ ctx.body = { success: true, message: 'Repository reconnected successfully' };
470
+ return;
471
+ }
472
+ }
473
+ ctx.throw(400, 'Directory already exists. Remove it before cloning again.');
474
+ }
475
+ } else if (!fs.existsSync(path.dirname(localPath))) {
476
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
477
+ }
478
+
479
+ try {
480
+ await createGit()
481
+ .env(credentialEnvironment(repoUrl, pat, username))
482
+ .clone(repoUrl, localPath, ['--branch', defaultBranch]);
483
+ await ctx.db.getRepository('gitRepositories').update({
484
+ filterByTk: repo.get('id'),
485
+ values: { status: 'connected' },
486
+ });
487
+ ctx.body = { success: true, message: 'Repository cloned successfully' };
488
+ } catch (err) {
489
+ await ctx.db.getRepository('gitRepositories').update({
490
+ filterByTk: repo.get('id'),
491
+ values: { status: 'error' },
492
+ });
493
+ // Redact embedded PAT before the error reaches the client / log
494
+ if (isMissingGitError(err) && !isGitAvailable()) {
495
+ const clusterStatus = await readClusterGitStatus(app as ClusterGitApp).catch(() => undefined);
496
+ ctx.throw(503, getGitMissingMessage(clusterStatus));
497
+ }
498
+ throw redactGitCredentialError(err, pat, username);
499
+ }
500
+ },
501
+ app?.lockManager,
502
+ );
298
503
  await next();
299
504
  }
300
505
 
@@ -307,8 +512,9 @@ export async function pull(ctx: Context, next: () => Promise<void>) {
307
512
  if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
308
513
  const { pat, username } = account;
309
514
 
310
- const git = getGit(ctx, localPath);
311
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.pull(), username);
515
+ const git = await getGit(ctx, localPath);
516
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
517
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.pull(), username, 'origin', lockManager);
312
518
 
313
519
  ctx.body = { success: true, data: result };
314
520
  await next();
@@ -323,8 +529,9 @@ export async function push(ctx: Context, next: () => Promise<void>) {
323
529
  if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
324
530
  const { pat, username } = account;
325
531
 
326
- const git = getGit(ctx, localPath);
327
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.push(), username);
532
+ const git = await getGit(ctx, localPath);
533
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
534
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.push(), username, 'origin', lockManager);
328
535
 
329
536
  ctx.body = { success: true, data: result };
330
537
  await next();
@@ -339,8 +546,9 @@ export async function fetch(ctx: Context, next: () => Promise<void>) {
339
546
  if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
340
547
  const { pat, username } = account;
341
548
 
342
- const git = getGit(ctx, localPath);
343
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.fetch(), username);
549
+ const git = await getGit(ctx, localPath);
550
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
551
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.fetch(), username, 'origin', lockManager);
344
552
 
345
553
  ctx.body = { success: true, data: result };
346
554
  await next();
@@ -351,7 +559,7 @@ export async function diff(ctx: Context, next: () => Promise<void>) {
351
559
  const localPath = validateLocalPath(repo.get('localPath'));
352
560
  const { file, commitHash, compareHash } = getGitActionParams(ctx);
353
561
 
354
- const git = getGit(ctx, localPath);
562
+ const git = await getGit(ctx, localPath);
355
563
  const args: string[] = [];
356
564
  if (commitHash && compareHash) {
357
565
  args.push(validateRef(commitHash), validateRef(compareHash));
@@ -359,8 +567,13 @@ export async function diff(ctx: Context, next: () => Promise<void>) {
359
567
  args.push(validateRef(commitHash) + '^', validateRef(commitHash));
360
568
  }
361
569
  if (file) {
362
- if (file.includes('..')) ctx.throw(400, 'Invalid file path');
363
- args.push('--', file);
570
+ let safeFile = '';
571
+ try {
572
+ safeFile = validateRepoRelativePath(file, 'file path');
573
+ } catch {
574
+ ctx.throw(400, 'Invalid file path');
575
+ }
576
+ args.push('--', safeFile);
364
577
  }
365
578
 
366
579
  const result = await git.diff(args);
@@ -371,7 +584,8 @@ export async function diff(ctx: Context, next: () => Promise<void>) {
371
584
  export async function status(ctx: Context, next: () => Promise<void>) {
372
585
  const repo = await getRepo(ctx);
373
586
  const localPath = validateLocalPath(repo.get('localPath'));
374
- const result = await getGit(ctx, localPath).status();
587
+ const git = await getGit(ctx, localPath);
588
+ const result = await git.status();
375
589
  ctx.body = { success: true, data: result };
376
590
  await next();
377
591
  }
@@ -379,16 +593,33 @@ export async function status(ctx: Context, next: () => Promise<void>) {
379
593
  export async function log(ctx: Context, next: () => Promise<void>) {
380
594
  const repo = await getRepo(ctx);
381
595
  const localPath = validateLocalPath(repo.get('localPath'));
382
- const { maxCount = 50, file } = getGitActionParams(ctx);
596
+ const { maxCount = 50, file, branch, skip } = getGitActionParams(ctx);
383
597
 
384
598
  const parsed = Number.parseInt(String(maxCount), 10);
385
- const options: Record<string, any> = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
599
+ const boundedMaxCount = Math.min(Math.max(parsed || 50, 1), 500);
600
+ let safeFile: string | undefined;
386
601
  if (file) {
387
- if (file.includes('..')) ctx.throw(400, 'Invalid file path');
388
- options.file = file;
602
+ try {
603
+ safeFile = validateRepoRelativePath(file, 'file path');
604
+ } catch {
605
+ ctx.throw(400, 'Invalid file path');
606
+ }
389
607
  }
390
608
 
391
- const result = await getGit(ctx, localPath).log(options);
609
+ const args: string[] = [];
610
+ if (branch) args.push(validateBranch(branch));
611
+ if (skip !== undefined) {
612
+ const parsedSkip = Number(skip);
613
+ if (!Number.isSafeInteger(parsedSkip) || parsedSkip < 0 || parsedSkip > 1000000) {
614
+ ctx.throw(400, 'Invalid history offset');
615
+ }
616
+ args.push(`--skip=${parsedSkip}`);
617
+ }
618
+ const git = await getGit(ctx, localPath);
619
+ const result =
620
+ args.length || safeFile
621
+ ? await git.log([...args, `--max-count=${boundedMaxCount}`, ...(safeFile ? ['--follow', '--', safeFile] : [])])
622
+ : await git.log({ maxCount: boundedMaxCount });
392
623
  ctx.body = { success: true, data: result };
393
624
  await next();
394
625
  }
@@ -396,7 +627,8 @@ export async function log(ctx: Context, next: () => Promise<void>) {
396
627
  export async function branches(ctx: Context, next: () => Promise<void>) {
397
628
  const repo = await getRepo(ctx);
398
629
  const localPath = validateLocalPath(repo.get('localPath'));
399
- const result = await getGit(ctx, localPath).branch();
630
+ const git = await getGit(ctx, localPath);
631
+ const result = await git.branch();
400
632
  ctx.body = { success: true, data: result };
401
633
  await next();
402
634
  }
@@ -407,7 +639,9 @@ export async function checkout(ctx: Context, next: () => Promise<void>) {
407
639
  const { branch } = getGitActionParams(ctx);
408
640
  if (!branch) ctx.throw(400, 'branch is required');
409
641
  validateBranch(branch);
410
- await getGit(ctx, localPath).checkout(branch);
642
+ const git = await getGit(ctx, localPath);
643
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
644
+ await withRepoLock(localPath, () => git.checkout(branch), lockManager);
411
645
  ctx.body = { success: true, message: `Switched to branch ${branch}` };
412
646
  await next();
413
647
  }
@@ -417,16 +651,21 @@ export async function fileTree(ctx: Context, next: () => Promise<void>) {
417
651
  const localPath = validateLocalPath(repo.get('localPath'));
418
652
  const { ref = 'HEAD', treePath = '', recursive } = getGitActionParams(ctx);
419
653
 
420
- const git = getGit(ctx, localPath);
654
+ const git = await getGit(ctx, localPath);
421
655
  validateRef(ref);
422
- if (treePath && treePath.includes('..')) {
423
- ctx.throw(400, 'Invalid tree path');
656
+ let safeTreePath = '';
657
+ if (treePath) {
658
+ try {
659
+ safeTreePath = validateRepoRelativePath(treePath, 'tree path');
660
+ } catch {
661
+ ctx.throw(400, 'Invalid tree path');
662
+ }
424
663
  }
425
664
 
426
- const detailArgs = ['ls-tree', '-l'];
665
+ const detailArgs = ['-c', 'core.quotePath=false', 'ls-tree', '-l'];
427
666
  if (recursive === true || recursive === 'true') detailArgs.push('-r');
428
- detailArgs.push(ref);
429
- if (treePath) detailArgs.push(treePath + '/');
667
+ detailArgs.push(ref, '--');
668
+ if (safeTreePath) detailArgs.push(`${safeTreePath}/`);
430
669
  const detailedResult = await git.raw(detailArgs);
431
670
  const items = detailedResult
432
671
  .trim()
@@ -469,14 +708,17 @@ export async function fileContent(ctx: Context, next: () => Promise<void>) {
469
708
  if (!filePath) {
470
709
  ctx.throw(400, 'filePath is required');
471
710
  }
472
- if (filePath.includes('..')) {
711
+ let safeFilePath = '';
712
+ try {
713
+ safeFilePath = validateRepoRelativePath(filePath, 'file path');
714
+ } catch {
473
715
  ctx.throw(400, 'Invalid file path');
474
716
  }
475
717
 
476
718
  validateRef(ref);
477
- const git = getGit(ctx, localPath);
478
- const content = await git.show([`${ref}:${filePath}`]);
479
- ctx.body = { success: true, data: { content, filePath, ref } };
719
+ const git = await getGit(ctx, localPath);
720
+ const content = await git.raw(['-c', 'core.quotePath=false', 'show', `${ref}:${safeFilePath}`]);
721
+ ctx.body = { success: true, data: { content, filePath: safeFilePath, ref } };
480
722
  await next();
481
723
  }
482
724
 
@@ -489,7 +731,7 @@ export async function commitDetail(ctx: Context, next: () => Promise<void>) {
489
731
  ctx.throw(400, 'commitHash is required');
490
732
  }
491
733
 
492
- const git = getGit(ctx, localPath);
734
+ const git = await getGit(ctx, localPath);
493
735
  validateRef(commitHash);
494
736
 
495
737
  // Use %x00 in format string to tell git to output null bytes, avoiding null bytes in args
@@ -531,3 +773,100 @@ export async function commitDetail(ctx: Context, next: () => Promise<void>) {
531
773
  };
532
774
  await next();
533
775
  }
776
+
777
+ async function readLimitedGitOutput(localPath: string, args: string[], maxBytes: number) {
778
+ return new Promise<{ text: string; truncated: boolean }>((resolve, reject) => {
779
+ const child = spawn(getGitBinaryPath(), args, {
780
+ cwd: localPath,
781
+ env: gitProcessEnvironment(),
782
+ windowsHide: true,
783
+ stdio: ['ignore', 'pipe', 'ignore'],
784
+ });
785
+ const chunks: Buffer[] = [];
786
+ let size = 0;
787
+ let truncated = false;
788
+ child.stdout.on('data', (chunk: Buffer) => {
789
+ const remaining = maxBytes - size;
790
+ if (remaining > 0) {
791
+ const data = chunk.subarray(0, remaining);
792
+ chunks.push(data);
793
+ size += data.length;
794
+ }
795
+ if (chunk.length > remaining) {
796
+ truncated = true;
797
+ child.kill();
798
+ }
799
+ });
800
+ child.on('error', reject);
801
+ child.on('close', (code) => {
802
+ if (code !== 0 && !truncated) {
803
+ reject(new Error('Unable to read commit diff'));
804
+ return;
805
+ }
806
+ const text = Buffer.concat(chunks)
807
+ .toString('utf8')
808
+ .replace(/\uFFFD$/, '');
809
+ resolve({ text, truncated });
810
+ });
811
+ });
812
+ }
813
+
814
+ /** Build a bounded commit context, comparing merge commits with their first parent. */
815
+ export async function readChatCommit(
816
+ ctx: Context,
817
+ commitHash: string,
818
+ maxFiles: number,
819
+ maxBytes: number,
820
+ repositoryId?: number | string,
821
+ ) {
822
+ if (!/^[a-f\d]{4,64}$/i.test(commitHash)) ctx.throw(400, 'Invalid commit hash');
823
+ const repo = await getRepo(ctx, repositoryId);
824
+ const localPath = validateLocalPath(repo.get('localPath'));
825
+ const git = await getGit(ctx, localPath);
826
+ const hash = (await git.raw(['rev-parse', '--verify', `${commitHash}^{commit}`])).trim();
827
+ const [metadata, parentLine] = await Promise.all([
828
+ git.raw(['show', '-s', '--format=%H%x00%an%x00%aI%x00%s%x00%b', hash]),
829
+ git.raw(['rev-list', '--parents', '-n', '1', hash]),
830
+ ]);
831
+ const [, author, date, subject, body] = metadata.split('\0');
832
+ const parent = parentLine.trim().split(/\s+/)[1];
833
+ const namesArgs = parent
834
+ ? ['diff', '--name-status', '-z', '-M', parent, hash, '--']
835
+ : ['diff-tree', '--root', '--no-commit-id', '-r', '--name-status', '-z', '-M', hash, '--'];
836
+ const tokens = (await git.raw(namesArgs)).split('\0');
837
+ const files: Array<{ oldPath: string; newPath: string; status: string }> = [];
838
+ for (let index = 0; index < tokens.length && tokens[index]; ) {
839
+ const status = tokens[index++];
840
+ const oldPath = tokens[index++];
841
+ const newPath = /^[RC]/.test(status) ? tokens[index++] : oldPath;
842
+ if (!oldPath || !newPath) break;
843
+ files.push({ oldPath, newPath, status });
844
+ }
845
+ const selectedFiles = files.slice(0, maxFiles);
846
+ const paths = Array.from(new Set(selectedFiles.flatMap((file) => [file.oldPath, file.newPath]))).map(
847
+ (file) => `:(literal)${file}`,
848
+ );
849
+ const patchArgs = parent
850
+ ? ['diff', '--no-ext-diff', '--no-textconv', '--no-color', parent, hash, '--', ...paths]
851
+ : ['show', '--format=', '--no-ext-diff', '--no-textconv', '--no-color', hash, '--', ...paths];
852
+ const patch = paths.length
853
+ ? await readLimitedGitOutput(localPath, patchArgs, maxBytes)
854
+ : { text: '', truncated: false };
855
+ const limitations: string[] = [];
856
+ if (files.length > maxFiles) limitations.push('Additional changed files were omitted.');
857
+ if (patch.truncated) limitations.push('The diff was truncated to the configured limit.');
858
+ if (/^Binary files .* differ$|^GIT binary patch$/m.test(patch.text)) {
859
+ limitations.push('Binary file contents are not included in the diff.');
860
+ }
861
+ return {
862
+ commitSha: hash,
863
+ author,
864
+ date,
865
+ subject,
866
+ body: body?.trim(),
867
+ files: selectedFiles,
868
+ diff: patch.text,
869
+ truncated: patch.truncated || files.length > maxFiles,
870
+ limitations,
871
+ };
872
+ }