plugin-git-manager 1.2.27 → 1.3.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 (138) hide show
  1. package/README.md +151 -108
  2. package/client-v2.d.ts +2 -2
  3. package/client-v2.js +1 -1
  4. package/client.d.ts +3 -3
  5. package/client.js +1 -1
  6. package/dist/client/{326.90c276058682b536.js → 313.d38fc1d40c4589b9.js} +1 -1
  7. package/dist/client/941.1793e67472872992.js +10 -0
  8. package/dist/client/index.js +1 -1
  9. package/dist/client-v2/156.445366026c1cc9a8.js +10 -0
  10. package/dist/client-v2/{326.42b7b53651ffab3a.js → 313.3c867179c3a1e817.js} +1 -1
  11. package/dist/client-v2/434.19c7579c06b9077c.js +10 -0
  12. package/dist/client-v2/928.bba701b5a1ece58e.js +10 -0
  13. package/dist/client-v2/941.b0d55429cd053f32.js +10 -0
  14. package/dist/client-v2/index.js +1 -1
  15. package/dist/externalVersion.js +9 -8
  16. package/dist/locale/en-US.json +396 -297
  17. package/dist/locale/vi-VN.json +384 -292
  18. package/dist/locale/zh-CN.json +150 -51
  19. package/dist/node_modules/simple-git/dist/cjs/index.js +25 -25
  20. package/dist/node_modules/simple-git/package.json +1 -1
  21. package/dist/node_modules/zod/index.cjs +1 -1
  22. package/dist/node_modules/zod/package.json +1 -1
  23. package/dist/server/actions/git-actions.js +90 -36
  24. package/dist/server/actions/gitlab-api.js +4 -2
  25. package/dist/server/actions/poller.js +5 -2
  26. package/dist/server/actions/review-cutover.js +137 -0
  27. package/dist/server/actions/review.js +150 -51
  28. package/dist/server/actions/role-permissions.js +1 -0
  29. package/dist/server/ai-tools.js +8 -9
  30. package/dist/server/collections/gitCodeReviews.js +10 -0
  31. package/dist/server/collections/gitReviewCutover.js +44 -0
  32. package/dist/server/collections/gitReviewFlows.js +3 -0
  33. package/dist/server/collections/gitReviewInbox.js +51 -0
  34. package/dist/server/collections/gitReviewProjects.js +43 -0
  35. package/dist/server/collections/gitReviewRequests.js +56 -0
  36. package/dist/server/index.js +8 -2
  37. package/dist/server/plugin.js +57 -20
  38. package/dist/server/poller.js +95 -74
  39. package/dist/server/repository-access.js +23 -5
  40. package/dist/server/request-method-policy.js +76 -0
  41. package/dist/server/review-control-access.js +79 -0
  42. package/dist/server/services/legacy-post-service.js +412 -0
  43. package/dist/server/services/registry-content-service.js +4 -3
  44. package/dist/server/services/review-service.js +1451 -0
  45. package/dist/server/services/review-source.js +325 -0
  46. package/dist/server/utils/get-repo-account.js +3 -2
  47. package/dist/server/utils/url-security.js +24 -0
  48. package/package.json +61 -43
  49. package/server.d.ts +2 -2
  50. package/server.js +1 -1
  51. package/src/client/__tests__/CommitHistory.test.tsx +79 -0
  52. package/src/client/__tests__/ReviewHistory.test.tsx +126 -0
  53. package/src/client/__tests__/RunReviewButton.test.tsx +84 -0
  54. package/src/client/__tests__/workflowRoutes.test.ts +65 -0
  55. package/src/client/ai-context.tsx +114 -114
  56. package/src/client/components/AIEmployeeSelect.tsx +63 -63
  57. package/src/client/components/CommitHistory.tsx +429 -374
  58. package/src/client/components/FileExplorer.tsx +386 -386
  59. package/src/client/components/GitAccounts.tsx +179 -179
  60. package/src/client/components/GitManagerSettings.tsx +160 -160
  61. package/src/client/components/GitOperations.tsx +220 -220
  62. package/src/client/components/LLMModelSelect.tsx +63 -63
  63. package/src/client/components/LLMServiceSelect.tsx +58 -58
  64. package/src/client/components/MarkdownView.tsx +80 -80
  65. package/src/client/components/MergeRequests.tsx +790 -790
  66. package/src/client/components/PollingStatus.tsx +225 -225
  67. package/src/client/components/RepositoryConfig.tsx +335 -335
  68. package/src/client/components/RepositoryPermissions.tsx +123 -123
  69. package/src/client/components/ReviewFlows.tsx +352 -303
  70. package/src/client/components/ReviewHistory.tsx +796 -566
  71. package/src/client/components/RunReviewButton.tsx +57 -173
  72. package/src/client/context/GitManagerContext.tsx +92 -92
  73. package/src/client/index.tsx +91 -82
  74. package/src/client/locale.ts +9 -9
  75. package/src/client/promptTemplates.ts +31 -31
  76. package/src/client/workflowRoutes.ts +42 -0
  77. package/src/client-v2/ai-context.tsx +99 -0
  78. package/src/client-v2/components/SubtreeSplits.tsx +547 -547
  79. package/src/client-v2/index.tsx +1 -1
  80. package/src/client-v2/locale.ts +8 -8
  81. package/src/client-v2/plugin.tsx +67 -39
  82. package/src/index.ts +2 -2
  83. package/src/locale/en-US.json +396 -297
  84. package/src/locale/vi-VN.json +384 -292
  85. package/src/locale/zh-CN.json +150 -51
  86. package/src/server/__tests__/git-actions.test.ts +24 -24
  87. package/src/server/__tests__/git-security.test.ts +170 -0
  88. package/src/server/__tests__/plugin-url-security.test.ts +17 -17
  89. package/src/server/__tests__/poller-lifecycle.test.ts +71 -0
  90. package/src/server/__tests__/poller.test.ts +37 -37
  91. package/src/server/__tests__/repository-access.test.ts +760 -752
  92. package/src/server/__tests__/review-service.integration.test.ts +1263 -0
  93. package/src/server/__tests__/review.test.ts +76 -137
  94. package/src/server/__tests__/role-permissions.test.ts +147 -147
  95. package/src/server/__tests__/smoke.test.ts +139 -17
  96. package/src/server/__tests__/subtree.test.ts +85 -85
  97. package/src/server/actions/git-actions.ts +540 -480
  98. package/src/server/actions/gitlab-api.ts +422 -411
  99. package/src/server/actions/poller.ts +39 -27
  100. package/src/server/actions/review-cutover.ts +121 -0
  101. package/src/server/actions/review.ts +1498 -1369
  102. package/src/server/actions/role-permissions.ts +331 -321
  103. package/src/server/actions/subtree.ts +508 -508
  104. package/src/server/ai-tools.ts +334 -319
  105. package/src/server/collections/gitAccounts.ts +56 -56
  106. package/src/server/collections/gitCodeReviews.ts +218 -199
  107. package/src/server/collections/gitRepositories.ts +87 -87
  108. package/src/server/collections/gitReviewCutover.ts +23 -0
  109. package/src/server/collections/gitReviewFlows.ts +120 -108
  110. package/src/server/collections/gitReviewInbox.ts +30 -0
  111. package/src/server/collections/gitReviewProjects.ts +22 -0
  112. package/src/server/collections/gitReviewRequests.ts +35 -0
  113. package/src/server/collections/gitSubtreeConfigs.ts +38 -38
  114. package/src/server/collections/gitSubtreeRuns.ts +30 -30
  115. package/src/server/index.ts +14 -2
  116. package/src/server/migrations/20260508000000-add-auto-review-flow-id.ts +29 -29
  117. package/src/server/migrations/20260712000000-add-git-accounts.ts +198 -198
  118. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +81 -81
  119. package/src/server/plugin.ts +409 -361
  120. package/src/server/poller.ts +365 -352
  121. package/src/server/repository-access.ts +803 -773
  122. package/src/server/request-method-policy.ts +56 -0
  123. package/src/server/review-control-access.ts +71 -0
  124. package/src/server/services/__tests__/registry-content-service.test.ts +359 -345
  125. package/src/server/services/__tests__/review-source.test.ts +226 -0
  126. package/src/server/services/legacy-post-service.ts +550 -0
  127. package/src/server/services/registry-content-service.ts +495 -484
  128. package/src/server/services/review-service.ts +1899 -0
  129. package/src/server/services/review-source.ts +359 -0
  130. package/src/server/utils/__tests__/redact.test.ts +56 -56
  131. package/src/server/utils/__tests__/url-security.test.ts +85 -85
  132. package/src/server/utils/get-repo-account.ts +51 -41
  133. package/src/server/utils/gitlab-url.ts +38 -38
  134. package/src/server/utils/redact.ts +87 -87
  135. package/src/server/utils/url-security.ts +128 -95
  136. package/dist/client/900.acf7d1fa22f95e71.js +0 -10
  137. package/dist/client-v2/434.7a27051db18526c0.js +0 -10
  138. package/dist/client-v2/900.f32b9dc85249fc0a.js +0 -10
