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
@@ -3,6 +3,7 @@
3
3
  import { Plugin } from '@nocobase/server';
4
4
  import type { Context } from '@nocobase/actions';
5
5
  import type { Database } from '@nocobase/database';
6
+ import * as fs from 'fs';
6
7
  import { resolve } from 'path';
7
8
  import { DataTypes } from 'sequelize';
8
9
  import * as gitActions from './actions/git-actions';
@@ -12,6 +13,7 @@ import * as reviewCutoverActions from './actions/review-cutover';
12
13
  import * as pollerActions from './actions/poller';
13
14
  import * as rolePermissionsActions from './actions/role-permissions';
14
15
  import * as subtreeActions from './actions/subtree';
16
+ import * as chatContextActions from './actions/chat-context';
15
17
  import { unregisterReviewQueue } from './actions/review';
16
18
  import { registerGitReviewAiTools } from './ai-tools';
17
19
  import { enforceGitRequestMethod } from './request-method-policy';
@@ -21,8 +23,15 @@ import { GitReviewService } from './services/review-service';
21
23
  import { LegacyPostService } from './services/legacy-post-service';
22
24
  import { enforceReviewControlAccess } from './review-control-access';
23
25
  import { enforceRepositoryAccess, enforceRepositoryCollectionAccess } from './repository-access';
26
+ import { enforceGitChatAdmission, registerGitChatContextStrategies } from './chat-context-admission';
24
27
  import { isGitManagerResourceResponse, redactCredentialFields } from './utils/redact';
25
- import { containsCredentialBearingUrlField, URL_USERINFO_NOT_ALLOWED } from './utils/url-security';
28
+ import {
29
+ assertAccountRepositoryUrl,
30
+ assertUrlHasNoUserInfo,
31
+ containsCredentialBearingUrlField,
32
+ URL_USERINFO_NOT_ALLOWED,
33
+ } from './utils/url-security';
34
+ import { dispatchClusterGitInstall, readClusterGitStatus } from './utils/cluster-git';
26
35
 
27
36
  const GIT_CONFIGURATION_URL_FIELDS = new Set(['repoUrl', 'baseUrl']);
28
37
 
