plugin-agent-orchestrator 1.1.3 → 1.1.5

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 (218) 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/253.59577b40d9875be0.js +10 -0
  6. package/dist/client-v2/264.7ed8bee71fa5935c.js +10 -0
  7. package/dist/client-v2/{41.ba6e080cc0488143.js → 41.3deb9e57a0f64fc4.js} +1 -1
  8. package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
  9. package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
  10. package/dist/client-v2/619.0a2144aaffefe018.js +10 -0
  11. package/dist/client-v2/{70.bda9518881c05360.js → 70.ffff2997c10fd4b0.js} +1 -1
  12. package/dist/client-v2/{794.9bbb8d3a61b2bdf2.js → 794.a67a2614405ba627.js} +1 -1
  13. package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
  14. package/dist/client-v2/{993.82778b6fd6db3cb1.js → 993.b0688fdc5ccb000a.js} +1 -1
  15. package/dist/client-v2/index.js +1 -1
  16. package/dist/externalVersion.js +8 -7
  17. package/dist/locale/en-US.json +199 -123
  18. package/dist/locale/vi-VN.json +199 -123
  19. package/dist/locale/zh-CN.json +199 -123
  20. package/dist/server/collections/agent-execution-spans.js +55 -0
  21. package/dist/server/collections/agent-harness-profile-versions.js +56 -0
  22. package/dist/server/collections/agent-harness-profiles.js +12 -0
  23. package/dist/server/collections/agent-loop-action-approvals.js +69 -0
  24. package/dist/server/collections/agent-loop-artifacts.js +55 -0
  25. package/dist/server/collections/agent-loop-circuit-states.js +53 -0
  26. package/dist/server/collections/agent-loop-control-settings.js +51 -0
  27. package/dist/server/collections/agent-loop-events.js +27 -0
  28. package/dist/server/collections/agent-loop-path-locks.js +57 -0
  29. package/dist/server/collections/agent-loop-patterns.js +72 -0
  30. package/dist/server/collections/agent-loop-runs.js +170 -3
  31. package/dist/server/collections/agent-loop-steps.js +76 -0
  32. package/dist/server/collections/agent-loop-usage-buckets.js +52 -0
  33. package/dist/server/collections/agent-loop-worktrees.js +55 -0
  34. package/dist/server/collections/skill-executions.js +8 -0
  35. package/dist/server/migrations/{20260427000000-change-packages-to-text.js → 20260427000002-change-packages-to-text.js} +2 -0
  36. package/dist/server/migrations/20260429000000-add-llm-fields.js +3 -2
  37. package/dist/server/migrations/{20260429000000-fix-inputargs-json-to-text.js → 20260429000001-fix-inputargs-json-to-text.js} +14 -6
  38. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.js +2 -1
  39. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +2 -1
  40. package/dist/server/migrations/20260803010000-backfill-loop-control-plane-data.js +262 -0
  41. package/dist/server/plugin.js +54 -150
  42. package/dist/server/resources/agent-harness-profile.js +117 -0
  43. package/dist/server/resources/agent-knowledge-insights.js +1 -3
  44. package/dist/server/resources/agent-loop-approval.js +108 -0
  45. package/dist/server/resources/agent-loop-artifact.js +86 -0
  46. package/dist/server/resources/agent-loop-events-stream.js +130 -0
  47. package/dist/server/resources/agent-loop.js +183 -139
  48. package/dist/server/resources/resource-helpers.js +63 -0
  49. package/dist/server/resources/tracing.js +121 -107
  50. package/dist/server/services/AgentMemoryContextService.js +34 -0
  51. package/dist/server/services/DurableCircuitBreakerService.js +229 -0
  52. package/dist/server/services/HarnessCompiler.js +175 -0
  53. package/dist/server/services/HarnessProfileService.js +233 -0
  54. package/dist/server/services/HarnessSchema.js +194 -0
  55. package/dist/server/services/LoopBudgetService.js +269 -0
  56. package/dist/server/services/LoopControlService.js +139 -0
  57. package/dist/server/services/LoopPatternSchema.js +195 -0
  58. package/dist/server/services/LoopPatternService.js +132 -0
  59. package/dist/server/services/LoopRunRepository.js +285 -0
  60. package/dist/server/services/LoopRunStateMachine.js +478 -0
  61. package/dist/server/services/LoopSchedulerService.js +193 -0
  62. package/dist/server/services/LoopTriggerService.js +165 -0
  63. package/dist/server/services/LoopWorkerService.js +699 -0
  64. package/dist/server/services/NativeSubAgentObserver.js +165 -23
  65. package/dist/server/services/PathLockService.js +288 -0
  66. package/dist/server/services/PluginAiRuntimeAdapter.js +226 -0
  67. package/dist/server/services/ToolLoopDetectionService.js +210 -0
  68. package/dist/server/services/VerificationSchema.js +59 -0
  69. package/dist/server/services/VerificationService.js +235 -0
  70. package/dist/server/services/harness-runtime-policy.js +139 -0
  71. package/dist/server/skill-hub/actions/git-import.js +13 -7
  72. package/dist/server/skill-hub/plugin.js +36 -3
  73. package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +1 -5
  74. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
  75. package/dist/server/utils/ensure-indexes.js +111 -0
  76. package/dist/server/utils/loop-pattern-context.js +56 -0
  77. package/package.json +53 -53
  78. package/src/client/ApprovalsTab.tsx +2 -0
  79. package/src/client/OrchestratorSettings.tsx +55 -0
  80. package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
  81. package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
  82. package/src/client/skill-hub/index.tsx +0 -52
  83. package/src/client-v2/components/AgentRunsTab.tsx +100 -18
  84. package/src/client-v2/components/ApprovalsTab.tsx +337 -0
  85. package/src/client-v2/components/HarnessProfilesTab.tsx +385 -100
  86. package/src/client-v2/components/MemoryInspectorTab.tsx +141 -125
  87. package/src/client-v2/components/TracingTab.tsx +160 -77
  88. package/src/client-v2/hooks/useApiRequest.ts +28 -8
  89. package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
  90. package/src/client-v2/plugin.tsx +6 -6
  91. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +11 -6
  92. package/src/locale/en-US.json +199 -123
  93. package/src/locale/vi-VN.json +199 -123
  94. package/src/locale/zh-CN.json +199 -123
  95. package/src/server/__tests__/circuit-breaker.test.ts +248 -169
  96. package/src/server/__tests__/harness-compiler.test.ts +214 -0
  97. package/src/server/__tests__/harness-profile-service.test.ts +167 -0
  98. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
  99. package/src/server/__tests__/harness-tool-plan.test.ts +172 -0
  100. package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
  101. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
  102. package/src/server/__tests__/loop-budget-service.test.ts +255 -0
  103. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -0
  104. package/src/server/__tests__/loop-pattern-schema.test.ts +73 -0
  105. package/src/server/__tests__/loop-pattern-service.test.ts +148 -0
  106. package/src/server/__tests__/loop-run-state-machine.test.ts +101 -0
  107. package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
  108. package/src/server/__tests__/loop-worker-claim.test.ts +341 -0
  109. package/src/server/__tests__/loop-worker-execution.test.ts +317 -0
  110. package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
  111. package/src/server/__tests__/path-lock-service.test.ts +254 -0
  112. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
  113. package/src/server/__tests__/smoke.test.ts +162 -121
  114. package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
  115. package/src/server/collections/agent-execution-spans.ts +55 -0
  116. package/src/server/collections/agent-harness-profile-versions.ts +26 -0
  117. package/src/server/collections/agent-harness-profiles.ts +71 -59
  118. package/src/server/collections/agent-loop-action-approvals.ts +39 -0
  119. package/src/server/collections/agent-loop-artifacts.ts +25 -0
  120. package/src/server/collections/agent-loop-circuit-states.ts +23 -0
  121. package/src/server/collections/agent-loop-control-settings.ts +21 -0
  122. package/src/server/collections/agent-loop-events.ts +98 -71
  123. package/src/server/collections/agent-loop-path-locks.ts +27 -0
  124. package/src/server/collections/agent-loop-patterns.ts +42 -0
  125. package/src/server/collections/agent-loop-runs.ts +170 -3
  126. package/src/server/collections/agent-loop-steps.ts +76 -0
  127. package/src/server/collections/agent-loop-usage-buckets.ts +22 -0
  128. package/src/server/collections/agent-loop-worktrees.ts +25 -0
  129. package/src/server/collections/skill-executions.ts +8 -0
  130. package/src/server/migrations/{20260427000000-change-packages-to-text.ts → 20260427000002-change-packages-to-text.ts} +52 -49
  131. package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -46
  132. package/src/server/migrations/{20260429000000-fix-inputargs-json-to-text.ts → 20260429000001-fix-inputargs-json-to-text.ts} +45 -38
  133. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -32
  134. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -30
  135. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -0
  136. package/src/server/plugin.ts +55 -167
  137. package/src/server/resources/agent-harness-profile.ts +94 -0
  138. package/src/server/resources/agent-knowledge-insights.ts +5 -3
  139. package/src/server/resources/agent-loop-approval.ts +84 -0
  140. package/src/server/resources/agent-loop-artifact.ts +56 -0
  141. package/src/server/resources/agent-loop-events-stream.ts +105 -0
  142. package/src/server/resources/agent-loop.ts +204 -143
  143. package/src/server/resources/agent-monitor.ts +482 -482
  144. package/src/server/resources/resource-helpers.ts +33 -0
  145. package/src/server/resources/tracing.ts +266 -258
  146. package/src/server/services/AgentMemoryContextService.ts +44 -0
  147. package/src/server/services/DurableCircuitBreakerService.ts +239 -0
  148. package/src/server/services/ExecutionSpanService.ts +2 -0
  149. package/src/server/services/HarnessCompiler.ts +170 -0
  150. package/src/server/services/HarnessProfileService.ts +239 -0
  151. package/src/server/services/HarnessSchema.ts +194 -0
  152. package/src/server/services/LoopBudgetService.ts +275 -0
  153. package/src/server/services/LoopControlService.ts +124 -0
  154. package/src/server/services/LoopPatternSchema.ts +185 -0
  155. package/src/server/services/LoopPatternService.ts +143 -0
  156. package/src/server/services/LoopRunRepository.ts +336 -0
  157. package/src/server/services/LoopRunStateMachine.ts +529 -0
  158. package/src/server/services/LoopSchedulerService.ts +199 -0
  159. package/src/server/services/LoopTriggerService.ts +157 -0
  160. package/src/server/services/LoopWorkerService.ts +822 -0
  161. package/src/server/services/NativeSubAgentObserver.ts +186 -21
  162. package/src/server/services/PathLockService.ts +321 -0
  163. package/src/server/services/PluginAiRuntimeAdapter.ts +332 -0
  164. package/src/server/services/ToolLoopDetectionService.ts +213 -0
  165. package/src/server/services/VerificationSchema.ts +31 -0
  166. package/src/server/services/VerificationService.ts +264 -0
  167. package/src/server/services/harness-runtime-policy.ts +141 -0
  168. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +15 -1
  169. package/src/server/skill-hub/actions/git-import.ts +9 -3
  170. package/src/server/skill-hub/plugin.ts +41 -3
  171. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -239
  172. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -63
  173. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
  174. package/src/server/utils/ensure-indexes.ts +96 -0
  175. package/src/server/utils/logging.ts +62 -63
  176. package/src/server/utils/loop-pattern-context.ts +20 -0
  177. package/dist/client-v2/214.79650a549273f163.js +0 -10
  178. package/dist/client-v2/253.9f0537713cee9e6c.js +0 -10
  179. package/dist/client-v2/264.718a107e43fc163c.js +0 -10
  180. package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
  181. package/dist/client-v2/418.ce8f5b2b8a229d1d.js +0 -10
  182. package/dist/client-v2/53.7c29c28043e9112d.js +0 -10
  183. package/dist/client-v2/619.bd3c5698b40705c3.js +0 -10
  184. package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
  185. package/dist/client-v2/925.f5370de8f6632d65.js +0 -10
  186. package/dist/server/services/AgentHarness.js +0 -81
  187. package/dist/server/services/AgentLoopController.js +0 -1023
  188. package/dist/server/services/AgentLoopRepository.js +0 -192
  189. package/dist/server/services/AgentLoopService.js +0 -142
  190. package/dist/server/services/AgentPlanValidator.js +0 -99
  191. package/dist/server/services/AgentPlannerService.js +0 -99
  192. package/dist/server/services/CircuitBreaker.js +0 -125
  193. package/dist/server/services/ContextAggregator.js +0 -201
  194. package/dist/server/services/PlanningPromptService.js +0 -95
  195. package/dist/server/tools/agent-loop.js +0 -373
  196. package/dist/server/tools/orchestrator-plan.js +0 -254
  197. package/src/client/AIEmployeeSelect.tsx +0 -47
  198. package/src/client/AIEmployeesContext.tsx +0 -102
  199. package/src/client/RulesTab.tsx +0 -2
  200. package/src/client/TracingTab.tsx +0 -436
  201. package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
  202. package/src/client-v2/components/RulesTab.tsx +0 -2
  203. package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
  204. package/src/server/__tests__/agent-loop-controller.test.ts +0 -375
  205. package/src/server/__tests__/context-aggregator.test.ts +0 -222
  206. package/src/server/__tests__/parallel-execution.test.ts +0 -318
  207. package/src/server/__tests__/planning-prompt-service.test.ts +0 -23
  208. package/src/server/services/AgentHarness.ts +0 -67
  209. package/src/server/services/AgentLoopController.ts +0 -1263
  210. package/src/server/services/AgentLoopRepository.ts +0 -178
  211. package/src/server/services/AgentLoopService.ts +0 -177
  212. package/src/server/services/AgentPlanValidator.ts +0 -73
  213. package/src/server/services/AgentPlannerService.ts +0 -80
  214. package/src/server/services/CircuitBreaker.ts +0 -126
  215. package/src/server/services/ContextAggregator.ts +0 -239
  216. package/src/server/services/PlanningPromptService.ts +0 -72
  217. package/src/server/tools/agent-loop.ts +0 -360
  218. package/src/server/tools/orchestrator-plan.ts +0 -255