@@ -1,508 +1,508 @@
1
- import { Context } from '@nocobase/actions';
2
- import * as fs from 'fs';
3
- import * as os from 'os';
4
- import * as path from 'path';
5
- import type { SimpleGit } from 'simple-git';
6
- import { createGit, validateBranch, validateLocalPath, withAuth } from './git-actions';
7
- import { getEffectiveActionParams } from '../repository-access';
8
- import { getRepoAccount } from '../utils/get-repo-account';
9
- import { redactError, redactPat } from '../utils/redact';
10
-
11
- export type SubtreePolicy = 'fastForward' | 'replace' | 'merge';
12
- export type SubtreeRelationship = 'target-missing' | 'already-up-to-date' | 'fast-forward' | 'diverged';
13
- export const SUBTREE_EXECUTION_MODE = 'app' as const;
14
-
15
- interface RecordLike {
16
- get(attribute: string): unknown;
17
- }
18
-
19
- interface SubtreeConfig {
20
- id: number | string;
21
- repositoryId: number | string;
22
- sourceBranch: string;
23
- sourcePrefix: string;
24
- sourcePrefixes: string[];
25
- targetBranch: string;
26
- remoteName: string;
27
- enabled: boolean;
28
- }
29
-
30
- interface PreviewResult {
31
- sourceSha: string;
32
- splitSha: string;
33
- targetExists: boolean;
34
- targetSha: string | null;
35
- relationship: SubtreeRelationship;
36
- recommendedPolicy: SubtreePolicy;
37
- availablePolicies: SubtreePolicy[];
38
- }
39
-
40
- interface RunParams {
41
- configId: number | string;
42
- policy: SubtreePolicy;
43
- push: boolean;
44
- expectedTargetSha?: string;
45
- }
46
-
47
- function stringValue(value: unknown, fallback = ''): string {
48
- return typeof value === 'string' ? value.trim() : fallback;
49
- }
50
-
51
- function booleanValue(value: unknown, fallback: boolean): boolean {
52
- return typeof value === 'boolean' ? value : fallback;
53
- }
54
-
55
- function recordToConfig(record: RecordLike): SubtreeConfig {
56
- const storedPrefixes = record.get('sourcePrefixes');
57
- const sourcePrefix = stringValue(record.get('sourcePrefix'));
58
- return {
59
- id: record.get('id') as number | string,
60
- repositoryId: record.get('repositoryId') as number | string,
61
- sourceBranch: stringValue(record.get('sourceBranch')),
62
- sourcePrefix,
63
- sourcePrefixes: validateSubtreePrefixes(Array.isArray(storedPrefixes) ? storedPrefixes : [sourcePrefix]),
64
- targetBranch: stringValue(record.get('targetBranch')),
65
- remoteName: stringValue(record.get('remoteName'), 'origin') || 'origin',
66
- enabled: record.get('enabled') !== false,
67
- };
68
- }
69
-
70
- export function validateSubtreePrefix(prefix: string): string {
71
- const normalized = prefix.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/$/, '');
72
- if (!normalized || path.posix.isAbsolute(normalized) || /^[a-zA-Z]:\//.test(normalized)) {
73
- throw new Error('Source folder must be a non-empty relative path');
74
- }
75
- if (normalized.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
76
- throw new Error('Source folder contains an invalid path segment');
77
- }
78
- return normalized;
79
- }
80
-
81
- export function validateSubtreePrefixes(prefixes: unknown[]): string[] {
82
- const normalized = Array.from(new Set(prefixes.map((prefix) => validateSubtreePrefix(stringValue(prefix))))).sort();
83
- for (const prefix of normalized) {
84
- if (normalized.some((candidate) => candidate !== prefix && prefix.startsWith(`${candidate}/`))) {
85
- throw new Error('Source folders cannot contain overlapping parent and child paths');
86
- }
87
- }
88
- return normalized;
89
- }
90
-
91
- export function validateRemoteName(remoteName: string): string {
92
- if (!/^(?!-)[a-zA-Z0-9._-]+$/.test(remoteName)) {
93
- throw new Error('Invalid Git remote name');
94
- }
95
- return remoteName;
96
- }
97
-
98
- export function validateSubtreePolicy(policy: unknown): SubtreePolicy {
99
- if (policy === 'fastForward' || policy === 'replace' || policy === 'merge') return policy;
100
- throw new Error('Invalid subtree update policy');
101
- }
102
-
103
- export function validateSubtreeConfigInput(values: Record<string, unknown>): void {
104
- const sourceBranch = stringValue(values.sourceBranch);
105
- const targetBranch = stringValue(values.targetBranch);
106
- if (sourceBranch) validateBranch(sourceBranch);
107
- if (targetBranch) validateBranch(targetBranch);
108
- if (sourceBranch && targetBranch && sourceBranch === targetBranch) {
109
- throw new Error('Source branch and target branch must be different');
110
- }
111
- if (values.sourcePrefixes !== undefined) {
112
- if (!Array.isArray(values.sourcePrefixes) || values.sourcePrefixes.length === 0) {
113
- throw new Error('At least one source folder is required');
114
- }
115
- validateSubtreePrefixes(values.sourcePrefixes);
116
- } else if (values.sourcePrefix !== undefined) {
117
- validateSubtreePrefix(stringValue(values.sourcePrefix));
118
- }
119
- if (values.remoteName !== undefined) validateRemoteName(stringValue(values.remoteName));
120
- if (values.defaultPolicy !== undefined) validateSubtreePolicy(values.defaultPolicy);
121
- }
122
-
123
- export function validateRunAgainstPreview(
124
- policy: SubtreePolicy,
125
- preview: Pick<PreviewResult, 'relationship' | 'targetSha'>,
126
- expectedTargetSha?: string,
127
- ): void {
128
- if (policy === 'fastForward' && preview.relationship === 'diverged') {
129
- throw new Error('Target branch cannot be fast-forwarded to the new subtree commit');
130
- }
131
- if (policy === 'replace' && preview.targetSha) {
132
- if (!expectedTargetSha) throw new Error('Replace policy requires the preview target SHA');
133
- if (expectedTargetSha !== preview.targetSha) {
134
- throw new Error('Target branch changed after preview; run preview again');
135
- }
136
- }
137
- }
138
-
139
- export async function recoverStuckSubtreeRuns(app: {
140
- db: { getRepository: (name: string) => { update: (options: unknown) => Promise<unknown> } };
141
- }): Promise<void> {
142
- const finishedAt = new Date();
143
- const staleBefore = new Date(finishedAt.getTime() - 60 * 60 * 1000);
144
- await app.db.getRepository('gitSubtreeRuns').update({
145
- filter: { status: 'running', startedAt: { $lt: staleBefore } },
146
- values: { status: 'failed', finishedAt, error: 'Subtree run was interrupted by a server restart' },
147
- });
148
- }
149
-
150
- async function resolveOptionalRef(git: SimpleGit, ref: string): Promise<string | null> {
151
- try {
152
- return (await git.revparse(['--verify', ref])).trim();
153
- } catch {
154
- return null;
155
- }
156
- }
157
-
158
- async function isAncestor(git: SimpleGit, ancestor: string, descendant: string): Promise<boolean> {
159
- try {
160
- await git.raw(['merge-base', '--is-ancestor', ancestor, descendant]);
161
- return true;
162
- } catch {
163
- return false;
164
- }
165
- }
166
-
167
- async function assertCleanWorkingTree(git: SimpleGit): Promise<void> {
168
- const status = await git.status();
169
- if (!status.isClean()) throw new Error('Repository working tree must be clean before running a subtree split');
170
- }
171
-
172
- async function assertGitBranchFormat(git: SimpleGit, branch: string): Promise<void> {
173
- try {
174
- await git.raw(['check-ref-format', '--branch', branch]);
175
- } catch {
176
- throw new Error(`Invalid branch name: ${branch}`);
177
- }
178
- }
179
-
180
- async function createCombinedSnapshot(git: SimpleGit, sourceSha: string, prefixes: string[]): Promise<string> {
181
- const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'nocobase-git-snapshot-'));
182
- const indexPath = path.join(temporaryRoot, 'index');
183
- const repositoryRoot = (await git.revparse(['--show-toplevel'])).trim();
184
- const indexGit = createGit(repositoryRoot).env('GIT_INDEX_FILE', indexPath);
185
- try {
186
- await indexGit.raw(['read-tree', '--empty']);
187
- for (const prefix of prefixes) {
188
- const treeSha = (await git.revparse([`${sourceSha}:${prefix}`])).trim();
189
- await indexGit.raw(['read-tree', `--prefix=${prefix}/`, treeSha]);
190
- }
191
- const treeSha = (await indexGit.raw(['write-tree'])).trim();
192
- return (
193
- await git.raw([
194
- '-c',
195
- 'user.name=NocoBase Git Manager',
196
- '-c',
197
- 'user.email=git-manager@nocobase.local',
198
- 'commit-tree',
199
- treeSha,
200
- '-m',
201
- `Snapshot selected folders from ${sourceSha}`,
202
- ])
203
- ).trim();
204
- } finally {
205
- fs.rmSync(temporaryRoot, { recursive: true, force: true });
206
- }
207
- }
208
-
209
- async function createPreview(git: SimpleGit, config: SubtreeConfig): Promise<PreviewResult> {
210
- validateBranch(config.sourceBranch);
211
- validateBranch(config.targetBranch);
212
- if (config.sourceBranch === config.targetBranch) {
213
- throw new Error('Source branch and target branch must be different');
214
- }
215
- const prefixes = validateSubtreePrefixes(config.sourcePrefixes);
216
- const remoteName = validateRemoteName(config.remoteName);
217
- const sourceRef = `refs/remotes/${remoteName}/${config.sourceBranch}`;
218
- const targetRef = `refs/remotes/${remoteName}/${config.targetBranch}`;
219
-
220
- await assertCleanWorkingTree(git);
221
- await assertGitBranchFormat(git, config.sourceBranch);
222
- await assertGitBranchFormat(git, config.targetBranch);
223
- await git.fetch(remoteName, ['--prune']);
224
- const sourceSha = await resolveOptionalRef(git, sourceRef);
225
- if (!sourceSha) throw new Error('Source branch was not found on the configured remote');
226
-
227
- for (const prefix of prefixes) {
228
- let objectType = '';
229
- try {
230
- objectType = (await git.raw(['cat-file', '-t', `${sourceSha}:${prefix}`])).trim();
231
- } catch {
232
- throw new Error(`Source folder was not found in the selected source branch: ${prefix}`);
233
- }
234
- if (objectType !== 'tree') throw new Error(`Selected source path is not a folder: ${prefix}`);
235
- }
236
-
237
- const splitSha = await createCombinedSnapshot(git, sourceSha, prefixes);
238
- if (!/^[a-f0-9]{40,64}$/i.test(splitSha)) throw new Error('Git subtree split did not return a valid commit');
239
-
240
- const targetSha = await resolveOptionalRef(git, targetRef);
241
- let relationship: SubtreeRelationship = 'target-missing';
242
- if (targetSha === splitSha) relationship = 'already-up-to-date';
243
- else if (targetSha) relationship = (await isAncestor(git, targetSha, splitSha)) ? 'fast-forward' : 'diverged';
244
-
245
- return {
246
- sourceSha,
247
- splitSha,
248
- targetExists: !!targetSha,
249
- targetSha,
250
- relationship,
251
- recommendedPolicy: relationship === 'diverged' ? 'merge' : 'fastForward',
252
- availablePolicies: ['fastForward', 'replace', 'merge'],
253
- };
254
- }
255
-
256
- async function updateTargetRef(git: SimpleGit, config: SubtreeConfig, sha: string): Promise<void> {
257
- await git.raw(['branch', '-f', config.targetBranch, sha]);
258
- }
259
-
260
- async function pushTarget(
261
- git: SimpleGit,
262
- config: SubtreeConfig,
263
- sha: string,
264
- forceWithLeaseSha?: string,
265
- ): Promise<void> {
266
- const args = ['push'];
267
- if (forceWithLeaseSha) {
268
- args.push(`--force-with-lease=refs/heads/${config.targetBranch}:${forceWithLeaseSha}`);
269
- }
270
- args.push(config.remoteName, `${sha}:refs/heads/${config.targetBranch}`);
271
- await git.raw(args);
272
- }
273
-
274
- async function mergeTarget(git: SimpleGit, config: SubtreeConfig, preview: PreviewResult): Promise<string> {
275
- if (!preview.targetSha) return preview.splitSha;
276
-
277
- const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'nocobase-git-subtree-'));
278
- const worktreePath = path.join(temporaryRoot, 'worktree');
279
- try {
280
- await git.raw(['worktree', 'add', '--detach', worktreePath, preview.targetSha]);
281
- const worktreeGit = createGit(worktreePath);
282
- try {
283
- await worktreeGit.raw([
284
- '-c',
285
- 'user.name=NocoBase Git Manager',
286
- '-c',
287
- 'user.email=git-manager@nocobase.local',
288
- 'merge',
289
- preview.splitSha,
290
- '--allow-unrelated-histories',
291
- '--no-edit',
292
- ]);
293
- } catch (error) {
294
- await worktreeGit.raw(['merge', '--abort']).catch(() => undefined);
295
- throw new Error(`Subtree merge has conflicts: ${redactPat(redactError(error).message)}`);
296
- }
297
- return (await worktreeGit.revparse(['HEAD'])).trim();
298
- } finally {
299
- await git.raw(['worktree', 'remove', '--force', worktreePath]).catch(() => undefined);
300
- fs.rmSync(temporaryRoot, { recursive: true, force: true });
301
- }
302
- }
303
-
304
- async function loadConfigAndRepository(ctx: Context, configId: number | string) {
305
- const configRecord = await ctx.db.getRepository('gitSubtreeConfigs').findOne({ filterByTk: configId });
306
- if (!configRecord) ctx.throw(404, 'Subtree configuration not found');
307
- const config = recordToConfig(configRecord as RecordLike);
308
- if (!config.enabled) ctx.throw(400, 'Subtree configuration is disabled');
309
-
310
- const repo = await ctx.db.getRepository('gitRepositories').findOne({ filterByTk: config.repositoryId });
311
- if (!repo) ctx.throw(404, 'Repository not found');
312
- const account = await getRepoAccount(ctx.db, repo);
313
- if (!account) ctx.throw(400, 'Repository has no Git account configured');
314
-
315
- return { configRecord, config, repo, account };
316
- }
317
-
318
- export async function subtreeOptions(ctx: Context, next: () => Promise<void>) {
319
- const params = getEffectiveActionParams(ctx);
320
- const repositoryId = params.repositoryId as number | string;
321
- if (!repositoryId) ctx.throw(400, 'repositoryId is required');
322
- const remoteName = validateRemoteName(stringValue(params.remoteName, 'origin') || 'origin');
323
- const sourceBranch = stringValue(params.sourceBranch);
324
- if (sourceBranch) validateBranch(sourceBranch);
325
-
326
- const repo = await ctx.db.getRepository('gitRepositories').findOne({ filterByTk: repositoryId });
327
- if (!repo) ctx.throw(404, 'Repository not found');
328
- const account = await getRepoAccount(ctx.db, repo);
329
- if (!account) ctx.throw(400, 'Repository has no Git account configured');
330
- const localPath = validateLocalPath(stringValue(repo.get('localPath')));
331
- const repoUrl = stringValue(repo.get('repoUrl'));
332
- const git = createGit(localPath);
333
-
334
- try {
335
- const data = await withAuth(
336
- git,
337
- localPath,
338
- repoUrl,
339
- account.pat,
340
- async () => {
341
- if (sourceBranch) await assertGitBranchFormat(git, sourceBranch);
342
- await git.fetch(remoteName, ['--prune']);
343
- const branchOutput = await git.raw([
344
- 'for-each-ref',
345
- '--format=%(refname:strip=3)',
346
- `refs/remotes/${remoteName}`,
347
- ]);
348
- const branches = branchOutput
349
- .split('\n')
350
- .map((branch) => branch.trim())
351
- .filter((branch) => branch && branch !== 'HEAD');
352
- let folders: string[] = [];
353
- if (sourceBranch) {
354
- const sourceRef = `refs/remotes/${remoteName}/${sourceBranch}`;
355
- if (!(await resolveOptionalRef(git, sourceRef))) {
356
- throw new Error('Source branch was not found on the configured remote');
357
- }
358
- const folderOutput = await git.raw(['ls-tree', '-d', '-r', '--name-only', sourceRef]);
359
- folders = folderOutput
360
- .split('\n')
361
- .map((folder) => folder.trim())
362
- .filter(Boolean);
363
- }
364
- return { branches: Array.from(new Set(branches)).sort(), folders };
365
- },
366
- account.username,
367
- remoteName,
368
- );
369
- ctx.body = { success: true, data };
370
- } catch (error) {
371
- const safeError = redactError(error);
372
- ctx.throw(400, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
373
- }
374
- await next();
375
- }
376
-
377
- export async function subtreePreview(ctx: Context, next: () => Promise<void>) {
378
- const params = getEffectiveActionParams(ctx);
379
- const configId = params.configId as number | string;
380
- if (!configId) ctx.throw(400, 'configId is required');
381
- const { config, repo, account } = await loadConfigAndRepository(ctx, configId);
382
- const localPath = validateLocalPath(stringValue(repo.get('localPath')));
383
- const repoUrl = stringValue(repo.get('repoUrl'));
384
- const git = createGit(localPath);
385
-
386
- try {
387
- const preview = await withAuth(
388
- git,
389
- localPath,
390
- repoUrl,
391
- account.pat,
392
- () => createPreview(git, config),
393
- account.username,
394
- config.remoteName,
395
- );
396
- ctx.body = { success: true, data: preview };
397
- } catch (error) {
398
- const safeError = redactError(error);
399
- ctx.throw(400, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
400
- }
401
- await next();
402
- }
403
-
404
- /**
405
- * Executes the complete subtree workflow inside the interactive app request.
406
- * This action intentionally does not enqueue work in the automatic-review queue.
407
- */
408
- export async function subtreeRunOnAppProcess(ctx: Context, next: () => Promise<void>) {
409
- const params = getEffectiveActionParams(ctx);
410
- const runParams: RunParams = {
411
- configId: params.configId as number | string,
412
- policy: validateSubtreePolicy(params.policy),
413
- push: booleanValue(params.push, true),
414
- expectedTargetSha: stringValue(params.expectedTargetSha) || undefined,
415
- };
416
- if (!runParams.configId) ctx.throw(400, 'configId is required');
417
- if (runParams.policy === 'replace' && ctx.action.actionName !== 'subtreeReplace') {
418
- ctx.throw(403, 'Replace policy requires the destructive subtree permission');
419
- }
420
-
421
- const { config, repo, account } = await loadConfigAndRepository(ctx, runParams.configId);
422
- const localPath = validateLocalPath(stringValue(repo.get('localPath')));
423
- const repoUrl = stringValue(repo.get('repoUrl'));
424
- const git = createGit(localPath);
425
- const runsRepository = ctx.db.getRepository('gitSubtreeRuns');
426
- const startedAt = new Date();
427
- const run = await runsRepository.create({
428
- values: {
429
- configId: config.id,
430
- policy: runParams.policy,
431
- executionMode: SUBTREE_EXECUTION_MODE,
432
- status: 'running',
433
- startedAt,
434
- triggeredById: (ctx as Context & { state?: { currentUser?: { id?: number | string } } }).state?.currentUser?.id,
435
- },
436
- });
437
-
438
- try {
439
- const result = await withAuth(
440
- git,
441
- localPath,
442
- repoUrl,
443
- account.pat,
444
- async () => {
445
- const preview = await createPreview(git, config);
446
- let targetAfterSha = preview.splitSha;
447
-
448
- validateRunAgainstPreview(runParams.policy, preview, runParams.expectedTargetSha);
449
- if (runParams.policy === 'merge') targetAfterSha = await mergeTarget(git, config, preview);
450
-
451
- if (runParams.push) {
452
- await pushTarget(
453
- git,
454
- config,
455
- targetAfterSha,
456
- runParams.policy === 'replace' && preview.targetSha ? preview.targetSha : undefined,
457
- );
458
- } else {
459
- await updateTargetRef(git, config, targetAfterSha);
460
- }
461
- return { preview, targetAfterSha };
462
- },
463
- account.username,
464
- config.remoteName,
465
- );
466
-
467
- const finishedAt = new Date();
468
- await runsRepository.update({
469
- filterByTk: run.get('id'),
470
- values: {
471
- sourceSha: result.preview.sourceSha,
472
- splitSha: result.preview.splitSha,
473
- targetBeforeSha: result.preview.targetSha,
474
- targetAfterSha: result.targetAfterSha,
475
- status: 'success',
476
- finishedAt,
477
- output: `Updated ${config.targetBranch} using ${runParams.policy}`,
478
- },
479
- });
480
- await ctx.db.getRepository('gitSubtreeConfigs').update({
481
- filterByTk: config.id,
482
- values: {
483
- lastRunAt: finishedAt,
484
- lastSplitSha: result.preview.splitSha,
485
- lastStatus: 'success',
486
- lastError: null,
487
- },
488
- });
489
- ctx.body = {
490
- success: true,
491
- data: { runId: run.get('id'), executionMode: SUBTREE_EXECUTION_MODE, ...result },
492
- };
493
- } catch (error) {
494
- const safeError = redactError(error);
495
- const status = /conflict/i.test(safeError.message) ? 'conflict' : 'failed';
496
- const finishedAt = new Date();
497
- await runsRepository.update({
498
- filterByTk: run.get('id'),
499
- values: { status, finishedAt, error: safeError.message },
500
- });
501
- await ctx.db.getRepository('gitSubtreeConfigs').update({
502
- filterByTk: config.id,
503
- values: { lastRunAt: finishedAt, lastStatus: status, lastError: safeError.message },
504
- });
505
- ctx.throw(status === 'conflict' ? 409 : 400, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
506
- }
507
- await next();
508
- }
1
+ import { Context } from '@nocobase/actions';
2
+ import * as fs from 'fs';
3
+ import * as os from 'os';
4
+ import * as path from 'path';
5
+ import type { SimpleGit } from 'simple-git';
6
+ import { createGit, validateBranch, validateLocalPath, withAuth } from './git-actions';
7
+ import { getEffectiveActionParams } from '../repository-access';
8
+ import { getRepoAccount } from '../utils/get-repo-account';
9
+ import { redactError, redactPat } from '../utils/redact';
10
+
11
+ export type SubtreePolicy = 'fastForward' | 'replace' | 'merge';
12
+ export type SubtreeRelationship = 'target-missing' | 'already-up-to-date' | 'fast-forward' | 'diverged';
13
+ export const SUBTREE_EXECUTION_MODE = 'app' as const;
14
+
15
+ interface RecordLike {
16
+ get(attribute: string): unknown;
17
+ }
18
+
19
+ interface SubtreeConfig {
20
+ id: number | string;
21
+ repositoryId: number | string;
22
+ sourceBranch: string;
23
+ sourcePrefix: string;
24
+ sourcePrefixes: string[];
25
+ targetBranch: string;
26
+ remoteName: string;
27
+ enabled: boolean;
28
+ }
29
+
30
+ interface PreviewResult {
31
+ sourceSha: string;
32
+ splitSha: string;
33
+ targetExists: boolean;
34
+ targetSha: string | null;
35
+ relationship: SubtreeRelationship;
36
+ recommendedPolicy: SubtreePolicy;
37
+ availablePolicies: SubtreePolicy[];
38
+ }
39
+
40
+ interface RunParams {
41
+ configId: number | string;
42
+ policy: SubtreePolicy;
43
+ push: boolean;
44
+ expectedTargetSha?: string;
45
+ }
46
+
47
+ function stringValue(value: unknown, fallback = ''): string {
48
+ return typeof value === 'string' ? value.trim() : fallback;
49
+ }
50
+
51
+ function booleanValue(value: unknown, fallback: boolean): boolean {
52
+ return typeof value === 'boolean' ? value : fallback;
53
+ }
54
+
55
+ function recordToConfig(record: RecordLike): SubtreeConfig {
56
+ const storedPrefixes = record.get('sourcePrefixes');
57
+ const sourcePrefix = stringValue(record.get('sourcePrefix'));
58
+ return {
59
+ id: record.get('id') as number | string,
60
+ repositoryId: record.get('repositoryId') as number | string,
61
+ sourceBranch: stringValue(record.get('sourceBranch')),
62
+ sourcePrefix,
63
+ sourcePrefixes: validateSubtreePrefixes(Array.isArray(storedPrefixes) ? storedPrefixes : [sourcePrefix]),
64
+ targetBranch: stringValue(record.get('targetBranch')),
65
+ remoteName: stringValue(record.get('remoteName'), 'origin') || 'origin',
66
+ enabled: record.get('enabled') !== false,
67
+ };
68
+ }
69
+
70
+ export function validateSubtreePrefix(prefix: string): string {
71
+ const normalized = prefix.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/$/, '');
72
+ if (!normalized || path.posix.isAbsolute(normalized) || /^[a-zA-Z]:\//.test(normalized)) {
73
+ throw new Error('Source folder must be a non-empty relative path');
74
+ }
75
+ if (normalized.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
76
+ throw new Error('Source folder contains an invalid path segment');
77
+ }
78
+ return normalized;
79
+ }
80
+
81
+ export function validateSubtreePrefixes(prefixes: unknown[]): string[] {
82
+ const normalized = Array.from(new Set(prefixes.map((prefix) => validateSubtreePrefix(stringValue(prefix))))).sort();
83
+ for (const prefix of normalized) {
84
+ if (normalized.some((candidate) => candidate !== prefix && prefix.startsWith(`${candidate}/`))) {
85
+ throw new Error('Source folders cannot contain overlapping parent and child paths');
86
+ }
87
+ }
88
+ return normalized;
89
+ }
90
+
91
+ export function validateRemoteName(remoteName: string): string {
92
+ if (!/^(?!-)[a-zA-Z0-9._-]+$/.test(remoteName)) {
93
+ throw new Error('Invalid Git remote name');
94
+ }
95
+ return remoteName;
96
+ }
97
+
98
+ export function validateSubtreePolicy(policy: unknown): SubtreePolicy {
99
+ if (policy === 'fastForward' || policy === 'replace' || policy === 'merge') return policy;
100
+ throw new Error('Invalid subtree update policy');
101
+ }
102
+
103
+ export function validateSubtreeConfigInput(values: Record<string, unknown>): void {
104
+ const sourceBranch = stringValue(values.sourceBranch);
105
+ const targetBranch = stringValue(values.targetBranch);
106
+ if (sourceBranch) validateBranch(sourceBranch);
107
+ if (targetBranch) validateBranch(targetBranch);
108
+ if (sourceBranch && targetBranch && sourceBranch === targetBranch) {
109
+ throw new Error('Source branch and target branch must be different');
110
+ }
111
+ if (values.sourcePrefixes !== undefined) {
112
+ if (!Array.isArray(values.sourcePrefixes) || values.sourcePrefixes.length === 0) {
113
+ throw new Error('At least one source folder is required');
114
+ }
115
+ validateSubtreePrefixes(values.sourcePrefixes);
116
+ } else if (values.sourcePrefix !== undefined) {
117
+ validateSubtreePrefix(stringValue(values.sourcePrefix));
118
+ }
119
+ if (values.remoteName !== undefined) validateRemoteName(stringValue(values.remoteName));
120
+ if (values.defaultPolicy !== undefined) validateSubtreePolicy(values.defaultPolicy);
121
+ }
122
+
123
+ export function validateRunAgainstPreview(
124
+ policy: SubtreePolicy,
125
+ preview: Pick<PreviewResult, 'relationship' | 'targetSha'>,
126
+ expectedTargetSha?: string,
127
+ ): void {
128
+ if (policy === 'fastForward' && preview.relationship === 'diverged') {
129
+ throw new Error('Target branch cannot be fast-forwarded to the new subtree commit');
130
+ }
131
+ if (policy === 'replace' && preview.targetSha) {
132
+ if (!expectedTargetSha) throw new Error('Replace policy requires the preview target SHA');
133
+ if (expectedTargetSha !== preview.targetSha) {
134
+ throw new Error('Target branch changed after preview; run preview again');
135
+ }
136
+ }
137
+ }
138
+
139
+ export async function recoverStuckSubtreeRuns(app: {
140
+ db: { getRepository: (name: string) => { update: (options: unknown) => Promise<unknown> } };
141
+ }): Promise<void> {
142
+ const finishedAt = new Date();
143
+ const staleBefore = new Date(finishedAt.getTime() - 60 * 60 * 1000);
144
+ await app.db.getRepository('gitSubtreeRuns').update({
145
+ filter: { status: 'running', startedAt: { $lt: staleBefore } },
146
+ values: { status: 'failed', finishedAt, error: 'Subtree run was interrupted by a server restart' },
147
+ });
148
+ }
149
+
150
+ async function resolveOptionalRef(git: SimpleGit, ref: string): Promise<string | null> {
151
+ try {
152
+ return (await git.revparse(['--verify', ref])).trim();
153
+ } catch {
154
+ return null;
155
+ }
156
+ }
157
+
158
+ async function isAncestor(git: SimpleGit, ancestor: string, descendant: string): Promise<boolean> {
159
+ try {
160
+ await git.raw(['merge-base', '--is-ancestor', ancestor, descendant]);
161
+ return true;
162
+ } catch {
163
+ return false;
164
+ }
165
+ }
166
+
167
+ async function assertCleanWorkingTree(git: SimpleGit): Promise<void> {
168
+ const status = await git.status();
169
+ if (!status.isClean()) throw new Error('Repository working tree must be clean before running a subtree split');
170
+ }
171
+
172
+ async function assertGitBranchFormat(git: SimpleGit, branch: string): Promise<void> {
173
+ try {
174
+ await git.raw(['check-ref-format', '--branch', branch]);
175
+ } catch {
176
+ throw new Error(`Invalid branch name: ${branch}`);
177
+ }
178
+ }
179
+
180
+ async function createCombinedSnapshot(git: SimpleGit, sourceSha: string, prefixes: string[]): Promise<string> {
181
+ const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'nocobase-git-snapshot-'));
182
+ const indexPath = path.join(temporaryRoot, 'index');
183
+ const repositoryRoot = (await git.revparse(['--show-toplevel'])).trim();
184
+ const indexGit = createGit(repositoryRoot).env('GIT_INDEX_FILE', indexPath);
185
+ try {
186
+ await indexGit.raw(['read-tree', '--empty']);
187
+ for (const prefix of prefixes) {
188
+ const treeSha = (await git.revparse([`${sourceSha}:${prefix}`])).trim();
189
+ await indexGit.raw(['read-tree', `--prefix=${prefix}/`, treeSha]);
190
+ }
191
+ const treeSha = (await indexGit.raw(['write-tree'])).trim();
192
+ return (
193
+ await git.raw([
194
+ '-c',
195
+ 'user.name=NocoBase Git Manager',
196
+ '-c',
197
+ 'user.email=git-manager@nocobase.local',
198
+ 'commit-tree',
199
+ treeSha,
200
+ '-m',
201
+ `Snapshot selected folders from ${sourceSha}`,
202
+ ])
203
+ ).trim();
204
+ } finally {
205
+ fs.rmSync(temporaryRoot, { recursive: true, force: true });
206
+ }
207
+ }
208
+
209
+ async function createPreview(git: SimpleGit, config: SubtreeConfig): Promise<PreviewResult> {
210
+ validateBranch(config.sourceBranch);
211
+ validateBranch(config.targetBranch);
212
+ if (config.sourceBranch === config.targetBranch) {
213
+ throw new Error('Source branch and target branch must be different');
214
+ }
215
+ const prefixes = validateSubtreePrefixes(config.sourcePrefixes);
216
+ const remoteName = validateRemoteName(config.remoteName);
217
+ const sourceRef = `refs/remotes/${remoteName}/${config.sourceBranch}`;
218
+ const targetRef = `refs/remotes/${remoteName}/${config.targetBranch}`;
219
+
220
+ await assertCleanWorkingTree(git);
221
+ await assertGitBranchFormat(git, config.sourceBranch);
222
+ await assertGitBranchFormat(git, config.targetBranch);
223
+ await git.fetch(remoteName, ['--prune']);
224
+ const sourceSha = await resolveOptionalRef(git, sourceRef);
225
+ if (!sourceSha) throw new Error('Source branch was not found on the configured remote');
226
+
227
+ for (const prefix of prefixes) {
228
+ let objectType = '';
229
+ try {
230
+ objectType = (await git.raw(['cat-file', '-t', `${sourceSha}:${prefix}`])).trim();
231
+ } catch {
232
+ throw new Error(`Source folder was not found in the selected source branch: ${prefix}`);
233
+ }
234
+ if (objectType !== 'tree') throw new Error(`Selected source path is not a folder: ${prefix}`);
235
+ }
236
+
237
+ const splitSha = await createCombinedSnapshot(git, sourceSha, prefixes);
238
+ if (!/^[a-f0-9]{40,64}$/i.test(splitSha)) throw new Error('Git subtree split did not return a valid commit');
239
+
240
+ const targetSha = await resolveOptionalRef(git, targetRef);
241
+ let relationship: SubtreeRelationship = 'target-missing';
242
+ if (targetSha === splitSha) relationship = 'already-up-to-date';
243
+ else if (targetSha) relationship = (await isAncestor(git, targetSha, splitSha)) ? 'fast-forward' : 'diverged';
244
+
245
+ return {
246
+ sourceSha,
247
+ splitSha,
248
+ targetExists: !!targetSha,
249
+ targetSha,
250
+ relationship,
251
+ recommendedPolicy: relationship === 'diverged' ? 'merge' : 'fastForward',
252
+ availablePolicies: ['fastForward', 'replace', 'merge'],
253
+ };
254
+ }
255
+
256
+ async function updateTargetRef(git: SimpleGit, config: SubtreeConfig, sha: string): Promise<void> {
257
+ await git.raw(['branch', '-f', config.targetBranch, sha]);
258
+ }
259
+
260
+ async function pushTarget(
261
+ git: SimpleGit,
262
+ config: SubtreeConfig,
263
+ sha: string,
264
+ forceWithLeaseSha?: string,
265
+ ): Promise<void> {
266
+ const args = ['push'];
267
+ if (forceWithLeaseSha) {
268
+ args.push(`--force-with-lease=refs/heads/${config.targetBranch}:${forceWithLeaseSha}`);
269
+ }
270
+ args.push(config.remoteName, `${sha}:refs/heads/${config.targetBranch}`);
271
+ await git.raw(args);
272
+ }
273
+
274
+ async function mergeTarget(git: SimpleGit, config: SubtreeConfig, preview: PreviewResult): Promise<string> {
275
+ if (!preview.targetSha) return preview.splitSha;
276
+
277
+ const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'nocobase-git-subtree-'));
278
+ const worktreePath = path.join(temporaryRoot, 'worktree');
279
+ try {
280
+ await git.raw(['worktree', 'add', '--detach', worktreePath, preview.targetSha]);
281
+ const worktreeGit = createGit(worktreePath);
282
+ try {
283
+ await worktreeGit.raw([
284
+ '-c',
285
+ 'user.name=NocoBase Git Manager',
286
+ '-c',
287
+ 'user.email=git-manager@nocobase.local',
288
+ 'merge',
289
+ preview.splitSha,
290
+ '--allow-unrelated-histories',
291
+ '--no-edit',
292
+ ]);
293
+ } catch (error) {
294
+ await worktreeGit.raw(['merge', '--abort']).catch(() => undefined);
295
+ throw new Error(`Subtree merge has conflicts: ${redactPat(redactError(error).message)}`);
296
+ }
297
+ return (await worktreeGit.revparse(['HEAD'])).trim();
298
+ } finally {
299
+ await git.raw(['worktree', 'remove', '--force', worktreePath]).catch(() => undefined);
300
+ fs.rmSync(temporaryRoot, { recursive: true, force: true });
301
+ }
302
+ }
303
+
304
+ async function loadConfigAndRepository(ctx: Context, configId: number | string) {
305
+ const configRecord = await ctx.db.getRepository('gitSubtreeConfigs').findOne({ filterByTk: configId });
306
+ if (!configRecord) ctx.throw(404, 'Subtree configuration not found');
307
+ const config = recordToConfig(configRecord as RecordLike);
308
+ if (!config.enabled) ctx.throw(400, 'Subtree configuration is disabled');
309
+
310
+ const repo = await ctx.db.getRepository('gitRepositories').findOne({ filterByTk: config.repositoryId });
311
+ if (!repo) ctx.throw(404, 'Repository not found');
312
+ const account = await getRepoAccount(ctx.db, repo);
313
+ if (!account) ctx.throw(400, 'Repository has no Git account configured');
314
+
315
+ return { configRecord, config, repo, account };
316
+ }
317
+
318
+ export async function subtreeOptions(ctx: Context, next: () => Promise<void>) {
319
+ const params = getEffectiveActionParams(ctx);
320
+ const repositoryId = params.repositoryId as number | string;
321
+ if (!repositoryId) ctx.throw(400, 'repositoryId is required');
322
+ const remoteName = validateRemoteName(stringValue(params.remoteName, 'origin') || 'origin');
323
+ const sourceBranch = stringValue(params.sourceBranch);
324
+ if (sourceBranch) validateBranch(sourceBranch);
325
+
326
+ const repo = await ctx.db.getRepository('gitRepositories').findOne({ filterByTk: repositoryId });
327
+ if (!repo) ctx.throw(404, 'Repository not found');
328
+ const account = await getRepoAccount(ctx.db, repo);
329
+ if (!account) ctx.throw(400, 'Repository has no Git account configured');
330
+ const localPath = validateLocalPath(stringValue(repo.get('localPath')));
331
+ const repoUrl = stringValue(repo.get('repoUrl'));
332
+ const git = createGit(localPath);
333
+
334
+ try {
335
+ const data = await withAuth(
336
+ git,
337
+ localPath,
338
+ repoUrl,
339
+ account.pat,
340
+ async () => {
341
+ if (sourceBranch) await assertGitBranchFormat(git, sourceBranch);
342
+ await git.fetch(remoteName, ['--prune']);
343
+ const branchOutput = await git.raw([
344
+ 'for-each-ref',
345
+ '--format=%(refname:strip=3)',
346
+ `refs/remotes/${remoteName}`,
347
+ ]);
348
+ const branches = branchOutput
349
+ .split('\n')
350
+ .map((branch) => branch.trim())
351
+ .filter((branch) => branch && branch !== 'HEAD');
352
+ let folders: string[] = [];
353
+ if (sourceBranch) {
354
+ const sourceRef = `refs/remotes/${remoteName}/${sourceBranch}`;
355
+ if (!(await resolveOptionalRef(git, sourceRef))) {
356
+ throw new Error('Source branch was not found on the configured remote');
357
+ }
358
+ const folderOutput = await git.raw(['ls-tree', '-d', '-r', '--name-only', sourceRef]);
359
+ folders = folderOutput
360
+ .split('\n')
361
+ .map((folder) => folder.trim())
362
+ .filter(Boolean);
363
+ }
364
+ return { branches: Array.from(new Set(branches)).sort(), folders };
365
+ },
366
+ account.username,
367
+ remoteName,
368
+ );
369
+ ctx.body = { success: true, data };
370
+ } catch (error) {
371
+ const safeError = redactError(error);
372
+ ctx.throw(400, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
373
+ }
374
+ await next();
375
+ }
376
+
377
+ export async function subtreePreview(ctx: Context, next: () => Promise<void>) {
378
+ const params = getEffectiveActionParams(ctx);
379
+ const configId = params.configId as number | string;
380
+ if (!configId) ctx.throw(400, 'configId is required');
381
+ const { config, repo, account } = await loadConfigAndRepository(ctx, configId);
382
+ const localPath = validateLocalPath(stringValue(repo.get('localPath')));
383
+ const repoUrl = stringValue(repo.get('repoUrl'));
384
+ const git = createGit(localPath);
385
+
386
+ try {
387
+ const preview = await withAuth(
388
+ git,
389
+ localPath,
390
+ repoUrl,
391
+ account.pat,
392
+ () => createPreview(git, config),
393
+ account.username,
394
+ config.remoteName,
395
+ );
396
+ ctx.body = { success: true, data: preview };
397
+ } catch (error) {
398
+ const safeError = redactError(error);
399
+ ctx.throw(400, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
400
+ }
401
+ await next();
402
+ }
403
+
404
+ /**
405
+ * Executes the complete subtree workflow inside the interactive app request.
406
+ * This action intentionally does not enqueue work in the automatic-review queue.
407
+ */
408
+ export async function subtreeRunOnAppProcess(ctx: Context, next: () => Promise<void>) {
409
+ const params = getEffectiveActionParams(ctx);
410
+ const runParams: RunParams = {
411
+ configId: params.configId as number | string,
412
+ policy: validateSubtreePolicy(params.policy),
413
+ push: booleanValue(params.push, true),
414
+ expectedTargetSha: stringValue(params.expectedTargetSha) || undefined,
415
+ };
416
+ if (!runParams.configId) ctx.throw(400, 'configId is required');
417
+ if (runParams.policy === 'replace' && ctx.action.actionName !== 'subtreeReplace') {
418
+ ctx.throw(403, 'Replace policy requires the destructive subtree permission');
419
+ }
420
+
421
+ const { config, repo, account } = await loadConfigAndRepository(ctx, runParams.configId);
422
+ const localPath = validateLocalPath(stringValue(repo.get('localPath')));
423
+ const repoUrl = stringValue(repo.get('repoUrl'));
424
+ const git = createGit(localPath);
425
+ const runsRepository = ctx.db.getRepository('gitSubtreeRuns');
426
+ const startedAt = new Date();
427
+ const run = await runsRepository.create({
428
+ values: {
429
+ configId: config.id,
430
+ policy: runParams.policy,
431
+ executionMode: SUBTREE_EXECUTION_MODE,
432
+ status: 'running',
433
+ startedAt,
434
+ triggeredById: (ctx as Context & { state?: { currentUser?: { id?: number | string } } }).state?.currentUser?.id,
435
+ },
436
+ });
437
+
438
+ try {
439
+ const result = await withAuth(
440
+ git,
441
+ localPath,
442
+ repoUrl,
443
+ account.pat,
444
+ async () => {
445
+ const preview = await createPreview(git, config);
446
+ let targetAfterSha = preview.splitSha;
447
+
448
+ validateRunAgainstPreview(runParams.policy, preview, runParams.expectedTargetSha);
449
+ if (runParams.policy === 'merge') targetAfterSha = await mergeTarget(git, config, preview);
450
+
451
+ if (runParams.push) {
452
+ await pushTarget(
453
+ git,
454
+ config,
455
+ targetAfterSha,
456
+ runParams.policy === 'replace' && preview.targetSha ? preview.targetSha : undefined,
457
+ );
458
+ } else {
459
+ await updateTargetRef(git, config, targetAfterSha);
460
+ }
461
+ return { preview, targetAfterSha };
462
+ },
463
+ account.username,
464
+ config.remoteName,
465
+ );
466
+
467
+ const finishedAt = new Date();
468
+ await runsRepository.update({
469
+ filterByTk: run.get('id'),
470
+ values: {
471
+ sourceSha: result.preview.sourceSha,
472
+ splitSha: result.preview.splitSha,
473
+ targetBeforeSha: result.preview.targetSha,
474
+ targetAfterSha: result.targetAfterSha,
475
+ status: 'success',
476
+ finishedAt,
477
+ output: `Updated ${config.targetBranch} using ${runParams.policy}`,
478
+ },
479
+ });
480
+ await ctx.db.getRepository('gitSubtreeConfigs').update({
481
+ filterByTk: config.id,
482
+ values: {
483
+ lastRunAt: finishedAt,
484
+ lastSplitSha: result.preview.splitSha,
485
+ lastStatus: 'success',
486
+ lastError: null,
487
+ },
488
+ });
489
+ ctx.body = {
490
+ success: true,
491
+ data: { runId: run.get('id'), executionMode: SUBTREE_EXECUTION_MODE, ...result },
492
+ };
493
+ } catch (error) {
494
+ const safeError = redactError(error);
495
+ const status = /conflict/i.test(safeError.message) ? 'conflict' : 'failed';
496
+ const finishedAt = new Date();
497
+ await runsRepository.update({
498
+ filterByTk: run.get('id'),
499
+ values: { status, finishedAt, error: safeError.message },
500
+ });
501
+ await ctx.db.getRepository('gitSubtreeConfigs').update({
502
+ filterByTk: config.id,
503
+ values: { lastRunAt: finishedAt, lastStatus: status, lastError: safeError.message },
504
+ });
505
+ ctx.throw(status === 'conflict' ? 409 : 400, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
506
+ }
507
+ await next();
508
+ }