plugin-agent-orchestrator 1.1.0 → 1.1.2

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 (162) hide show
  1. package/dist/externalVersion.js +6 -6
  2. package/dist/locale/en-US.json +7 -1
  3. package/dist/locale/vi-VN.json +7 -1
  4. package/dist/locale/zh-CN.json +7 -1
  5. package/dist/node_modules/ajv/.tonic_example.js +20 -0
  6. package/dist/node_modules/ajv/LICENSE +22 -0
  7. package/dist/node_modules/ajv/dist/ajv.bundle.js +7189 -0
  8. package/dist/node_modules/ajv/dist/ajv.min.js +3 -0
  9. package/dist/node_modules/ajv/lib/ajv.d.ts +397 -0
  10. package/dist/node_modules/ajv/lib/ajv.js +3 -0
  11. package/dist/node_modules/ajv/lib/cache.js +26 -0
  12. package/dist/node_modules/ajv/lib/compile/async.js +90 -0
  13. package/dist/node_modules/ajv/lib/compile/equal.js +5 -0
  14. package/dist/node_modules/ajv/lib/compile/error_classes.js +34 -0
  15. package/dist/node_modules/ajv/lib/compile/formats.js +142 -0
  16. package/dist/node_modules/ajv/lib/compile/index.js +387 -0
  17. package/dist/node_modules/ajv/lib/compile/resolve.js +270 -0
  18. package/dist/node_modules/ajv/lib/compile/rules.js +66 -0
  19. package/dist/node_modules/ajv/lib/compile/schema_obj.js +9 -0
  20. package/dist/node_modules/ajv/lib/compile/ucs2length.js +20 -0
  21. package/dist/node_modules/ajv/lib/compile/util.js +239 -0
  22. package/dist/node_modules/ajv/lib/data.js +49 -0
  23. package/dist/node_modules/ajv/lib/definition_schema.js +37 -0
  24. package/dist/node_modules/ajv/lib/dot/_limit.jst +113 -0
  25. package/dist/node_modules/ajv/lib/dot/_limitItems.jst +12 -0
  26. package/dist/node_modules/ajv/lib/dot/_limitLength.jst +12 -0
  27. package/dist/node_modules/ajv/lib/dot/_limitProperties.jst +12 -0
  28. package/dist/node_modules/ajv/lib/dot/allOf.jst +32 -0
  29. package/dist/node_modules/ajv/lib/dot/anyOf.jst +46 -0
  30. package/dist/node_modules/ajv/lib/dot/coerce.def +51 -0
  31. package/dist/node_modules/ajv/lib/dot/comment.jst +9 -0
  32. package/dist/node_modules/ajv/lib/dot/const.jst +11 -0
  33. package/dist/node_modules/ajv/lib/dot/contains.jst +55 -0
  34. package/dist/node_modules/ajv/lib/dot/custom.jst +191 -0
  35. package/dist/node_modules/ajv/lib/dot/defaults.def +47 -0
  36. package/dist/node_modules/ajv/lib/dot/definitions.def +203 -0
  37. package/dist/node_modules/ajv/lib/dot/dependencies.jst +79 -0
  38. package/dist/node_modules/ajv/lib/dot/enum.jst +30 -0
  39. package/dist/node_modules/ajv/lib/dot/errors.def +194 -0
  40. package/dist/node_modules/ajv/lib/dot/format.jst +106 -0
  41. package/dist/node_modules/ajv/lib/dot/if.jst +73 -0
  42. package/dist/node_modules/ajv/lib/dot/items.jst +98 -0
  43. package/dist/node_modules/ajv/lib/dot/missing.def +39 -0
  44. package/dist/node_modules/ajv/lib/dot/multipleOf.jst +22 -0
  45. package/dist/node_modules/ajv/lib/dot/not.jst +43 -0
  46. package/dist/node_modules/ajv/lib/dot/oneOf.jst +54 -0
  47. package/dist/node_modules/ajv/lib/dot/pattern.jst +14 -0
  48. package/dist/node_modules/ajv/lib/dot/properties.jst +245 -0
  49. package/dist/node_modules/ajv/lib/dot/propertyNames.jst +52 -0
  50. package/dist/node_modules/ajv/lib/dot/ref.jst +85 -0
  51. package/dist/node_modules/ajv/lib/dot/required.jst +108 -0
  52. package/dist/node_modules/ajv/lib/dot/uniqueItems.jst +62 -0
  53. package/dist/node_modules/ajv/lib/dot/validate.jst +276 -0
  54. package/dist/node_modules/ajv/lib/dotjs/_limit.js +163 -0
  55. package/dist/node_modules/ajv/lib/dotjs/_limitItems.js +80 -0
  56. package/dist/node_modules/ajv/lib/dotjs/_limitLength.js +85 -0
  57. package/dist/node_modules/ajv/lib/dotjs/_limitProperties.js +80 -0
  58. package/dist/node_modules/ajv/lib/dotjs/allOf.js +42 -0
  59. package/dist/node_modules/ajv/lib/dotjs/anyOf.js +73 -0
  60. package/dist/node_modules/ajv/lib/dotjs/comment.js +14 -0
  61. package/dist/node_modules/ajv/lib/dotjs/const.js +56 -0
  62. package/dist/node_modules/ajv/lib/dotjs/contains.js +81 -0
  63. package/dist/node_modules/ajv/lib/dotjs/custom.js +228 -0
  64. package/dist/node_modules/ajv/lib/dotjs/dependencies.js +168 -0
  65. package/dist/node_modules/ajv/lib/dotjs/enum.js +66 -0
  66. package/dist/node_modules/ajv/lib/dotjs/format.js +150 -0
  67. package/dist/node_modules/ajv/lib/dotjs/if.js +103 -0
  68. package/dist/node_modules/ajv/lib/dotjs/index.js +33 -0
  69. package/dist/node_modules/ajv/lib/dotjs/items.js +140 -0
  70. package/dist/node_modules/ajv/lib/dotjs/multipleOf.js +80 -0
  71. package/dist/node_modules/ajv/lib/dotjs/not.js +84 -0
  72. package/dist/node_modules/ajv/lib/dotjs/oneOf.js +73 -0
  73. package/dist/node_modules/ajv/lib/dotjs/pattern.js +75 -0
  74. package/dist/node_modules/ajv/lib/dotjs/properties.js +335 -0
  75. package/dist/node_modules/ajv/lib/dotjs/propertyNames.js +81 -0
  76. package/dist/node_modules/ajv/lib/dotjs/ref.js +124 -0
  77. package/dist/node_modules/ajv/lib/dotjs/required.js +270 -0
  78. package/dist/node_modules/ajv/lib/dotjs/uniqueItems.js +86 -0
  79. package/dist/node_modules/ajv/lib/dotjs/validate.js +482 -0
  80. package/dist/node_modules/ajv/lib/keyword.js +146 -0
  81. package/dist/node_modules/ajv/lib/refs/data.json +17 -0
  82. package/dist/node_modules/ajv/lib/refs/json-schema-draft-04.json +149 -0
  83. package/dist/node_modules/ajv/lib/refs/json-schema-draft-06.json +154 -0
  84. package/dist/node_modules/ajv/lib/refs/json-schema-draft-07.json +168 -0
  85. package/dist/node_modules/ajv/lib/refs/json-schema-secure.json +94 -0
  86. package/dist/node_modules/ajv/node_modules/json-schema-traverse/.eslintrc.yml +27 -0
  87. package/dist/node_modules/ajv/node_modules/json-schema-traverse/.travis.yml +8 -0
  88. package/dist/node_modules/ajv/node_modules/json-schema-traverse/index.js +89 -0
  89. package/dist/node_modules/ajv/node_modules/json-schema-traverse/package.json +43 -0
  90. package/dist/node_modules/ajv/node_modules/json-schema-traverse/spec/.eslintrc.yml +6 -0
  91. package/dist/node_modules/ajv/node_modules/json-schema-traverse/spec/fixtures/schema.js +125 -0
  92. package/dist/node_modules/ajv/node_modules/json-schema-traverse/spec/index.spec.js +171 -0
  93. package/dist/node_modules/ajv/package.json +1 -0
  94. package/dist/node_modules/ajv/scripts/.eslintrc.yml +3 -0
  95. package/dist/node_modules/ajv/scripts/bundle.js +61 -0
  96. package/dist/node_modules/ajv/scripts/compile-dots.js +73 -0
  97. package/dist/node_modules/ajv/scripts/info +10 -0
  98. package/dist/node_modules/ajv/scripts/prepare-tests +12 -0
  99. package/dist/node_modules/ajv/scripts/publish-built-version +32 -0
  100. package/dist/node_modules/ajv/scripts/travis-gh-pages +23 -0
  101. package/dist/server/collections/skill-definitions.js +31 -0
  102. package/dist/server/collections/skill-executions.js +19 -0
  103. package/dist/server/collections/skill-registry-installations.js +70 -0
  104. package/dist/server/migrations/20260727010000-backfill-skill-tool-names.js +66 -0
  105. package/dist/server/plugin.js +96 -1
  106. package/dist/server/services/AgentExecutionContext.js +45 -0
  107. package/dist/server/services/CodeValidator.js +1 -0
  108. package/dist/server/services/ExecutionSpanService.js +10 -2
  109. package/dist/server/services/InputSchemaValidator.js +83 -0
  110. package/dist/server/services/NativeSubAgentObserver.js +55 -8
  111. package/dist/server/services/SandboxRunner.js +6 -2
  112. package/dist/server/services/SkillAccessService.js +109 -0
  113. package/dist/server/services/SkillManager.js +2 -0
  114. package/dist/server/services/SkillRepositoryService.js +70 -0
  115. package/dist/server/skill-hub/actions/git-import.js +479 -216
  116. package/dist/server/skill-hub/mcp/McpController.js +8 -5
  117. package/dist/server/skill-hub/middlewares/git-import-request-method-policy.js +69 -0
  118. package/dist/server/skill-hub/plugin.js +68 -14
  119. package/dist/server/skill-hub/services/RegistrySkillInstallationService.js +249 -0
  120. package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +228 -0
  121. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +15 -3
  122. package/dist/server/tools/skill-execute.js +23 -2
  123. package/dist/server/utils/ctx-utils.js +2 -2
  124. package/dist/server/utils/skill-tool-name.js +73 -0
  125. package/package.json +9 -3
  126. package/src/locale/en-US.json +7 -1
  127. package/src/locale/vi-VN.json +7 -1
  128. package/src/locale/zh-CN.json +7 -1
  129. package/src/server/__tests__/agent-execution-context.test.ts +18 -0
  130. package/src/server/__tests__/input-schema-validator.test.ts +26 -0
  131. package/src/server/__tests__/native-sub-agent-observer.test.ts +52 -2
  132. package/src/server/__tests__/skill-access-service.test.ts +64 -0
  133. package/src/server/__tests__/skill-execute.test.ts +37 -0
  134. package/src/server/__tests__/skill-tool-name.test.ts +23 -0
  135. package/src/server/collections/skill-definitions.ts +31 -0
  136. package/src/server/collections/skill-executions.ts +19 -0
  137. package/src/server/collections/skill-registry-installations.ts +41 -0
  138. package/src/server/migrations/20260727010000-backfill-skill-tool-names.ts +45 -0
  139. package/src/server/plugin.ts +104 -1
  140. package/src/server/services/AgentExecutionContext.ts +23 -0
  141. package/src/server/services/CodeValidator.ts +1 -0
  142. package/src/server/services/ExecutionSpanService.ts +119 -110
  143. package/src/server/services/InputSchemaValidator.ts +44 -0
  144. package/src/server/services/NativeSubAgentObserver.ts +64 -10
  145. package/src/server/services/SandboxRunner.ts +6 -0
  146. package/src/server/services/SkillAccessService.ts +100 -0
  147. package/src/server/services/SkillManager.ts +2 -0
  148. package/src/server/services/SkillRepositoryService.ts +98 -2
  149. package/src/server/services/__tests__/SkillRepositoryService.test.ts +33 -0
  150. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +501 -0
  151. package/src/server/skill-hub/actions/git-import.ts +682 -236
  152. package/src/server/skill-hub/mcp/McpController.ts +8 -14
  153. package/src/server/skill-hub/middlewares/git-import-request-method-policy.ts +51 -0
  154. package/src/server/skill-hub/plugin.ts +79 -13
  155. package/src/server/skill-hub/services/RegistrySkillInstallationService.ts +281 -0
  156. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +239 -0
  157. package/src/server/skill-hub/services/__tests__/RegistrySkillInstallationService.test.ts +295 -0
  158. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +63 -0
  159. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +14 -2
  160. package/src/server/tools/skill-execute.ts +24 -2
  161. package/src/server/utils/ctx-utils.ts +1 -1
  162. package/src/server/utils/skill-tool-name.ts +58 -0