@@ -0,0 +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
+ });
@@ -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
+ });
@@ -1,121 +1,162 @@
1
- import { createMockServer } from '@nocobase/test';
2
-
3
- describe('Agent Orchestrator plugin smoke', () => {
4
- let app;
5
-
6
- afterEach(async () => {
7
- await app?.destroy();
8
- });
9
-
10
- it('loads without starting the full app', async () => {
11
- app = await createMockServer({
12
- plugins: ['nocobase', 'plugin-agent-orchestrator'],
13
- });
14
- expect(app).toBeTruthy();
15
- });
16
-
17
- it('registers collection definitions', async () => {
18
- app = await createMockServer({
19
- plugins: ['nocobase', 'plugin-agent-orchestrator'],
20
- });
21
- const collections = [
22
- 'agentLoopRuns',
23
- 'agentLoopSteps',
24
- 'agentLoopEvents',
25
- 'orchestratorConfig',
26
- 'orchestratorLogs',
27
- 'agentExecutionSpans',
28
- 'agentMemoryContexts',
29
- 'agentHarnessProfiles',
30
- 'skillDefinitions',
31
- 'skillExecutions',
32
- 'skillLoopConfigs',
33
- 'skillWorkerConfigs',
34
- ];
35
- for (const name of collections) {
36
- const collection = app.db.getCollection(name);
37
- expect(collection).toBeTruthy();
38
- }
39
- });
40
-
41
- it('has agentLoopRuns schema with required fields', async () => {
42
- app = await createMockServer({
43
- plugins: ['nocobase', 'plugin-agent-orchestrator'],
44
- });
45
- const collection = app.db.getCollection('agentLoopRuns');
46
- expect(collection).toBeTruthy();
47
-
48
- const fields = {
49
- goal: 'text',
50
- status: 'string',
51
- planVersion: 'integer',
52
- iterationCount: 'integer',
53
- totalTokens: 'integer',
54
- totalCost: 'float',
55
- };
56
-
57
- for (const [name, type] of Object.entries(fields)) {
58
- const field = collection.getField(name);
59
- expect(field).toBeTruthy();
60
- expect(field.type).toBe(type);
61
- }
62
- });
63
-
64
- it('can create an agentLoopRun record', async () => {
65
- app = await createMockServer({
66
- plugins: ['nocobase', 'plugin-agent-orchestrator'],
67
- });
68
- const repo = app.db.getRepository('agentLoopRuns');
69
- const run = await repo.create({
70
- values: {
71
- rootRunId: 'test-root',
72
- goal: 'Test goal',
73
- status: 'planning',
74
- },
75
- });
76
- expect(run.id).toBeTruthy();
77
- expect(run.goal).toBe('Test goal');
78
- expect(run.status).toBe('planning');
79
- expect(run.rootRunId).toBe('test-root');
80
- });
81
-
82
- it('can create agentLoopSteps with parent-child relationship', async () => {
83
- app = await createMockServer({
84
- plugins: ['nocobase', 'plugin-agent-orchestrator'],
85
- });
86
- const runRepo = app.db.getRepository('agentLoopRuns');
87
- const stepRepo = app.db.getRepository('agentLoopSteps');
88
-
89
- const run = await runRepo.create({
90
- values: {
91
- rootRunId: 'test-root-2',
92
- goal: 'Multi-step test',
93
- },
94
- });
95
-
96
- const parentStep = await stepRepo.create({
97
- values: {
98
- runId: run.id,
99
- planKey: 'step_1',
100
- title: 'Parent step',
101
- type: 'reasoning',
102
- status: 'succeeded',
103
- },
104
- });
105
-
106
- const childStep = await stepRepo.create({
107
- values: {
108
- runId: run.id,
109
- planKey: 'step_2',
110
- title: 'Child step',
111
- type: 'skill',
112
- status: 'pending',
113
- dependsOn: ['step_1'],
114
- },
115
- });
116
-
117
- expect(parentStep.id).toBeTruthy();
118
- expect(childStep.id).toBeTruthy();
119
- expect(childStep.dependsOn).toEqual(['step_1']);
120
- });
121
- });
1
+ import { createMockServer, MockServer } from '@nocobase/test';
2
+ import { PluginAgentOrchestratorServer } from '../plugin';
3
+ import { ensureAgentOrchestratorIndexes } from '../utils/ensure-indexes';
4
+
5
+ type DatabaseIndex = {
6
+ name?: string;
7
+ unique?: boolean;
8
+ fields?: Array<{ attribute?: string; name?: string }>;
9
+ };
10
+
11
+ describe('Agent Orchestrator plugin smoke', () => {
12
+ let app: MockServer;
13
+
14
+ beforeAll(async () => {
15
+ const createdApp = await createMockServer({
16
+ plugins: ['nocobase', PluginAgentOrchestratorServer],
17
+ name: `agent-orchestrator-smoke-${process.pid}`,
18
+ skipSupervisor: true,
19
+ beforeInstall: async (mockApp) => {
20
+ app = mockApp;
21
+ },
22
+ });
23
+ app = createdApp;
24
+ });
25
+
26
+ afterAll(async () => {
27
+ await app?.destroy();
28
+ });
29
+
30
+ it('loads without starting the full app', async () => {
31
+ expect(app).toBeTruthy();
32
+ });
33
+
34
+ it('registers collection definitions', async () => {
35
+ const collections = [
36
+ 'agentLoopRuns',
37
+ 'agentLoopSteps',
38
+ 'agentLoopEvents',
39
+ 'orchestratorConfig',
40
+ 'orchestratorLogs',
41
+ 'agentExecutionSpans',
42
+ 'agentMemoryContexts',
43
+ 'agentHarnessProfiles',
44
+ 'agentHarnessProfileVersions',
45
+ 'agentLoopPatterns',
46
+ 'agentLoopActionApprovals',
47
+ 'agentLoopArtifacts',
48
+ 'agentLoopWorktrees',
49
+ 'agentLoopPathLocks',
50
+ 'agentLoopCircuitStates',
51
+ 'agentLoopUsageBuckets',
52
+ 'agentLoopControlSettings',
53
+ 'skillDefinitions',
54
+ 'skillExecutions',
55
+ 'skillLoopConfigs',
56
+ 'skillWorkerConfigs',
57
+ ];
58
+ for (const name of collections) {
59
+ const collection = app.db.getCollection(name);
60
+ expect(collection).toBeTruthy();
61
+ }
62
+ });
63
+
64
+ it('has agentLoopRuns schema with required fields and indexes', async () => {
65
+ const collection = app.db.getCollection('agentLoopRuns');
66
+ expect(collection).toBeTruthy();
67
+
68
+ const fields = {
69
+ goal: 'text',
70
+ status: 'string',
71
+ runtimeVersion: 'string',
72
+ recordMode: 'string',
73
+ patternId: 'bigInt',
74
+ pattern: 'belongsTo',
75
+ userId: 'bigInt',
76
+ policySnapshot: 'json',
77
+ planVersion: 'integer',
78
+ iterationCount: 'integer',
79
+ totalTokens: 'integer',
80
+ totalCost: 'float',
81
+ };
82
+
83
+ for (const [name, type] of Object.entries(fields)) {
84
+ const field = collection.getField(name);
85
+ expect(field).toBeTruthy();
86
+ expect(field.type).toBe(type);
87
+ }
88
+
89
+ await ensureAgentOrchestratorIndexes(app.db);
90
+ await ensureAgentOrchestratorIndexes(app.db);
91
+
92
+ const indexes = (await app.db.sequelize
93
+ .getQueryInterface()
94
+ .showIndex(collection.getTableNameWithSchema())) as DatabaseIndex[];
95
+ const fieldNames = (index: DatabaseIndex) => index.fields?.map((field) => field.attribute || field.name).join(',');
96
+
97
+ expect(indexes.some((index) => fieldNames(index) === 'userId,status')).toBe(true);
98
+ expect(
99
+ indexes.some(
100
+ (index) =>
101
+ index.name === 'agent_loop_runs_pattern_id_trigger_key' &&
102
+ index.unique === true &&
103
+ fieldNames(index) === 'patternId,triggerKey',
104
+ ),
105
+ ).toBe(true);
106
+
107
+ const indexNames = indexes.flatMap((index) => (index.name ? [index.name] : []));
108
+ expect(new Set(indexNames).size).toBe(indexNames.length);
109
+ });
110
+
111
+ it('can create an agentLoopRun record', async () => {
112
+ const repo = app.db.getRepository('agentLoopRuns');
113
+ const run = await repo.create({
114
+ values: {
115
+ rootRunId: 'test-root',
116
+ goal: 'Test goal',
117
+ status: 'queued',
118
+ },
119
+ });
120
+ expect(run.id).toBeTruthy();
121
+ expect(run.goal).toBe('Test goal');
122
+ expect(run.status).toBe('queued');
123
+ expect(run.rootRunId).toBe('test-root');
124
+ });
125
+
126
+ it('can create agentLoopSteps with parent-child relationship', async () => {
127
+ const runRepo = app.db.getRepository('agentLoopRuns');
128
+ const stepRepo = app.db.getRepository('agentLoopSteps');
129
+
130
+ const run = await runRepo.create({
131
+ values: {
132
+ rootRunId: 'test-root-2',
133
+ goal: 'Multi-step test',
134
+ },
135
+ });
136
+
137
+ const parentStep = await stepRepo.create({
138
+ values: {
139
+ runId: run.id,
140
+ planKey: 'step_1',
141
+ title: 'Parent step',
142
+ type: 'reasoning',
143
+ status: 'succeeded',
144
+ },
145
+ });
146
+
147
+ const childStep = await stepRepo.create({
148
+ values: {
149
+ runId: run.id,
150
+ planKey: 'step_2',
151
+ title: 'Child step',
152
+ type: 'skill',
153
+ status: 'pending',
154
+ dependsOn: ['step_1'],
155
+ },
156
+ });
157
+
158
+ expect(parentStep.id).toBeTruthy();
159
+ expect(childStep.id).toBeTruthy();
160
+ expect(childStep.dependsOn).toEqual(['step_1']);
161
+ });
162
+ });