plugin-agent-orchestrator 1.1.4 → 1.1.6

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 (148) hide show
  1. package/README.md +204 -114
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/117.7565cff57c39318a.js +10 -0
  4. package/dist/client-v2/214.106635011859dede.js +10 -0
  5. package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
  6. package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
  7. package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +7 -8
  10. package/dist/locale/en-US.json +226 -170
  11. package/dist/locale/vi-VN.json +226 -170
  12. package/dist/locale/zh-CN.json +226 -170
  13. package/dist/server/collections/agent-execution-spans.js +8 -0
  14. package/dist/server/collections/agent-loop-action-approvals.js +1 -0
  15. package/dist/server/collections/agent-loop-runs.js +7 -1
  16. package/dist/server/collections/agent-loop-steps.js +7 -0
  17. package/dist/server/collections/skill-executions.js +8 -0
  18. package/dist/server/plugin.js +3 -1
  19. package/dist/server/resources/agent-harness-profile.js +117 -0
  20. package/dist/server/resources/agent-knowledge-insights.js +1 -3
  21. package/dist/server/resources/agent-loop-approval.js +25 -0
  22. package/dist/server/resources/agent-loop.js +3 -1
  23. package/dist/server/services/AgentMemoryContextService.js +34 -0
  24. package/dist/server/services/HarnessCompiler.js +35 -2
  25. package/dist/server/services/HarnessProfileService.js +74 -9
  26. package/dist/server/services/HarnessSchema.js +30 -3
  27. package/dist/server/services/LoopPatternSchema.js +16 -1
  28. package/dist/server/services/LoopRunRepository.js +80 -0
  29. package/dist/server/services/LoopRunStateMachine.js +92 -3
  30. package/dist/server/services/LoopTriggerService.js +37 -0
  31. package/dist/server/services/LoopWorkerService.js +261 -23
  32. package/dist/server/services/NativeSubAgentObserver.js +165 -23
  33. package/dist/server/services/PluginAiRuntimeAdapter.js +16 -5
  34. package/dist/server/services/ToolLoopDetectionService.js +210 -0
  35. package/dist/server/services/VerificationService.js +66 -0
  36. package/dist/server/services/harness-runtime-policy.js +139 -0
  37. package/dist/server/skill-hub/plugin.js +36 -3
  38. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
  39. package/package.json +53 -53
  40. package/src/client/ApprovalsTab.tsx +2 -0
  41. package/src/client/OrchestratorSettings.tsx +11 -0
  42. package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
  43. package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
  44. package/src/client/skill-hub/index.tsx +0 -52
  45. package/src/client-v2/components/AgentRunsTab.tsx +576 -576
  46. package/src/client-v2/components/ApprovalsTab.tsx +337 -0
  47. package/src/client-v2/components/HarnessProfilesTab.tsx +385 -105
  48. package/src/client-v2/components/MemoryInspectorTab.tsx +141 -141
  49. package/src/client-v2/components/TracingTab.tsx +515 -515
  50. package/src/client-v2/hooks/useApiRequest.ts +141 -141
  51. package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
  52. package/src/client-v2/plugin.tsx +6 -6
  53. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +5 -2
  54. package/src/locale/en-US.json +226 -174
  55. package/src/locale/vi-VN.json +226 -174
  56. package/src/locale/zh-CN.json +226 -174
  57. package/src/server/__tests__/circuit-breaker.test.ts +248 -248
  58. package/src/server/__tests__/harness-compiler.test.ts +83 -0
  59. package/src/server/__tests__/harness-profile-service.test.ts +51 -0
  60. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
  61. package/src/server/__tests__/harness-tool-plan.test.ts +24 -0
  62. package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
  63. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
  64. package/src/server/__tests__/loop-budget-service.test.ts +255 -255
  65. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -266
  66. package/src/server/__tests__/loop-pattern-schema.test.ts +18 -1
  67. package/src/server/__tests__/loop-pattern-service.test.ts +148 -148
  68. package/src/server/__tests__/loop-run-state-machine.test.ts +11 -0
  69. package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
  70. package/src/server/__tests__/loop-worker-claim.test.ts +341 -341
  71. package/src/server/__tests__/loop-worker-execution.test.ts +82 -1
  72. package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
  73. package/src/server/__tests__/path-lock-service.test.ts +254 -254
  74. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
  75. package/src/server/__tests__/smoke.test.ts +162 -162
  76. package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
  77. package/src/server/collections/agent-execution-spans.ts +8 -0
  78. package/src/server/collections/agent-harness-profile-versions.ts +26 -26
  79. package/src/server/collections/agent-harness-profiles.ts +71 -71
  80. package/src/server/collections/agent-loop-action-approvals.ts +1 -0
  81. package/src/server/collections/agent-loop-artifacts.ts +25 -25
  82. package/src/server/collections/agent-loop-circuit-states.ts +23 -23
  83. package/src/server/collections/agent-loop-control-settings.ts +21 -21
  84. package/src/server/collections/agent-loop-events.ts +98 -98
  85. package/src/server/collections/agent-loop-path-locks.ts +27 -27
  86. package/src/server/collections/agent-loop-patterns.ts +42 -42
  87. package/src/server/collections/agent-loop-runs.ts +7 -1
  88. package/src/server/collections/agent-loop-steps.ts +7 -0
  89. package/src/server/collections/agent-loop-usage-buckets.ts +22 -22
  90. package/src/server/collections/agent-loop-worktrees.ts +25 -25
  91. package/src/server/collections/skill-executions.ts +8 -0
  92. package/src/server/migrations/20260427000002-change-packages-to-text.ts +52 -52
  93. package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -47
  94. package/src/server/migrations/20260429000001-fix-inputargs-json-to-text.ts +45 -45
  95. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -33
  96. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -31
  97. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -293
  98. package/src/server/plugin.ts +3 -1
  99. package/src/server/resources/agent-harness-profile.ts +94 -0
  100. package/src/server/resources/agent-knowledge-insights.ts +5 -3
  101. package/src/server/resources/agent-loop-approval.ts +32 -0
  102. package/src/server/resources/agent-loop-artifact.ts +56 -56
  103. package/src/server/resources/agent-loop-events-stream.ts +105 -105
  104. package/src/server/resources/agent-loop.ts +3 -1
  105. package/src/server/resources/resource-helpers.ts +33 -33
  106. package/src/server/resources/tracing.ts +266 -266
  107. package/src/server/services/AgentMemoryContextService.ts +44 -0
  108. package/src/server/services/DurableCircuitBreakerService.ts +239 -239
  109. package/src/server/services/ExecutionSpanService.ts +2 -0
  110. package/src/server/services/HarnessCompiler.ts +37 -0
  111. package/src/server/services/HarnessProfileService.ts +92 -10
  112. package/src/server/services/HarnessSchema.ts +31 -0
  113. package/src/server/services/LoopBudgetService.ts +275 -275
  114. package/src/server/services/LoopControlService.ts +124 -124
  115. package/src/server/services/LoopPatternSchema.ts +19 -1
  116. package/src/server/services/LoopPatternService.ts +143 -143
  117. package/src/server/services/LoopRunRepository.ts +99 -0
  118. package/src/server/services/LoopRunStateMachine.ts +100 -3
  119. package/src/server/services/LoopSchedulerService.ts +199 -199
  120. package/src/server/services/LoopTriggerService.ts +42 -0
  121. package/src/server/services/LoopWorkerService.ts +327 -27
  122. package/src/server/services/NativeSubAgentObserver.ts +186 -21
  123. package/src/server/services/PathLockService.ts +321 -321
  124. package/src/server/services/PluginAiRuntimeAdapter.ts +24 -7
  125. package/src/server/services/ToolLoopDetectionService.ts +213 -0
  126. package/src/server/services/VerificationSchema.ts +31 -31
  127. package/src/server/services/VerificationService.ts +81 -2
  128. package/src/server/services/harness-runtime-policy.ts +141 -0
  129. package/src/server/skill-hub/plugin.ts +41 -3
  130. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -235
  131. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -61
  132. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
  133. package/src/server/utils/ensure-indexes.ts +96 -96
  134. package/src/server/utils/logging.ts +62 -62
  135. package/src/server/utils/loop-pattern-context.ts +20 -20
  136. package/dist/client-v2/214.b063f33ba044a808.js +0 -10
  137. package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
  138. package/dist/client-v2/418.58fa350f5496efd3.js +0 -10
  139. package/dist/client-v2/53.9a10455323390f14.js +0 -10
  140. package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
  141. package/dist/client-v2/925.e5925bf21ed68e7a.js +0 -10
  142. package/src/client/AIEmployeeSelect.tsx +0 -47
  143. package/src/client/AIEmployeesContext.tsx +0 -102
  144. package/src/client/RulesTab.tsx +0 -2
  145. package/src/client/TracingTab.tsx +0 -436
  146. package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
  147. package/src/client-v2/components/RulesTab.tsx +0 -2
  148. package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