@@ -57,6 +66,14 @@ export class PluginGitManagerServer extends Plugin {
57
66
  skillHubContentService!: SkillHubGitContentService;
58
67
  reviewService!: GitReviewService;
59
68
  legacyPostService!: LegacyPostService;
69
+ private gitAutoRestoreTimer: NodeJS.Timeout | null = null;
70
+
71
+ private stopGitAutoRestore() {
72
+ if (this.gitAutoRestoreTimer) {
73
+ clearTimeout(this.gitAutoRestoreTimer);
74
+ this.gitAutoRestoreTimer = null;
75
+ }
76
+ }
60
77
 
61
78
  async afterAdd() {
62
79
  this.reviewService = new GitReviewService(this.app);
@@ -111,6 +128,8 @@ export class PluginGitManagerServer extends Plugin {
111
128
  mergeRequests: gitlabApi.mergeRequests,
112
129
  mergeRequestDetail: gitlabApi.mergeRequestDetail,
113
130
  mergeRequestNotes: gitlabApi.mergeRequestNotes,
131
+ chatContextOptions: chatContextActions.chatContextOptions,
132
+ chatContextContent: chatContextActions.chatContextContent,
114
133
  triggerReview: reviewActions.triggerReview,
115
134
  reviewApprovePost: reviewActions.reviewApprovePost,
116
135
  reviewLegacyPostStatus: reviewActions.reviewLegacyPostStatus,
@@ -132,9 +151,15 @@ export class PluginGitManagerServer extends Plugin {
132
151
  subtreeOptions: subtreeActions.subtreeOptions,
133
152
  subtreeRun: subtreeActions.subtreeRunOnAppProcess,
134
153
  subtreeReplace: subtreeActions.subtreeRunOnAppProcess,
154
+ runtimeStatus: gitActions.runtimeStatus,
155
+ installGit: gitActions.installGit,
135
156
  },
136
157
  });
137
158
 
159
+ // These actions perform their own checks against the caller's existing Git and collection permissions.
160
+ this.app.acl.allow('gitManager', 'chatContextOptions', 'loggedIn');
161
+ this.app.acl.allow('gitManager', 'chatContextContent', 'loggedIn');
162
+
138
163
  const legacyApprovalAction = this.app.acl.getAvailableAction('reviewApprovePost');
139
164
  const priorAliases = legacyApprovalAction?.options?.aliases;
140
165
  this.app.acl.setAvailableAction('reviewApprovePost', {
@@ -149,7 +174,7 @@ export class PluginGitManagerServer extends Plugin {
149
174
  // Existing repository permissions are stored on fileContent and triggerReview.
150
175
  // Aliases let the ACL apply those same grants and scopes to review controls.
151
176
  for (const [action, aliases] of [
152
- ['fileContent', ['reviewCutoverStatus']],
177
+ ['fileContent', ['reviewCutoverStatus', 'runtimeStatus']],
153
178
  [
154
179
  'triggerReview',
155
180
  [
@@ -186,6 +211,7 @@ export class PluginGitManagerServer extends Plugin {
186
211
  }
187
212
 
188
213
  this.app.resourceManager.use(enforceGitRequestMethod);
214
+ this.app.resourceManager.use(enforceGitChatAdmission);
189
215
  this.app.resourceManager.use(enforceReviewControlAccess);
190
216
  (this as any).app.resourceManager.use(enforceRepositoryAccess);
191
217
  (this as any).app.resourceManager.use(enforceRepositoryCollectionAccess);
@@ -211,6 +237,8 @@ export class PluginGitManagerServer extends Plugin {
211
237
 
212
238
  registerGitReviewAiTools((this as any).app);
213
239
 
240
+ this.app.on('afterLoad', () => registerGitChatContextStrategies(this.app));
241
+
214
242
  (this as any).app.on('afterStart', async () => {
215
243
  await ensureAutoReviewFlowSchema((this as any).app).catch(
216
244
  (err) => (this as any).app.log?.error?.('plugin-git-manager: ensure schema error', err),
@@ -223,13 +251,29 @@ export class PluginGitManagerServer extends Plugin {
223
251
  .recoverStuckSubtreeRuns((this as any).app)
224
252
  .catch((err) => (this as any).app.log?.error?.('plugin-git-manager: recover subtree runs error', err));
225
253
  startPoller((this as any).app);
254
+
255
+ this.stopGitAutoRestore();
256
+ const restoreTimer = setTimeout(async () => {
257
+ this.gitAutoRestoreTimer = null;
258
+ if (gitActions.isGitAvailable()) return;
259
+ const clusterStatus = await readClusterGitStatus(this.app).catch(() => undefined);
260
+ if (clusterStatus?.available && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
261
+ await dispatchClusterGitInstall(this.app).catch(
262
+ (err) => this.app.log?.warn?.('plugin-git-manager: startup git restore via Cluster Manager failed', err),
263
+ );
264
+ }
265
+ }, 5_000);
266
+ restoreTimer.unref?.();
267
+ this.gitAutoRestoreTimer = restoreTimer;
226
268
  });
227
269
  (this as any).app.on('beforeStop', () => {
270
+ this.stopGitAutoRestore();
228
271
  unregisterReviewQueue((this as any).app);
229
272
  this.reviewService.stop();
230
273
  stopPoller(this.app);
231
274
  });
232
275
  (this as any).app.on('beforeDestroy', () => {
276
+ this.stopGitAutoRestore();
233
277
  unregisterReviewQueue((this as any).app);
234
278
  this.reviewService.stop();
235
279
  stopPoller(this.app);
@@ -265,6 +309,7 @@ export class PluginGitManagerServer extends Plugin {
265
309
  'gitManager:subtreePreview',
266
310
  'gitManager:subtreeOptions',
267
311
  'gitManager:reviewCutoverStatus',
312
+ 'gitManager:runtimeStatus',
268
313
  'workflowGitReview:status',
269
314
  ],
270
315
  });
@@ -304,6 +349,7 @@ export class PluginGitManagerServer extends Plugin {
304
349
  'gitManager:reviewResetPostClaim',
305
350
  'gitManager:reviewCancelQueued',
306
351
  'gitManager:reviewLegacyReleaseHold',
352
+ 'gitManager:installGit',
307
353
  'workflowGitReview:setup',
308
354
  'workflowGitReview:repair',
309
355
  ],
@@ -317,7 +363,7 @@ export class PluginGitManagerServer extends Plugin {
317
363
  // Repositories config — CRUD on gitRepositories and gitAccounts (no operations)
318
364
  (this as any).app.acl.registerSnippet({
319
365
  name: `pm.${(this as any).name}.repositories`,
320
- actions: ['gitRepositories:*', 'gitAccounts:*'],
366
+ actions: ['gitRepositories:*', 'gitAccounts:*', 'gitManager:runtimeStatus', 'gitManager:installGit'],
321
367
  });
322
368
 
323
369
  // Full management — all git manager actions
@@ -401,7 +447,119 @@ export class PluginGitManagerServer extends Plugin {
401
447
  if (ctx.request.body?.pat === '••••••••') {
402
448
  delete ctx.request.body.pat;
403
449
  }
450
+
451
+ const mergedValues: Record<string, unknown> = {
452
+ ...(requestBody && typeof requestBody === 'object' && !Array.isArray(requestBody) ? requestBody : {}),
453
+ ...(requestBody?.values && typeof requestBody.values === 'object' && !Array.isArray(requestBody.values)
454
+ ? requestBody.values
455
+ : {}),
456
+ ...(actionParams?.values && typeof actionParams.values === 'object' && !Array.isArray(actionParams.values)
457
+ ? actionParams.values
458
+ : {}),
459
+ };
460
+
461
+ try {
462
+ if (resource === 'gitAccounts') {
463
+ let existingAccount: { get(attribute: string): unknown } | null = null;
464
+ if (ctx.action?.actionName === 'update' && actionParams?.filterByTk != null) {
465
+ existingAccount = await ctx.db
466
+ .getRepository('gitAccounts')
467
+ .findOne({ filterByTk: actionParams.filterByTk });
468
+ }
469
+ const provider = String(mergedValues.provider ?? existingAccount?.get('provider') ?? 'gitlab').trim();
470
+ const rawBaseUrl =
471
+ mergedValues.baseUrl !== undefined ? mergedValues.baseUrl : existingAccount?.get('baseUrl');
472
+ const baseUrl = typeof rawBaseUrl === 'string' && rawBaseUrl.trim() ? rawBaseUrl.trim() : null;
473
+ if (baseUrl) {
474
+ assertUrlHasNoUserInfo(baseUrl);
475
+ let parsedBase: URL;
476
+ try {
477
+ parsedBase = new URL(baseUrl);
478
+ } catch {
479
+ throw new Error('Invalid repository or account URL');
480
+ }
481
+ if (parsedBase.protocol !== 'https:') {
482
+ throw new Error('Only HTTPS repository and account URLs are allowed');
483
+ }
484
+ if (provider === 'github' && parsedBase.origin !== 'https://github.com') {
485
+ throw new Error('GitHub accounts currently require github.com');
486
+ }
487
+ }
488
+ }
489
+
490
+ if (resource === 'gitRepositories') {
491
+ if (mergedValues.localPath !== undefined) {
492
+ gitActions.validateLocalPath(String(mergedValues.localPath));
493
+ }
494
+ if (mergedValues.repoUrl !== undefined) {
495
+ gitActions.validateRepoUrl(String(mergedValues.repoUrl).trim());
496
+ }
497
+ if (mergedValues.defaultBranch !== undefined && String(mergedValues.defaultBranch).trim()) {
498
+ gitActions.validateBranch(String(mergedValues.defaultBranch).trim());
499
+ }
500
+ if (mergedValues.repoUrl !== undefined || mergedValues.gitAccountId !== undefined) {
501
+ let existingRepo: { get(attribute: string): unknown } | null = null;
502
+ if (ctx.action?.actionName === 'update' && actionParams?.filterByTk != null) {
503
+ existingRepo = await ctx.db
504
+ .getRepository('gitRepositories')
505
+ .findOne({ filterByTk: actionParams.filterByTk });
506
+ }
507
+ const effectiveRepoUrl = String(
508
+ mergedValues.repoUrl !== undefined ? mergedValues.repoUrl : existingRepo?.get('repoUrl') || '',
509
+ ).trim();
510
+ const effectiveAccountId =
511
+ mergedValues.gitAccountId !== undefined ? mergedValues.gitAccountId : existingRepo?.get('gitAccountId');
512
+ if (
513
+ effectiveRepoUrl &&
514
+ (typeof effectiveAccountId === 'number' || typeof effectiveAccountId === 'string') &&
515
+ String(effectiveAccountId).trim()
516
+ ) {
517
+ const account = await ctx.db.getRepository('gitAccounts').findOne({ filterByTk: effectiveAccountId });
518
+ if (account) {
519
+ const baseUrl = String(account.get('baseUrl') || '').trim() || null;
520
+ const provider = String(account.get('provider') || 'gitlab').trim();
521
+ assertAccountRepositoryUrl(effectiveRepoUrl, baseUrl, provider);
522
+ }
523
+ }
524
+ }
525
+ }
526
+ } catch (error) {
527
+ const message = error instanceof Error ? error.message : String(error);
528
+ ctx.throw(400, ctx.t(message, { ns: (this as any).name }));
529
+ }
404
530
  }
531
+
532
+ if (resource === 'gitRepositories' && ctx.action?.actionName === 'destroy') {
533
+ const targetRepos = (await ctx.db.getRepository('gitRepositories').find({
534
+ filterByTk: ctx.action.params?.filterByTk,
535
+ filter: ctx.action.params?.filter,
536
+ fields: ['id', 'localPath'],
537
+ })) as Array<{ get: (attribute: string) => unknown }>;
538
+ const localPaths = Array.from(
539
+ new Set(
540
+ targetRepos
541
+ .map((item) => item.get('localPath'))
542
+ .filter((value): value is string => typeof value === 'string' && Boolean(value.trim())),
543
+ ),
544
+ );
545
+ await next();
546
+ for (const rawLocalPath of localPaths) {
547
+ const remainingCount = await ctx.db.getRepository('gitRepositories').count({
548
+ filter: { localPath: rawLocalPath },
549
+ });
550
+ if (remainingCount > 0) continue;
551
+ try {
552
+ const resolvedPath = gitActions.validateLocalPath(rawLocalPath);
553
+ if (fs.existsSync(resolvedPath)) {
554
+ fs.rmSync(resolvedPath, { recursive: true, force: true });
555
+ }
556
+ } catch {
557
+ // Legacy invalid paths are ignored so record deletion still succeeds.
558
+ }
559
+ }
560
+ return;
561
+ }
562
+
405
563
  return next();
406
564
  });
407
565
 
@@ -448,12 +606,14 @@ export class PluginGitManagerServer extends Plugin {
448
606
  }
449
607
 
450
608
  async beforeDisable() {
609
+ this.stopGitAutoRestore();
451
610
  unregisterReviewQueue((this as any).app);
452
611
  this.reviewService.stop();
453
612
  stopPoller(this.app);
454
613
  }
455
614
 
456
615
  async beforeUnload() {
616
+ this.stopGitAutoRestore();
457
617
  unregisterReviewQueue((this as any).app);
458
618
  this.reviewService.stop();
459
619
  stopPoller(this.app);
@@ -801,8 +801,8 @@ export async function enforceRepositoryAccess(ctx: RepositoryAccessContext, next
801
801
  const reviewId = asRepositoryId(params.reviewId);
802
802
  if (reviewId == null) return ctx.throw(400, 'reviewId is required');
803
803
  repositoryId = await repositoryIdFromReview(ctx, reviewId);
804
- } else if (actionName === 'pollNow') {
805
- repositoryId = asRepositoryId(params.repositoryId);
804
+ } else if (actionName === 'pollNow' || actionName === 'installGit') {
805
+ repositoryId = actionName === 'pollNow' ? asRepositoryId(params.repositoryId) : undefined;
806
806
  if (repositoryId == null) {
807
807
  const allowed = await hasUnrestrictedRepositoryAccess({
808
808
  acl: ctx.app.acl,
@@ -13,9 +13,12 @@ const READ_ACTIONS = new Set([
13
13
  'mergeRequests',
14
14
  'mergeRequestDetail',
15
15
  'mergeRequestNotes',
16
+ 'chatContextOptions',
17
+ 'chatContextContent',
16
18
  'pollerStatus',
17
19
  'rolePermissions',
18
20
  'reviewCutoverStatus',
21
+ 'runtimeStatus',
19
22
  ]);
20
23
 
21
24
  export async function enforceGitRequestMethod(ctx: Context, next: () => Promise<void>) {
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { createHash } from 'crypto';
4
4
  import type { Database } from '@nocobase/database';
5
- import { createGit, validateBranch, validateLocalPath, validateRef } from '../actions/git-actions';
5
+ import { assertLocalGitReady, createGit, validateBranch, validateLocalPath, validateRef } from '../actions/git-actions';
6
6
  import { getRepoAccount } from '../utils/get-repo-account';
7
7
  import { parseGitLabProject } from '../utils/gitlab-url';
8
8
 
@@ -87,7 +87,8 @@ export async function resolveReviewProjectKey(db: Database, repo: RecordGetter):
87
87
  }
88
88
 
89
89
  async function validateCheckoutProject(db: Database, repo: RecordGetter, expectedProjectKey: string): Promise<void> {
90
- const git = createGit(validateLocalPath(String(repo.get('localPath') || '')));
90
+ const localPath = validateLocalPath(String(repo.get('localPath') || ''));
91
+ const git = await assertLocalGitReady(localPath);
91
92
  let origin: string;
92
93
  try {
93
94
  origin = (await git.raw(['remote', 'get-url', 'origin'])).trim();
@@ -0,0 +1,209 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ const CLUSTER_INSTALL_CHANNEL = 'cluster-manager.install-packages';
4
+ const AUTO_RESTORE_LOCK_KEY = 'git-manager:cluster-git-install';
5
+ const AUTO_RESTORE_COOLDOWN_MS = 45_000;
6
+
7
+ let lastDispatchAt = 0;
8
+
9
+ interface RecordGetter {
10
+ get(attribute: string): unknown;
11
+ }
12
+
13
+ interface PackageConfigRepository {
14
+ findOne(): Promise<RecordGetter | null>;
15
+ create(options: { values: Record<string, unknown> }): Promise<RecordGetter>;
16
+ update(options: { filterByTk: unknown; values: Record<string, unknown> }): Promise<unknown>;
17
+ }
18
+
19
+ interface PubSubLike {
20
+ isConnected?: () => Promise<boolean> | boolean;
21
+ publish(channel: string, payload: unknown): Promise<unknown>;
22
+ }
23
+
24
+ interface LockManagerLike {
25
+ runExclusive<T>(key: string, fn: () => Promise<T>, ttl?: number): Promise<T>;
26
+ }
27
+
28
+ export interface ClusterGitApp {
29
+ pm?: { get?: (name: string) => unknown };
30
+ db?: {
31
+ getCollection?: (name: string) => unknown;
32
+ getRepository?: (name: string) => PackageConfigRepository | undefined;
33
+ };
34
+ pubSubManager?: PubSubLike;
35
+ lockManager?: LockManagerLike;
36
+ log?: {
37
+ info?: (message: string, meta?: unknown) => void;
38
+ warn?: (message: string, meta?: unknown) => void;
39
+ error?: (message: string, meta?: unknown) => void;
40
+ };
41
+ }
42
+
43
+ export interface ClusterGitStatus {
44
+ available: boolean;
45
+ gitConfigured: boolean;
46
+ previouslyInitialized: boolean;
47
+ status: 'idle' | 'running' | 'succeeded' | 'failed';
48
+ progressPercent: number;
49
+ }
50
+
51
+ function parseAptPackages(raw: unknown): string[] {
52
+ if (typeof raw !== 'string' || !raw.trim()) return [];
53
+ return Array.from(
54
+ new Set(
55
+ raw
56
+ .split(/[\r\n,]+/)
57
+ .map((item) => item.trim())
58
+ .filter(Boolean),
59
+ ),
60
+ );
61
+ }
62
+
63
+ function hasGitInWhitelist(raw: unknown): boolean {
64
+ if (!raw) return false;
65
+ try {
66
+ const parsed = typeof raw === 'string' ? (JSON.parse(raw) as { apt?: unknown }) : (raw as { apt?: unknown });
67
+ return Array.isArray(parsed?.apt) && parsed.apt.includes('git');
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ function normalizeStatus(raw: unknown): ClusterGitStatus['status'] {
74
+ if (raw === 'running' || raw === 'succeeded' || raw === 'failed') return raw;
75
+ return 'idle';
76
+ }
77
+
78
+ function isClusterManagerEnabled(app?: ClusterGitApp): boolean {
79
+ if (!app?.db?.getCollection?.('workerPackagesConfigs')) return false;
80
+ if (!app.pm?.get) return true;
81
+ return Boolean(app.pm.get('plugin-cluster-manager') || app.pm.get('cluster-manager'));
82
+ }
83
+
84
+ export async function readClusterGitStatus(app?: ClusterGitApp): Promise<ClusterGitStatus> {
85
+ if (!isClusterManagerEnabled(app)) {
86
+ return {
87
+ available: false,
88
+ gitConfigured: false,
89
+ previouslyInitialized: false,
90
+ status: 'idle',
91
+ progressPercent: 0,
92
+ };
93
+ }
94
+
95
+ const repo = app?.db?.getRepository?.('workerPackagesConfigs');
96
+ if (!repo) {
97
+ return {
98
+ available: false,
99
+ gitConfigured: false,
100
+ previouslyInitialized: false,
101
+ status: 'idle',
102
+ progressPercent: 0,
103
+ };
104
+ }
105
+
106
+ const config = await repo.findOne();
107
+ if (!config) {
108
+ return {
109
+ available: true,
110
+ gitConfigured: false,
111
+ previouslyInitialized: false,
112
+ status: 'idle',
113
+ progressPercent: 0,
114
+ };
115
+ }
116
+
117
+ const aptPackages = parseAptPackages(config.get('aptPackages'));
118
+ const whitelisted = hasGitInWhitelist(config.get('packageWhitelist'));
119
+ const status = normalizeStatus(config.get('initStatus'));
120
+ const rawPercent = Number(config.get('initProgressPercent') ?? 0);
121
+
122
+ return {
123
+ available: true,
124
+ gitConfigured: aptPackages.includes('git') || whitelisted,
125
+ previouslyInitialized: Boolean(config.get('lastInitAt') || whitelisted || status === 'succeeded'),
126
+ status,
127
+ progressPercent: Number.isFinite(rawPercent) ? Math.min(Math.max(rawPercent, 0), 100) : 0,
128
+ };
129
+ }
130
+
131
+ export async function dispatchClusterGitInstall(
132
+ app: ClusterGitApp | undefined,
133
+ options: { ensureGitInConfig?: boolean; force?: boolean } = {},
134
+ ): Promise<{ dispatched: boolean; reason?: string }> {
135
+ if (!isClusterManagerEnabled(app)) {
136
+ return { dispatched: false, reason: 'Cluster Manager plugin is not enabled' };
137
+ }
138
+
139
+ const pubSub = app?.pubSubManager;
140
+ const connected = pubSub ? (pubSub.isConnected ? await pubSub.isConnected() : true) : false;
141
+ if (!pubSub || !connected) {
142
+ return { dispatched: false, reason: 'Cluster PubSub is not connected' };
143
+ }
144
+
145
+ const repo = app?.db?.getRepository?.('workerPackagesConfigs');
146
+ if (!repo) {
147
+ return { dispatched: false, reason: 'Cluster package configuration repository is unavailable' };
148
+ }
149
+
150
+ const runDispatch = async (): Promise<{ dispatched: boolean; reason?: string }> => {
151
+ const now = Date.now();
152
+ if (!options.force && now - lastDispatchAt < AUTO_RESTORE_COOLDOWN_MS) {
153
+ return { dispatched: false, reason: 'Recent install dispatch still in cooldown' };
154
+ }
155
+
156
+ let config = await repo.findOne();
157
+ if (!config) {
158
+ if (!options.ensureGitInConfig) {
159
+ return { dispatched: false, reason: 'Cluster package configuration has not been initialized' };
160
+ }
161
+ config = await repo.create({ values: { aptPackages: 'git' } });
162
+ }
163
+
164
+ const currentStatus = normalizeStatus(config.get('initStatus'));
165
+ if (!options.force && currentStatus === 'running') {
166
+ return { dispatched: false, reason: 'Cluster package installation is already running' };
167
+ }
168
+
169
+ const aptPackages = parseAptPackages(config.get('aptPackages'));
170
+ if (!aptPackages.includes('git')) {
171
+ if (!options.ensureGitInConfig && !hasGitInWhitelist(config.get('packageWhitelist'))) {
172
+ return { dispatched: false, reason: 'git is not configured in Cluster Manager packages' };
173
+ }
174
+ if (options.ensureGitInConfig) {
175
+ aptPackages.push('git');
176
+ }
177
+ }
178
+
179
+ const aptMirrorUrl = String(config.get('aptMirrorUrl') || process.env.APT_MIRROR_URL || '').trim() || undefined;
180
+ await repo.update({
181
+ filterByTk: config.get('id'),
182
+ values: {
183
+ ...(options.ensureGitInConfig ? { aptPackages: aptPackages.join('\n') } : {}),
184
+ initStatus: 'running',
185
+ lastInitAt: new Date(),
186
+ initProgressPercent: 5,
187
+ initProgressLog: 'Installing git on app/worker nodes via Cluster Manager...',
188
+ },
189
+ });
190
+
191
+ await pubSub.publish(CLUSTER_INSTALL_CHANNEL, {
192
+ targetRole: 'all',
193
+ packages: { apt: ['git'] },
194
+ registryConfig: { aptMirrorUrl },
195
+ });
196
+ lastDispatchAt = Date.now();
197
+ app?.log?.info?.('plugin-git-manager: dispatched git installation via Cluster Manager');
198
+ return { dispatched: true };
199
+ };
200
+
201
+ if (app?.lockManager?.runExclusive) {
202
+ return app.lockManager.runExclusive(AUTO_RESTORE_LOCK_KEY, runDispatch, 30_000);
203
+ }
204
+ return runDispatch();
205
+ }
206
+
207
+ export function resetClusterGitDispatchCooldownForTests(): void {
208
+ lastDispatchAt = 0;
209
+ }