@@ -1,5 +1,15 @@
1
- import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'fs';
2
- import { resolve, relative } from 'path';
1
+ import {
2
+ cpSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ readdirSync,
7
+ renameSync,
8
+ rmSync,
9
+ statSync,
10
+ writeFileSync,
11
+ } from 'fs';
12
+ import { dirname, relative, resolve, sep } from 'path';
3
13
  import AdmZip from 'adm-zip';
4
14
  import { parseSkillMarkdown } from '../skill-hub/utils/json-fields';
5
15
  export interface SkillPackageMetadata {
@@ -9,6 +19,11 @@ export interface SkillPackageMetadata {
9
19
  code: string | null;
10
20
  }
11
21
 
22
+ export interface SkillPackageFile {
23
+ path: string;
24
+ content: Buffer;
25
+ }
26
+
12
27
  export class SkillRepositoryService {
13
28
  private baseDir: string;
14
29
 
@@ -43,6 +58,39 @@ export class SkillRepositoryService {
43
58
  return resolve(this.baseDir, skillName);
44
59
  }
45
60
 
61
+ readSkillPackageFiles(skillName: string): SkillPackageFile[] | null {
62
+ const targetDir = this.getSkillPath(skillName);
63
+ if (!existsSync(targetDir)) {
64
+ return null;
65
+ }
66
+ const files: SkillPackageFile[] = [];
67
+ const collect = (directory: string) => {
68
+ for (const item of readdirSync(directory)) {
69
+ const fullPath = resolve(directory, item);
70
+ const stat = statSync(fullPath);
71
+ if (stat.isDirectory()) {
72
+ collect(fullPath);
73
+ continue;
74
+ }
75
+ if (!stat.isFile()) {
76
+ continue;
77
+ }
78
+ const relativePath = relative(targetDir, fullPath).replace(/\\/g, '/');
79
+ files.push({ path: relativePath, content: readFileSync(fullPath) });
80
+ }
81
+ };
82
+ collect(targetDir);
83
+ return files;
84
+ }
85
+
86
+ removeSkillPackage(skillName: string): void {
87
+ const targetDir = this.getSkillPath(skillName);
88
+ if (!targetDir.startsWith(`${this.baseDir}${sep}`)) {
89
+ throw new Error(`Invalid skill package name: ${skillName}`);
90
+ }
91
+ rmSync(targetDir, { recursive: true, force: true });
92
+ }
93
+
46
94
  getSkillCode(skillName: string): string | null {
47
95
  const dir = this.getSkillPath(skillName);
48
96
  if (!existsSync(dir)) return null;
@@ -55,6 +103,54 @@ export class SkillRepositoryService {
55
103
  this.copyDirectoryTo(srcDir, destDir);
56
104
  }
57
105
 
106
+ writeSkillPackage(skillName: string, files: SkillPackageFile[]): void {
107
+ const targetDir = this.getSkillPath(skillName);
108
+ const temporaryDir = `${targetDir}.next-${Date.now()}`;
109
+ const backupDir = `${targetDir}.previous-${Date.now()}`;
110
+ const filePaths = new Set<string>();
111
+
112
+ rmSync(temporaryDir, { recursive: true, force: true });
113
+ mkdirSync(temporaryDir, { recursive: true });
114
+ try {
115
+ for (const file of files) {
116
+ const path = file.path.replace(/\\/g, '/');
117
+ if (
118
+ !path ||
119
+ path.includes('\0') ||
120
+ path.startsWith('/') ||
121
+ path.split('/').some((part) => !part || part === '.' || part === '..') ||
122
+ filePaths.has(path)
123
+ ) {
124
+ throw new Error(`Invalid skill package path: ${file.path}`);
125
+ }
126
+ filePaths.add(path);
127
+ const outputPath = resolve(temporaryDir, path);
128
+ if (!outputPath.startsWith(`${temporaryDir}${sep}`)) {
129
+ throw new Error(`Skill package path is outside its package root: ${file.path}`);
130
+ }
131
+ mkdirSync(dirname(outputPath), { recursive: true });
132
+ writeFileSync(outputPath, file.content);
133
+ }
134
+
135
+ if (existsSync(targetDir)) {
136
+ rmSync(backupDir, { recursive: true, force: true });
137
+ renameSync(targetDir, backupDir);
138
+ }
139
+ try {
140
+ renameSync(temporaryDir, targetDir);
141
+ } catch (error) {
142
+ if (existsSync(backupDir)) {
143
+ renameSync(backupDir, targetDir);
144
+ }
145
+ throw error;
146
+ }
147
+ rmSync(backupDir, { recursive: true, force: true });
148
+ } catch (error) {
149
+ rmSync(temporaryDir, { recursive: true, force: true });
150
+ throw error;
151
+ }
152
+ }
153
+
58
154
  readSkillPackage(packageDir: string): SkillPackageMetadata {
59
155
  const rootDir = resolve(packageDir);
60
156
  if (!existsSync(rootDir)) {
@@ -0,0 +1,33 @@
1
+ import { mkdtempSync, readFileSync, rmSync } from 'fs';
2
+ import { tmpdir } from 'os';
3
+ import { join } from 'path';
4
+
5
+ import { SkillRepositoryService } from '../SkillRepositoryService';
6
+
7
+ describe('SkillRepositoryService registry package materialization', () => {
8
+ let storagePath = '';
9
+
10
+ beforeEach(() => {
11
+ storagePath = mkdtempSync(join(tmpdir(), 'skill-repository-service-'));
12
+ });
13
+
14
+ afterEach(() => {
15
+ rmSync(storagePath, { recursive: true, force: true });
16
+ });
17
+
18
+ it('materializes all portable artifact files and rejects traversal paths', () => {
19
+ const repository = new SkillRepositoryService(storagePath);
20
+
21
+ repository.writeSkillPackage('registry-acme-report', [
22
+ { path: 'SKILL.md', content: Buffer.from('# Report\n') },
23
+ { path: 'src/index.py', content: Buffer.from('from .format import render\n') },
24
+ { path: 'src/format.py', content: Buffer.from('def render():\n return "ok"\n') },
25
+ ]);
26
+
27
+ const packageRoot = repository.getSkillPath('registry-acme-report');
28
+ expect(readFileSync(join(packageRoot, 'src', 'format.py'), 'utf8')).toContain('return "ok"');
29
+ expect(() =>
30
+ repository.writeSkillPackage('registry-acme-report', [{ path: '../escape.py', content: Buffer.alloc(0) }]),
31
+ ).toThrow('Invalid skill package path');
32
+ });
33
+ });
@@ -0,0 +1,501 @@
1
+ import type { Context } from '@nocobase/actions';
2
+
3
+ import { GIT_SKILL_MARKDOWN_LIMITS, gitListSkills, gitSyncSkills } from '../git-import';
4
+ import { createGitImportRequestMethodPolicy } from '../../middlewares/git-import-request-method-policy';
5
+
6
+ const commitSha = 'a'.repeat(40);
7
+ const actor = { kind: 'user' as const, roles: ['developer'] };
8
+
9
+ type GitEntry = { type: 'blob' | 'tree'; path: string; size: number };
10
+
11
+ type SkillDefinitionsRepository = {
12
+ find?: ReturnType<typeof vi.fn>;
13
+ findOne: ReturnType<typeof vi.fn>;
14
+ create?: ReturnType<typeof vi.fn>;
15
+ };
16
+
17
+ type ContentService = {
18
+ contractVersion: number;
19
+ capabilities: string[];
20
+ resolveCommit: ReturnType<typeof vi.fn>;
21
+ listTree: ReturnType<typeof vi.fn>;
22
+ readFile: ReturnType<typeof vi.fn>;
23
+ };
24
+
25
+ type TestContext = {
26
+ context: Context;
27
+ getRepository: ReturnType<typeof vi.fn>;
28
+ skillDefinitions: SkillDefinitionsRepository;
29
+ };
30
+
31
+ function gitError(code: string, message = code): Error & { code: string } {
32
+ const error = new Error(message) as Error & { code: string };
33
+ error.code = code;
34
+ return error;
35
+ }
36
+
37
+ function httpError(status: number, message: string): Error & { status: number } {
38
+ const error = new Error(message) as Error & { status: number };
39
+ error.status = status;
40
+ return error;
41
+ }
42
+
43
+ function createContentService(input?: Partial<ContentService>): ContentService {
44
+ return {
45
+ contractVersion: 2,
46
+ capabilities: ['skill-hub-content-with-actor'],
47
+ resolveCommit: vi.fn().mockResolvedValue(commitSha),
48
+ listTree: vi.fn().mockResolvedValue([]),
49
+ readFile: vi.fn().mockResolvedValue(Buffer.from(JSON.stringify({ skills: [] }))),
50
+ ...input,
51
+ };
52
+ }
53
+
54
+ function skillsRootEntries(rootPath: string): GitEntry[] {
55
+ if (rootPath === 'skills') {
56
+ return [{ type: 'tree', path: 'alpha', size: 0 }];
57
+ }
58
+ if (rootPath === 'skills/alpha') {
59
+ return [{ type: 'blob', path: 'SKILL.md', size: 16 }];
60
+ }
61
+ return [];
62
+ }
63
+
64
+ function createContext(input: {
65
+ service?: ContentService;
66
+ params: Record<string, unknown>;
67
+ skillDefinitions?: SkillDefinitionsRepository;
68
+ }): TestContext {
69
+ const skillDefinitions =
70
+ input.skillDefinitions ||
71
+ ({
72
+ find: vi.fn().mockResolvedValue([]),
73
+ findOne: vi.fn().mockResolvedValue(null),
74
+ create: vi.fn().mockResolvedValue(undefined),
75
+ } satisfies SkillDefinitionsRepository);
76
+ const getRepository = vi.fn((name: string) => {
77
+ if (name === 'gitRepositories') {
78
+ throw new Error('Git repositories must only be read through Git Manager.');
79
+ }
80
+ if (name === 'skillDefinitions') {
81
+ return skillDefinitions;
82
+ }
83
+ throw new Error(`Unexpected repository: ${name}`);
84
+ });
85
+ const context = {
86
+ action: { params: input.params },
87
+ state: { currentRoles: actor.roles },
88
+ app: {
89
+ pm: {
90
+ get: vi.fn().mockReturnValue(input.service ? { skillHubContentService: input.service } : undefined),
91
+ },
92
+ },
93
+ db: { getRepository },
94
+ throw(status: number, message: string): never {
95
+ throw httpError(status, message);
96
+ },
97
+ } as unknown as Context;
98
+ return { context, getRepository, skillDefinitions };
99
+ }
100
+
101
+ function createMethodContext(actionName: 'gitListSkills' | 'gitSyncSkills', method: string) {
102
+ const headers = new Map<string, string>();
103
+ return {
104
+ headers,
105
+ method,
106
+ action: { resourceName: 'skillHub', actionName, params: {} },
107
+ set(name: string, value: string) {
108
+ headers.set(name, value);
109
+ },
110
+ throw(status: number, message: string): never {
111
+ throw httpError(status, message);
112
+ },
113
+ } as unknown as Context;
114
+ }
115
+
116
+ describe('Skill Hub Git import', () => {
117
+ it('allows only GET/HEAD for listing and POST for syncing', async () => {
118
+ const middleware = createGitImportRequestMethodPolicy();
119
+ const next = vi.fn().mockResolvedValue(undefined);
120
+
121
+ await middleware(createMethodContext('gitListSkills', 'GET'), next);
122
+ await middleware(createMethodContext('gitListSkills', 'HEAD'), next);
123
+ await middleware(createMethodContext('gitSyncSkills', 'POST'), next);
124
+ expect(next).toHaveBeenCalledTimes(3);
125
+
126
+ const rejectedList = createMethodContext('gitListSkills', 'POST');
127
+ await expect(middleware(rejectedList, next)).rejects.toMatchObject({ status: 405 });
128
+ expect((rejectedList as unknown as { headers: Map<string, string> }).headers.get('Allow')).toBe('GET, HEAD');
129
+
130
+ const rejectedSync = createMethodContext('gitSyncSkills', 'GET');
131
+ await expect(middleware(rejectedSync, next)).rejects.toMatchObject({ status: 405 });
132
+ expect((rejectedSync as unknown as { headers: Map<string, string> }).headers.get('Allow')).toBe('POST');
133
+ });
134
+
135
+ it('lists skills through the actor-aware Git Manager service without reading gitRepositories', async () => {
136
+ const service = createContentService({
137
+ listTree: vi.fn().mockImplementation(async ({ rootPath }: { rootPath: string }) => skillsRootEntries(rootPath)),
138
+ readFile: vi
139
+ .fn()
140
+ .mockResolvedValue(
141
+ Buffer.from(JSON.stringify({ skills: [{ folder: 'alpha', name: 'alpha', title: 'Alpha' }] })),
142
+ ),
143
+ });
144
+ const { context, getRepository } = createContext({
145
+ service,
146
+ params: { repositoryId: 42, rootFolder: 'skills' },
147
+ });
148
+ const next = vi.fn().mockResolvedValue(undefined);
149
+
150
+ await gitListSkills(context, next);
151
+
152
+ expect(service.resolveCommit).toHaveBeenCalledWith(42, 'HEAD', actor);
153
+ expect(service.readFile).toHaveBeenCalledWith(
154
+ { repositoryId: 42, commitSha, filePath: 'skills/skills.json' },
155
+ actor,
156
+ );
157
+ expect(getRepository).toHaveBeenCalledWith('skillDefinitions');
158
+ expect(getRepository).not.toHaveBeenCalledWith('gitRepositories');
159
+ expect((context as unknown as { body: { data: Array<{ name: string }> } }).body.data).toEqual([
160
+ expect.objectContaining({ name: 'alpha', existsInDb: false }),
161
+ ]);
162
+ expect(next).toHaveBeenCalledOnce();
163
+ });
164
+
165
+ it('rejects a role outside the Git repository scope before any database read', async () => {
166
+ const service = createContentService({
167
+ resolveCommit: vi.fn().mockRejectedValue(gitError('SKILL_HUB_REPOSITORY_ACCESS_DENIED', 'Scope denied')),
168
+ });
169
+ const { context, getRepository } = createContext({
170
+ service,
171
+ params: { repositoryId: 42, rootFolder: 'skills' },
172
+ });
173
+
174
+ await expect(gitListSkills(context, vi.fn())).rejects.toMatchObject({ status: 403, message: 'Scope denied' });
175
+ expect(getRepository).not.toHaveBeenCalled();
176
+ expect(service.listTree).not.toHaveBeenCalled();
177
+ expect(service.readFile).not.toHaveBeenCalled();
178
+ });
179
+
180
+ it('uses a virtual manifest without writing a Git checkout when skills.json is missing', async () => {
181
+ const service = createContentService({
182
+ listTree: vi.fn().mockImplementation(async ({ rootPath }: { rootPath: string }) => skillsRootEntries(rootPath)),
183
+ readFile: vi.fn().mockRejectedValue(gitError('REGISTRY_GIT_FILE_NOT_FOUND')),
184
+ });
185
+ const { context } = createContext({
186
+ service,
187
+ params: { repositoryId: 42, rootFolder: 'skills' },
188
+ });
189
+
190
+ await gitListSkills(context, vi.fn());
191
+
192
+ const body = context as unknown as {
193
+ body: { data: Array<{ name: string }>; config: { initializedSkillsJson: boolean } };
194
+ };
195
+ expect(body.body.data).toEqual([expect.objectContaining({ name: 'alpha' })]);
196
+ expect(body.body.config.initializedSkillsJson).toBe(false);
197
+ });
198
+
199
+ it('uses the same actor and pinned commit when syncing a selected skill', async () => {
200
+ const created: Array<Record<string, unknown>> = [];
201
+ const service = createContentService({
202
+ listTree: vi.fn().mockImplementation(async ({ rootPath }: { rootPath: string }) => skillsRootEntries(rootPath)),
203
+ readFile: vi
204
+ .fn()
205
+ .mockResolvedValue(
206
+ Buffer.from(JSON.stringify({ skills: [{ name: 'alpha', storageType: 'plugin', pluginSource: 'alpha' }] })),
207
+ ),
208
+ });
209
+ const skillDefinitions: SkillDefinitionsRepository = {
210
+ findOne: vi.fn().mockResolvedValue(null),
211
+ create: vi.fn().mockImplementation(async ({ values }: { values: Record<string, unknown> }) => {
212
+ created.push(values);
213
+ }),
214
+ };
215
+ const { context, getRepository } = createContext({
216
+ service,
217
+ skillDefinitions,
218
+ params: { repositoryId: 42, rootFolder: 'skills', values: { skills: ['alpha'] } },
219
+ });
220
+
221
+ await gitSyncSkills(context, vi.fn());
222
+
223
+ expect(getRepository).not.toHaveBeenCalledWith('gitRepositories');
224
+ expect(service.resolveCommit).toHaveBeenCalledWith(42, 'HEAD', actor);
225
+ expect(service.readFile).toHaveBeenCalledWith(
226
+ { repositoryId: 42, commitSha, filePath: 'skills/skills.json' },
227
+ actor,
228
+ );
229
+ expect(created).toEqual([
230
+ expect.objectContaining({ name: 'alpha', storageUrl: `git://42/skills@${commitSha}#alpha` }),
231
+ ]);
232
+ });
233
+
234
+ it('rejects a selected key absent from an explicit skills.json manifest before writing a skill', async () => {
235
+ const service = createContentService({
236
+ listTree: vi.fn().mockImplementation(async ({ rootPath }: { rootPath: string }) => skillsRootEntries(rootPath)),
237
+ readFile: vi
238
+ .fn()
239
+ .mockResolvedValue(Buffer.from(JSON.stringify({ skills: [{ folder: 'alpha', name: 'alpha' }] }))),
240
+ });
241
+ const skillDefinitions: SkillDefinitionsRepository = {
242
+ findOne: vi.fn(),
243
+ create: vi.fn(),
244
+ };
245
+ const { context } = createContext({
246
+ service,
247
+ skillDefinitions,
248
+ params: { repositoryId: 42, rootFolder: 'skills', values: { skills: ['unlisted'] } },
249
+ });
250
+
251
+ await expect(gitSyncSkills(context, vi.fn())).rejects.toMatchObject({
252
+ status: 400,
253
+ message: 'Selected skills are not listed in the explicit skills.json manifest: unlisted',
254
+ });
255
+ expect(skillDefinitions.findOne).not.toHaveBeenCalled();
256
+ expect(skillDefinitions.create).not.toHaveBeenCalled();
257
+ });
258
+
259
+ it('allows a selected key from a virtual manifest when skills.json is absent', async () => {
260
+ const service = createContentService({
261
+ listTree: vi.fn().mockImplementation(async ({ rootPath }: { rootPath: string }) => skillsRootEntries(rootPath)),
262
+ readFile: vi.fn().mockRejectedValue(gitError('REGISTRY_GIT_FILE_NOT_FOUND')),
263
+ });
264
+ const skillDefinitions: SkillDefinitionsRepository = {
265
+ findOne: vi.fn().mockResolvedValue(null),
266
+ create: vi.fn(),
267
+ };
268
+ const { context } = createContext({
269
+ service,
270
+ skillDefinitions,
271
+ params: { repositoryId: 42, rootFolder: 'skills', values: { skills: ['alpha'] } },
272
+ });
273
+
274
+ await gitSyncSkills(context, vi.fn());
275
+
276
+ expect(skillDefinitions.create).toHaveBeenCalledOnce();
277
+ });
278
+
279
+ it('rejects too many supplemental Markdown files before reading any of them', async () => {
280
+ const supplementalFiles: GitEntry[] = Array.from(
281
+ { length: GIT_SKILL_MARKDOWN_LIMITS.maxFiles + 1 },
282
+ (_, index) => ({
283
+ type: 'blob',
284
+ path: `docs/${index}.md`,
285
+ size: 1,
286
+ }),
287
+ );
288
+ const service = createContentService({
289
+ listTree: vi
290
+ .fn()
291
+ .mockImplementation(async ({ rootPath, recursive }: { rootPath: string; recursive: boolean }) => {
292
+ if (rootPath === 'skills') return [{ type: 'tree', path: 'alpha', size: 0 }];
293
+ if (rootPath === 'skills/alpha' && recursive) return supplementalFiles;
294
+ if (rootPath === 'skills/alpha') return [{ type: 'blob', path: 'SKILL.md', size: 16 }];
295
+ return [];
296
+ }),
297
+ readFile: vi.fn().mockImplementation(async ({ filePath }: { filePath: string }) => {
298
+ if (filePath === 'skills/skills.json') {
299
+ return Buffer.from(JSON.stringify({ skills: [{ folder: 'alpha', name: 'alpha' }] }));
300
+ }
301
+ if (filePath === 'skills/alpha/SKILL.md') {
302
+ return Buffer.from('# Alpha');
303
+ }
304
+ throw new Error(`Unexpected file read: ${filePath}`);
305
+ }),
306
+ });
307
+ const skillDefinitions: SkillDefinitionsRepository = {
308
+ findOne: vi.fn(),
309
+ create: vi.fn(),
310
+ };
311
+ const { context } = createContext({
312
+ service,
313
+ skillDefinitions,
314
+ params: { repositoryId: 42, rootFolder: 'skills', values: { skills: ['alpha'] } },
315
+ });
316
+
317
+ await expect(gitSyncSkills(context, vi.fn())).rejects.toMatchObject({ status: 422 });
318
+ expect(service.readFile).not.toHaveBeenCalledWith(
319
+ expect.objectContaining({ filePath: 'skills/alpha/docs/0.md' }),
320
+ actor,
321
+ );
322
+ expect(skillDefinitions.create).not.toHaveBeenCalled();
323
+ });
324
+
325
+ it('rejects supplemental Markdown whose declared aggregate size exceeds the import limit before reading it', async () => {
326
+ const service = createContentService({
327
+ listTree: vi
328
+ .fn()
329
+ .mockImplementation(async ({ rootPath, recursive }: { rootPath: string; recursive: boolean }) => {
330
+ if (rootPath === 'skills') return [{ type: 'tree', path: 'alpha', size: 0 }];
331
+ if (rootPath === 'skills/alpha' && recursive) {
332
+ return [{ type: 'blob', path: 'GUIDE.md', size: GIT_SKILL_MARKDOWN_LIMITS.maxBytes }];
333
+ }
334
+ if (rootPath === 'skills/alpha') return [{ type: 'blob', path: 'SKILL.md', size: 16 }];
335
+ return [];
336
+ }),
337
+ readFile: vi.fn().mockImplementation(async ({ filePath }: { filePath: string }) => {
338
+ if (filePath === 'skills/skills.json') {
339
+ return Buffer.from(JSON.stringify({ skills: [{ folder: 'alpha', name: 'alpha' }] }));
340
+ }
341
+ if (filePath === 'skills/alpha/SKILL.md') {
342
+ return Buffer.from('# Alpha');
343
+ }
344
+ throw new Error(`Unexpected file read: ${filePath}`);
345
+ }),
346
+ });
347
+ const skillDefinitions: SkillDefinitionsRepository = {
348
+ findOne: vi.fn(),
349
+ create: vi.fn(),
350
+ };
351
+ const { context } = createContext({
352
+ service,
353
+ skillDefinitions,
354
+ params: { repositoryId: 42, rootFolder: 'skills', values: { skills: ['alpha'] } },
355
+ });
356
+
357
+ await expect(gitSyncSkills(context, vi.fn())).rejects.toMatchObject({ status: 422 });
358
+ expect(service.readFile).not.toHaveBeenCalledWith(
359
+ expect.objectContaining({ filePath: 'skills/alpha/GUIDE.md' }),
360
+ actor,
361
+ );
362
+ expect(skillDefinitions.create).not.toHaveBeenCalled();
363
+ });
364
+
365
+ it('caps each supplemental Markdown read by the remaining aggregate budget', async () => {
366
+ const service = createContentService({
367
+ listTree: vi
368
+ .fn()
369
+ .mockImplementation(async ({ rootPath, recursive }: { rootPath: string; recursive: boolean }) => {
370
+ if (rootPath === 'skills') return [{ type: 'tree', path: 'alpha', size: 0 }];
371
+ if (rootPath === 'skills/alpha' && recursive) return [{ type: 'blob', path: 'GUIDE.md', size: 1 }];
372
+ if (rootPath === 'skills/alpha') return [{ type: 'blob', path: 'SKILL.md', size: 16 }];
373
+ return [];
374
+ }),
375
+ readFile: vi.fn().mockImplementation(async ({ filePath }: { filePath: string }) => {
376
+ if (filePath === 'skills/skills.json') {
377
+ return Buffer.from(JSON.stringify({ skills: [{ folder: 'alpha', name: 'alpha' }] }));
378
+ }
379
+ if (filePath === 'skills/alpha/SKILL.md') {
380
+ return Buffer.from('# Alpha');
381
+ }
382
+ if (filePath === 'skills/alpha/GUIDE.md') {
383
+ return Buffer.alloc(GIT_SKILL_MARKDOWN_LIMITS.maxBytes, 'a');
384
+ }
385
+ throw new Error(`Unexpected file read: ${filePath}`);
386
+ }),
387
+ });
388
+ const skillDefinitions: SkillDefinitionsRepository = {
389
+ findOne: vi.fn(),
390
+ create: vi.fn(),
391
+ };
392
+ const { context } = createContext({
393
+ service,
394
+ skillDefinitions,
395
+ params: { repositoryId: 42, rootFolder: 'skills', values: { skills: ['alpha'] } },
396
+ });
397
+
398
+ await expect(gitSyncSkills(context, vi.fn())).rejects.toMatchObject({ status: 422 });
399
+ expect(service.readFile).toHaveBeenCalledWith(
400
+ expect.objectContaining({
401
+ filePath: 'skills/alpha/GUIDE.md',
402
+ maxBytes: expect.any(Number),
403
+ }),
404
+ actor,
405
+ );
406
+ expect(skillDefinitions.create).not.toHaveBeenCalled();
407
+ });
408
+
409
+ it('does not convert an access denial during sync into a per-skill error', async () => {
410
+ const service = createContentService({
411
+ listTree: vi.fn().mockImplementation(async ({ rootPath }: { rootPath: string }) => skillsRootEntries(rootPath)),
412
+ readFile: vi.fn().mockImplementation(async ({ filePath }: { filePath: string }) => {
413
+ if (filePath === 'skills/skills.json') {
414
+ return Buffer.from(JSON.stringify({ skills: [{ folder: 'alpha', name: 'alpha' }] }));
415
+ }
416
+ throw gitError('SKILL_HUB_REPOSITORY_ACCESS_DENIED', 'Scope was revoked');
417
+ }),
418
+ });
419
+ const skillDefinitions: SkillDefinitionsRepository = {
420
+ findOne: vi.fn().mockResolvedValue(null),
421
+ create: vi.fn(),
422
+ };
423
+ const { context } = createContext({
424
+ service,
425
+ skillDefinitions,
426
+ params: { repositoryId: 42, rootFolder: 'skills', values: { skills: ['alpha'] } },
427
+ });
428
+
429
+ await expect(gitSyncSkills(context, vi.fn())).rejects.toMatchObject({ status: 403, message: 'Scope was revoked' });
430
+ expect(skillDefinitions.create).not.toHaveBeenCalled();
431
+ });
432
+
433
+ it('requires the Skill Hub actor-aware Git Manager contract', async () => {
434
+ const service = createContentService({
435
+ contractVersion: 1,
436
+ capabilities: ['registry-content-with-actor'],
437
+ });
438
+ const { context, getRepository } = createContext({
439
+ service,
440
+ params: { repositoryId: 42, rootFolder: 'skills' },
441
+ });
442
+
443
+ await expect(gitListSkills(context, vi.fn())).rejects.toMatchObject({ status: 424 });
444
+ expect(getRepository).not.toHaveBeenCalled();
445
+ expect(service.resolveCommit).not.toHaveBeenCalled();
446
+ });
447
+
448
+ it('uses the configured skills root before falling back to a nested skills folder', async () => {
449
+ const service = createContentService({
450
+ listTree: vi.fn().mockImplementation(async ({ rootPath }: { rootPath: string }) => {
451
+ if (rootPath === 'agent-assets/skills') {
452
+ return [{ type: 'tree', path: 'alpha', size: 0 }];
453
+ }
454
+ if (rootPath === 'agent-assets/skills/alpha') {
455
+ return [{ type: 'blob', path: 'SKILL.md', size: 16 }];
456
+ }
457
+ if (rootPath === 'agent-assets/skills/skills') {
458
+ throw new Error('must not fall back to skills/skills');
459
+ }
460
+ return [];
461
+ }),
462
+ readFile: vi.fn().mockRejectedValue(gitError('REGISTRY_GIT_FILE_NOT_FOUND')),
463
+ });
464
+ const { context } = createContext({
465
+ service,
466
+ params: { repositoryId: 42, rootFolder: 'agent-assets/skills' },
467
+ });
468
+
469
+ await gitListSkills(context, vi.fn());
470
+
471
+ expect(service.listTree).not.toHaveBeenCalledWith(
472
+ expect.objectContaining({ rootPath: 'agent-assets/skills/skills' }),
473
+ actor,
474
+ );
475
+ });
476
+
477
+ it('keeps a direct child folder named skills when the configured root already ends in skills', async () => {
478
+ const service = createContentService({
479
+ listTree: vi.fn().mockImplementation(async ({ rootPath }: { rootPath: string }) => {
480
+ if (rootPath === 'agent-assets/skills') {
481
+ return [{ type: 'tree', path: 'skills', size: 0 }];
482
+ }
483
+ if (rootPath === 'agent-assets/skills/skills') {
484
+ return [{ type: 'blob', path: 'SKILL.md', size: 16 }];
485
+ }
486
+ return [];
487
+ }),
488
+ readFile: vi.fn().mockRejectedValue(gitError('REGISTRY_GIT_FILE_NOT_FOUND')),
489
+ });
490
+ const { context } = createContext({
491
+ service,
492
+ params: { repositoryId: 42, rootFolder: 'agent-assets/skills' },
493
+ });
494
+
495
+ await gitListSkills(context, vi.fn());
496
+
497
+ expect((context as unknown as { body: { data: Array<{ name: string }> } }).body.data).toEqual([
498
+ expect.objectContaining({ name: 'skills' }),
499
+ ]);
500
+ });
501
+ });