@@ -1,254 +1,254 @@
1
- import type { Database } from '@nocobase/database';
2
- import { describe, expect, it } from 'vitest';
3
- import {
4
- PathLockService,
5
- lockPathsOverlap,
6
- normalizeLockPath,
7
- pathSetsOverlap,
8
- waitGraphHasCycle,
9
- } from '../services/PathLockService';
10
-
11
- type Row = Record<string, unknown>;
12
-
13
- class MemoryRepository {
14
- private nextId = 1;
15
-
16
- constructor(readonly rows: Row[] = []) {}
17
-
18
- async find(options: Row = {}) {
19
- const filter = (options.filter as Row | undefined) || {};
20
- return this.rows.filter((row) => Object.entries(filter).every(([key, value]) => row[key] === value));
21
- }
22
-
23
- async findOne(options: Row) {
24
- if (options.filterByTk !== undefined) return this.rows.find((row) => row.id === options.filterByTk) || null;
25
- return (await this.find(options))[0] || null;
26
- }
27
-
28
- async create(options: Row) {
29
- const row = { id: this.nextId++, ...((options.values as Row | undefined) || {}) };
30
- this.rows.push(row);
31
- return row;
32
- }
33
-
34
- async update(options: Row) {
35
- const values = (options.values as Row | undefined) || {};
36
- for (const row of this.rows) {
37
- if (row.id === options.filterByTk) Object.assign(row, values);
38
- }
39
- }
40
- }
41
-
42
- function createService(rows: Row[] = []) {
43
- const locks = new MemoryRepository(rows);
44
- const database = {
45
- getRepository(name: string) {
46
- if (name !== 'agentLoopPathLocks') throw new Error(`Unexpected repository ${name}`);
47
- return locks;
48
- },
49
- sequelize: {
50
- // Writes made inside a transaction that throws must disappear, otherwise a test cannot tell
51
- // an audit write that commits from one that is rolled back with the error that follows it.
52
- async transaction<T>(callback: (value: { LOCK: { UPDATE: string } }) => Promise<T>) {
53
- const snapshot = structuredClone(locks.rows);
54
- try {
55
- return await callback({ LOCK: { UPDATE: 'UPDATE' } });
56
- } catch (error) {
57
- locks.rows.splice(0, locks.rows.length, ...snapshot);
58
- throw error;
59
- }
60
- },
61
- },
62
- };
63
- const distributedLock = { runExclusive: <T>(_key: string, operation: () => Promise<T>) => operation() };
64
- return { locks, service: new PathLockService(database as unknown as Database, distributedLock) };
65
- }
66
-
67
- describe('PathLockService primitives', () => {
68
- it('compares repository paths by segment instead of string prefix', () => {
69
- expect(lockPathsOverlap('src/a/**', 'src/a/tests/**')).toBe(true);
70
- expect(lockPathsOverlap('src/a/**', 'src/ab/**')).toBe(false);
71
- expect(lockPathsOverlap('packages/*/src/**', 'packages/plugin-a/src/file.ts')).toBe(true);
72
- expect(pathSetsOverlap(['src/a/**', 'docs/**'], ['src/ab/**', 'tests/**'])).toBe(false);
73
- });
74
-
75
- it('rejects paths outside the repository namespace', () => {
76
- expect(() => normalizeLockPath('../secret')).toThrow('dot segments');
77
- expect(() => normalizeLockPath('/absolute/path')).toThrow('repository-relative');
78
- expect(() => normalizeLockPath('C:/absolute/path')).toThrow('repository-relative');
79
- });
80
-
81
- it('detects waiter cycles without treating a normal wait chain as deadlock', () => {
82
- const waiting = [
83
- {
84
- id: 1,
85
- runId: 1,
86
- repositoryKey: 'repo',
87
- paths: ['src/a/**'],
88
- status: 'waiting' as const,
89
- blockerRunIds: [2],
90
- },
91
- {
92
- id: 2,
93
- runId: 2,
94
- repositoryKey: 'repo',
95
- paths: ['src/b/**'],
96
- status: 'waiting' as const,
97
- blockerRunIds: [3],
98
- },
99
- ];
100
- expect(waitGraphHasCycle(waiting, 3, [4])).toBe(false);
101
- expect(waitGraphHasCycle(waiting, 3, [1])).toBe(true);
102
- });
103
- });
104
-
105
- describe('PathLockService TTL enforcement', () => {
106
- it('expires a held lock past its TTL instead of treating it as a blocker', async () => {
107
- const { locks, service } = createService([
108
- {
109
- id: 1,
110
- runId: 1,
111
- repositoryKey: 'repo',
112
- owner: 'worker-dead',
113
- paths: ['src/a/**'],
114
- status: 'held',
115
- blockerRunIds: [],
116
- expiresAt: new Date(Date.now() - 1_000),
117
- },
118
- ]);
119
-
120
- const result = await service.acquire({
121
- runId: 2,
122
- repositoryKey: 'repo',
123
- owner: 'worker-b',
124
- paths: ['src/a/file.ts'],
125
- ttlMs: 60_000,
126
- });
127
-
128
- expect(result.acquired).toBe(true);
129
- expect(locks.rows[0]).toMatchObject({ id: 1, status: 'expired' });
130
- expect(locks.rows[1]).toMatchObject({ runId: 2, status: 'held', owner: 'worker-b' });
131
- });
132
-
133
- it('keeps an unexpired held lock as a blocker for an overlapping path', async () => {
134
- const { locks, service } = createService([
135
- {
136
- id: 1,
137
- runId: 1,
138
- repositoryKey: 'repo',
139
- owner: 'worker-a',
140
- paths: ['src/a/**'],
141
- status: 'held',
142
- blockerRunIds: [],
143
- expiresAt: new Date(Date.now() + 60_000),
144
- },
145
- ]);
146
-
147
- const result = await service.acquire({
148
- runId: 2,
149
- repositoryKey: 'repo',
150
- owner: 'worker-b',
151
- paths: ['src/a/file.ts'],
152
- ttlMs: 60_000,
153
- });
154
-
155
- expect(result).toMatchObject({ acquired: false, deadlocked: false, blockers: [1] });
156
- expect(locks.rows[0].status).toBe('held');
157
- expect(locks.rows[1]).toMatchObject({ runId: 2, status: 'waiting', blockerRunIds: [1] });
158
- });
159
-
160
- it('refuses to renew a lock whose TTL already lapsed', async () => {
161
- const { locks, service } = createService([
162
- {
163
- id: 1,
164
- runId: 1,
165
- repositoryKey: 'repo',
166
- owner: 'worker-a',
167
- paths: ['src/a/**'],
168
- status: 'held',
169
- blockerRunIds: [],
170
- expiresAt: new Date(Date.now() - 1),
171
- },
172
- ]);
173
-
174
- await expect(service.renew(1, 'repo', 60_000, 'worker-a')).rejects.toThrow('expired');
175
- // The `expired` mark must survive the error. It is only durable because the audit write commits
176
- // in its own transaction; writing it in the transaction that throws would roll it back to `held`.
177
- expect(locks.rows[0].status).toBe('expired');
178
- expect(locks.rows[0].blockerRunIds).toEqual([]);
179
- });
180
-
181
- it('rejects a release from a worker that no longer owns the lock and keeps it held', async () => {
182
- const { locks, service } = createService([
183
- {
184
- id: 1,
185
- runId: 1,
186
- repositoryKey: 'repo',
187
- owner: 'worker-a',
188
- paths: ['src/a/**'],
189
- status: 'held',
190
- blockerRunIds: [],
191
- expiresAt: new Date(Date.now() + 60_000),
192
- },
193
- ]);
194
-
195
- // worker-b reclaimed the run and now owns the lock; the stale worker-a must not free it.
196
- await expect(service.release(1, 'repo', 'worker-b')).resolves.toBe(false);
197
- expect(locks.rows[0].status).toBe('held');
198
-
199
- await expect(service.release(1, 'repo', 'worker-a')).resolves.toBe(true);
200
- expect(locks.rows[0].status).toBe('released');
201
- });
202
-
203
- it('rejects a renew from a worker that no longer owns the lock', async () => {
204
- const { service } = createService([
205
- {
206
- id: 1,
207
- runId: 1,
208
- repositoryKey: 'repo',
209
- owner: 'worker-a',
210
- paths: ['src/a/**'],
211
- status: 'held',
212
- blockerRunIds: [],
213
- expiresAt: new Date(Date.now() + 60_000),
214
- },
215
- ]);
216
-
217
- await expect(service.renew(1, 'repo', 60_000, 'worker-b')).rejects.toThrow('no longer owned');
218
- });
219
-
220
- it('reuses an existing held lock only for the same owner and paths', async () => {
221
- const { locks, service } = createService([
222
- {
223
- id: 1,
224
- runId: 1,
225
- repositoryKey: 'repo',
226
- owner: 'worker-a',
227
- paths: ['src/a/**'],
228
- status: 'held',
229
- blockerRunIds: [],
230
- expiresAt: new Date(Date.now() + 60_000),
231
- },
232
- ]);
233
-
234
- await expect(
235
- service.acquire({ runId: 1, repositoryKey: 'repo', owner: 'worker-a', paths: ['src/a/**'], ttlMs: 60_000 }),
236
- ).resolves.toMatchObject({ acquired: true });
237
- expect(locks.rows).toHaveLength(1);
238
-
239
- // A different owner token means the previous worker's lease is gone; the row is re-taken
240
- // rather than silently shared.
241
- await expect(
242
- service.acquire({ runId: 1, repositoryKey: 'repo', owner: 'worker-b', paths: ['src/a/**'], ttlMs: 60_000 }),
243
- ).resolves.toMatchObject({ acquired: true });
244
- expect(locks.rows).toHaveLength(1);
245
- expect(locks.rows[0].owner).toBe('worker-b');
246
- });
247
-
248
- it('rejects a non-positive TTL', async () => {
249
- const { service } = createService();
250
- await expect(
251
- service.acquire({ runId: 1, repositoryKey: 'repo', owner: 'worker-a', paths: ['src/a/**'], ttlMs: 0 }),
252
- ).rejects.toThrow('positive number of milliseconds');
253
- });
254
- });
1
+ import type { Database } from '@nocobase/database';
2
+ import { describe, expect, it } from 'vitest';
3
+ import {
4
+ PathLockService,
5
+ lockPathsOverlap,
6
+ normalizeLockPath,
7
+ pathSetsOverlap,
8
+ waitGraphHasCycle,
9
+ } from '../services/PathLockService';
10
+
11
+ type Row = Record<string, unknown>;
12
+
13
+ class MemoryRepository {
14
+ private nextId = 1;
15
+
16
+ constructor(readonly rows: Row[] = []) {}
17
+
18
+ async find(options: Row = {}) {
19
+ const filter = (options.filter as Row | undefined) || {};
20
+ return this.rows.filter((row) => Object.entries(filter).every(([key, value]) => row[key] === value));
21
+ }
22
+
23
+ async findOne(options: Row) {
24
+ if (options.filterByTk !== undefined) return this.rows.find((row) => row.id === options.filterByTk) || null;
25
+ return (await this.find(options))[0] || null;
26
+ }
27
+
28
+ async create(options: Row) {
29
+ const row = { id: this.nextId++, ...((options.values as Row | undefined) || {}) };
30
+ this.rows.push(row);
31
+ return row;
32
+ }
33
+
34
+ async update(options: Row) {
35
+ const values = (options.values as Row | undefined) || {};
36
+ for (const row of this.rows) {
37
+ if (row.id === options.filterByTk) Object.assign(row, values);
38
+ }
39
+ }
40
+ }
41
+
42
+ function createService(rows: Row[] = []) {
43
+ const locks = new MemoryRepository(rows);
44
+ const database = {
45
+ getRepository(name: string) {
46
+ if (name !== 'agentLoopPathLocks') throw new Error(`Unexpected repository ${name}`);
47
+ return locks;
48
+ },
49
+ sequelize: {
50
+ // Writes made inside a transaction that throws must disappear, otherwise a test cannot tell
51
+ // an audit write that commits from one that is rolled back with the error that follows it.
52
+ async transaction<T>(callback: (value: { LOCK: { UPDATE: string } }) => Promise<T>) {
53
+ const snapshot = structuredClone(locks.rows);
54
+ try {
55
+ return await callback({ LOCK: { UPDATE: 'UPDATE' } });
56
+ } catch (error) {
57
+ locks.rows.splice(0, locks.rows.length, ...snapshot);
58
+ throw error;
59
+ }
60
+ },
61
+ },
62
+ };
63
+ const distributedLock = { runExclusive: <T>(_key: string, operation: () => Promise<T>) => operation() };
64
+ return { locks, service: new PathLockService(database as unknown as Database, distributedLock) };
65
+ }
66
+
67
+ describe('PathLockService primitives', () => {
68
+ it('compares repository paths by segment instead of string prefix', () => {
69
+ expect(lockPathsOverlap('src/a/**', 'src/a/tests/**')).toBe(true);
70
+ expect(lockPathsOverlap('src/a/**', 'src/ab/**')).toBe(false);
71
+ expect(lockPathsOverlap('packages/*/src/**', 'packages/plugin-a/src/file.ts')).toBe(true);
72
+ expect(pathSetsOverlap(['src/a/**', 'docs/**'], ['src/ab/**', 'tests/**'])).toBe(false);
73
+ });
74
+
75
+ it('rejects paths outside the repository namespace', () => {
76
+ expect(() => normalizeLockPath('../secret')).toThrow('dot segments');
77
+ expect(() => normalizeLockPath('/absolute/path')).toThrow('repository-relative');
78
+ expect(() => normalizeLockPath('C:/absolute/path')).toThrow('repository-relative');
79
+ });
80
+
81
+ it('detects waiter cycles without treating a normal wait chain as deadlock', () => {
82
+ const waiting = [
83
+ {
84
+ id: 1,
85
+ runId: 1,
86
+ repositoryKey: 'repo',
87
+ paths: ['src/a/**'],
88
+ status: 'waiting' as const,
89
+ blockerRunIds: [2],
90
+ },
91
+ {
92
+ id: 2,
93
+ runId: 2,
94
+ repositoryKey: 'repo',
95
+ paths: ['src/b/**'],
96
+ status: 'waiting' as const,
97
+ blockerRunIds: [3],
98
+ },
99
+ ];
100
+ expect(waitGraphHasCycle(waiting, 3, [4])).toBe(false);
101
+ expect(waitGraphHasCycle(waiting, 3, [1])).toBe(true);
102
+ });
103
+ });
104
+
105
+ describe('PathLockService TTL enforcement', () => {
106
+ it('expires a held lock past its TTL instead of treating it as a blocker', async () => {
107
+ const { locks, service } = createService([
108
+ {
109
+ id: 1,
110
+ runId: 1,
111
+ repositoryKey: 'repo',
112
+ owner: 'worker-dead',
113
+ paths: ['src/a/**'],
114
+ status: 'held',
115
+ blockerRunIds: [],
116
+ expiresAt: new Date(Date.now() - 1_000),
117
+ },
118
+ ]);
119
+
120
+ const result = await service.acquire({
121
+ runId: 2,
122
+ repositoryKey: 'repo',
123
+ owner: 'worker-b',
124
+ paths: ['src/a/file.ts'],
125
+ ttlMs: 60_000,
126
+ });
127
+
128
+ expect(result.acquired).toBe(true);
129
+ expect(locks.rows[0]).toMatchObject({ id: 1, status: 'expired' });
130
+ expect(locks.rows[1]).toMatchObject({ runId: 2, status: 'held', owner: 'worker-b' });
131
+ });
132
+
133
+ it('keeps an unexpired held lock as a blocker for an overlapping path', async () => {
134
+ const { locks, service } = createService([
135
+ {
136
+ id: 1,
137
+ runId: 1,
138
+ repositoryKey: 'repo',
139
+ owner: 'worker-a',
140
+ paths: ['src/a/**'],
141
+ status: 'held',
142
+ blockerRunIds: [],
143
+ expiresAt: new Date(Date.now() + 60_000),
144
+ },
145
+ ]);
146
+
147
+ const result = await service.acquire({
148
+ runId: 2,
149
+ repositoryKey: 'repo',
150
+ owner: 'worker-b',
151
+ paths: ['src/a/file.ts'],
152
+ ttlMs: 60_000,
153
+ });
154
+
155
+ expect(result).toMatchObject({ acquired: false, deadlocked: false, blockers: [1] });
156
+ expect(locks.rows[0].status).toBe('held');
157
+ expect(locks.rows[1]).toMatchObject({ runId: 2, status: 'waiting', blockerRunIds: [1] });
158
+ });
159
+
160
+ it('refuses to renew a lock whose TTL already lapsed', async () => {
161
+ const { locks, service } = createService([
162
+ {
163
+ id: 1,
164
+ runId: 1,
165
+ repositoryKey: 'repo',
166
+ owner: 'worker-a',
167
+ paths: ['src/a/**'],
168
+ status: 'held',
169
+ blockerRunIds: [],
170
+ expiresAt: new Date(Date.now() - 1),
171
+ },
172
+ ]);
173
+
174
+ await expect(service.renew(1, 'repo', 60_000, 'worker-a')).rejects.toThrow('expired');
175
+ // The `expired` mark must survive the error. It is only durable because the audit write commits
176
+ // in its own transaction; writing it in the transaction that throws would roll it back to `held`.
177
+ expect(locks.rows[0].status).toBe('expired');
178
+ expect(locks.rows[0].blockerRunIds).toEqual([]);
179
+ });
180
+
181
+ it('rejects a release from a worker that no longer owns the lock and keeps it held', async () => {
182
+ const { locks, service } = createService([
183
+ {
184
+ id: 1,
185
+ runId: 1,
186
+ repositoryKey: 'repo',
187
+ owner: 'worker-a',
188
+ paths: ['src/a/**'],
189
+ status: 'held',
190
+ blockerRunIds: [],
191
+ expiresAt: new Date(Date.now() + 60_000),
192
+ },
193
+ ]);
194
+
195
+ // worker-b reclaimed the run and now owns the lock; the stale worker-a must not free it.
196
+ await expect(service.release(1, 'repo', 'worker-b')).resolves.toBe(false);
197
+ expect(locks.rows[0].status).toBe('held');
198
+
199
+ await expect(service.release(1, 'repo', 'worker-a')).resolves.toBe(true);
200
+ expect(locks.rows[0].status).toBe('released');
201
+ });
202
+
203
+ it('rejects a renew from a worker that no longer owns the lock', async () => {
204
+ const { service } = createService([
205
+ {
206
+ id: 1,
207
+ runId: 1,
208
+ repositoryKey: 'repo',
209
+ owner: 'worker-a',
210
+ paths: ['src/a/**'],
211
+ status: 'held',
212
+ blockerRunIds: [],
213
+ expiresAt: new Date(Date.now() + 60_000),
214
+ },
215
+ ]);
216
+
217
+ await expect(service.renew(1, 'repo', 60_000, 'worker-b')).rejects.toThrow('no longer owned');
218
+ });
219
+
220
+ it('reuses an existing held lock only for the same owner and paths', async () => {
221
+ const { locks, service } = createService([
222
+ {
223
+ id: 1,
224
+ runId: 1,
225
+ repositoryKey: 'repo',
226
+ owner: 'worker-a',
227
+ paths: ['src/a/**'],
228
+ status: 'held',
229
+ blockerRunIds: [],
230
+ expiresAt: new Date(Date.now() + 60_000),
231
+ },
232
+ ]);
233
+
234
+ await expect(
235
+ service.acquire({ runId: 1, repositoryKey: 'repo', owner: 'worker-a', paths: ['src/a/**'], ttlMs: 60_000 }),
236
+ ).resolves.toMatchObject({ acquired: true });
237
+ expect(locks.rows).toHaveLength(1);
238
+
239
+ // A different owner token means the previous worker's lease is gone; the row is re-taken
240
+ // rather than silently shared.
241
+ await expect(
242
+ service.acquire({ runId: 1, repositoryKey: 'repo', owner: 'worker-b', paths: ['src/a/**'], ttlMs: 60_000 }),
243
+ ).resolves.toMatchObject({ acquired: true });
244
+ expect(locks.rows).toHaveLength(1);
245
+ expect(locks.rows[0].owner).toBe('worker-b');
246
+ });
247
+
248
+ it('rejects a non-positive TTL', async () => {
249
+ const { service } = createService();
250
+ await expect(
251
+ service.acquire({ runId: 1, repositoryKey: 'repo', owner: 'worker-a', paths: ['src/a/**'], ttlMs: 0 }),
252
+ ).rejects.toThrow('positive number of milliseconds');
253
+ });
254
+ });
@@ -0,0 +1,140 @@
1
+ import { mkdtempSync, readFileSync, rmSync } from 'fs';
2
+ import { tmpdir } from 'os';
3
+ import { resolve } from 'path';
4
+ import { afterAll, describe, expect, it, vi } from 'vitest';
5
+ import type Application from '@nocobase/server';
6
+ import { FileManager } from '../services/FileManager';
7
+ import type { SandboxRunner } from '../services/SandboxRunner';
8
+ import type { SkillRepositoryService } from '../services/SkillRepositoryService';
9
+ import { SkillExecutionTask } from '../skill-hub/tasks/SkillExecutionTask';
10
+ import { parseJsonText } from '../skill-hub/utils/json-fields';
11
+
12
+ const tempDirs: string[] = [];
13
+
14
+ afterAll(() => {
15
+ for (const dir of tempDirs) {
16
+ try {
17
+ rmSync(dir, { recursive: true, force: true });
18
+ } catch {
19
+ // best effort cleanup
20
+ }
21
+ }
22
+ });
23
+
24
+ function createTask(options: {
25
+ runtimePolicy?: Record<string, unknown> | null;
26
+ stdout?: string;
27
+ skillTimeoutSeconds?: number;
28
+ }) {
29
+ const storagePath = mkdtempSync(resolve(tmpdir(), 'skill-task-policy-'));
30
+ tempDirs.push(storagePath);
31
+ const fileManager = new FileManager(storagePath);
32
+ const updates: Array<{ values: Record<string, unknown>; where: Record<string, unknown> }> = [];
33
+ const doneMessages: Array<Record<string, unknown>> = [];
34
+ const sandboxRunner = {
35
+ execute: vi.fn(async (params: Record<string, unknown>) => ({
36
+ success: true,
37
+ stdout: options.stdout ?? 'hello',
38
+ stderr: '',
39
+ files: [],
40
+ durationMs: 12,
41
+ })),
42
+ };
43
+ const skillRepoService = {
44
+ getSkillPath: (name: string) => resolve(storagePath, 'skills', name),
45
+ copySkillPackageTo: vi.fn(),
46
+ copyDirectoryTo: vi.fn(),
47
+ };
48
+ const skill = {
49
+ storageType: 'inline',
50
+ codeTemplate: 'console.log("hi")',
51
+ language: 'node',
52
+ timeoutSeconds: options.skillTimeoutSeconds ?? 60,
53
+ maxOutputSizeMb: 50,
54
+ name: 'test-skill',
55
+ fileId: null,
56
+ };
57
+ const executionValues: Record<string, unknown> = {
58
+ id: 42,
59
+ status: 'running',
60
+ workerId: 'worker-1',
61
+ inputArgs: '{}',
62
+ runtimePolicy: options.runtimePolicy ?? null,
63
+ skill,
64
+ };
65
+ const execution = { get: (key: string) => executionValues[key] };
66
+ const app = {
67
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
68
+ pubSubManager: {
69
+ subscribe: vi.fn(async () => undefined),
70
+ unsubscribe: vi.fn(async () => undefined),
71
+ publish: vi.fn(async (channel: string, message: Record<string, unknown>) => {
72
+ if (channel === 'skill-hub.done.42') doneMessages.push(message);
73
+ }),
74
+ },
75
+ db: {
76
+ getRepository: vi.fn(() => ({ findOne: async () => null })),
77
+ getModel: vi.fn(() => ({
78
+ update: async (values: Record<string, unknown>, opts: { where: Record<string, unknown> }) => {
79
+ updates.push({ values, where: opts.where });
80
+ return [1];
81
+ },
82
+ })),
83
+ },
84
+ pm: { get: vi.fn(() => null), getPlugins: vi.fn(() => new Map()) },
85
+ };
86
+ const task = new SkillExecutionTask(
87
+ execution,
88
+ sandboxRunner as unknown as SandboxRunner,
89
+ fileManager,
90
+ skillRepoService as unknown as SkillRepositoryService,
91
+ app as unknown as Application,
92
+ );
93
+ return { task, sandboxRunner, fileManager, updates, doneMessages };
94
+ }
95
+
96
+ describe('SkillExecutionTask harness runtime policy', () => {
97
+ it('caps the sandbox timeout with the harness policy without widening it', async () => {
98
+ const capped = createTask({ runtimePolicy: { timeoutSeconds: 15 }, skillTimeoutSeconds: 60 });
99
+ await capped.task.run();
100
+ expect(capped.sandboxRunner.execute.mock.calls[0][0].timeoutSeconds).toBe(15);
101
+
102
+ const permissive = createTask({ runtimePolicy: { timeoutSeconds: 120 }, skillTimeoutSeconds: 60 });
103
+ await permissive.task.run();
104
+ expect(permissive.sandboxRunner.execute.mock.calls[0][0].timeoutSeconds).toBe(60);
105
+ });
106
+
107
+ it('spills oversized stdout to the output directory and stores a bounded preview', async () => {
108
+ const stdout = `START-MARKER ${'z'.repeat(8000)} END-MARKER`;
109
+ const { task, fileManager, updates, doneMessages } = createTask({
110
+ runtimePolicy: { spillMaxInlineBytes: 600 },
111
+ stdout,
112
+ });
113
+
114
+ await task.run();
115
+
116
+ const finalUpdate = updates[updates.length - 1]?.values;
117
+ expect(finalUpdate?.status).toBe('succeeded');
118
+ const storedStdout = String(finalUpdate?.stdout);
119
+ expect(storedStdout).toContain('START-MARKER');
120
+ expect(storedStdout).toContain('END-MARKER');
121
+ expect(storedStdout).toContain('/api/skillHub:download?execId=42&f=');
122
+ expect(Buffer.byteLength(storedStdout, 'utf8')).toBeLessThanOrEqual(600);
123
+
124
+ // The full text is retrievable through the output directory.
125
+ const spillPath = resolve(fileManager.getOutputDir('42'), 'stdout-full.txt');
126
+ expect(readFileSync(spillPath, 'utf8')).toBe(stdout);
127
+
128
+ const outputFiles = parseJsonText(finalUpdate?.outputFiles, [] as Array<{ name: string }>);
129
+ expect(outputFiles.some((file) => file.name === 'stdout-full.txt')).toBe(true);
130
+ expect(doneMessages[0]?.stdout).toBe(storedStdout.slice(0, 3000));
131
+ });
132
+
133
+ it('keeps stdout inline when no spill budget applies', async () => {
134
+ const { task, updates } = createTask({ stdout: 'plain output' });
135
+
136
+ await task.run();
137
+
138
+ expect(updates[updates.length - 1]?.values.stdout).toBe('plain output');
139
+ });
140
+ });