Repository: kubevela/kubevela

Issue:
[Feature] Vela Addon Registry should store token in secrets
**Is your feature request related to a problem? Please describe.**
When we register an addon registry, the kubevela CLI updates the registry configmap and store the VCS token in the configmap in plain text. This does not comply with the Kubernetes standards.

**Describe the solution you'd like**
Tokens should be stored in secrets. 



Hints from issue comments:
@AshvinBambhaniya2003: Hi, @rohank2002, I am looking into this feature also. Thanks.@AshvinBambhaniya2003: ### The Plan

The implementation will be broken into two main phases: first, modifying the backend storage logic to handle both Secrets and the legacy ConfigMap storage, and second, ensuring the CLI properly uses this new logic.

---

### Phase 1: Modify Backend Logic in `pkg/addon/registry.go`

The goal here is to make the backend smart enough to handle both old and new data formats. The CLI and other parts of the system should not need to know the difference.

1.  **Update the Data Structures:**
    *   In `pkg/addon/registry.go`, modify the source structs (`GitAddonSource`, `GiteeAddonSource`, `GitlabAddonSource`) to include a new field that will hold a reference to the Kubernetes Secret.

    ```go
    // In pkg/addon/source.go

    type GitAddonSource struct {
        URL    string `json:"url,omitempty"`
        Path   string `json:"path,omitempty"`
        Token  string `json:"token,omitempty"` // This will be used for in-memory operations only
        // This new field will be stored in the ConfigMap
        TokenSecretRef string `json:"tokenSecretRef,omitempty"`
    }

    // ... repeat for GiteeAddonSource and GitlabAddonSource
    ```

2.  **Modify the `AddRegistry` Function:**
    *   When `AddRegistry` is called with a `Registry` object that contains a token in the `.Git.Token` field:
        *   **Create a Secret:** Generate a uniquely named Kubernetes Secret (e.g., `addon-registry-<registry-name>`). Store the token inside this Secret.
        *   **Clear the Token:** Before saving to the ConfigMap, set the `.Git.Token` field to an empty string (`""`).
        *   **Set the Reference:** Set the new `.Git.TokenSecretRef` field to the name of the Secret you just created.
        *   **Save to ConfigMap:** Proceed to marshal and save the `Registry` object to the `vela-addon-registry` ConfigMap as usual. The saved object will now contain the secret reference instead of the token itself.

3.  **Modify the `UpdateRegistry` Function (The Migration Logic):**
    *   This function will handle the seamless, automatic migration.
    *   When `UpdateRegistry` is called:
        *   Check if the incoming `Registry` object has a value in the `.Git.Token` field.
        *   **If it does**, this means the user is either setting a new token or updating an existing one. Follow the exact same logic as in `AddRegistry`: create/update the Secret, clear the `.Git.Token` field, and set the `.Git.TokenSecretRef`.
        *   This automatically migrates any existing, insecurely stored tokens the moment a user updates their registry for any reason.

4.  **Modify `GetRegistry` and `ListRegistries` (Backward Compatibility Logic):**
    *   These functions must be able to read both the old and new formats.
    *   When fetching registry data from the ConfigMap:
        *   Unmarshal the JSON into the `Registry` struct.
        *   **Check for the new format first:** If the `.Git.TokenSecretRef` field is not empty, fetch the corresponding Secret from Kubernetes. Read the token from the Secret's data and populate the `.Git.Token` field in the `Registry` object in memory.
        *   **Handle the old format:** If the `.Git.TokenSecretRef` field is empty, the code will do nothing extra. The `.Git.Token` field will already be populated from the unmarshaled ConfigMap data.
        *   **Return the object:** Return the fully "hydrated" `Registry` object. The calling function (e.g., the CLI) gets a complete object with the token ready to use, and it remains completely unaware of *how* the token was stored.

---

### Phase 2: Adjust CLI in `references/cli/addon-registry.go`

The beauty of the backend-heavy approach is that the CLI requires minimal changes.

1.  **`add` and `update` commands:**
    *   The `getRegistryFromArgs` function, which parses the `--gitToken` flag, can remain almost exactly as it is. It will continue to populate the `.Git.Token` field.
    *   The backend's `AddRegistry` and `UpdateRegistry` functions will now automatically handle the secure storage logic. No changes are needed in the CLI's `add` or `update` command logic itself.

2.  **`get` and `list` commands:**
    *   These commands will also work without changes because the backend `GetRegistry` and `ListRegistries` functions will always return a complete `Registry` object with the `.Git.Token` field populated, regardless of the storage method.
    *   **Optional Enhancement:** To encourage users to migrate, we could add a warning message in the `vela addon registry list` or `get` command. If the backend logic detects a registry is using the old format (i.e., `TokenSecretRef` is empty but `Token` is not), it could return a flag or a specific error that the CLI can catch and use to display a warning like: `Warning: Registry 'my-repo' uses a deprecated insecure token. Update the registry to migrate to secure storage.`

3.  **`delete` command:**
    *   The `deleteAddonRegistry` function must be updated. When it deletes a registry from the ConfigMap, it must also delete the associated `Secret` (using the `TokenSecretRef`) to ensure no orphaned secrets are left in the cluster.
@semmet95: @AshvinBambhaniya2003 the plan looks good, please feel free to go ahead with the implementation and the tests.@briankane: Yup, looks good! Thanks for looking after it

Solution patch:
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 16c3e7aa..087d1d9d 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -1,35 +1,35 @@
 # This file is a github code protect rule follow the codeowners https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/about-code-owners#example-of-a-codeowners-file
 
-*                                  @barnettZQG @wonderflow @leejanee @Somefive @jefree-cat @FogDong @wangyikewxgm @chivalryq @anoop2811
-design/                            @barnettZQG @leejanee @wonderflow @Somefive @jefree-cat @FogDong @anoop2811
+*                                  @barnettZQG @wonderflow @leejanee @Somefive @jefree-cat @FogDong @wangyikewxgm @chivalryq @anoop2811 @briankane @jguionnet
+design/                            @barnettZQG @leejanee @wonderflow @Somefive @jefree-cat @FogDong @anoop2811 @briankane @jguionnet
 
 # Owner of Core Controllers
-pkg/controller/core.oam.dev       @Somefive @FogDong @barnettZQG @wonderflow @wangyikewxgm @chivalryq @anoop2811
+pkg/controller/core.oam.dev       @Somefive @FogDong @barnettZQG @wonderflow @wangyikewxgm @chivalryq @anoop2811 @briankane @jguionnet
 
 # Owner of Standard Controllers
-pkg/controller/standard.oam.dev   @wangyikewxgm @barnettZQG @wonderflow @Somefive @anoop2811 @FogDong
+pkg/controller/standard.oam.dev   @wangyikewxgm @barnettZQG @wonderflow @Somefive @anoop2811 @FogDong @briankane @jguionnet
 
 # Owner of CUE
-pkg/cue                            @leejanee @FogDong @Somefive @anoop2811
-pkg/stdlib                         @leejanee @FogDong @Somefive @anoop2811
+pkg/cue                            @leejanee @FogDong @Somefive @anoop2811 @briankane @jguionnet
+pkg/stdlib                         @leejanee @FogDong @Somefive @anoop2811 @briankane @jguionnet
 
 # Owner of Workflow
-pkg/workflow                       @leejanee @FogDong @Somefive @wangyikewxgm @chivalryq @anoop2811
+pkg/workflow                       @leejanee @FogDong @Somefive @wangyikewxgm @chivalryq @anoop2811 @briankane @jguionnet
 
 # Owner of vela templates
-vela-templates/                     @Somefive @barnettZQG @wonderflow @FogDong @wangyikewxgm @chivalryq @anoop2811
+vela-templates/                     @Somefive @barnettZQG @wonderflow @FogDong @wangyikewxgm @chivalryq @anoop2811 @briankane @jguionnet
 
 # Owner of vela CLI
-references/cli/                     @Somefive @StevenLeiZhang @charlie0129 @wangyikewxgm @chivalryq @anoop2811 @FogDong
+references/cli/                     @Somefive @StevenLeiZhang @charlie0129 @wangyikewxgm @chivalryq @anoop2811 @FogDong @briankane @jguionnet
 
 # Owner of vela addon framework
-pkg/addon/                         @wangyikewxgm @wonderflow @charlie0129 @anoop2811 @FogDong
+pkg/addon/                         @wangyikewxgm @wonderflow @charlie0129 @anoop2811 @FogDong @briankane @jguionnet
 
 # Owner of resource keeper and tracker
-pkg/resourcekeeper                 @Somefive @FogDong @chivalryq @anoop2811
-pkg/resourcetracker                @Somefive @FogDong @chivalryq @anoop2811
+pkg/resourcekeeper                 @Somefive @FogDong @chivalryq @anoop2811 @briankane @jguionnet
+pkg/resourcetracker                @Somefive @FogDong @chivalryq @anoop2811 @briankane @jguionnet
 
-.github/                           @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811
-makefiles                          @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811
-go.*                               @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811
+.github/                           @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811 @briankane @jguionnet
+makefiles                          @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811 @briankane @jguionnet
+go.*                               @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811 @briankane @jguionnet
 
diff --git a/.github/comment.userlist b/.github/comment.userlist
index c3f04aff..785e8fd8 100644
--- a/.github/comment.userlist
+++ b/.github/comment.userlist
@@ -11,4 +11,7 @@ wangyuan249
 chivalryq
 FogDong
 leejanee
-barnettZQG
\ No newline at end of file
+barnettZQG
+anoop2811 
+briankane 
+jguionnet
\ No newline at end of file
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 2c700185..e13e73fa 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -111,16 +111,9 @@ jobs:
     steps:
       - name: Checkout
         uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608
+
       - name: Update kubectl plugin version in krew-index
         uses: rajatjindal/krew-release-bot@df3eb197549e3568be8b4767eec31c5e8e8e6ad8 # v0.0.46
-      - name: Update Homebrew formula
-        uses: dawidd6/action-homebrew-bump-formula@d3667e5ae14df19579e4414897498e3e88f2f458 # v3.10.0
-        with:
-          token: ${{ secrets.HOMEBREW_TOKEN }}
-          formula: kubevela
-          tag: ${{ github.ref }}
-          revision: ${{ github.sha }}
-          force: false
 
   provenance-vela-bins:
     name: generate provenance for binaries
diff --git a/.github/workflows/sync-sdk.yaml b/.github/workflows/sync-sdk.yaml
index 796d9b3a..64738572 100644
--- a/.github/workflows/sync-sdk.yaml
+++ b/.github/workflows/sync-sdk.yaml
@@ -28,10 +28,15 @@ jobs:
       - name: Install Go tools
         run: |
           make goimports
-          
+
       - name: Build CLI
         run: make vela-cli
 
+      - name: Setup KinD
+        uses: ./.github/actions/setup-kind-cluster
+        with:
+          name: sync-sdk
+
       - name: Get the version
         id: get_version
         run: echo "VERSION=${GITHUB_REF}" >> $GITHUB_OUTPUT
diff --git a/charts/vela-core/templates/defwithtemplate/apply-application-in-parallel.yaml b/charts/vela-core/templates/defwithtemplate/apply-application-in-parallel.yaml
index 8813eada..bcc51d33 100644
--- a/charts/vela-core/templates/defwithtemplate/apply-application-in-parallel.yaml
+++ b/charts/vela-core/templates/defwithtemplate/apply-application-in-parallel.yaml
@@ -15,9 +15,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        )
+        import "vela/op"
 
         output: op.#ApplyApplicationInParallel & {}
 
diff --git a/charts/vela-core/templates/defwithtemplate/apply-application.yaml b/charts/vela-core/templates/defwithtemplate/apply-application.yaml
index 6f0934b9..71036449 100644
--- a/charts/vela-core/templates/defwithtemplate/apply-application.yaml
+++ b/charts/vela-core/templates/defwithtemplate/apply-application.yaml
@@ -16,9 +16,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        )
+        import "vela/op"
 
         // apply application
         output: op.#ApplyApplication & {}
diff --git a/charts/vela-core/templates/defwithtemplate/apply-deployment.yaml b/charts/vela-core/templates/defwithtemplate/apply-deployment.yaml
index 71518b5a..54553cbe 100644
--- a/charts/vela-core/templates/defwithtemplate/apply-deployment.yaml
+++ b/charts/vela-core/templates/defwithtemplate/apply-deployment.yaml
@@ -13,12 +13,8 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"strconv"
-        	"strings"
-        	"vela/kube"
-        	"vela/builtin"
-        )
+        import "vela/kube"
+        import "vela/builtin"
 
         output: kube.#Apply & {
         	$params: {
diff --git a/charts/vela-core/templates/defwithtemplate/apply-object.yaml b/charts/vela-core/templates/defwithtemplate/apply-object.yaml
index 1b51ac8b..871097dc 100644
--- a/charts/vela-core/templates/defwithtemplate/apply-object.yaml
+++ b/charts/vela-core/templates/defwithtemplate/apply-object.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/kube"
-        )
+        import "vela/kube"
 
         apply: kube.#Apply & {
         	$params: parameter
diff --git a/charts/vela-core/templates/defwithtemplate/apply-remaining.yaml b/charts/vela-core/templates/defwithtemplate/apply-remaining.yaml
index 13a5def0..0b025004 100644
--- a/charts/vela-core/templates/defwithtemplate/apply-remaining.yaml
+++ b/charts/vela-core/templates/defwithtemplate/apply-remaining.yaml
@@ -16,9 +16,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        )
+        import "vela/op"
 
         // apply remaining components and traits
         apply: op.#ApplyRemaining & {
diff --git a/charts/vela-core/templates/defwithtemplate/apply-terraform-config.yaml b/charts/vela-core/templates/defwithtemplate/apply-terraform-config.yaml
index 4f7a894b..fcd83b00 100644
--- a/charts/vela-core/templates/defwithtemplate/apply-terraform-config.yaml
+++ b/charts/vela-core/templates/defwithtemplate/apply-terraform-config.yaml
@@ -13,10 +13,8 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/kube"
-        	"vela/builtin"
-        )
+        import "vela/kube"
+        import "vela/builtin"
 
         apply: kube.#Apply & {
         	$params: value: {
diff --git a/charts/vela-core/templates/defwithtemplate/apply-terraform-provider.yaml b/charts/vela-core/templates/defwithtemplate/apply-terraform-provider.yaml
index 6a899993..b263a7c2 100644
--- a/charts/vela-core/templates/defwithtemplate/apply-terraform-provider.yaml
+++ b/charts/vela-core/templates/defwithtemplate/apply-terraform-provider.yaml
@@ -13,12 +13,9 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/config"
-        	"vela/kube"
-        	"vela/builtin"
-        	"strings"
-        )
+        import "vela/config"
+        import "vela/kube"
+        import "vela/builtin"
 
         cfg: config.#CreateConfig & {
         	$params: {
@@ -87,9 +84,9 @@ spec:
         	}
         }
         providerBasic: {
-        	accessKey: string
-        	secretKey: string
-        	region:    string
+        	accessKey!: string
+        	secretKey!: string
+        	region!:    string
         }
         #AlibabaProvider: {
         	providerBasic
@@ -141,5 +138,5 @@ spec:
         	type:       "ucloud"
         	name:       *"ucloud-provider" | string
         }
-        parameter: *#AlibabaProvider | #AWSProvider | #AzureProvider | #BaiduProvider | #ECProvider | #GCPProvider | #TencentProvider | #UCloudProvider
+        parameter: #AlibabaProvider | #AWSProvider | #AzureProvider | #BaiduProvider | #ECProvider | #GCPProvider | #TencentProvider | #UCloudProvider
 
diff --git a/charts/vela-core/templates/defwithtemplate/build-push-image.yaml b/charts/vela-core/templates/defwithtemplate/build-push-image.yaml
index e89ff07a..8976826c 100644
--- a/charts/vela-core/templates/defwithtemplate/build-push-image.yaml
+++ b/charts/vela-core/templates/defwithtemplate/build-push-image.yaml
@@ -13,13 +13,10 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/builtin"
-        	"vela/kube"
-        	"vela/util"
-        	"encoding/json"
-        	"strings"
-        )
+        import "vela/builtin"
+        import "vela/kube"
+        import "vela/util"
+        import "strings"
 
         url: {
         	if parameter.context.git != _|_ {
diff --git a/charts/vela-core/templates/defwithtemplate/check-metrics.yaml b/charts/vela-core/templates/defwithtemplate/check-metrics.yaml
index 573b29ec..c50a5128 100644
--- a/charts/vela-core/templates/defwithtemplate/check-metrics.yaml
+++ b/charts/vela-core/templates/defwithtemplate/check-metrics.yaml
@@ -14,10 +14,8 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/metrics"
-        	"vela/builtin"
-        )
+        import "vela/metrics"
+        import "vela/builtin"
 
         check: metrics.#PromCheck & {
         	$params: {
diff --git a/charts/vela-core/templates/defwithtemplate/clean-jobs.yaml b/charts/vela-core/templates/defwithtemplate/clean-jobs.yaml
index b6c4bd7a..0a301335 100644
--- a/charts/vela-core/templates/defwithtemplate/clean-jobs.yaml
+++ b/charts/vela-core/templates/defwithtemplate/clean-jobs.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/kube"
-        )
+        import "vela/kube"
 
         parameter: {
         	labelselector?: {...}
diff --git a/charts/vela-core/templates/defwithtemplate/collect-service-endpoints.yaml b/charts/vela-core/templates/defwithtemplate/collect-service-endpoints.yaml
index e1b2a0e3..7af4d24a 100644
--- a/charts/vela-core/templates/defwithtemplate/collect-service-endpoints.yaml
+++ b/charts/vela-core/templates/defwithtemplate/collect-service-endpoints.yaml
@@ -12,11 +12,9 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/builtin"
-        	"vela/query"
-        	"strconv"
-        )
+        import "vela/builtin"
+        import "vela/query"
+        import "strconv"
 
         collect: query.#CollectServiceEndpoints & {
         	$params: app: {
diff --git a/charts/vela-core/templates/defwithtemplate/command.yaml b/charts/vela-core/templates/defwithtemplate/command.yaml
index 4b97a22d..7575dbb4 100644
--- a/charts/vela-core/templates/defwithtemplate/command.yaml
+++ b/charts/vela-core/templates/defwithtemplate/command.yaml
@@ -16,6 +16,8 @@ spec:
   schematic:
     cue:
       template: |
+        import "list"
+
         #PatchParams: {
         	// +usage=Specify the name of the target container, if not set, use the component name
         	containerName: *"" | string
@@ -73,7 +75,7 @@ spec:
         		}
 
         		// +patchStrategy=replace
-        		args: [for a in _args if _delArgs[a] == _|_ {a}] + [for a in _addArgs if _delArgs[a] == _|_ && _argsMap[a] == _|_ {a}]
+        		args: list.Concat([[for a in _args if _delArgs[a] == _|_ {a}], [for a in _addArgs if _delArgs[a] == _|_ && _argsMap[a] == _|_ {a}]])
         	}
         }
         // +patchStrategy=open
diff --git a/charts/vela-core/templates/defwithtemplate/container-ports.yaml b/charts/vela-core/templates/defwithtemplate/container-ports.yaml
index f26ab340..5c41e874 100644
--- a/charts/vela-core/templates/defwithtemplate/container-ports.yaml
+++ b/charts/vela-core/templates/defwithtemplate/container-ports.yaml
@@ -17,10 +17,9 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"strconv"
-        	"strings"
-        )
+        import "strconv"
+        import "strings"
+        import "list"
 
         #PatchParams: {
         	// +usage=Specify the name of the target container, if not set, use the component name
@@ -67,7 +66,7 @@ spec:
         			_basePortsMap: {for _basePort in _basePorts {(strings.ToLower(_basePort.protocol) + strconv.FormatInt(_basePort.containerPort, 10)): _basePort}}
         			_portsMap: {for port in _params.ports {(strings.ToLower(port.protocol) + strconv.FormatInt(port.containerPort, 10)): port}}
         			// +patchStrategy=replace
-        			ports: [for portVar in _basePorts {
+        			ports: list.Concat([[for portVar in _basePorts {
         				containerPort: portVar.containerPort
         				protocol:      portVar.protocol
         				name:          portVar.name
@@ -80,7 +79,7 @@ spec:
         						hostIP: _portsMap[_uniqueKey].hostIP
         					}
         				}
-        			}] + [for port in _params.ports if _basePortsMap[strings.ToLower(port.protocol)+strconv.FormatInt(port.containerPort, 10)] == _|_ {
+        			}], [for port in _params.ports if _basePortsMap[strings.ToLower(port.protocol)+strconv.FormatInt(port.containerPort, 10)] == _|_ {
         				if port.containerPort != _|_ {
         					containerPort: port.containerPort
         				}
@@ -93,7 +92,7 @@ spec:
         				if port.hostIP != _|_ {
         					hostIP: port.hostIP
         				}
-        			}]
+        			}]])
         		}
         	}
         }
diff --git a/charts/vela-core/templates/defwithtemplate/create-config.yaml b/charts/vela-core/templates/defwithtemplate/create-config.yaml
index 03e049d4..7a4ccb74 100644
--- a/charts/vela-core/templates/defwithtemplate/create-config.yaml
+++ b/charts/vela-core/templates/defwithtemplate/create-config.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/config"
-        )
+        import "vela/config"
 
         deploy: config.#CreateConfig & {
         	$params: parameter
diff --git a/charts/vela-core/templates/defwithtemplate/cron-task.yaml b/charts/vela-core/templates/defwithtemplate/cron-task.yaml
index 9cdcc23b..a4cfa74c 100644
--- a/charts/vela-core/templates/defwithtemplate/cron-task.yaml
+++ b/charts/vela-core/templates/defwithtemplate/cron-task.yaml
@@ -11,6 +11,8 @@ spec:
   schematic:
     cue:
       template: |
+        import "list"
+
         mountsArray: {
         	pvc: *[
         		for v in parameter.volumeMounts.pvc {
@@ -130,7 +132,7 @@ spec:
         		},
         	] | []
         }
-        volumesList: volumesArray.pvc + volumesArray.configMap + volumesArray.secret + volumesArray.emptyDir + volumesArray.hostPath
+        volumesList: list.Concat([volumesArray.pvc, volumesArray.configMap, volumesArray.secret, volumesArray.emptyDir, volumesArray.hostPath])
         deDupVolumesArray: [
         	for val in [
         		for i, vi in volumesList {
diff --git a/charts/vela-core/templates/defwithtemplate/daemon.yaml b/charts/vela-core/templates/defwithtemplate/daemon.yaml
index 75cb38aa..2f5965e4 100644
--- a/charts/vela-core/templates/defwithtemplate/daemon.yaml
+++ b/charts/vela-core/templates/defwithtemplate/daemon.yaml
@@ -11,9 +11,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"strconv"
-        )
+        import "strconv"
 
         mountsArray: [
         	if parameter.volumeMounts != _|_ && parameter.volumeMounts.pvc != _|_ for v in parameter.volumeMounts.pvc {
diff --git a/charts/vela-core/templates/defwithtemplate/delete-config.yaml b/charts/vela-core/templates/defwithtemplate/delete-config.yaml
index f1d261aa..0c4462c4 100644
--- a/charts/vela-core/templates/defwithtemplate/delete-config.yaml
+++ b/charts/vela-core/templates/defwithtemplate/delete-config.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/config"
-        )
+        import "vela/config"
 
         deploy: config.#DeleteConfig & {
         	$params: parameter
diff --git a/charts/vela-core/templates/defwithtemplate/depends-on-app.yaml b/charts/vela-core/templates/defwithtemplate/depends-on-app.yaml
index 2dec6031..26bcbede 100644
--- a/charts/vela-core/templates/defwithtemplate/depends-on-app.yaml
+++ b/charts/vela-core/templates/defwithtemplate/depends-on-app.yaml
@@ -12,11 +12,9 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/kube"
-        	"vela/builtin"
-        	"encoding/yaml"
-        )
+        import "vela/kube"
+        import "vela/builtin"
+        import "encoding/yaml"
 
         dependsOn: kube.#Read & {
         	$params: value: {
diff --git a/charts/vela-core/templates/defwithtemplate/deploy-cloud-resource.yaml b/charts/vela-core/templates/defwithtemplate/deploy-cloud-resource.yaml
index 7a9c5b5d..862fe0af 100644
--- a/charts/vela-core/templates/defwithtemplate/deploy-cloud-resource.yaml
+++ b/charts/vela-core/templates/defwithtemplate/deploy-cloud-resource.yaml
@@ -14,9 +14,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        )
+        import "vela/op"
 
         app: op.#DeployCloudResource & {
         	env:    parameter.env
diff --git a/charts/vela-core/templates/defwithtemplate/deploy.yaml b/charts/vela-core/templates/defwithtemplate/deploy.yaml
index 338e493f..2b335ad9 100644
--- a/charts/vela-core/templates/defwithtemplate/deploy.yaml
+++ b/charts/vela-core/templates/defwithtemplate/deploy.yaml
@@ -14,10 +14,9 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/multicluster"
-        	"vela/builtin"
-        )
+        import "vela/multicluster"
+        import "vela/builtin"
+
 
         if parameter.auto == false {
         	suspend: builtin.#Suspend & {$params: message: "Waiting approval to the deploy step \"\(context.stepName)\""}
diff --git a/charts/vela-core/templates/defwithtemplate/deploy2env.yaml b/charts/vela-core/templates/defwithtemplate/deploy2env.yaml
index 16e93d32..94fb365f 100644
--- a/charts/vela-core/templates/defwithtemplate/deploy2env.yaml
+++ b/charts/vela-core/templates/defwithtemplate/deploy2env.yaml
@@ -15,9 +15,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        )
+        import "vela/op"
 
         app: op.#ApplyEnvBindApp & {
         	env:      parameter.env
diff --git a/charts/vela-core/templates/defwithtemplate/deploy2runtime.yaml b/charts/vela-core/templates/defwithtemplate/deploy2runtime.yaml
index 07069066..ee03e13f 100644
--- a/charts/vela-core/templates/defwithtemplate/deploy2runtime.yaml
+++ b/charts/vela-core/templates/defwithtemplate/deploy2runtime.yaml
@@ -15,9 +15,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        )
+        import "vela/op"
 
         app: op.#Steps & {
         	load: op.#Load
diff --git a/charts/vela-core/templates/defwithtemplate/env.yaml b/charts/vela-core/templates/defwithtemplate/env.yaml
index 8f51afad..377b97df 100644
--- a/charts/vela-core/templates/defwithtemplate/env.yaml
+++ b/charts/vela-core/templates/defwithtemplate/env.yaml
@@ -16,6 +16,8 @@ spec:
   schematic:
     cue:
       template: |
+        import "list"
+
         #PatchParams: {
         	// +usage=Specify the name of the target container, if not set, use the component name
         	containerName: *"" | string
@@ -49,7 +51,7 @@ spec:
         		if _baseEnv != _|_ {
         			_baseEnvMap: {for envVar in _baseEnv {(envVar.name): envVar}}
         			// +patchStrategy=replace
-        			env: [for envVar in _baseEnv if _delKeys[envVar.name] == _|_ && !_params.replace {
+        			env: list.Concat([[for envVar in _baseEnv if _delKeys[envVar.name] == _|_ && !_params.replace {
         				name: envVar.name
         				if _params.env[envVar.name] != _|_ {
         					value: _params.env[envVar.name]
@@ -62,10 +64,10 @@ spec:
         						valueFrom: envVar.valueFrom
         					}
         				}
-        			}] + [for k, v in _params.env if _delKeys[k] == _|_ && (_params.replace || _baseEnvMap[k] == _|_) {
+        			}], [for k, v in _params.env if _delKeys[k] == _|_ && (_params.replace || _baseEnvMap[k] == _|_) {
         				name:  k
         				value: v
-        			}]
+        			}]])
         		}
         	}
         }
diff --git a/charts/vela-core/templates/defwithtemplate/export-data.yaml b/charts/vela-core/templates/defwithtemplate/export-data.yaml
index a6ba2972..d86d40d5 100644
--- a/charts/vela-core/templates/defwithtemplate/export-data.yaml
+++ b/charts/vela-core/templates/defwithtemplate/export-data.yaml
@@ -14,10 +14,8 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        	"vela/kube"
-        )
+        import "vela/op"
+        import "vela/kube"
 
         object: {
         	apiVersion: "v1"
diff --git a/charts/vela-core/templates/defwithtemplate/export-service.yaml b/charts/vela-core/templates/defwithtemplate/export-service.yaml
index 54217f33..baae45ef 100644
--- a/charts/vela-core/templates/defwithtemplate/export-service.yaml
+++ b/charts/vela-core/templates/defwithtemplate/export-service.yaml
@@ -14,10 +14,8 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        	"vela/kube"
-        )
+        import "vela/op"
+        import "vela/kube"
 
         meta: {
         	name:      *context.name | string
diff --git a/charts/vela-core/templates/defwithtemplate/export2config.yaml b/charts/vela-core/templates/defwithtemplate/export2config.yaml
index 6d4e6a6e..171bb03c 100644
--- a/charts/vela-core/templates/defwithtemplate/export2config.yaml
+++ b/charts/vela-core/templates/defwithtemplate/export2config.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/kube"
-        )
+        import "vela/kube"
 
         apply: kube.#Apply & {
         	$params: {
diff --git a/charts/vela-core/templates/defwithtemplate/export2secret.yaml b/charts/vela-core/templates/defwithtemplate/export2secret.yaml
index 26e218a6..c5c55e08 100644
--- a/charts/vela-core/templates/defwithtemplate/export2secret.yaml
+++ b/charts/vela-core/templates/defwithtemplate/export2secret.yaml
@@ -12,11 +12,9 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/kube"
-        	"encoding/base64"
-        	"encoding/json"
-        )
+        import "vela/kube"
+        import "encoding/base64"
+        import "encoding/json"
 
         secret: {
         	data: *parameter.data | {}
diff --git a/charts/vela-core/templates/defwithtemplate/expose.yaml b/charts/vela-core/templates/defwithtemplate/expose.yaml
index 81033a13..0feff34e 100644
--- a/charts/vela-core/templates/defwithtemplate/expose.yaml
+++ b/charts/vela-core/templates/defwithtemplate/expose.yaml
@@ -15,10 +15,8 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"strconv"
-        	"strings"
-        )
+        import "strconv"
+        import "strings"
 
         outputs: service: {
         	apiVersion: "v1"
@@ -96,21 +94,17 @@ spec:
   stage: PostDispatch
   status:
     customStatus: |-
-      message: *"" | string
       service: context.outputs.service
+      message: *"" | string
       if service.spec.type == "ClusterIP" {
       	message: "ClusterIP: \(service.spec.clusterIP)"
       }
       if service.spec.type == "LoadBalancer" {
       	status: service.status
       	isHealth: *false | bool
+      	message: *"ExternalIP: Pending" | string
       	if status != _|_ if status.loadBalancer != _|_ if status.loadBalancer.ingress != _|_ if len(status.loadBalancer.ingress) > 0 if status.loadBalancer.ingress[0].ip != _|_ {
       		isHealth: true
-      	}
-      	if !isHealth {
-      		message: "ExternalIP: Pending"
-      	}
-      	if isHealth {
       		message: "ExternalIP: \(status.loadBalancer.ingress[0].ip)"
       	}
       }
diff --git a/charts/vela-core/templates/defwithtemplate/gateway.yaml b/charts/vela-core/templates/defwithtemplate/gateway.yaml
index d8370b48..1357b443 100644
--- a/charts/vela-core/templates/defwithtemplate/gateway.yaml
+++ b/charts/vela-core/templates/defwithtemplate/gateway.yaml
@@ -17,6 +17,7 @@ spec:
       template: |
         import "strconv"
 
+
         let nameSuffix = {
         	if parameter.name != _|_ {"-" + parameter.name}
         	if parameter.name == _|_ {""}
@@ -160,13 +161,17 @@ spec:
         if parameter.name == _|_ { "" }
       }
       let ingressMetaName = context.name + nameSuffix
-      let ig  = [for i in context.outputs if (i.kind == "Ingress") && (i.metadata.name == ingressMetaName) {i}][0]
+      let igList = [for i in context.outputs if (i.kind == "Ingress") && (i.metadata.name == ingressMetaName) {i}]
+      ig: *_|_ | _
+      if len(igList) > 0 {
+        ig: igList[0]
+      }
       igs: *{} | {}
-      if ig != _|_ if ig.status != _|_ if ig.status.loadbalancer != _|_ {
+      if ig != _|_ if ig.status != _|_ if ig.status.loadbalancer != _|_ if len(ig.status.loadbalancer.ingress) > 0 {
         igs: ig.status.loadbalancer.ingress[0]
       }
       igr: *{} | {}
-      if ig != _|_ if ig.spec != _|_  {
+      if ig != _|_ if ig.spec != _|_ if len(ig.spec.rules) > 0 {
         igr: ig.spec.rules[0]
       }
       if igs == _|_ {
diff --git a/charts/vela-core/templates/defwithtemplate/generate-jdbc-connection.yaml b/charts/vela-core/templates/defwithtemplate/generate-jdbc-connection.yaml
index 7f9d3530..9430d68c 100644
--- a/charts/vela-core/templates/defwithtemplate/generate-jdbc-connection.yaml
+++ b/charts/vela-core/templates/defwithtemplate/generate-jdbc-connection.yaml
@@ -12,11 +12,9 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/kube"
-        	"vela/util"
-        	"encoding/base64"
-        )
+        import "vela/kube"
+        import "vela/util"
+        import "encoding/base64"
 
         output: kube.#Read & {
         	$params: value: {
diff --git a/charts/vela-core/templates/defwithtemplate/ingress-1-20.yaml b/charts/vela-core/templates/defwithtemplate/ingress-1-20.yaml
index ed85f6d2..5f4daf77 100644
--- a/charts/vela-core/templates/defwithtemplate/ingress-1-20.yaml
+++ b/charts/vela-core/templates/defwithtemplate/ingress-1-20.yaml
@@ -69,11 +69,16 @@ spec:
         message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + "'\n"
       }
       if len(igs) > 0 {
+        let rules = context.outputs.ingress.spec.rules
+        host: *"" | string
+        if rules != _|_ if len(rules) > 0 if rules[0].host != _|_ {
+      	  host: rules[0].host
+        }
         if igs[0].ip != _|_ {
-      	  message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + igs[0].ip
+      	  message: "Visiting URL: " + host + ", IP: " + igs[0].ip
         }
         if igs[0].ip == _|_ {
-      	  message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host
+      	  message: "Visiting URL: " + host
         }
       }
     healthPolicy: 'isHealth: len(context.outputs.service.spec.clusterIP) > 0'
diff --git a/charts/vela-core/templates/defwithtemplate/ingress.yaml b/charts/vela-core/templates/defwithtemplate/ingress.yaml
index 20ee4506..3eb0467f 100644
--- a/charts/vela-core/templates/defwithtemplate/ingress.yaml
+++ b/charts/vela-core/templates/defwithtemplate/ingress.yaml
@@ -62,11 +62,16 @@ spec:
       	message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + "'\n"
       }
       if len(igs) > 0 {
+      	let rules = context.outputs.ingress.spec.rules
+      	host: *"" | string
+      	if rules != _|_ if len(rules) > 0 if rules[0].host != _|_ {
+      		host: rules[0].host
+      	}
       	if igs[0].ip != _|_ {
-      		message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + igs[0].ip
+      		message: "Visiting URL: " + host + ", IP: " + igs[0].ip
       	}
       	if igs[0].ip == _|_ {
-      		message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host
+      		message: "Visiting URL: " + host
       	}
       }
     healthPolicy: 'isHealth: len(context.outputs.service.spec.clusterIP) > 0'
diff --git a/charts/vela-core/templates/defwithtemplate/init-container.yaml b/charts/vela-core/templates/defwithtemplate/init-container.yaml
index 123ee70d..cc1558d5 100644
--- a/charts/vela-core/templates/defwithtemplate/init-container.yaml
+++ b/charts/vela-core/templates/defwithtemplate/init-container.yaml
@@ -17,6 +17,8 @@ spec:
   schematic:
     cue:
       template: |
+        import "list"
+
         patch: spec: template: spec: {
         	// +patchKey=name
         	containers: [{
@@ -43,10 +45,10 @@ spec:
         		}
 
         		// +patchKey=name
-        		volumeMounts: [{
+        		volumeMounts: list.Concat([[{
         			name:      parameter.mountName
         			mountPath: parameter.initMountPath
-        		}] + parameter.extraVolumeMounts
+        		}], parameter.extraVolumeMounts])
         	}]
         	// +patchKey=name
         	volumes: [{
diff --git a/charts/vela-core/templates/defwithtemplate/k8s-objects.yaml b/charts/vela-core/templates/defwithtemplate/k8s-objects.yaml
index 49bf1e9a..f8215dbb 100644
--- a/charts/vela-core/templates/defwithtemplate/k8s-objects.yaml
+++ b/charts/vela-core/templates/defwithtemplate/k8s-objects.yaml
@@ -11,7 +11,12 @@ spec:
   schematic:
     cue:
       template: |
-        output: parameter.objects[0]
+        output: {
+        	if len(parameter.objects) > 0 {
+        		parameter.objects[0]
+        	}
+        	...
+        }
 
         outputs: {
         	for i, v in parameter.objects {
diff --git a/charts/vela-core/templates/defwithtemplate/list-config.yaml b/charts/vela-core/templates/defwithtemplate/list-config.yaml
index 50b8b16a..dc8fa924 100644
--- a/charts/vela-core/templates/defwithtemplate/list-config.yaml
+++ b/charts/vela-core/templates/defwithtemplate/list-config.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/config"
-        )
+        import "vela/config"
 
         output: config.#ListConfig & {
         	$params: parameter
diff --git a/charts/vela-core/templates/defwithtemplate/nocalhost.yaml b/charts/vela-core/templates/defwithtemplate/nocalhost.yaml
index 1624fd66..04437df7 100644
--- a/charts/vela-core/templates/defwithtemplate/nocalhost.yaml
+++ b/charts/vela-core/templates/defwithtemplate/nocalhost.yaml
@@ -19,9 +19,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"encoding/json"
-        )
+        import "encoding/json"
 
         outputs: nocalhostService: {
         	apiVersion: "v1"
diff --git a/charts/vela-core/templates/defwithtemplate/notification.yaml b/charts/vela-core/templates/defwithtemplate/notification.yaml
index 58625da0..fae370c7 100644
--- a/charts/vela-core/templates/defwithtemplate/notification.yaml
+++ b/charts/vela-core/templates/defwithtemplate/notification.yaml
@@ -12,14 +12,12 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/http"
-        	"vela/email"
-        	"vela/kube"
-        	"vela/util"
-        	"encoding/base64"
-        	"encoding/json"
-        )
+        import "vela/http"
+        import "vela/email"
+        import "vela/kube"
+        import "vela/util"
+        import "encoding/base64"
+        import "encoding/json"
 
         parameter: {
         	// +usage=Please fulfill its url and message if you want to send Lark messages
diff --git a/charts/vela-core/templates/defwithtemplate/print-message-in-status.yaml b/charts/vela-core/templates/defwithtemplate/print-message-in-status.yaml
index 6e455afc..f1995582 100644
--- a/charts/vela-core/templates/defwithtemplate/print-message-in-status.yaml
+++ b/charts/vela-core/templates/defwithtemplate/print-message-in-status.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/builtin"
-        )
+        import "vela/builtin"
 
         parameter: message: string
 
diff --git a/charts/vela-core/templates/defwithtemplate/pure-ingress.yaml b/charts/vela-core/templates/defwithtemplate/pure-ingress.yaml
index 55f680b3..7885a6ea 100644
--- a/charts/vela-core/templates/defwithtemplate/pure-ingress.yaml
+++ b/charts/vela-core/templates/defwithtemplate/pure-ingress.yaml
@@ -49,11 +49,16 @@ spec:
       	message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + " --route'\n"
       }
       if len(igs) > 0 {
+      	let rules = context.outputs.ingress.spec.rules
+      	host: *"" | string
+      	if rules != _|_ if len(rules) > 0 if rules[0].host != _|_ {
+      		host: rules[0].host
+      	}
       	if igs[0].ip != _|_ {
-      		message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + igs[0].ip
+      		message: "Visiting URL: " + host + ", IP: " + igs[0].ip
       	}
       	if igs[0].ip == _|_ {
-      		message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host
+      		message: "Visiting URL: " + host
       	}
       }
   workloadRefPath: ""
diff --git a/charts/vela-core/templates/defwithtemplate/read-config.yaml b/charts/vela-core/templates/defwithtemplate/read-config.yaml
index 33d1af4f..2db44b1d 100644
--- a/charts/vela-core/templates/defwithtemplate/read-config.yaml
+++ b/charts/vela-core/templates/defwithtemplate/read-config.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/config"
-        )
+        import "vela/config"
 
         output: config.#ReadConfig & {
         	$params: parameter
diff --git a/charts/vela-core/templates/defwithtemplate/read-object.yaml b/charts/vela-core/templates/defwithtemplate/read-object.yaml
index 23a349c0..5e2f426f 100644
--- a/charts/vela-core/templates/defwithtemplate/read-object.yaml
+++ b/charts/vela-core/templates/defwithtemplate/read-object.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/kube"
-        )
+        import "vela/kube"
 
         output: kube.#Read & {
         	$params: {
diff --git a/charts/vela-core/templates/defwithtemplate/request.yaml b/charts/vela-core/templates/defwithtemplate/request.yaml
index 8461dfc0..f15d7a94 100644
--- a/charts/vela-core/templates/defwithtemplate/request.yaml
+++ b/charts/vela-core/templates/defwithtemplate/request.yaml
@@ -13,11 +13,9 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        	"vela/http"
-        	"encoding/json"
-        )
+        import "vela/op"
+        import "vela/http"
+        import "encoding/json"
 
         req: http.#HTTPDo & {
         	$params: {
diff --git a/charts/vela-core/templates/defwithtemplate/share-cloud-resource.yaml b/charts/vela-core/templates/defwithtemplate/share-cloud-resource.yaml
index 120a5307..762a786e 100644
--- a/charts/vela-core/templates/defwithtemplate/share-cloud-resource.yaml
+++ b/charts/vela-core/templates/defwithtemplate/share-cloud-resource.yaml
@@ -14,9 +14,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/op"
-        )
+        import "vela/op"
 
         app: op.#ShareCloudResource & {
         	env:        parameter.env
diff --git a/charts/vela-core/templates/defwithtemplate/statefulset.yaml b/charts/vela-core/templates/defwithtemplate/statefulset.yaml
index e230d068..4f00355b 100644
--- a/charts/vela-core/templates/defwithtemplate/statefulset.yaml
+++ b/charts/vela-core/templates/defwithtemplate/statefulset.yaml
@@ -11,10 +11,8 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"strconv"
-        	"strings"
-        )
+        import "strconv"
+        import "strings"
 
         mountsArray: [
         	if parameter.volumeMounts != _|_ if parameter.volumeMounts.pvc != _|_ for v in parameter.volumeMounts.pvc {
diff --git a/charts/vela-core/templates/defwithtemplate/suspend.yaml b/charts/vela-core/templates/defwithtemplate/suspend.yaml
index b612c152..db0736f5 100644
--- a/charts/vela-core/templates/defwithtemplate/suspend.yaml
+++ b/charts/vela-core/templates/defwithtemplate/suspend.yaml
@@ -12,9 +12,7 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/builtin"
-        )
+        import "vela/builtin"
 
         suspend: builtin.#Suspend & {
         	$params: parameter
diff --git a/charts/vela-core/templates/defwithtemplate/vela-cli.yaml b/charts/vela-core/templates/defwithtemplate/vela-cli.yaml
index a1f349ca..db850a15 100644
--- a/charts/vela-core/templates/defwithtemplate/vela-cli.yaml
+++ b/charts/vela-core/templates/defwithtemplate/vela-cli.yaml
@@ -12,11 +12,9 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/kube"
-        	"vela/builtin"
-        	"vela/util"
-        )
+        import "vela/kube"
+        import "vela/builtin"
+        import "vela/util"
 
         mountsArray: [
         	if parameter.storage != _|_ && parameter.storage.secret != _|_ for v in parameter.storage.secret {
@@ -126,8 +124,6 @@ spec:
         }
 
         parameter: {
-        	// +usage=Specify the name of the addon.
-        	addonName: string
         	// +usage=Specify the vela command
         	command: [...string]
         	// +usage=Specify the image
diff --git a/charts/vela-core/templates/defwithtemplate/webhook.yaml b/charts/vela-core/templates/defwithtemplate/webhook.yaml
index 2d3a559e..8d4d503c 100644
--- a/charts/vela-core/templates/defwithtemplate/webhook.yaml
+++ b/charts/vela-core/templates/defwithtemplate/webhook.yaml
@@ -12,13 +12,11 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"vela/http"
-        	"vela/kube"
-        	"vela/util"
-        	"encoding/json"
-        	"encoding/base64"
-        )
+        import "vela/http"
+        import "vela/kube"
+        import "vela/util"
+        import "encoding/json"
+        import "encoding/base64"
 
         data: {
         	if parameter.data == _|_ {
diff --git a/charts/vela-core/templates/defwithtemplate/webservice.yaml b/charts/vela-core/templates/defwithtemplate/webservice.yaml
index e05f4345..32262268 100644
--- a/charts/vela-core/templates/defwithtemplate/webservice.yaml
+++ b/charts/vela-core/templates/defwithtemplate/webservice.yaml
@@ -11,10 +11,8 @@ spec:
   schematic:
     cue:
       template: |
-        import (
-        	"strconv"
-        	"strings"
-        )
+        import "strconv"
+        import "strings"
 
         mountsArray: [
         	if parameter.volumeMounts != _|_ && parameter.volumeMounts.pvc != _|_ for v in parameter.volumeMounts.pvc {
diff --git a/cmd/core/app/config/admission.go b/cmd/core/app/config/admission.go
new file mode 100644
index 00000000..f32bf990
--- /dev/null
+++ b/cmd/core/app/config/admission.go
@@ -0,0 +1,38 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/spf13/pflag"
+
+	standardcontroller "github.com/oam-dev/kubevela/pkg/controller"
+)
+
+// AdmissionConfig contains admission control configuration.
+type AdmissionConfig struct {
+	// Fields will be populated based on what standardcontroller.AddAdmissionFlags sets
+}
+
+// NewAdmissionConfig creates a new AdmissionConfig with defaults.
+func NewAdmissionConfig() *AdmissionConfig {
+	return &AdmissionConfig{}
+}
+
+// AddFlags registers admission configuration flags.
+func (c *AdmissionConfig) AddFlags(fs *pflag.FlagSet) {
+	standardcontroller.AddAdmissionFlags(fs)
+}
diff --git a/cmd/core/app/config/application.go b/cmd/core/app/config/application.go
new file mode 100644
index 00000000..c65cc601
--- /dev/null
+++ b/cmd/core/app/config/application.go
@@ -0,0 +1,56 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"time"
+
+	"github.com/spf13/pflag"
+
+	commonconfig "github.com/oam-dev/kubevela/pkg/controller/common"
+)
+
+// ApplicationConfig contains application-specific configuration.
+type ApplicationConfig struct {
+	ReSyncPeriod time.Duration
+}
+
+// NewApplicationConfig creates a new ApplicationConfig with defaults.
+func NewApplicationConfig() *ApplicationConfig {
+	return &ApplicationConfig{
+		ReSyncPeriod: commonconfig.ApplicationReSyncPeriod,
+	}
+}
+
+// AddFlags registers application configuration flags.
+func (c *ApplicationConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.DurationVar(&c.ReSyncPeriod,
+		"application-re-sync-period",
+		c.ReSyncPeriod,
+		"Re-sync period for application to re-sync, also known as the state-keep interval.")
+}
+
+// SyncToApplicationGlobals syncs the parsed configuration values to application package global variables.
+// This should be called after flag parsing to ensure the application controller uses the configured values.
+//
+// NOTE: This method exists for backward compatibility with legacy code that depends on global
+// variables in the commonconfig package. Ideally, configuration should be injected rather than using globals.
+//
+// The flow is: CLI flags -> ApplicationConfig struct fields -> commonconfig globals (via this method)
+func (c *ApplicationConfig) SyncToApplicationGlobals() {
+	commonconfig.ApplicationReSyncPeriod = c.ReSyncPeriod
+}
diff --git a/cmd/core/app/config/client.go b/cmd/core/app/config/client.go
new file mode 100644
index 00000000..ef6a27e3
--- /dev/null
+++ b/cmd/core/app/config/client.go
@@ -0,0 +1,40 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	pkgclient "github.com/kubevela/pkg/controller/client"
+	"github.com/spf13/pflag"
+)
+
+// ClientConfig contains controller client configuration.
+// This wraps the external package's client configuration flags.
+type ClientConfig struct {
+	// Note: The actual configuration is managed by the pkgclient package
+	// This is a wrapper to maintain consistency with our config pattern
+}
+
+// NewClientConfig creates a new ClientConfig with defaults.
+func NewClientConfig() *ClientConfig {
+	return &ClientConfig{}
+}
+
+// AddFlags registers client configuration flags.
+// Delegates to the external package's flag registration.
+func (c *ClientConfig) AddFlags(fs *pflag.FlagSet) {
+	pkgclient.AddTimeoutControllerClientFlags(fs)
+}
diff --git a/cmd/core/app/config/controller.go b/cmd/core/app/config/controller.go
new file mode 100644
index 00000000..896ad754
--- /dev/null
+++ b/cmd/core/app/config/controller.go
@@ -0,0 +1,67 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/spf13/pflag"
+
+	oamcontroller "github.com/oam-dev/kubevela/pkg/controller/core.oam.dev"
+)
+
+// ControllerConfig wraps the oamcontroller.Args configuration.
+// While this appears to duplicate the Args struct, it serves as the new home for
+// controller flag registration after the AddFlags method was moved here from
+// the oamcontroller package during refactoring.
+type ControllerConfig struct {
+	// Embed the existing Args struct to reuse its fields
+	oamcontroller.Args
+}
+
+// NewControllerConfig creates a new ControllerConfig with defaults.
+func NewControllerConfig() *ControllerConfig {
+	return &ControllerConfig{
+		Args: oamcontroller.Args{
+			RevisionLimit:                                50,
+			AppRevisionLimit:                             10,
+			DefRevisionLimit:                             20,
+			AutoGenWorkloadDefinition:                    true,
+			ConcurrentReconciles:                         4,
+			IgnoreAppWithoutControllerRequirement:        false,
+			IgnoreDefinitionWithoutControllerRequirement: false,
+		},
+	}
+}
+
+// AddFlags registers controller configuration flags.
+// This method was moved here from oamcontroller.Args during refactoring
+// to centralize configuration management.
+func (c *ControllerConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.IntVar(&c.RevisionLimit, "revision-limit", c.RevisionLimit,
+		"RevisionLimit is the maximum number of revisions that will be maintained. The default value is 50.")
+	fs.IntVar(&c.AppRevisionLimit, "application-revision-limit", c.AppRevisionLimit,
+		"application-revision-limit is the maximum number of application useless revisions that will be maintained, if the useless revisions exceed this number, older ones will be GCed first.The default value is 10.")
+	fs.IntVar(&c.DefRevisionLimit, "definition-revision-limit", c.DefRevisionLimit,
+		"definition-revision-limit is the maximum number of component/trait definition useless revisions that will be maintained, if the useless revisions exceed this number, older ones will be GCed first.The default value is 20.")
+	fs.BoolVar(&c.AutoGenWorkloadDefinition, "autogen-workload-definition", c.AutoGenWorkloadDefinition,
+		"Automatic generated workloadDefinition which componentDefinition refers to.")
+	fs.IntVar(&c.ConcurrentReconciles, "concurrent-reconciles", c.ConcurrentReconciles,
+		"concurrent-reconciles is the concurrent reconcile number of the controller. The default value is 4")
+	fs.BoolVar(&c.IgnoreAppWithoutControllerRequirement, "ignore-app-without-controller-version", c.IgnoreAppWithoutControllerRequirement,
+		"If true, application controller will not process the app without 'app.oam.dev/controller-version-require' annotation")
+	fs.BoolVar(&c.IgnoreDefinitionWithoutControllerRequirement, "ignore-definition-without-controller-version", c.IgnoreDefinitionWithoutControllerRequirement,
+		"If true, trait/component/workflowstep definition controller will not process the definition without 'definition.oam.dev/controller-version-require' annotation")
+}
diff --git a/cmd/core/app/config/cue.go b/cmd/core/app/config/cue.go
new file mode 100644
index 00000000..42ec4a4b
--- /dev/null
+++ b/cmd/core/app/config/cue.go
@@ -0,0 +1,61 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/kubevela/pkg/cue/cuex"
+	"github.com/spf13/pflag"
+)
+
+// CUEConfig contains CUE language configuration.
+type CUEConfig struct {
+	EnableExternalPackage      bool
+	EnableExternalPackageWatch bool
+}
+
+// NewCUEConfig creates a new CUEConfig with defaults.
+func NewCUEConfig() *CUEConfig {
+	return &CUEConfig{
+		EnableExternalPackage:      cuex.EnableExternalPackageForDefaultCompiler,
+		EnableExternalPackageWatch: cuex.EnableExternalPackageWatchForDefaultCompiler,
+	}
+}
+
+// AddFlags registers CUE configuration flags.
+func (c *CUEConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.BoolVar(&c.EnableExternalPackage,
+		"enable-external-package-for-default-compiler",
+		c.EnableExternalPackage,
+		"Enable loading third-party CUE packages into the default CUE compiler. When enabled, external CUE packages can be imported and used in CUE templates.")
+	fs.BoolVar(&c.EnableExternalPackageWatch,
+		"enable-external-package-watch-for-default-compiler",
+		c.EnableExternalPackageWatch,
+		"Enable watching for changes in external CUE packages and automatically reload them when modified. Requires enable-external-package-for-default-compiler to be enabled.")
+}
+
+// SyncToCUEGlobals syncs the parsed configuration values to CUE package global variables.
+// This should be called after flag parsing to ensure the CUE compiler uses the configured values.
+//
+// NOTE: This method exists for backward compatibility with legacy code that depends on global
+// variables in the cuex package. Ideally, the CUE compiler configuration should be injected
+// rather than relying on globals.
+//
+// The flow is: CLI flags -> CUEConfig struct fields -> cuex globals (via this method)
+func (c *CUEConfig) SyncToCUEGlobals() {
+	cuex.EnableExternalPackageForDefaultCompiler = c.EnableExternalPackage
+	cuex.EnableExternalPackageWatchForDefaultCompiler = c.EnableExternalPackageWatch
+}
diff --git a/cmd/core/app/config/feature.go b/cmd/core/app/config/feature.go
new file mode 100644
index 00000000..a9be874c
--- /dev/null
+++ b/cmd/core/app/config/feature.go
@@ -0,0 +1,40 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/spf13/pflag"
+	utilfeature "k8s.io/apiserver/pkg/util/feature"
+)
+
+// FeatureConfig contains feature gate configuration.
+// This wraps the Kubernetes feature gate system.
+type FeatureConfig struct {
+	// Note: The actual configuration is managed by the utilfeature package
+	// This is a wrapper to maintain consistency with our config pattern
+}
+
+// NewFeatureConfig creates a new FeatureConfig with defaults.
+func NewFeatureConfig() *FeatureConfig {
+	return &FeatureConfig{}
+}
+
+// AddFlags registers feature gate configuration flags.
+// Delegates to the Kubernetes feature gate system.
+func (c *FeatureConfig) AddFlags(fs *pflag.FlagSet) {
+	utilfeature.DefaultMutableFeatureGate.AddFlag(fs)
+}
diff --git a/cmd/core/app/config/klog.go b/cmd/core/app/config/klog.go
new file mode 100644
index 00000000..5d92812c
--- /dev/null
+++ b/cmd/core/app/config/klog.go
@@ -0,0 +1,42 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	utillog "github.com/kubevela/pkg/util/log"
+	"github.com/spf13/pflag"
+)
+
+// KLogConfig contains klog configuration.
+// This wraps the Kubernetes logging configuration.
+type KLogConfig struct {
+	// Reference to observability config for log settings
+	observability *ObservabilityConfig
+}
+
+// NewKLogConfig creates a new KLogConfig.
+func NewKLogConfig(observability *ObservabilityConfig) *KLogConfig {
+	return &KLogConfig{
+		observability: observability,
+	}
+}
+
+// AddFlags registers klog configuration flags.
+func (c *KLogConfig) AddFlags(fs *pflag.FlagSet) {
+	// Add base klog flags
+	utillog.AddFlags(fs)
+}
diff --git a/cmd/core/app/config/kubernetes.go b/cmd/core/app/config/kubernetes.go
new file mode 100644
index 00000000..f376740c
--- /dev/null
+++ b/cmd/core/app/config/kubernetes.go
@@ -0,0 +1,49 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"time"
+
+	"github.com/spf13/pflag"
+)
+
+// KubernetesConfig contains Kubernetes API client configuration.
+type KubernetesConfig struct {
+	QPS                float64
+	Burst              int
+	InformerSyncPeriod time.Duration
+}
+
+// NewKubernetesConfig creates a new KubernetesConfig with defaults.
+func NewKubernetesConfig() *KubernetesConfig {
+	return &KubernetesConfig{
+		QPS:                50,
+		Burst:              100,
+		InformerSyncPeriod: 10 * time.Hour,
+	}
+}
+
+// AddFlags registers Kubernetes configuration flags.
+func (c *KubernetesConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.Float64Var(&c.QPS, "kube-api-qps", c.QPS,
+		"the qps for reconcile clients. Low qps may lead to low throughput. High qps may give stress to api-server. Raise this value if concurrent-reconciles is set to be high.")
+	fs.IntVar(&c.Burst, "kube-api-burst", c.Burst,
+		"the burst for reconcile clients. Recommend setting it qps*2.")
+	fs.DurationVar(&c.InformerSyncPeriod, "informer-sync-period", c.InformerSyncPeriod,
+		"The re-sync period for informer in controller-runtime. This is a system-level configuration.")
+}
diff --git a/cmd/core/app/config/multicluster.go b/cmd/core/app/config/multicluster.go
new file mode 100644
index 00000000..cd58dc5d
--- /dev/null
+++ b/cmd/core/app/config/multicluster.go
@@ -0,0 +1,53 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"time"
+
+	pkgmulticluster "github.com/kubevela/pkg/multicluster"
+	"github.com/spf13/pflag"
+)
+
+// MultiClusterConfig contains multi-cluster configuration.
+type MultiClusterConfig struct {
+	EnableClusterGateway   bool
+	EnableClusterMetrics   bool
+	ClusterMetricsInterval time.Duration
+}
+
+// NewMultiClusterConfig creates a new MultiClusterConfig with defaults.
+func NewMultiClusterConfig() *MultiClusterConfig {
+	return &MultiClusterConfig{
+		EnableClusterGateway:   false,
+		EnableClusterMetrics:   false,
+		ClusterMetricsInterval: 15 * time.Second,
+	}
+}
+
+// AddFlags registers multi-cluster configuration flags.
+func (c *MultiClusterConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.BoolVar(&c.EnableClusterGateway, "enable-cluster-gateway", c.EnableClusterGateway,
+		"Enable cluster-gateway to use multicluster, disabled by default.")
+	fs.BoolVar(&c.EnableClusterMetrics, "enable-cluster-metrics", c.EnableClusterMetrics,
+		"Enable cluster-metrics-management to collect metrics from clusters with cluster-gateway, disabled by default. When this param is enabled, enable-cluster-gateway should be enabled")
+	fs.DurationVar(&c.ClusterMetricsInterval, "cluster-metrics-interval", c.ClusterMetricsInterval,
+		"The interval that ClusterMetricsMgr will collect metrics from clusters, default value is 15 seconds.")
+
+	// Also register additional multicluster flags from external package
+	pkgmulticluster.AddFlags(fs)
+}
diff --git a/cmd/core/app/config/oam.go b/cmd/core/app/config/oam.go
new file mode 100644
index 00000000..be52fc86
--- /dev/null
+++ b/cmd/core/app/config/oam.go
@@ -0,0 +1,54 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/spf13/pflag"
+
+	"github.com/oam-dev/kubevela/pkg/oam"
+)
+
+// OAMConfig contains OAM-specific configuration.
+type OAMConfig struct {
+	SystemDefinitionNamespace string
+}
+
+// NewOAMConfig creates a new OAMConfig with defaults.
+func NewOAMConfig() *OAMConfig {
+	return &OAMConfig{
+		SystemDefinitionNamespace: "vela-system",
+	}
+}
+
+// AddFlags registers OAM configuration flags.
+func (c *OAMConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.StringVar(&c.SystemDefinitionNamespace,
+		"system-definition-namespace",
+		c.SystemDefinitionNamespace,
+		"Define the namespace of the system-level definition")
+}
+
+// SyncToOAMGlobals syncs the parsed configuration values to OAM package global variables.
+// This should be called after flag parsing to ensure the OAM runtime uses the configured values.
+//
+// NOTE: This method exists for backward compatibility with legacy code that depends on global
+// variables in the oam package. Ideally, configuration should be injected rather than using globals.
+//
+// The flow is: CLI flags -> OAMConfig struct fields -> oam globals (via this method)
+func (c *OAMConfig) SyncToOAMGlobals() {
+	oam.SystemDefinitionNamespace = c.SystemDefinitionNamespace
+}
diff --git a/cmd/core/app/config/observability.go b/cmd/core/app/config/observability.go
new file mode 100644
index 00000000..20e1e92e
--- /dev/null
+++ b/cmd/core/app/config/observability.go
@@ -0,0 +1,55 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/spf13/pflag"
+)
+
+// ObservabilityConfig contains metrics and logging configuration.
+type ObservabilityConfig struct {
+	MetricsAddr    string
+	LogFilePath    string
+	LogFileMaxSize uint64
+	LogDebug       bool
+	DevLogs        bool
+}
+
+// NewObservabilityConfig creates a new ObservabilityConfig with defaults.
+func NewObservabilityConfig() *ObservabilityConfig {
+	return &ObservabilityConfig{
+		MetricsAddr:    ":8080",
+		LogFilePath:    "",
+		LogFileMaxSize: 1024,
+		LogDebug:       false,
+		DevLogs:        false,
+	}
+}
+
+// AddFlags registers observability configuration flags.
+func (c *ObservabilityConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.StringVar(&c.MetricsAddr, "metrics-addr", c.MetricsAddr,
+		"The address the metric endpoint binds to.")
+	fs.StringVar(&c.LogFilePath, "log-file-path", c.LogFilePath,
+		"The file to write logs to.")
+	fs.Uint64Var(&c.LogFileMaxSize, "log-file-max-size", c.LogFileMaxSize,
+		"Defines the maximum size a log file can grow to, Unit is megabytes.")
+	fs.BoolVar(&c.LogDebug, "log-debug", c.LogDebug,
+		"Enable debug logs for development purpose")
+	fs.BoolVar(&c.DevLogs, "dev-logs", c.DevLogs,
+		"Enable ANSI color formatting for console logs (ignored when log-file-path is set)")
+}
diff --git a/cmd/core/app/config/performance.go b/cmd/core/app/config/performance.go
new file mode 100644
index 00000000..f09b500b
--- /dev/null
+++ b/cmd/core/app/config/performance.go
@@ -0,0 +1,58 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/spf13/pflag"
+
+	standardcontroller "github.com/oam-dev/kubevela/pkg/controller"
+	commonconfig "github.com/oam-dev/kubevela/pkg/controller/common"
+)
+
+// PerformanceConfig contains performance and optimization configuration.
+type PerformanceConfig struct {
+	PerfEnabled bool
+}
+
+// NewPerformanceConfig creates a new PerformanceConfig with defaults.
+func NewPerformanceConfig() *PerformanceConfig {
+	return &PerformanceConfig{
+		PerfEnabled: commonconfig.PerfEnabled,
+	}
+}
+
+// AddFlags registers performance configuration flags.
+func (c *PerformanceConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.BoolVar(&c.PerfEnabled,
+		"perf-enabled",
+		c.PerfEnabled,
+		"Enable performance logging for controllers, disabled by default.")
+
+	// Add optimization flags from the standard controller
+	standardcontroller.AddOptimizeFlags(fs)
+}
+
+// SyncToPerformanceGlobals syncs the parsed configuration values to performance package global variables.
+// This should be called after flag parsing to ensure the performance monitoring uses the configured values.
+//
+// NOTE: This method exists for backward compatibility with legacy code that depends on global
+// variables in the commonconfig package. Ideally, configuration should be injected rather than using globals.
+//
+// The flow is: CLI flags -> PerformanceConfig struct fields -> commonconfig globals (via this method)
+func (c *PerformanceConfig) SyncToPerformanceGlobals() {
+	commonconfig.PerfEnabled = c.PerfEnabled
+}
diff --git a/cmd/core/app/config/profiling.go b/cmd/core/app/config/profiling.go
new file mode 100644
index 00000000..6fad82b1
--- /dev/null
+++ b/cmd/core/app/config/profiling.go
@@ -0,0 +1,40 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/kubevela/pkg/util/profiling"
+	"github.com/spf13/pflag"
+)
+
+// ProfilingConfig contains profiling configuration.
+// This wraps the external package's profiling configuration flags.
+type ProfilingConfig struct {
+	// Note: The actual configuration is managed by the profiling package
+	// This is a wrapper to maintain consistency with our config pattern
+}
+
+// NewProfilingConfig creates a new ProfilingConfig with defaults.
+func NewProfilingConfig() *ProfilingConfig {
+	return &ProfilingConfig{}
+}
+
+// AddFlags registers profiling configuration flags.
+// Delegates to the external package's flag registration.
+func (c *ProfilingConfig) AddFlags(fs *pflag.FlagSet) {
+	profiling.AddFlags(fs)
+}
diff --git a/cmd/core/app/config/reconcile.go b/cmd/core/app/config/reconcile.go
new file mode 100644
index 00000000..224a8c7e
--- /dev/null
+++ b/cmd/core/app/config/reconcile.go
@@ -0,0 +1,40 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	ctrlrec "github.com/kubevela/pkg/controller/reconciler"
+	"github.com/spf13/pflag"
+)
+
+// ReconcileConfig contains controller reconciliation configuration.
+// This wraps the external package's reconciler configuration flags.
+type ReconcileConfig struct {
+	// Note: The actual configuration is managed by the ctrlrec package
+	// This is a wrapper to maintain consistency with our config pattern
+}
+
+// NewReconcileConfig creates a new ReconcileConfig with defaults.
+func NewReconcileConfig() *ReconcileConfig {
+	return &ReconcileConfig{}
+}
+
+// AddFlags registers reconcile configuration flags.
+// Delegates to the external package's flag registration.
+func (c *ReconcileConfig) AddFlags(fs *pflag.FlagSet) {
+	ctrlrec.AddFlags(fs)
+}
diff --git a/cmd/core/app/config/resource.go b/cmd/core/app/config/resource.go
new file mode 100644
index 00000000..805289ea
--- /dev/null
+++ b/cmd/core/app/config/resource.go
@@ -0,0 +1,55 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/spf13/pflag"
+
+	"github.com/oam-dev/kubevela/pkg/resourcekeeper"
+)
+
+// ResourceConfig contains resource management configuration.
+type ResourceConfig struct {
+	MaxDispatchConcurrent int
+}
+
+// NewResourceConfig creates a new ResourceConfig with defaults.
+func NewResourceConfig() *ResourceConfig {
+	return &ResourceConfig{
+		MaxDispatchConcurrent: 10,
+	}
+}
+
+// AddFlags registers resource configuration flags.
+func (c *ResourceConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.IntVar(&c.MaxDispatchConcurrent,
+		"max-dispatch-concurrent",
+		c.MaxDispatchConcurrent,
+		"Set the max dispatch concurrent number, default is 10")
+}
+
+// SyncToResourceGlobals syncs the parsed configuration values to resource package global variables.
+// This should be called after flag parsing to ensure the resource keeper uses the configured values.
+//
+// NOTE: This method exists for backward compatibility with legacy code that depends on global
+// variables in the resourcekeeper package. The long-term goal should be to refactor to use
+// dependency injection rather than globals.
+//
+// The flow is: CLI flags -> ResourceConfig struct fields -> resourcekeeper globals (via this method)
+func (c *ResourceConfig) SyncToResourceGlobals() {
+	resourcekeeper.MaxDispatchConcurrent = c.MaxDispatchConcurrent
+}
diff --git a/cmd/core/app/config/server.go b/cmd/core/app/config/server.go
new file mode 100644
index 00000000..06b28141
--- /dev/null
+++ b/cmd/core/app/config/server.go
@@ -0,0 +1,65 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"time"
+
+	"github.com/spf13/pflag"
+)
+
+// ServerConfig contains server-level configuration.
+type ServerConfig struct {
+	HealthAddr              string
+	StorageDriver           string
+	EnableLeaderElection    bool
+	LeaderElectionNamespace string
+	LeaseDuration           time.Duration
+	RenewDeadline           time.Duration
+	RetryPeriod             time.Duration
+}
+
+// NewServerConfig creates a new ServerConfig with defaults.
+func NewServerConfig() *ServerConfig {
+	return &ServerConfig{
+		HealthAddr:              ":9440",
+		StorageDriver:           "Local",
+		EnableLeaderElection:    false,
+		LeaderElectionNamespace: "",
+		LeaseDuration:           15 * time.Second,
+		RenewDeadline:           10 * time.Second,
+		RetryPeriod:             2 * time.Second,
+	}
+}
+
+// AddFlags registers server configuration flags.
+func (c *ServerConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.StringVar(&c.HealthAddr, "health-addr", c.HealthAddr,
+		"The address the health endpoint binds to.")
+	fs.StringVar(&c.StorageDriver, "storage-driver", c.StorageDriver,
+		"Application storage driver.")
+	fs.BoolVar(&c.EnableLeaderElection, "enable-leader-election", c.EnableLeaderElection,
+		"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
+	fs.StringVar(&c.LeaderElectionNamespace, "leader-election-namespace", c.LeaderElectionNamespace,
+		"Determines the namespace in which the leader election configmap will be created.")
+	fs.DurationVar(&c.LeaseDuration, "leader-election-lease-duration", c.LeaseDuration,
+		"The duration that non-leader candidates will wait to force acquire leadership")
+	fs.DurationVar(&c.RenewDeadline, "leader-election-renew-deadline", c.RenewDeadline,
+		"The duration that the acting controlplane will retry refreshing leadership before giving up")
+	fs.DurationVar(&c.RetryPeriod, "leader-election-retry-period", c.RetryPeriod,
+		"The duration the LeaderElector clients should wait between tries of actions")
+}
diff --git a/cmd/core/app/config/sharding.go b/cmd/core/app/config/sharding.go
new file mode 100644
index 00000000..c70b3126
--- /dev/null
+++ b/cmd/core/app/config/sharding.go
@@ -0,0 +1,40 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/kubevela/pkg/controller/sharding"
+	"github.com/spf13/pflag"
+)
+
+// ShardingConfig contains controller sharding configuration.
+// This wraps the external package's sharding configuration flags.
+type ShardingConfig struct {
+	// Note: The actual configuration is managed by the sharding package
+	// This is a wrapper to maintain consistency with our config pattern
+}
+
+// NewShardingConfig creates a new ShardingConfig with defaults.
+func NewShardingConfig() *ShardingConfig {
+	return &ShardingConfig{}
+}
+
+// AddFlags registers sharding configuration flags.
+// Delegates to the external package's flag registration.
+func (c *ShardingConfig) AddFlags(fs *pflag.FlagSet) {
+	sharding.AddFlags(fs)
+}
diff --git a/cmd/core/app/config/webhook.go b/cmd/core/app/config/webhook.go
new file mode 100644
index 00000000..4a6ba621
--- /dev/null
+++ b/cmd/core/app/config/webhook.go
@@ -0,0 +1,47 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/spf13/pflag"
+)
+
+// WebhookConfig contains webhook configuration.
+type WebhookConfig struct {
+	UseWebhook  bool
+	CertDir     string
+	WebhookPort int
+}
+
+// NewWebhookConfig creates a new WebhookConfig with defaults.
+func NewWebhookConfig() *WebhookConfig {
+	return &WebhookConfig{
+		UseWebhook:  false,
+		CertDir:     "/k8s-webhook-server/serving-certs",
+		WebhookPort: 9443,
+	}
+}
+
+// AddFlags registers webhook configuration flags.
+func (c *WebhookConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.BoolVar(&c.UseWebhook, "use-webhook", c.UseWebhook,
+		"Enable Admission Webhook")
+	fs.StringVar(&c.CertDir, "webhook-cert-dir", c.CertDir,
+		"Admission webhook cert/key dir.")
+	fs.IntVar(&c.WebhookPort, "webhook-port", c.WebhookPort,
+		"admission webhook listen address")
+}
diff --git a/cmd/core/app/config/workflow.go b/cmd/core/app/config/workflow.go
new file mode 100644
index 00000000..b4767954
--- /dev/null
+++ b/cmd/core/app/config/workflow.go
@@ -0,0 +1,69 @@
+/*
+Copyright 2025 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package config
+
+import (
+	"github.com/spf13/pflag"
+
+	wfTypes "github.com/kubevela/workflow/pkg/types"
+)
+
+// WorkflowConfig contains workflow engine configuration.
+type WorkflowConfig struct {
+	MaxWaitBackoffTime     int
+	MaxFailedBackoffTime   int
+	MaxStepErrorRetryTimes int
+}
+
+// NewWorkflowConfig creates a new WorkflowConfig with defaults.
+func NewWorkflowConfig() *WorkflowConfig {
+	return &WorkflowConfig{
+		MaxWaitBackoffTime:     60,
+		MaxFailedBackoffTime:   300,
+		MaxStepErrorRetryTimes: 10,
+	}
+}
+
+// AddFlags registers workflow configuration flags.
+func (c *WorkflowConfig) AddFlags(fs *pflag.FlagSet) {
+	fs.IntVar(&c.MaxWaitBackoffTime,
+		"max-workflow-wait-backoff-time",
+		c.MaxWaitBackoffTime,
+		"Set the max workflow wait backoff time, default is 60")
+	fs.IntVar(&c.MaxFailedBackoffTime,
+		"max-workflow-failed-backoff-time",
+		c.MaxFailedBackoffTime,
+		"Set the max workflow failed backoff time, default is 300")
+	fs.IntVar(&c.MaxStepErrorRetryTimes,
+		"max-workflow-step-error-retry-times",
+		c.MaxStepErrorRetryTimes,
+		"Set the max workflow step error retry times, default is 10")
+}
+
+// SyncToWorkflowGlobals syncs the parsed configuration values to workflow package global variables.
+// This should be called after flag parsing to ensure the workflow engine uses the configured values.
+//
+// NOTE: This method exists for backward compatibility with legacy code that depends on global
+// variables in the wfTypes package. The long-term goal should be to refactor the workflow
+// package to accept configuration via dependency injection rather than globals.
+//
+// The flow is: CLI flags -> WorkflowConfig struct fields -> wfTypes globals (via this method)
+func (c *WorkflowConfig) SyncToWorkflowGlobals() {
+	wfTypes.MaxWorkflowWaitBackoffTime = c.MaxWaitBackoffTime
+	wfTypes.MaxWorkflowFailedBackoffTime = c.MaxFailedBackoffTime
+	wfTypes.MaxWorkflowStepErrorRetryTimes = c.MaxStepErrorRetryTimes
+}
diff --git a/cmd/core/app/options/options.go b/cmd/core/app/options/options.go
index 7959c0f8..daa387ef 100644
--- a/cmd/core/app/options/options.go
+++ b/cmd/core/app/options/options.go
@@ -17,88 +17,81 @@ limitations under the License.
 package options
 
 import (
-	"strconv"
-	"time"
-
-	"github.com/kubevela/pkg/cue/cuex"
-
-	pkgclient "github.com/kubevela/pkg/controller/client"
-	ctrlrec "github.com/kubevela/pkg/controller/reconciler"
-	"github.com/kubevela/pkg/controller/sharding"
-	pkgmulticluster "github.com/kubevela/pkg/multicluster"
-	utillog "github.com/kubevela/pkg/util/log"
-	"github.com/kubevela/pkg/util/profiling"
-	wfTypes "github.com/kubevela/workflow/pkg/types"
-	utilfeature "k8s.io/apiserver/pkg/util/feature"
 	cliflag "k8s.io/component-base/cli/flag"
 
-	standardcontroller "github.com/oam-dev/kubevela/pkg/controller"
-	commonconfig "github.com/oam-dev/kubevela/pkg/controller/common"
-	oamcontroller "github.com/oam-dev/kubevela/pkg/controller/core.oam.dev"
-	"github.com/oam-dev/kubevela/pkg/oam"
-	"github.com/oam-dev/kubevela/pkg/resourcekeeper"
+	"github.com/oam-dev/kubevela/cmd/core/app/config"
 )
 
 // CoreOptions contains everything necessary to create and run vela-core
 type CoreOptions struct {
-	UseWebhook              bool
-	CertDir                 string
-	WebhookPort             int
-	MetricsAddr             string
-	EnableLeaderElection    bool
-	LeaderElectionNamespace string
-	LogFilePath             string
-	LogFileMaxSize          uint64
-	LogDebug                bool
-	DevLogs                 bool
-	ControllerArgs          *oamcontroller.Args
-	HealthAddr              string
-	StorageDriver           string
-	InformerSyncPeriod      time.Duration
-	QPS                     float64
-	Burst                   int
-	LeaseDuration           time.Duration
-	RenewDeadLine           time.Duration
-	RetryPeriod             time.Duration
-	EnableClusterGateway    bool
-	EnableClusterMetrics    bool
-	ClusterMetricsInterval  time.Duration
+	// Config modules - clean, well-organized configuration
+	Server        *config.ServerConfig
+	Webhook       *config.WebhookConfig
+	Observability *config.ObservabilityConfig
+	Kubernetes    *config.KubernetesConfig
+	MultiCluster  *config.MultiClusterConfig
+	CUE           *config.CUEConfig
+	Application   *config.ApplicationConfig
+	OAM           *config.OAMConfig
+	Performance   *config.PerformanceConfig
+	Workflow      *config.WorkflowConfig
+	Admission     *config.AdmissionConfig
+	Resource      *config.ResourceConfig
+	Client        *config.ClientConfig
+	Reconcile     *config.ReconcileConfig
+	Sharding      *config.ShardingConfig
+	Feature       *config.FeatureConfig
+	Profiling     *config.ProfilingConfig
+	KLog          *config.KLogConfig
+	Controller    *config.ControllerConfig
 }
 
 // NewCoreOptions creates a new NewVelaCoreOptions object with default parameters
 func NewCoreOptions() *CoreOptions {
+	// Initialize config modules
+	server := config.NewServerConfig()
+	webhook := config.NewWebhookConfig()
+	observability := config.NewObservabilityConfig()
+	kubernetes := config.NewKubernetesConfig()
+	multiCluster := config.NewMultiClusterConfig()
+	cue := config.NewCUEConfig()
+	application := config.NewApplicationConfig()
+	oam := config.NewOAMConfig()
+	performance := config.NewPerformanceConfig()
+	workflow := config.NewWorkflowConfig()
+	admission := config.NewAdmissionConfig()
+	resource := config.NewResourceConfig()
+	client := config.NewClientConfig()
+	reconcile := config.NewReconcileConfig()
+	sharding := config.NewShardingConfig()
+	feature := config.NewFeatureConfig()
+	profiling := config.NewProfilingConfig()
+	klog := config.NewKLogConfig(observability)
+	controller := config.NewControllerConfig()
+
 	s := &CoreOptions{
-		UseWebhook:              false,
-		CertDir:                 "/k8s-webhook-server/serving-certs",
-		WebhookPort:             9443,
-		MetricsAddr:             ":8080",
-		EnableLeaderElection:    false,
-		LeaderElectionNamespace: "",
-		LogFilePath:             "",
-		LogFileMaxSize:          1024,
-		LogDebug:                false,
-		DevLogs:                 false,
-		ControllerArgs: &oamcontroller.Args{
-			RevisionLimit:                                50,
-			AppRevisionLimit:                             10,
-			DefRevisionLimit:                             20,
-			AutoGenWorkloadDefinition:                    true,
-			ConcurrentReconciles:                         4,
-			IgnoreAppWithoutControllerRequirement:        false,
-			IgnoreDefinitionWithoutControllerRequirement: false,
-		},
-		HealthAddr:             ":9440",
-		StorageDriver:          "Local",
-		InformerSyncPeriod:     10 * time.Hour,
-		QPS:                    50,
-		Burst:                  100,
-		LeaseDuration:          15 * time.Second,
-		RenewDeadLine:          10 * time.Second,
-		RetryPeriod:            2 * time.Second,
-		EnableClusterGateway:   false,
-		EnableClusterMetrics:   false,
-		ClusterMetricsInterval: 15 * time.Second,
+		// Config modules
+		Server:        server,
+		Webhook:       webhook,
+		Observability: observability,
+		Kubernetes:    kubernetes,
+		MultiCluster:  multiCluster,
+		CUE:           cue,
+		Application:   application,
+		OAM:           oam,
+		Performance:   performance,
+		Workflow:      workflow,
+		Admission:     admission,
+		Resource:      resource,
+		Client:        client,
+		Reconcile:     reconcile,
+		Sharding:      sharding,
+		Feature:       feature,
+		Profiling:     profiling,
+		KLog:          klog,
+		Controller:    controller,
 	}
+
 	return s
 }
 
@@ -106,75 +99,28 @@ func NewCoreOptions() *CoreOptions {
 func (s *CoreOptions) Flags() cliflag.NamedFlagSets {
 	fss := cliflag.NamedFlagSets{}
 
-	gfs := fss.FlagSet("generic")
-	gfs.BoolVar(&s.UseWebhook, "use-webhook", s.UseWebhook, "Enable Admission Webhook")
-	gfs.StringVar(&s.CertDir, "webhook-cert-dir", s.CertDir, "Admission webhook cert/key dir.")
-	gfs.IntVar(&s.WebhookPort, "webhook-port", s.WebhookPort, "admission webhook listen address")
-	gfs.StringVar(&s.MetricsAddr, "metrics-addr", s.MetricsAddr, "The address the metric endpoint binds to.")
-	gfs.BoolVar(&s.EnableLeaderElection, "enable-leader-election", s.EnableLeaderElection,
-		"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
-	gfs.StringVar(&s.LeaderElectionNamespace, "leader-election-namespace", s.LeaderElectionNamespace,
-		"Determines the namespace in which the leader election configmap will be created.")
-	gfs.StringVar(&s.LogFilePath, "log-file-path", s.LogFilePath, "The file to write logs to.")
-	gfs.Uint64Var(&s.LogFileMaxSize, "log-file-max-size", s.LogFileMaxSize, "Defines the maximum size a log file can grow to, Unit is megabytes.")
-	gfs.BoolVar(&s.LogDebug, "log-debug", s.LogDebug, "Enable debug logs for development purpose")
-	gfs.BoolVar(&s.DevLogs, "dev-logs", s.DevLogs, "Enable ANSI color formatting for console logs (ignored when log-file-path is set)")
-	gfs.StringVar(&s.HealthAddr, "health-addr", s.HealthAddr, "The address the health endpoint binds to.")
-	gfs.DurationVar(&s.InformerSyncPeriod, "informer-sync-period", s.InformerSyncPeriod,
-		"The re-sync period for informer in controller-runtime. This is a system-level configuration.")
-	gfs.Float64Var(&s.QPS, "kube-api-qps", s.QPS, "the qps for reconcile clients. Low qps may lead to low throughput. High qps may give stress to api-server. Raise this value if concurrent-reconciles is set to be high.")
-	gfs.IntVar(&s.Burst, "kube-api-burst", s.Burst, "the burst for reconcile clients. Recommend setting it qps*2.")
-	gfs.DurationVar(&s.LeaseDuration, "leader-election-lease-duration", s.LeaseDuration,
-		"The duration that non-leader candidates will wait to force acquire leadership")
-	gfs.DurationVar(&s.RenewDeadLine, "leader-election-renew-deadline", s.RenewDeadLine,
-		"The duration that the acting controlplane will retry refreshing leadership before giving up")
-	gfs.DurationVar(&s.RetryPeriod, "leader-election-retry-period", s.RetryPeriod,
-		"The duration the LeaderElector clients should wait between tries of actions")
-	gfs.BoolVar(&s.EnableClusterGateway, "enable-cluster-gateway", s.EnableClusterGateway, "Enable cluster-gateway to use multicluster, disabled by default.")
-	gfs.BoolVar(&s.EnableClusterMetrics, "enable-cluster-metrics", s.EnableClusterMetrics, "Enable cluster-metrics-management to collect metrics from clusters with cluster-gateway, disabled by default. When this param is enabled, enable-cluster-gateway should be enabled")
-	gfs.DurationVar(&s.ClusterMetricsInterval, "cluster-metrics-interval", s.ClusterMetricsInterval, "The interval that ClusterMetricsMgr will collect metrics from clusters, default value is 15 seconds.")
-	gfs.BoolVar(&cuex.EnableExternalPackageForDefaultCompiler, "enable-external-package-for-default-compiler", cuex.EnableExternalPackageForDefaultCompiler, "Enable external package for default compiler")
-	gfs.BoolVar(&cuex.EnableExternalPackageWatchForDefaultCompiler, "enable-external-package-watch-for-default-compiler", cuex.EnableExternalPackageWatchForDefaultCompiler, "Enable external package watch for default compiler")
-
-	s.ControllerArgs.AddFlags(fss.FlagSet("controllerArgs"), s.ControllerArgs)
-
-	cfs := fss.FlagSet("commonconfig")
-	cfs.DurationVar(&commonconfig.ApplicationReSyncPeriod, "application-re-sync-period", commonconfig.ApplicationReSyncPeriod,
-		"Re-sync period for application to re-sync, also known as the state-keep interval.")
-	cfs.BoolVar(&commonconfig.PerfEnabled, "perf-enabled", commonconfig.PerfEnabled, "Enable performance logging for controllers, disabled by default.")
-
-	ofs := fss.FlagSet("oam")
-	ofs.StringVar(&oam.SystemDefinitionNamespace, "system-definition-namespace", "vela-system", "define the namespace of the system-level definition")
-
-	standardcontroller.AddOptimizeFlags(fss.FlagSet("optimize"))
-	standardcontroller.AddAdmissionFlags(fss.FlagSet("admission"))
-
-	rfs := fss.FlagSet("resourcekeeper")
-	rfs.IntVar(&resourcekeeper.MaxDispatchConcurrent, "max-dispatch-concurrent", 10, "Set the max dispatch concurrent number, default is 10")
-
-	wfs := fss.FlagSet("wfTypes")
-	wfs.IntVar(&wfTypes.MaxWorkflowWaitBackoffTime, "max-workflow-wait-backoff-time", 60, "Set the max workflow wait backoff time, default is 60")
-	wfs.IntVar(&wfTypes.MaxWorkflowFailedBackoffTime, "max-workflow-failed-backoff-time", 300, "Set the max workflow failed backoff time, default is 300")
-	wfs.IntVar(&wfTypes.MaxWorkflowStepErrorRetryTimes, "max-workflow-step-error-retry-times", 10, "Set the max workflow step error retry times, default is 10")
-
-	pkgmulticluster.AddFlags(fss.FlagSet("multicluster"))
-	ctrlrec.AddFlags(fss.FlagSet("controllerreconciles"))
-	utilfeature.DefaultMutableFeatureGate.AddFlag(fss.FlagSet("featuregate"))
-	sharding.AddFlags(fss.FlagSet("sharding"))
-	kfs := fss.FlagSet("klog")
-	pkgclient.AddTimeoutControllerClientFlags(fss.FlagSet("controllerclient"))
-	utillog.AddFlags(kfs)
-	profiling.AddFlags(fss.FlagSet("profiling"))
-
-	if s.LogDebug {
-		_ = kfs.Set("v", strconv.Itoa(int(commonconfig.LogDebug)))
-	}
-
-	if s.LogFilePath != "" {
-		_ = kfs.Set("logtostderr", "false")
-		_ = kfs.Set("log_file", s.LogFilePath)
-		_ = kfs.Set("log_file_max_size", strconv.FormatUint(s.LogFileMaxSize, 10))
-	}
+	// Use config modules to register flags - clean delegation pattern
+	s.Server.AddFlags(fss.FlagSet("server"))
+	s.Webhook.AddFlags(fss.FlagSet("webhook"))
+	s.Observability.AddFlags(fss.FlagSet("observability"))
+	s.Kubernetes.AddFlags(fss.FlagSet("kubernetes"))
+	s.MultiCluster.AddFlags(fss.FlagSet("multicluster"))
+	s.CUE.AddFlags(fss.FlagSet("cue"))
+	s.Application.AddFlags(fss.FlagSet("application"))
+	s.OAM.AddFlags(fss.FlagSet("oam"))
+	s.Performance.AddFlags(fss.FlagSet("performance"))
+	s.Admission.AddFlags(fss.FlagSet("admission"))
+	s.Resource.AddFlags(fss.FlagSet("resource"))
+	s.Workflow.AddFlags(fss.FlagSet("workflow"))
+	s.Controller.AddFlags(fss.FlagSet("controller"))
+
+	// External package configurations (now wrapped in config modules)
+	s.Client.AddFlags(fss.FlagSet("client"))
+	s.Reconcile.AddFlags(fss.FlagSet("reconcile"))
+	s.Sharding.AddFlags(fss.FlagSet("sharding"))
+	s.Feature.AddFlags(fss.FlagSet("feature"))
+	s.Profiling.AddFlags(fss.FlagSet("profiling"))
+	s.KLog.AddFlags(fss.FlagSet("klog"))
 
 	return fss
 }
diff --git a/cmd/core/app/server.go b/cmd/core/app/server.go
index 36eef859..39a1b924 100644
--- a/cmd/core/app/server.go
+++ b/cmd/core/app/server.go
@@ -18,6 +18,7 @@ package app
 
 import (
 	"context"
+	"flag"
 	"fmt"
 	"io"
 	"os"
@@ -98,14 +99,32 @@ func NewCoreCommand() *cobra.Command {
 }
 
 func run(ctx context.Context, s *options.CoreOptions) error {
+	// Sync parsed config values to external package global variables
+	s.Workflow.SyncToWorkflowGlobals()
+	s.CUE.SyncToCUEGlobals()
+	s.Application.SyncToApplicationGlobals()
+	s.Performance.SyncToPerformanceGlobals()
+	s.Resource.SyncToResourceGlobals()
+	s.OAM.SyncToOAMGlobals()
+
 	restConfig := ctrl.GetConfigOrDie()
 	restConfig.UserAgent = types.KubeVelaName + "/" + version.GitRevision
-	restConfig.QPS = float32(s.QPS)
-	restConfig.Burst = s.Burst
+	restConfig.QPS = float32(s.Kubernetes.QPS)
+	restConfig.Burst = s.Kubernetes.Burst
 	restConfig.Wrap(auth.NewImpersonatingRoundTripper)
 
+	// Configure klog based on parsed observability settings
+	if s.Observability.LogDebug {
+		_ = flag.Set("v", strconv.Itoa(int(commonconfig.LogDebug)))
+	}
+	if s.Observability.LogFilePath != "" {
+		_ = flag.Set("logtostderr", "false")
+		_ = flag.Set("log_file", s.Observability.LogFilePath)
+		_ = flag.Set("log_file_max_size", strconv.FormatUint(s.Observability.LogFileMaxSize, 10))
+	}
+
 	// Set logger (use --dev-logs=true for local development)
-	if s.DevLogs {
+	if s.Observability.DevLogs {
 		logOutput := newColorWriter(os.Stdout)
 		klog.LogToStderr(false)
 		klog.SetOutput(logOutput)
@@ -122,15 +141,15 @@ func run(ctx context.Context, s *options.CoreOptions) error {
 	go profiling.StartProfilingServer(nil)
 
 	// wrapper the round tripper by multi cluster rewriter
-	if s.EnableClusterGateway {
+	if s.MultiCluster.EnableClusterGateway {
 		client, err := multicluster.Initialize(restConfig, true)
 		if err != nil {
 			klog.ErrorS(err, "failed to enable multi-cluster capability")
 			return err
 		}
 
-		if s.EnableClusterMetrics {
-			_, err := multicluster.NewClusterMetricsMgr(context.Background(), client, s.ClusterMetricsInterval)
+		if s.MultiCluster.EnableClusterMetrics {
+			_, err := multicluster.NewClusterMetricsMgr(context.Background(), client, s.MultiCluster.ClusterMetricsInterval)
 			if err != nil {
 				klog.ErrorS(err, "failed to enable multi-cluster-metrics capability")
 				return err
@@ -139,32 +158,32 @@ func run(ctx context.Context, s *options.CoreOptions) error {
 	}
 
 	if utilfeature.DefaultMutableFeatureGate.Enabled(features.ApplyOnce) {
-		commonconfig.ApplicationReSyncPeriod = s.InformerSyncPeriod
+		commonconfig.ApplicationReSyncPeriod = s.Kubernetes.InformerSyncPeriod
 	}
 
-	leaderElectionID := util.GenerateLeaderElectionID(types.KubeVelaName, s.ControllerArgs.IgnoreAppWithoutControllerRequirement)
+	leaderElectionID := util.GenerateLeaderElectionID(types.KubeVelaName, s.Controller.IgnoreAppWithoutControllerRequirement)
 	leaderElectionID += sharding.GetShardIDSuffix()
 	mgr, err := ctrl.NewManager(restConfig, ctrl.Options{
 		Scheme: scheme,
 		Metrics: metricsserver.Options{
-			BindAddress: s.MetricsAddr,
+			BindAddress: s.Observability.MetricsAddr,
 		},
-		LeaderElection:          s.EnableLeaderElection,
-		LeaderElectionNamespace: s.LeaderElectionNamespace,
+		LeaderElection:          s.Server.EnableLeaderElection,
+		LeaderElectionNamespace: s.Server.LeaderElectionNamespace,
 		LeaderElectionID:        leaderElectionID,
 		WebhookServer: ctrlwebhook.NewServer(ctrlwebhook.Options{
-			Port:    s.WebhookPort,
-			CertDir: s.CertDir,
+			Port:    s.Webhook.WebhookPort,
+			CertDir: s.Webhook.CertDir,
 		}),
-		HealthProbeBindAddress: s.HealthAddr,
-		LeaseDuration:          &s.LeaseDuration,
-		RenewDeadline:          &s.RenewDeadLine,
-		RetryPeriod:            &s.RetryPeriod,
+		HealthProbeBindAddress: s.Server.HealthAddr,
+		LeaseDuration:          &s.Server.LeaseDuration,
+		RenewDeadline:          &s.Server.RenewDeadline,
+		RetryPeriod:            &s.Server.RetryPeriod,
 		NewClient:              velaclient.DefaultNewControllerClient,
 		NewCache: cache.BuildCache(ctx,
 			ctrlcache.Options{
 				Scheme:     scheme,
-				SyncPeriod: &s.InformerSyncPeriod,
+				SyncPeriod: &s.Kubernetes.InformerSyncPeriod,
 				// SyncPeriod is configured with default value, aka. 10h. First, controller-runtime does not
 				// recommend use it as a time trigger, instead, it is expected to work for failure tolerance
 				// of controller-runtime. Additionally, set this value will affect not only application
@@ -210,7 +229,7 @@ func run(ctx context.Context, s *options.CoreOptions) error {
 		klog.ErrorS(err, "Failed to run manager")
 		return err
 	}
-	if s.LogFilePath != "" {
+	if s.Observability.LogFilePath != "" {
 		klog.Flush()
 	}
 	klog.Info("Safely stops Program...")
@@ -228,7 +247,7 @@ func prepareRunInShardingMode(ctx context.Context, mgr manager.Manager, s *optio
 		}
 	} else {
 		klog.Infof("controller running in sharding mode, current shard id: %s", sharding.ShardID)
-		if err := application.Setup(mgr, *s.ControllerArgs); err != nil {
+		if err := application.Setup(mgr, s.Controller.Args); err != nil {
 			return err
 		}
 	}
@@ -237,16 +256,16 @@ func prepareRunInShardingMode(ctx context.Context, mgr manager.Manager, s *optio
 }
 
 func prepareRun(ctx context.Context, mgr manager.Manager, s *options.CoreOptions) error {
-	if s.UseWebhook {
-		klog.InfoS("Enable webhook", "server port", strconv.Itoa(s.WebhookPort))
-		oamwebhook.Register(mgr, *s.ControllerArgs)
-		if err := waitWebhookSecretVolume(s.CertDir, waitSecretTimeout, waitSecretInterval); err != nil {
+	if s.Webhook.UseWebhook {
+		klog.InfoS("Enable webhook", "server port", strconv.Itoa(s.Webhook.WebhookPort))
+		oamwebhook.Register(mgr, s.Controller.Args)
+		if err := waitWebhookSecretVolume(s.Webhook.CertDir, waitSecretTimeout, waitSecretInterval); err != nil {
 			klog.ErrorS(err, "Unable to get webhook secret")
 			return err
 		}
 	}
 
-	if err := oamv1beta1.Setup(mgr, *s.ControllerArgs); err != nil {
+	if err := oamv1beta1.Setup(mgr, s.Controller.Args); err != nil {
 		klog.ErrorS(err, "Unable to setup the oam controller")
 		return err
 	}
diff --git a/go.mod b/go.mod
index 4219a0c1..9bf0a0a6 100644
--- a/go.mod
+++ b/go.mod
@@ -3,7 +3,7 @@ module github.com/oam-dev/kubevela
 go 1.23.8
 
 require (
-	cuelang.org/go v0.9.2
+	cuelang.org/go v0.14.1
 	github.com/AlecAivazis/survey/v2 v2.1.1
 	github.com/FogDong/uitable v0.0.5
 	github.com/Masterminds/semver v1.5.0
@@ -37,8 +37,8 @@ require (
 	github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174
 	github.com/imdario/mergo v0.3.16
 	github.com/jeremywohl/flatten/v2 v2.0.0-20211013061545-07e4a09fb8e4
-	github.com/kubevela/pkg v1.9.3-0.20250625225831-a2894a62a307
-	github.com/kubevela/workflow v0.6.3-0.20250717221743-56b80cee4121
+	github.com/kubevela/pkg v1.9.3-0.20251007211343-a91fd1f290c6
+	github.com/kubevela/workflow v0.6.3-0.20251007211423-415593c3cee0
 	github.com/kyokomi/emoji v2.2.4+incompatible
 	github.com/magiconair/properties v1.8.7
 	github.com/mattn/go-runewidth v0.0.15
@@ -59,21 +59,21 @@ require (
 	github.com/prometheus/client_model v0.6.1
 	github.com/rivo/tview v0.0.0-20221128165837-db36428c92d9
 	github.com/sirupsen/logrus v1.9.3
-	github.com/spf13/cobra v1.8.1
-	github.com/spf13/pflag v1.0.5
+	github.com/spf13/cobra v1.9.1
+	github.com/spf13/pflag v1.0.7
 	github.com/stretchr/testify v1.10.0
 	github.com/tidwall/gjson v1.14.4
 	github.com/wercker/stern v0.0.0-20190705090245-4fa46dd6987f
 	github.com/xlab/treeprint v1.2.0
 	gitlab.com/gitlab-org/api/client-go v0.127.0
 	go.uber.org/multierr v1.11.0
-	golang.org/x/crypto v0.37.0
-	golang.org/x/mod v0.24.0
-	golang.org/x/oauth2 v0.29.0
-	golang.org/x/sync v0.13.0
-	golang.org/x/term v0.31.0
-	golang.org/x/text v0.24.0
-	golang.org/x/tools v0.31.0
+	golang.org/x/crypto v0.40.0
+	golang.org/x/mod v0.26.0
+	golang.org/x/oauth2 v0.30.0
+	golang.org/x/sync v0.16.0
+	golang.org/x/term v0.33.0
+	golang.org/x/text v0.27.0
+	golang.org/x/tools v0.35.0
 	gomodules.xyz/jsonpatch/v2 v2.4.0
 	gopkg.in/yaml.v3 v3.0.1
 	helm.sh/helm/v3 v3.14.4
@@ -99,7 +99,7 @@ require (
 )
 
 require (
-	cuelabs.dev/go/oci/ociregistry v0.0.0-20240404174027-a39bec0462d2 // indirect
+	cuelabs.dev/go/oci/ociregistry v0.0.0-20250715075730-49cab49c8e9d // indirect
 	dario.cat/mergo v1.0.0 // indirect
 	github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 // indirect
 	github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect
@@ -134,7 +134,7 @@ require (
 	github.com/containerd/stargz-snapshotter/estargz v0.15.1 // indirect
 	github.com/coreos/go-semver v0.3.1 // indirect
 	github.com/coreos/go-systemd/v22 v22.5.0 // indirect
-	github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect
+	github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect
 	github.com/creack/pty v1.1.18 // indirect
 	github.com/cyphar/filepath-securejoin v0.4.1 // indirect
 	github.com/distribution/reference v0.6.0 // indirect
@@ -145,7 +145,7 @@ require (
 	github.com/docker/go-connections v0.5.0 // indirect
 	github.com/docker/go-metrics v0.0.1 // indirect
 	github.com/emicklei/go-restful/v3 v3.12.0 // indirect
-	github.com/emicklei/proto v1.10.0 // indirect
+	github.com/emicklei/proto v1.14.2 // indirect
 	github.com/emirpasic/gods v1.18.1 // indirect
 	github.com/evanphx/json-patch v5.7.0+incompatible // indirect
 	github.com/evanphx/json-patch/v5 v5.9.0 // indirect
@@ -232,15 +232,16 @@ require (
 	github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 // indirect
 	github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 // indirect
 	github.com/opencontainers/go-digest v1.0.0 // indirect
-	github.com/opencontainers/image-spec v1.1.0 // indirect
+	github.com/opencontainers/image-spec v1.1.1 // indirect
 	github.com/openshift/library-go v0.0.0-20230327085348-8477ec72b725 // indirect
+	github.com/pelletier/go-toml/v2 v2.2.4 // indirect
 	github.com/perimeterx/marshmallow v1.1.5 // indirect
 	github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
 	github.com/pjbgf/sha1cd v0.3.2 // indirect
 	github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
 	github.com/prometheus/common v0.55.0 // indirect
 	github.com/prometheus/procfs v0.15.1 // indirect
-	github.com/protocolbuffers/txtpbfmt v0.0.0-20230328191034-3462fbc510c0 // indirect
+	github.com/protocolbuffers/txtpbfmt v0.0.0-20250627152318-f293424e46b5 // indirect
 	github.com/rivo/uniseg v0.4.3 // indirect
 	github.com/robfig/cron/v3 v3.0.1 // indirect
 	github.com/rogpeppe/go-internal v1.14.1 // indirect
@@ -276,9 +277,10 @@ require (
 	go.uber.org/automaxprocs v1.5.3 // indirect
 	go.uber.org/zap v1.26.0 // indirect
 	golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect
-	golang.org/x/net v0.39.0 // indirect
-	golang.org/x/sys v0.32.0 // indirect
+	golang.org/x/net v0.42.0 // indirect
+	golang.org/x/sys v0.34.0 // indirect
 	golang.org/x/time v0.10.0 // indirect
+	golang.org/x/tools/go/expect v0.1.0-deprecated // indirect
 	google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de // indirect
 	google.golang.org/genproto/googleapis/api v0.0.0-20240814211410-ddb44dafa142 // indirect
 	google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 // indirect
diff --git a/go.sum b/go.sum
index 926f357c..cde51a13 100644
--- a/go.sum
+++ b/go.sum
@@ -1,9 +1,9 @@
 cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w99A=
 cloud.google.com/go/compute v0.1.0/go.mod h1:GAesmwr110a34z04OlxYkATPBEfVhkymfTBXtfbBFow=
-cuelabs.dev/go/oci/ociregistry v0.0.0-20240404174027-a39bec0462d2 h1:BnG6pr9TTr6CYlrJznYUDj6V7xldD1W+1iXPum0wT/w=
-cuelabs.dev/go/oci/ociregistry v0.0.0-20240404174027-a39bec0462d2/go.mod h1:pK23AUVXuNzzTpfMCA06sxZGeVQ/75FdVtW249de9Uo=
-cuelang.org/go v0.9.2 h1:pfNiry2PdRBr02G/aKm5k2vhzmqbAOoaB4WurmEbWvs=
-cuelang.org/go v0.9.2/go.mod h1:qpAYsLOf7gTM1YdEg6cxh553uZ4q9ZDWlPbtZr9q1Wk=
+cuelabs.dev/go/oci/ociregistry v0.0.0-20250715075730-49cab49c8e9d h1:lX0EawyoAu4kgMJJfy7MmNkIHioBcdBGFRSKDZ+CWo0=
+cuelabs.dev/go/oci/ociregistry v0.0.0-20250715075730-49cab49c8e9d/go.mod h1:4WWeZNxUO1vRoZWAHIG0KZOd6dA25ypyWuwD3ti0Tdc=
+cuelang.org/go v0.14.1 h1:kxFAHr7bvrCikbtVps2chPIARazVdnRmlz65dAzKyWg=
+cuelang.org/go v0.14.1/go.mod h1:aSP9UZUM5m2izHAHUvqtq0wTlWn5oLjuv2iBMQZBLLs=
 dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk=
 dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
 filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
@@ -144,8 +144,8 @@ github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03V
 github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=
 github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
 github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
-github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
-github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
+github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0=
+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
 github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
 github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY=
 github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
@@ -185,8 +185,8 @@ github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o
 github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=
 github.com/emicklei/go-restful/v3 v3.12.0 h1:y2DdzBAURM29NFF94q6RaY4vjIH1rtwDapwQtU84iWk=
 github.com/emicklei/go-restful/v3 v3.12.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
-github.com/emicklei/proto v1.10.0 h1:pDGyFRVV5RvV+nkBK9iy3q67FBy9Xa7vwrOTE+g5aGw=
-github.com/emicklei/proto v1.10.0/go.mod h1:rn1FgRS/FANiZdD2djyH7TMA9jdRDcYQ9IEN9yvjX0A=
+github.com/emicklei/proto v1.14.2 h1:wJPxPy2Xifja9cEMrcA/g08art5+7CGJNFNk35iXC1I=
+github.com/emicklei/proto v1.14.2/go.mod h1:rn1FgRS/FANiZdD2djyH7TMA9jdRDcYQ9IEN9yvjX0A=
 github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
 github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
 github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
@@ -476,10 +476,10 @@ github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
 github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
 github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
 github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
-github.com/kubevela/pkg v1.9.3-0.20250625225831-a2894a62a307 h1:6vebFO0h5vU/0gSol3l/9KlgZeuZzYhl3/DlDr0jI6E=
-github.com/kubevela/pkg v1.9.3-0.20250625225831-a2894a62a307/go.mod h1:P1yK32LmSs+NRjGu3Wu45VeCeKgIXiRg4qItN1MbgA8=
-github.com/kubevela/workflow v0.6.3-0.20250717221743-56b80cee4121 h1:clU2P7FyrhLm1l/xviiLO1Cen00ZI01oOfPxAOoMi0w=
-github.com/kubevela/workflow v0.6.3-0.20250717221743-56b80cee4121/go.mod h1:79KSLzfgBnJboWgxy5P/1GCc2ZUOLEYlF+vS4xQ3FNo=
+github.com/kubevela/pkg v1.9.3-0.20251007211343-a91fd1f290c6 h1:7REKNm1RC8pcvkYKyTD+mRMWp10+Jdkv/YqL/LE6VSE=
+github.com/kubevela/pkg v1.9.3-0.20251007211343-a91fd1f290c6/go.mod h1:P5FmkdwbXKt42LOhR0oMfMiQffYYKie9s2mLDJaPzjc=
+github.com/kubevela/workflow v0.6.3-0.20251007211423-415593c3cee0 h1:23CTZ0d7/KOB1TH52E+dvzKkp5vCMcrqGyyGLOelb9c=
+github.com/kubevela/workflow v0.6.3-0.20251007211423-415593c3cee0/go.mod h1:8mZrIj+6Oe08ikz/IpvGFTB/WzP2stwb8G6M01TCqac=
 github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
 github.com/kyokomi/emoji v2.2.4+incompatible h1:np0woGKwx9LiHAQmwZx79Oc0rHpNw3o+3evou4BEPv4=
@@ -596,8 +596,8 @@ github.com/onsi/gomega v1.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8=
 github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY=
 github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
-github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
-github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
+github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
+github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
 github.com/openkruise/kruise-api v1.4.0 h1:MDDXQIYvaCh0ioIJSRniF4kCKby9JI3/ec6pZHHw/Ao=
 github.com/openkruise/kruise-api v1.4.0/go.mod h1:HyRlDV0MfW5Zm+3g36bx7u4CcWHcKBxL8g/c/2bjcd4=
 github.com/openkruise/rollouts v0.3.0 h1:T02r9BxHJ02MRkbc7C4F12qMGgrziZVjgmukwz6k60s=
@@ -607,6 +607,8 @@ github.com/openshift/library-go v0.0.0-20230327085348-8477ec72b725/go.mod h1:Osp
 github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
 github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
 github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
+github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
+github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
 github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s=
 github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw=
 github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI=
@@ -655,8 +657,8 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1
 github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
 github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
 github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
-github.com/protocolbuffers/txtpbfmt v0.0.0-20230328191034-3462fbc510c0 h1:sadMIsgmHpEOGbUs6VtHBXRR1OHevnj7hLx9ZcdNGW4=
-github.com/protocolbuffers/txtpbfmt v0.0.0-20230328191034-3462fbc510c0/go.mod h1:jgxiZysxFPM+iWKwQwPR+y+Jvo54ARd4EisXxKYpB5c=
+github.com/protocolbuffers/txtpbfmt v0.0.0-20250627152318-f293424e46b5 h1:WWs1ZFnGobK5ZXNu+N9If+8PDNVB9xAqrib/stUXsV4=
+github.com/protocolbuffers/txtpbfmt v0.0.0-20250627152318-f293424e46b5/go.mod h1:BnHogPTyzYAReeQLZrOxyxzS739DaTNtTvohVdbENmA=
 github.com/rivo/tview v0.0.0-20221128165837-db36428c92d9 h1:ccTgRxA37ypj3q8zB8G4k3xGPfBbIaMwrf3Yw6k50NY=
 github.com/rivo/tview v0.0.0-20221128165837-db36428c92d9/go.mod h1:YX2wUZOcJGOIycErz2s9KvDaP0jnWwRCirQMPLPpQ+Y=
 github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
@@ -691,10 +693,12 @@ github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkU
 github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w=
 github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU=
 github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g=
-github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
-github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
-github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
+github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
+github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
 github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M=
+github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
 github.com/stoewer/go-strcase v1.2.0 h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU=
 github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8=
 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -817,8 +821,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y
 golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
 golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
 golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
-golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
-golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
+golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
+golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
 golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8=
 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY=
@@ -833,8 +837,8 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
 golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
 golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
 golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
-golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU=
-golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
+golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
+golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
 golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
 golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
 golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -861,8 +865,8 @@ golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY=
 golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
 golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
 golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
-golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
-golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
+golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
+golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
 golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
 golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
 golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -870,8 +874,8 @@ golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ
 golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
 golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
 golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
-golang.org/x/oauth2 v0.29.0 h1:WdYw2tdTK1S8olAzWHdgeqfy+Mtm9XNhv/xJsY65d98=
-golang.org/x/oauth2 v0.29.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8=
+golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
+golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
 golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -882,8 +886,8 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ
 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
-golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
+golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
+golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
 golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -922,16 +926,16 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
-golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
+golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
 golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
 golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
 golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
 golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
-golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=
-golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=
+golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
+golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
 golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
 golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
 golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@@ -942,8 +946,8 @@ golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
 golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
 golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
 golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
-golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
-golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
+golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
+golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
 golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
 golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=
 golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
@@ -960,8 +964,12 @@ golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
 golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
 golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
 golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
-golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU=
-golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ=
+golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
+golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
+golang.org/x/tools/go/expect v0.1.0-deprecated h1:jY2C5HGYR5lqex3gEniOQL0r7Dq5+VGVgY1nudX5lXY=
+golang.org/x/tools/go/expect v0.1.0-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
+golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM=
+golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
 golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
 golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
 golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
diff --git a/hack/docgen/cli/gen.go b/hack/docgen/cli/gen.go
index 2111073b..b6987ab7 100644
--- a/hack/docgen/cli/gen.go
+++ b/hack/docgen/cli/gen.go
@@ -153,9 +153,8 @@ func main() {
 				lines[idx] = ""
 				continue
 			}
-			if strings.Contains(line, ".md") && strings.Contains(line, "](") {
-				lines[idx] = strings.Replace(line, ".md", "", -1)
-			}
+			// Don't remove .md extensions - Docusaurus handles them properly
+			// and keeping them provides better IDE support and compatibility
 		}
 
 		newlines = append(newlines, lines...)
diff --git a/hack/docgen/def/mods/component.go b/hack/docgen/def/mods/component.go
index c27b8d4b..20c21db8 100644
--- a/hack/docgen/def/mods/component.go
+++ b/hack/docgen/def/mods/component.go
@@ -42,12 +42,12 @@ var ComponentDefDirs = []string{"./vela-templates/definitions/internal/component
 
 // CustomComponentHeaderEN .
 var CustomComponentHeaderEN = `---
-title: Built-in ParsedComponents Type
+title: Built-in Components Type
 ---
 
 This documentation will walk through all the built-in component types sorted alphabetically.
 
-` + fmt.Sprintf("> It was generated automatically by [scripts](../../contributor/cli-ref-doc), please don't update manually, last updated at %s.\n\n", time.Now().Format(time.RFC3339))
+` + fmt.Sprintf("> It was generated automatically by [scripts](../../contributor/cli-ref-doc.md), please don't update manually, last updated at %s.\n\n", time.Now().Format(time.RFC3339))
 
 // CustomComponentHeaderZH .
 var CustomComponentHeaderZH = `---
@@ -56,7 +56,7 @@ title: 内置组件列表
 
 本文档将**按字典序**展示所有内置组件的参数列表。
 
-` + fmt.Sprintf("> 本文档由[脚本](../../contributor/cli-ref-doc)自动生成，请勿手动修改，上次更新于 %s。\n\n", time.Now().Format(time.RFC3339))
+` + fmt.Sprintf("> 本文档由[脚本](../../contributor/cli-ref-doc.md)自动生成，请勿手动修改，上次更新于 %s。\n\n", time.Now().Format(time.RFC3339))
 
 // ComponentDef generate component def reference doc
 func ComponentDef(ctx context.Context, c common.Args, opt Options) {
diff --git a/hack/docgen/def/mods/policy.go b/hack/docgen/def/mods/policy.go
index b18df2e8..10d13ae6 100644
--- a/hack/docgen/def/mods/policy.go
+++ b/hack/docgen/def/mods/policy.go
@@ -47,7 +47,7 @@ title: Built-in Policy Type
 
 This documentation will walk through all the built-in policy types sorted alphabetically.
 
-` + fmt.Sprintf("> It was generated automatically by [scripts](../../contributor/cli-ref-doc), please don't update manually, last updated at %s.\n\n", time.Now().Format(time.RFC3339))
+` + fmt.Sprintf("> It was generated automatically by [scripts](../../contributor/cli-ref-doc.md), please don't update manually, last updated at %s.\n\n", time.Now().Format(time.RFC3339))
 
 // CustomPolicyHeaderZH .
 var CustomPolicyHeaderZH = `---
@@ -56,7 +56,7 @@ title: 内置策略列表
 
 本文档将**按字典序**展示所有内置策略的参数列表。
 
-` + fmt.Sprintf("> 本文档由[脚本](../../contributor/cli-ref-doc)自动生成，请勿手动修改，上次更新于 %s。\n\n", time.Now().Format(time.RFC3339))
+` + fmt.Sprintf("> 本文档由[脚本](../../contributor/cli-ref-doc.md)自动生成，请勿手动修改，上次更新于 %s。\n\n", time.Now().Format(time.RFC3339))
 
 // PolicyDef generate policy def reference doc
 func PolicyDef(ctx context.Context, c common.Args, opt Options) {
diff --git a/hack/docgen/def/mods/trait.go b/hack/docgen/def/mods/trait.go
index 9376f84d..ed0ae9d3 100644
--- a/hack/docgen/def/mods/trait.go
+++ b/hack/docgen/def/mods/trait.go
@@ -47,7 +47,7 @@ title: Built-in Trait Type
 
 This documentation will walk through all the built-in trait types sorted alphabetically.
 
-` + fmt.Sprintf("> It was generated automatically by [scripts](../../contributor/cli-ref-doc), please don't update manually, last updated at %s.\n\n", time.Now().Format(time.RFC3339))
+` + fmt.Sprintf("> It was generated automatically by [scripts](../../contributor/cli-ref-doc.md), please don't update manually, last updated at %s.\n\n", time.Now().Format(time.RFC3339))
 
 // CustomTraitHeaderZH .
 var CustomTraitHeaderZH = `---
@@ -56,7 +56,7 @@ title: 内置运维特征列表
 
 本文档将**按字典序**展示所有内置运维特征的参数列表。
 
-` + fmt.Sprintf("> 本文档由[脚本](../../contributor/cli-ref-doc)自动生成，请勿手动修改，上次更新于 %s。\n\n", time.Now().Format(time.RFC3339))
+` + fmt.Sprintf("> 本文档由[脚本](../../contributor/cli-ref-doc.md)自动生成，请勿手动修改，上次更新于 %s。\n\n", time.Now().Format(time.RFC3339))
 
 // TraitDef generate trait def reference doc
 func TraitDef(ctx context.Context, c common.Args, opt Options) {
diff --git a/hack/docgen/def/mods/workflow.go b/hack/docgen/def/mods/workflow.go
index 0d047b76..257abb1e 100644
--- a/hack/docgen/def/mods/workflow.go
+++ b/hack/docgen/def/mods/workflow.go
@@ -47,7 +47,7 @@ title: Built-in WorkflowStep Type
 
 This documentation will walk through all the built-in workflow step types sorted alphabetically.
 
-` + fmt.Sprintf("> It was generated automatically by [scripts](../../contributor/cli-ref-doc), please don't update manually, last updated at %s.\n\n", time.Now().Format(time.RFC3339))
+` + fmt.Sprintf("> It was generated automatically by [scripts](../../contributor/cli-ref-doc.md), please don't update manually, last updated at %s.\n\n", time.Now().Format(time.RFC3339))
 
 // CustomWorkflowHeaderZH .
 var CustomWorkflowHeaderZH = `---
@@ -56,7 +56,7 @@ title: 内置工作流步骤列表
 
 本文档将**按字典序**展示所有内置工作流步骤的参数列表。
 
-` + fmt.Sprintf("> 本文档由[脚本](../../contributor/cli-ref-doc)自动生成，请勿手动修改，上次更新于 %s。\n\n", time.Now().Format(time.RFC3339))
+` + fmt.Sprintf("> 本文档由[脚本](../../contributor/cli-ref-doc.md)自动生成，请勿手动修改，上次更新于 %s。\n\n", time.Now().Format(time.RFC3339))
 
 // WorkflowDef generate workflow def reference doc
 func WorkflowDef(ctx context.Context, c common.Args, opt Options) {
diff --git a/makefiles/dependency.mk b/makefiles/dependency.mk
index 8e9e3bc7..ac8be178 100644
--- a/makefiles/dependency.mk
+++ b/makefiles/dependency.mk
@@ -50,7 +50,7 @@ else
 GOIMPORTS=$(shell which goimports)
 endif
 
-CUE_VERSION ?= v0.9.2
+CUE_VERSION ?= v0.14.1
 .PHONY: installcue
 installcue:
 ifeq (, $(shell which cue))
diff --git a/pkg/addon/reader_gitlab.go b/pkg/addon/reader_gitlab.go
index d2a0bcb1..8fe46399 100644
--- a/pkg/addon/reader_gitlab.go
+++ b/pkg/addon/reader_gitlab.go
@@ -52,6 +52,9 @@ func (g GitLabItem) GetType() string {
 
 // GetPath get addon's sub item path
 func (g GitLabItem) GetPath() string {
+	if g.basePath == "" {
+		return g.path
+	}
 	return g.path[len(g.basePath)+1:]
 }
 
diff --git a/pkg/addon/registry.go b/pkg/addon/registry.go
index be17b308..fe12d5db 100644
--- a/pkg/addon/registry.go
+++ b/pkg/addon/registry.go
@@ -24,14 +24,43 @@ import (
 	v1 "k8s.io/api/core/v1"
 	apierrors "k8s.io/apimachinery/pkg/api/errors"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime/schema"
 	"k8s.io/apimachinery/pkg/types"
 	"sigs.k8s.io/controller-runtime/pkg/client"
+	logf "sigs.k8s.io/controller-runtime/pkg/log"
 
 	velatypes "github.com/oam-dev/kubevela/apis/types"
 )
 
 const registryConfigMapName = "vela-addon-registry"
 const registriesKey = "registries"
+const tokenSecretNamePrefix = "addon-registry-"
+
+// TokenSource is an interface for addon source that has token
+type TokenSource interface {
+	// GetToken return the token of the source
+	GetToken() string
+	// SetToken set the token of the source
+	SetToken(string)
+	// SetTokenSecretRef set the token secret ref to the source
+	SetTokenSecretRef(string)
+	// GetTokenSecretRef return the token secret ref of the source
+	GetTokenSecretRef() string
+}
+
+// GetTokenSource return the token source of the registry
+func (r *Registry) GetTokenSource() TokenSource {
+	if r.Git != nil {
+		return r.Git
+	}
+	if r.Gitee != nil {
+		return r.Gitee
+	}
+	if r.Gitlab != nil {
+		return r.Gitlab
+	}
+	return nil
+}
 
 // Registry represent a addon registry model
 type Registry struct {
@@ -62,28 +91,49 @@ type registryImpl struct {
 	client client.Client
 }
 
-func (r registryImpl) ListRegistries(ctx context.Context) ([]Registry, error) {
+// getRegistries is a helper to fetch and unmarshal all registries from the ConfigMap
+func (r registryImpl) getRegistries(ctx context.Context) (map[string]Registry, *v1.ConfigMap, error) {
 	cm := &v1.ConfigMap{}
-	if err := r.client.Get(ctx, types.NamespacedName{Namespace: velatypes.DefaultKubeVelaNS, Name: registryConfigMapName}, cm); err != nil {
-		return nil, err
+	err := r.client.Get(ctx, types.NamespacedName{Namespace: velatypes.DefaultKubeVelaNS, Name: registryConfigMapName}, cm)
+	if err != nil {
+		return nil, nil, err
 	}
 	if _, ok := cm.Data[registriesKey]; !ok {
-		return nil, NewAddonError("Error addon registry configmap registry-key not exist")
+		return nil, nil, NewAddonError("error addon registry configmap registry-key not exist")
 	}
 	registries := map[string]Registry{}
 	if err := json.Unmarshal([]byte(cm.Data[registriesKey]), &registries); err != nil {
+		return nil, cm, err
+	}
+	return registries, cm, nil
+}
+
+func (r registryImpl) ListRegistries(ctx context.Context) ([]Registry, error) {
+	registries, _, err := r.getRegistries(ctx)
+	if err != nil {
+		if apierrors.IsNotFound(err) {
+			return []Registry{}, nil
+		}
 		return nil, err
 	}
+
 	var res []Registry
 	for _, registry := range registries {
+		if err := loadTokenFromSecret(ctx, r.client, &registry); err != nil {
+			return nil, err
+		}
 		res = append(res, registry)
 	}
 	return res, nil
 }
 
 func (r registryImpl) AddRegistry(ctx context.Context, registry Registry) error {
-	cm := &v1.ConfigMap{}
-	if err := r.client.Get(ctx, types.NamespacedName{Namespace: velatypes.DefaultKubeVelaNS, Name: registryConfigMapName}, cm); err != nil {
+	if err := createOrUpdateTokenSecret(ctx, r.client, &registry); err != nil {
+		return err
+	}
+
+	registries, cm, err := r.getRegistries(ctx)
+	if err != nil {
 		if apierrors.IsNotFound(err) {
 			b, err := json.Marshal(map[string]Registry{
 				registry.Name: registry,
@@ -91,7 +141,7 @@ func (r registryImpl) AddRegistry(ctx context.Context, registry Registry) error
 			if err != nil {
 				return err
 			}
-			cm = &v1.ConfigMap{
+			cm := &v1.ConfigMap{
 				ObjectMeta: metav1.ObjectMeta{
 					Name:      registryConfigMapName,
 					Namespace: velatypes.DefaultKubeVelaNS,
@@ -104,48 +154,110 @@ func (r registryImpl) AddRegistry(ctx context.Context, registry Registry) error
 		}
 		return err
 	}
-	registries := map[string]Registry{}
-	if err := json.Unmarshal([]byte(cm.Data[registriesKey]), &registries); err != nil {
-		return err
-	}
+
 	registries[registry.Name] = registry
 	b, err := json.Marshal(registries)
 	if err != nil {
 		return err
 	}
-	cm.Data = map[string]string{
-		registriesKey: string(b),
-	}
+	cm.Data[registriesKey] = string(b)
 	return r.client.Update(ctx, cm)
 }
 
-func (r registryImpl) DeleteRegistry(ctx context.Context, name string) error {
-	cm := &v1.ConfigMap{}
-	if err := r.client.Get(ctx, types.NamespacedName{Namespace: velatypes.DefaultKubeVelaNS, Name: registryConfigMapName}, cm); err != nil {
+// createOrUpdateTokenSecret will create or update a secret to store registry token
+func createOrUpdateTokenSecret(ctx context.Context, cli client.Client, registry *Registry) error {
+	source := registry.GetTokenSource()
+	if source == nil {
+		return nil
+	}
+	token := source.GetToken()
+	if token == "" {
+		return nil
+	}
+	return migrateInlineTokenToSecret(ctx, cli, registry, source, token)
+}
+
+// migrateInlineTokenToSecret will migrate an inline token to a secret.
+// It will take the token from the registry object, create/update a secret, and set the secret ref on the registry object.
+func migrateInlineTokenToSecret(ctx context.Context, cli client.Client, registry *Registry, source TokenSource, token string) error {
+	log := logf.FromContext(ctx)
+	secretName := tokenSecretNamePrefix + registry.Name
+	source.SetTokenSecretRef(secretName)
+
+	secret := &v1.Secret{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      secretName,
+			Namespace: velatypes.DefaultKubeVelaNS,
+		},
+		Type: v1.SecretTypeOpaque,
+		Data: map[string][]byte{
+			"token": []byte(token),
+		},
+	}
+
+	err := cli.Create(ctx, secret)
+	if err != nil {
+		if apierrors.IsAlreadyExists(err) {
+			existingSecret := &v1.Secret{}
+			if err := cli.Get(ctx, types.NamespacedName{Name: secretName, Namespace: velatypes.DefaultKubeVelaNS}, existingSecret); err != nil {
+				return err
+			}
+			existingSecret.Data = secret.Data
+			if err := cli.Update(ctx, existingSecret); err != nil {
+				return err
+			}
+			log.Info("Successfully updated secret for addon registry token", "registry", registry.Name, "secret", secretName)
+			return nil
+		}
 		return err
 	}
-	registries := map[string]Registry{}
-	if err := json.Unmarshal([]byte(cm.Data[registriesKey]), &registries); err != nil {
+	log.Info("Successfully created secret for addon registry token", "registry", registry.Name, "secret", secretName)
+	return nil
+}
+
+func (r registryImpl) DeleteRegistry(ctx context.Context, name string) error {
+	registries, cm, err := r.getRegistries(ctx)
+	if err != nil {
+		if apierrors.IsNotFound(err) {
+			return nil
+		}
 		return err
 	}
+
+	reg, ok := registries[name]
+	if !ok {
+		return nil
+	}
+
+	if source := reg.GetTokenSource(); source != nil {
+		if secretName := source.GetTokenSecretRef(); secretName != "" {
+			secret := &v1.Secret{
+				ObjectMeta: metav1.ObjectMeta{
+					Name:      secretName,
+					Namespace: velatypes.DefaultKubeVelaNS,
+				},
+			}
+			if err := r.client.Delete(ctx, secret); err != nil && !apierrors.IsNotFound(err) {
+				return err
+			}
+		}
+	}
+
 	delete(registries, name)
 	b, err := json.Marshal(registries)
 	if err != nil {
 		return err
 	}
-	cm.Data = map[string]string{
-		registriesKey: string(b),
-	}
+	cm.Data[registriesKey] = string(b)
 	return r.client.Update(ctx, cm)
 }
 
 func (r registryImpl) UpdateRegistry(ctx context.Context, registry Registry) error {
-	cm := &v1.ConfigMap{}
-	if err := r.client.Get(ctx, types.NamespacedName{Namespace: velatypes.DefaultKubeVelaNS, Name: registryConfigMapName}, cm); err != nil {
+	if err := createOrUpdateTokenSecret(ctx, r.client, &registry); err != nil {
 		return err
 	}
-	registries := map[string]Registry{}
-	if err := json.Unmarshal([]byte(cm.Data[registriesKey]), &registries); err != nil {
+	registries, cm, err := r.getRegistries(ctx)
+	if err != nil {
 		return err
 	}
 	if _, ok := registries[registry.Name]; !ok {
@@ -156,25 +268,50 @@ func (r registryImpl) UpdateRegistry(ctx context.Context, registry Registry) err
 	if err != nil {
 		return err
 	}
-	cm.Data = map[string]string{
-		registriesKey: string(b),
-	}
+	cm.Data[registriesKey] = string(b)
 	return r.client.Update(ctx, cm)
 }
 
 func (r registryImpl) GetRegistry(ctx context.Context, name string) (Registry, error) {
-	var res Registry
-	cm := &v1.ConfigMap{}
-	if err := r.client.Get(ctx, types.NamespacedName{Namespace: velatypes.DefaultKubeVelaNS, Name: registryConfigMapName}, cm); err != nil {
-		return res, err
+	registries, _, err := r.getRegistries(ctx)
+	if err != nil {
+		return Registry{}, err
 	}
-	registries := map[string]Registry{}
-	if err := json.Unmarshal([]byte(cm.Data[registriesKey]), &registries); err != nil {
-		return res, err
+	res, ok := registries[name]
+	if !ok {
+		return res, apierrors.NewNotFound(schema.GroupResource{Group: "addons.kubevela.io", Resource: "Registry"}, name)
 	}
-	var notExist bool
-	if res, notExist = registries[name]; !notExist {
-		return res, fmt.Errorf("registry name %s not found", name)
+	if err := loadTokenFromSecret(ctx, r.client, &res); err != nil {
+		return res, err
 	}
 	return res, nil
 }
+
+// loadTokenFromSecret will load token from secret if exists
+// and set it to the source of the registry object
+func loadTokenFromSecret(ctx context.Context, cli client.Client, registry *Registry) error {
+	source := registry.GetTokenSource()
+	if source == nil {
+		return nil
+	}
+	secretName := source.GetTokenSecretRef()
+	if secretName == "" {
+		if source.GetToken() != "" {
+			// For backward compatibility, token can be stored in configmap directly.
+			// This is not secure, so we print a warning and recommend user to upgrade.
+			// The upgrade can be done by editing and saving the addon registry again.
+			fmt.Printf("Warning: addon registry %s is using an insecure token stored in ConfigMap. Please edit and save this addon registry again to migrate the token to a secret.\n", registry.Name)
+		}
+		return nil
+	}
+	secret := &v1.Secret{}
+	if err := cli.Get(ctx, types.NamespacedName{Namespace: velatypes.DefaultKubeVelaNS, Name: secretName}, secret); err != nil {
+		if apierrors.IsNotFound(err) {
+			// If the secret is not found, we consider the token is empty
+			return nil
+		}
+		return err
+	}
+	source.SetToken(string(secret.Data["token"]))
+	return nil
+}
diff --git a/pkg/addon/source.go b/pkg/addon/source.go
index 37c1a76f..7703500a 100644
--- a/pkg/addon/source.go
+++ b/pkg/addon/source.go
@@ -56,37 +56,32 @@ type Source interface {
 
 // GitAddonSource defines the information about the Git as addon source
 type GitAddonSource struct {
-	URL   string `json:"url,omitempty" validate:"required"`
-	Path  string `json:"path,omitempty"`
-	Token string `json:"token,omitempty"`
+	URL            string `json:"url,omitempty" validate:"required"`
+	Path           string `json:"path,omitempty"`
+	Token          string `json:"token,omitempty"`
+	TokenSecretRef string `json:"tokenSecretRef,omitempty"`
 }
 
-// GiteeAddonSource defines the information about the Gitee as addon source
-type GiteeAddonSource struct {
-	URL   string `json:"url,omitempty" validate:"required"`
-	Path  string `json:"path,omitempty"`
-	Token string `json:"token,omitempty"`
+// GetToken returns the token of the source
+func (g *GitAddonSource) GetToken() string {
+	return g.Token
 }
 
-// GitlabAddonSource defines the information about the Gitlab as addon source
-type GitlabAddonSource struct {
-	URL   string `json:"url,omitempty" validate:"required"`
-	Repo  string `json:"repo,omitempty" validate:"required"`
-	Path  string `json:"path,omitempty"`
-	Token string `json:"token,omitempty"`
+// SetToken set the token of the source
+func (g *GitAddonSource) SetToken(token string) {
+	g.Token = token
+	g.TokenSecretRef = ""
 }
 
-// HelmSource  defines the information about the helm repo addon source
-type HelmSource struct {
-	URL             string `json:"url,omitempty" validate:"required"`
-	InsecureSkipTLS bool   `json:"insecureSkipTLS,omitempty"`
-	Username        string `json:"username,omitempty"`
-	Password        string `json:"password,omitempty"`
+// SetTokenSecretRef set the token secret ref to the source
+func (g *GitAddonSource) SetTokenSecretRef(secretName string) {
+	g.Token = ""
+	g.TokenSecretRef = secretName
 }
 
-// SafeCopier is an interface to copy Struct without sensitive fields, such as Token, Username, Password
-type SafeCopier interface {
-	SafeCopy() interface{}
+// GetTokenSecretRef return the token secret ref of the source
+func (g *GitAddonSource) GetTokenSecretRef() string {
+	return g.TokenSecretRef
 }
 
 // SafeCopy hides field Token
@@ -95,22 +90,85 @@ func (g *GitAddonSource) SafeCopy() *GitAddonSource {
 		return nil
 	}
 	return &GitAddonSource{
-		URL:  g.URL,
-		Path: g.Path,
+		URL:            g.URL,
+		Path:           g.Path,
+		TokenSecretRef: g.TokenSecretRef,
 	}
 }
 
+// GiteeAddonSource defines the information about the Gitee as addon source
+type GiteeAddonSource struct {
+	URL            string `json:"url,omitempty" validate:"required"`
+	Path           string `json:"path,omitempty"`
+	Token          string `json:"token,omitempty"`
+	TokenSecretRef string `json:"tokenSecretRef,omitempty"`
+}
+
+// GetToken return the token of the source
+func (g *GiteeAddonSource) GetToken() string {
+	return g.Token
+}
+
+// SetToken set the token of the source
+func (g *GiteeAddonSource) SetToken(token string) {
+	g.Token = token
+	g.TokenSecretRef = ""
+}
+
+// SetTokenSecretRef set the token secret ref to the source
+func (g *GiteeAddonSource) SetTokenSecretRef(secretName string) {
+	g.Token = ""
+	g.TokenSecretRef = secretName
+}
+
+// GetTokenSecretRef return the token secret ref of the source
+func (g *GiteeAddonSource) GetTokenSecretRef() string {
+	return g.TokenSecretRef
+}
+
 // SafeCopy hides field Token
 func (g *GiteeAddonSource) SafeCopy() *GiteeAddonSource {
 	if g == nil {
 		return nil
 	}
 	return &GiteeAddonSource{
-		URL:  g.URL,
-		Path: g.Path,
+		URL:            g.URL,
+		Path:           g.Path,
+		TokenSecretRef: g.TokenSecretRef,
 	}
 }
 
+// GitlabAddonSource defines the information about Gitlab as an addon source
+type GitlabAddonSource struct {
+	URL            string `json:"url,omitempty" validate:"required"`
+	Repo           string `json:"repo,omitempty" validate:"required"`
+	Path           string `json:"path,omitempty"`
+	Token          string `json:"token,omitempty"`
+	TokenSecretRef string `json:"tokenSecretRef,omitempty"`
+}
+
+// GetToken return the token of the source
+func (g *GitlabAddonSource) GetToken() string {
+	return g.Token
+}
+
+// SetToken set the token of the source
+func (g *GitlabAddonSource) SetToken(token string) {
+	g.Token = token
+	g.TokenSecretRef = ""
+}
+
+// SetTokenSecretRef set the token secret ref to the source
+func (g *GitlabAddonSource) SetTokenSecretRef(secretName string) {
+	g.Token = ""
+	g.TokenSecretRef = secretName
+}
+
+// GetTokenSecretRef return the token secret ref of the source
+func (g *GitlabAddonSource) GetTokenSecretRef() string {
+	return g.TokenSecretRef
+}
+
 // SafeCopy hides field Token
 func (g *GitlabAddonSource) SafeCopy() *GitlabAddonSource {
 	if g == nil {
@@ -123,6 +181,19 @@ func (g *GitlabAddonSource) SafeCopy() *GitlabAddonSource {
 	}
 }
 
+// HelmSource  defines the information about the helm repo addon source
+type HelmSource struct {
+	URL             string `json:"url,omitempty" validate:"required"`
+	InsecureSkipTLS bool   `json:"insecureSkipTLS,omitempty"`
+	Username        string `json:"username,omitempty"`
+	Password        string `json:"password,omitempty"`
+}
+
+// SafeCopier is an interface to copy struct without sensitive fields, such as Token, Username, Password
+type SafeCopier interface {
+	SafeCopy() interface{}
+}
+
 // SafeCopy hides field Username, Password
 func (h *HelmSource) SafeCopy() *HelmSource {
 	if h == nil {
diff --git a/pkg/addon/utils.go b/pkg/addon/utils.go
index df12d15d..9da82373 100644
--- a/pkg/addon/utils.go
+++ b/pkg/addon/utils.go
@@ -465,7 +465,12 @@ func checkConflictDefs(ctx context.Context, k8sClient client.Client, defs []*uns
 			}
 			if owner.Name != appName {
 				// if addon not belong to an addon or addon name is another one, we should put them in result
-				res[checkDef.GetName()] = fmt.Sprintf("definition: %s in this addon already exist in %s \n", checkDef.GetName(), addon.AppName2Addon(appName))
+				addonName := addon.AppName2Addon(owner.Name)
+				// If owner.Name isn't an addon app name, show the owner's name directly as the addon name
+				if addonName == "" {
+					addonName = owner.Name
+				}
+				res[checkDef.GetName()] = fmt.Sprintf("definition: %s in this addon already exist in %s \n", checkDef.GetName(), addonName)
 			}
 		}
 		if err != nil && !errors2.IsNotFound(err) {
diff --git a/pkg/builtin/http/http.go b/pkg/builtin/http/http.go
index d58d3fe7..4b6edc8a 100644
--- a/pkg/builtin/http/http.go
+++ b/pkg/builtin/http/http.go
@@ -152,7 +152,7 @@ func parseHeaders(obj cue.Value, label string) (http.Header, error) {
 		if err != nil {
 			return nil, err
 		}
-		h.Add(iter.Label(), str)
+		h.Add(iter.Selector().Unquoted(), str)
 	}
 	return h, nil
 }
diff --git a/pkg/controller/core.oam.dev/oamruntime_controller.go b/pkg/controller/core.oam.dev/oamruntime_controller.go
index f89f17a2..04bd4c83 100644
--- a/pkg/controller/core.oam.dev/oamruntime_controller.go
+++ b/pkg/controller/core.oam.dev/oamruntime_controller.go
@@ -16,10 +16,6 @@ limitations under the License.
 
 package core_oam_dev
 
-import (
-	"github.com/spf13/pflag"
-)
-
 // Args args used by controller
 type Args struct {
 
@@ -47,17 +43,3 @@ type Args struct {
 	// IgnoreDefinitionWithoutControllerRequirement indicates that trait/component/workflowstep definition controller will not process the definition without 'definition.oam.dev/controller-version-require' annotation.
 	IgnoreDefinitionWithoutControllerRequirement bool
 }
-
-// AddFlags adds flags to the specified FlagSet
-func (a *Args) AddFlags(fs *pflag.FlagSet, c *Args) {
-	fs.IntVar(&a.RevisionLimit, "revision-limit", c.RevisionLimit,
-		"RevisionLimit is the maximum number of revisions that will be maintained. The default value is 50.")
-	fs.IntVar(&a.AppRevisionLimit, "application-revision-limit", c.AppRevisionLimit,
-		"application-revision-limit is the maximum number of application useless revisions that will be maintained, if the useless revisions exceed this number, older ones will be GCed first.The default value is 10.")
-	fs.IntVar(&a.DefRevisionLimit, "definition-revision-limit", c.DefRevisionLimit,
-		"definition-revision-limit is the maximum number of component/trait definition useless revisions that will be maintained, if the useless revisions exceed this number, older ones will be GCed first.The default value is 20.")
-	fs.BoolVar(&a.AutoGenWorkloadDefinition, "autogen-workload-definition", c.AutoGenWorkloadDefinition, "Automatic generated workloadDefinition which componentDefinition refers to.")
-	fs.IntVar(&a.ConcurrentReconciles, "concurrent-reconciles", c.ConcurrentReconciles, "concurrent-reconciles is the concurrent reconcile number of the controller. The default value is 4")
-	fs.BoolVar(&a.IgnoreAppWithoutControllerRequirement, "ignore-app-without-controller-version", c.IgnoreAppWithoutControllerRequirement, "If true, application controller will not process the app without 'app.oam.dev/controller-version-require' annotation")
-	fs.BoolVar(&a.IgnoreDefinitionWithoutControllerRequirement, "ignore-definition-without-controller-version", c.IgnoreDefinitionWithoutControllerRequirement, "If true, trait/component/workflowstep definition controller will not process the definition without 'definition.oam.dev/controller-version-require' annotation")
-}
diff --git a/pkg/cue/convert.go b/pkg/cue/convert.go
index 93dffd82..267b8d4d 100644
--- a/pkg/cue/convert.go
+++ b/pkg/cue/convert.go
@@ -47,8 +47,9 @@ func GetParameters(templateStr string) ([]types.Parameter, error) {
 		if iter.Selector().IsDefinition() {
 			continue
 		}
+		name := GetSelectorLabel(iter.Selector())
 		var param = types.Parameter{
-			Name:     iter.Label(),
+			Name:     name,
 			Required: !iter.IsOptional(),
 		}
 		val := iter.Value()
diff --git a/pkg/cue/definition/health/health.go b/pkg/cue/definition/health/health.go
index ebcbfd50..e7a3faab 100644
--- a/pkg/cue/definition/health/health.go
+++ b/pkg/cue/definition/health/health.go
@@ -27,6 +27,8 @@ import (
 	"github.com/kubevela/workflow/pkg/cue/model/value"
 	"github.com/pkg/errors"
 	"k8s.io/klog/v2"
+
+	velacue "github.com/oam-dev/kubevela/pkg/cue"
 )
 
 const (
@@ -143,7 +145,8 @@ func getStatusMap(templateContext map[string]interface{}, statusFields string, p
 		return templateContext, nil, errors.WithMessage(err, "get context fields")
 	}
 	for iter.Next() {
-		contextLabels = append(contextLabels, iter.Label())
+		label := velacue.GetSelectorLabel(iter.Selector())
+		contextLabels = append(contextLabels, label)
 	}
 
 	cueBuffer := runtimeContextBuff + "\n" + statusFields
@@ -160,7 +163,7 @@ func getStatusMap(templateContext map[string]interface{}, statusFields string, p
 
 outer:
 	for iter.Next() {
-		label := iter.Label()
+		label := velacue.GetSelectorLabel(iter.Selector())
 
 		if len(label) >= 32 {
 			klog.Warningf("status.details field label %s is too long, skipping", label)
diff --git a/pkg/cue/definition/template.go b/pkg/cue/definition/template.go
index b16e92a5..0a11760e 100644
--- a/pkg/cue/definition/template.go
+++ b/pkg/cue/definition/template.go
@@ -38,6 +38,7 @@ import (
 	"github.com/kubevela/workflow/pkg/cue/model/value"
 	"github.com/kubevela/workflow/pkg/cue/process"
 
+	velacue "github.com/oam-dev/kubevela/pkg/cue"
 	velaprocess "github.com/oam-dev/kubevela/pkg/cue/process"
 	"github.com/oam-dev/kubevela/pkg/cue/task"
 	"github.com/oam-dev/kubevela/pkg/oam"
@@ -139,7 +140,7 @@ func (wd *workloadDef) Complete(ctx process.Context, abstractTemplate string, pa
 			continue
 		}
 		other, err := model.NewOther(iter.Value())
-		name := iter.Label()
+		name := velacue.GetSelectorLabel(iter.Selector())
 		if err != nil {
 			return errors.WithMessagef(err, "invalid outputs(%s) of workload %s", name, wd.name)
 		}
@@ -272,7 +273,7 @@ func (td *traitDef) Complete(ctx process.Context, abstractTemplate string, param
 				continue
 			}
 			other, err := model.NewOther(iter.Value())
-			name := iter.Label()
+			name := velacue.GetSelectorLabel(iter.Selector())
 			if err != nil {
 				return errors.WithMessagef(err, "invalid outputs(resource=%s) of trait %s", name, td.name)
 			}
diff --git a/pkg/cue/utils.go b/pkg/cue/utils.go
new file mode 100644
index 00000000..88ca22e7
--- /dev/null
+++ b/pkg/cue/utils.go
@@ -0,0 +1,33 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package cue
+
+import "cuelang.org/go/cue"
+
+// GetSelectorLabel safely extracts a label from a CUE selector.
+// It uses String() by default to avoid panics on pattern parameter selectors,
+// and only uses Unquoted() when it's safe (i.e., for StringLabel with concrete names).
+// This prevents panics that would occur when calling Unquoted() on pattern constraints like [string]: T.
+func GetSelectorLabel(selector cue.Selector) string {
+	// Use String() as a safe default
+	label := selector.String()
+	// If it's a quoted string, unquote it safely
+	if selector.IsString() && selector.LabelType() == cue.StringLabel {
+		label = selector.Unquoted()
+	}
+	return label
+}
diff --git a/pkg/definition/definition.go b/pkg/definition/definition.go
index 2afe1dd1..cac7e22e 100644
--- a/pkg/definition/definition.go
+++ b/pkg/definition/definition.go
@@ -225,18 +225,25 @@ func (def *Definition) ToCUEString() (string, error) {
 	if err != nil {
 		return "", errors.Wrapf(err, "failed to parse template cue string")
 	}
+
+	// Extract imports before fix.File() clears them
+	importPaths := extractImportsFromFile(f)
+
 	f = fix.File(f)
-	var importDecls, templateDecls []ast.Decl
+	var templateDecls []ast.Decl
 	for _, decl := range f.Decls {
-		if importDecl, ok := decl.(*ast.ImportDecl); ok {
-			importDecls = append(importDecls, importDecl)
-		} else {
+		if _, ok := decl.(*ast.ImportDecl); !ok {
 			templateDecls = append(templateDecls, decl)
 		}
 	}
-	importString, err := encodeDeclsToString(importDecls)
-	if err != nil {
-		return "", errors.Wrapf(err, "failed to encode import decls")
+	var importString string
+	if len(importPaths) > 0 {
+		// Reconstruct import statements from extracted paths
+		var importLines []string
+		for _, importPath := range importPaths {
+			importLines = append(importLines, fmt.Sprintf("import %s", importPath))
+		}
+		importString = strings.Join(importLines, "\n") + "\n"
 	}
 	templateString, err = encodeDeclsToString(templateDecls)
 	if err != nil {
@@ -244,7 +251,12 @@ func (def *Definition) ToCUEString() (string, error) {
 	}
 	templateString = fmt.Sprintf("template: {\n%s}", templateString)
 
-	completeCUEString := importString + "\n" + metadataString + "\n" + templateString
+	var completeCUEString string
+	if importString != "" {
+		completeCUEString = importString + "\n" + metadataString + "\n" + templateString
+	} else {
+		completeCUEString = metadataString + "\n" + templateString
+	}
 	if completeCUEString, err = formatCUEString(completeCUEString); err != nil {
 		return "", errors.Wrapf(err, "failed to format cue format string")
 	}
@@ -647,17 +659,68 @@ func GetDefinitionDefaultSpec(kind string) map[string]interface{} {
 	return map[string]interface{}{}
 }
 
+// extractImportsFromFile extracts import paths from an AST file before fix.File() clears them.
+// This is necessary because fix.File() removes import declarations that are not directly used.
+// Returns a slice of import paths, where named imports are formatted as "name path".
+func extractImportsFromFile(f *ast.File) []string {
+	var importPaths []string
+	for _, decl := range f.Decls {
+		if importDecl, ok := decl.(*ast.ImportDecl); ok {
+			for _, spec := range importDecl.Specs {
+				if spec.Path != nil {
+					importPath := spec.Path.Value
+					if spec.Name != nil {
+						// Handle named imports
+						importPaths = append(importPaths, fmt.Sprintf("%s %s", spec.Name.Name, importPath))
+					} else {
+						importPaths = append(importPaths, importPath)
+					}
+				}
+			}
+		}
+	}
+	return importPaths
+}
+
 func formatCUEString(cueString string) (string, error) {
 	f, err := parser.ParseFile("-", cueString, parser.ParseComments)
 	if err != nil {
 		return "", errors.Wrapf(err, "failed to parse file during format cue string")
 	}
+
+	// Extract imports before fix.File() clears them
+	importPaths := extractImportsFromFile(f)
+
 	n := fix.File(f)
-	b, err := format.Node(n, format.Simplify())
-	if err != nil {
-		return "", errors.Wrapf(err, "failed to format node during formating cue string")
+
+	// Format only non-import declarations
+	var nonImportDecls []ast.Decl
+	for _, decl := range n.Decls {
+		if _, ok := decl.(*ast.ImportDecl); !ok {
+			nonImportDecls = append(nonImportDecls, decl)
+		}
 	}
-	return string(b), nil
+
+	var result strings.Builder
+
+	// Add imports first
+	if len(importPaths) > 0 {
+		for _, importPath := range importPaths {
+			result.WriteString(fmt.Sprintf("import %s\n", importPath))
+		}
+		result.WriteString("\n")
+	}
+
+	// Format and add other declarations
+	if len(nonImportDecls) > 0 {
+		b, err := format.Node(&ast.File{Decls: nonImportDecls}, format.Simplify())
+		if err != nil {
+			return "", errors.Wrapf(err, "failed to format node during formating cue string")
+		}
+		result.WriteString(string(b))
+	}
+
+	return result.String(), nil
 }
 
 func findAndDecodeFieldByLabel(slit *ast.StructLit, targetLabel string) (*ast.Field, error) {
diff --git a/pkg/workflow/providers/legacy/multicluster/multicluster.cue b/pkg/workflow/providers/legacy/multicluster/multicluster.cue
index 3988ed33..7b232a4a 100644
--- a/pkg/workflow/providers/legacy/multicluster/multicluster.cue
+++ b/pkg/workflow/providers/legacy/multicluster/multicluster.cue
@@ -103,7 +103,9 @@
 	envBindingPolicies: []
 	if inputs.policy == "" && loadPolicies.value != _|_ {
 		envBindingPolicies: [for k, v in loadPolicies.value if v.type == "env-binding" {k}]
-		policy_: envBindingPolicies[0]
+		if len(envBindingPolicies) > 0 {
+			policy_: envBindingPolicies[0]
+		}
 	}
 	if inputs.policy != "" {
 		policy_: inputs.policy
diff --git a/references/appfile/addon.go b/references/appfile/addon.go
index 5e88da79..448ba298 100644
--- a/references/appfile/addon.go
+++ b/references/appfile/addon.go
@@ -95,11 +95,7 @@ func ApplyTerraform(app *v1beta1.Application, k8sClient client.Client, ioStream
 				return nil, err
 			}
 
-			outputList := strings.Split(strings.ReplaceAll(string(outputs), " ", ""), "\n")
-			if outputList[len(outputList)-1] == "" {
-				outputList = outputList[:len(outputList)-1]
-			}
-			if err := generateSecretFromTerraformOutput(k8sClient, outputList, name, namespace); err != nil {
+			if err := generateSecretFromTerraformOutput(k8sClient, string(outputs), name, namespace); err != nil {
 				return nil, err
 			}
 		default:
@@ -135,21 +131,32 @@ func callTerraform(tfJSONDir string) ([]byte, error) {
 }
 
 // generateSecretFromTerraformOutput generates secret from Terraform output
-func generateSecretFromTerraformOutput(k8sClient client.Client, outputList []string, name, namespace string) error {
+func generateSecretFromTerraformOutput(k8sClient client.Client, rawOutput string, name, namespace string) error {
 	ctx := context.TODO()
-	err := k8sClient.Create(ctx, &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}})
-	if err == nil {
-		return fmt.Errorf("namespace %s doesn't exist", namespace)
+
+	// Check if namespace exists
+	var ns v1.Namespace
+	if err := k8sClient.Get(ctx, client.ObjectKey{Name: namespace}, &ns); err != nil {
+		if errors.IsNotFound(err) {
+			return fmt.Errorf("namespace %s doesn't exist", namespace)
+		}
+		return fmt.Errorf("failed to get namespace %s: %w", namespace, err)
 	}
-	var cmData = make(map[string]string, len(outputList))
+
+	var cmData = make(map[string]string)
+	outputList := strings.Split(rawOutput, "\n")
 	for _, i := range outputList {
-		line := strings.Split(i, "=")
+		if strings.TrimSpace(i) == "" {
+			continue
+		}
+		line := strings.SplitN(i, "=", 2)
 		if len(line) != 2 {
-			return fmt.Errorf("terraform output isn't in the right format")
+			return fmt.Errorf("terraform output isn't in the right format: %q", i)
 		}
 		k := strings.TrimSpace(line[0])
-		v := strings.TrimSpace(line[1])
-		if k != "" && v != "" {
+		// Terraform string outputs are quoted, remove them.
+		v := strings.Trim(strings.TrimSpace(line[1]), "\"")
+		if k != "" {
 			cmData[k] = v
 		}
 	}
diff --git a/references/cli/adopt-templates/default.cue b/references/cli/adopt-templates/default.cue
index cae5e499..0e06ae07 100644
--- a/references/cli/adopt-templates/default.cue
+++ b/references/cli/adopt-templates/default.cue
@@ -138,7 +138,7 @@ import (
 							metadata: name: r.metadata.name
 						}]
 					},
-					for r in resourceMap.workload + resourceMap.service {
+					for r in list.Concat([resourceMap.workload, resourceMap.service]) {
 						type: "k8s-objects"
 						name: _prefix + strings.ToLower("\(r.kind)-\(r.metadata.name)")
 						properties: objects: [{
diff --git a/references/cli/debug.go b/references/cli/debug.go
index 93debae1..ff8878c6 100644
--- a/references/cli/debug.go
+++ b/references/cli/debug.go
@@ -322,7 +322,7 @@ func (d *debugOpts) separateBySteps(v cue.Value, ioStreams cmdutil.IOStreams) er
 		if it.Value().IncompleteKind() == cue.BottomKind {
 			break
 		}
-		fieldName := it.Label()
+		fieldName := it.Selector().String()
 		fieldList = append(fieldList, fieldName)
 		fieldMap[fieldName] = it.Value()
 	}
diff --git a/references/cuegen/convert.go b/references/cuegen/convert.go
index 9469815e..4541b267 100644
--- a/references/cuegen/convert.go
+++ b/references/cuegen/convert.go
@@ -252,8 +252,7 @@ func (g *Generator) addFields(st *cueast.StructLit, x *gotypes.Struct, names map
 
 		// process field with optional tag(omitempty in json tag)
 		if opts.Optional {
-			f.Token = cuetoken.COLON
-			f.Optional = cuetoken.Blank.Pos()
+			f.Constraint = cuetoken.OPTION
 		}
 
 		makeComments(f, comments[i])
diff --git a/references/docgen/def-doc/trait/container-ports.eg.md b/references/docgen/def-doc/trait/container-ports.eg.md
index da00d019..bd46218b 100644
--- a/references/docgen/def-doc/trait/container-ports.eg.md
+++ b/references/docgen/def-doc/trait/container-ports.eg.md
@@ -1,5 +1,5 @@
 It's used to define Pod networks directly. hostPort routes the container's port directly to the port on the scheduled node, so that you can access the Pod through the host's IP plus hostPort.
-Don't specify a hostPort for a Pod unless it is absolutely necessary(run `DaemonSet` service). When you bind a Pod to a hostPort, it limits the number of places the Pod can be scheduled, because each <hostIP, hostPort, protocol> combination must be unique. If you don't specify the hostIP and protocol explicitly, Kubernetes will use 0.0.0.0 as the default hostIP and TCP as the default protocol.
+Don't specify a hostPort for a Pod unless it is absolutely necessary(run `DaemonSet` service). When you bind a Pod to a hostPort, it limits the number of places the Pod can be scheduled, because each `<hostIP, hostPort, protocol>` combination must be unique. If you don't specify the hostIP and protocol explicitly, Kubernetes will use 0.0.0.0 as the default hostIP and TCP as the default protocol.
 If you explicitly need to expose a Pod's port on the node, consider using `expose` or `gateway` trait, or exposeType and ports parameter of `webservice` component before resorting to `container-ports` trait.
 ```yaml
 apiVersion: core.oam.dev/v1beta1
diff --git a/references/docgen/provider.go b/references/docgen/provider.go
index 16815b87..fa806915 100644
--- a/references/docgen/provider.go
+++ b/references/docgen/provider.go
@@ -27,6 +27,8 @@ import (
 	"cuelang.org/go/cue"
 	"cuelang.org/go/cue/cuecontext"
 	"golang.org/x/sync/errgroup"
+
+	velacue "github.com/oam-dev/kubevela/pkg/cue"
 )
 
 // GenerateProvidersMarkdown generates markdown documentation for providers.
@@ -99,8 +101,9 @@ func GenerateProviderMarkdown(provider io.Reader, w io.Writer) error {
 			pkg = t
 		}
 
-		// header
-		fmt.Fprintf(docs, "## %s\n", iter.Label())
+		// header - handle both string and non-string selectors
+		selectorStr := velacue.GetSelectorLabel(iter.Selector())
+		fmt.Fprintf(docs, "## %s\n", selectorStr)
 
 		doc, _, err := ref.parseParameters("", item.LookupPath(cue.ParsePath(paramsKey)), "*Params*", 0, true)
 		if err != nil {
diff --git a/vela-templates/definitions/deprecated/ingress-1-20.cue b/vela-templates/definitions/deprecated/ingress-1-20.cue
index 5108b557..05c93fbf 100644
--- a/vela-templates/definitions/deprecated/ingress-1-20.cue
+++ b/vela-templates/definitions/deprecated/ingress-1-20.cue
@@ -14,11 +14,16 @@
 				  message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + "'\n"
 				}
 				if len(igs) > 0 {
+				  let rules = context.outputs.ingress.spec.rules
+				  host: *"" | string
+				  if rules != _|_ if len(rules) > 0 if rules[0].host != _|_ {
+					  host: rules[0].host
+				  }
 				  if igs[0].ip != _|_ {
-					  message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + igs[0].ip
+					  message: "Visiting URL: " + host + ", IP: " + igs[0].ip
 				  }
 				  if igs[0].ip == _|_ {
-					  message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host
+					  message: "Visiting URL: " + host
 				  }
 				}
 				"""#
diff --git a/vela-templates/definitions/deprecated/ingress.cue b/vela-templates/definitions/deprecated/ingress.cue
index 74cbe27b..93bce4b2 100644
--- a/vela-templates/definitions/deprecated/ingress.cue
+++ b/vela-templates/definitions/deprecated/ingress.cue
@@ -14,11 +14,16 @@ ingress: {
 					message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + "'\n"
 				}
 				if len(igs) > 0 {
+					let rules = context.outputs.ingress.spec.rules
+					host: *"" | string
+					if rules != _|_ if len(rules) > 0 if rules[0].host != _|_ {
+						host: rules[0].host
+					}
 					if igs[0].ip != _|_ {
-						message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + igs[0].ip
+						message: "Visiting URL: " + host + ", IP: " + igs[0].ip
 					}
 					if igs[0].ip == _|_ {
-						message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host
+						message: "Visiting URL: " + host
 					}
 				}
 				"""#
diff --git a/vela-templates/definitions/internal/component/cron-task.cue b/vela-templates/definitions/internal/component/cron-task.cue
index 93a575fe..a0e71480 100644
--- a/vela-templates/definitions/internal/component/cron-task.cue
+++ b/vela-templates/definitions/internal/component/cron-task.cue
@@ -1,3 +1,5 @@
+import "list"
+
 "cron-task": {
 	type: "component"
 	annotations: {}
@@ -125,7 +127,7 @@ template: {
 			},
 		] | []
 	}
-	volumesList: volumesArray.pvc + volumesArray.configMap + volumesArray.secret + volumesArray.emptyDir + volumesArray.hostPath
+	volumesList: list.Concat([volumesArray.pvc, volumesArray.configMap, volumesArray.secret, volumesArray.emptyDir, volumesArray.hostPath])
 	deDupVolumesArray: [
 		for val in [
 			for i, vi in volumesList {
diff --git a/vela-templates/definitions/internal/component/k8s-objects.cue b/vela-templates/definitions/internal/component/k8s-objects.cue
index d9a2a447..a9b61f48 100644
--- a/vela-templates/definitions/internal/component/k8s-objects.cue
+++ b/vela-templates/definitions/internal/component/k8s-objects.cue
@@ -6,7 +6,12 @@
 	attributes: workload: type: "autodetects.core.oam.dev"
 }
 template: {
-	output: parameter.objects[0]
+	output: {
+		if len(parameter.objects) > 0 {
+			parameter.objects[0]
+		}
+		...
+	}
 
 	outputs: {
 		for i, v in parameter.objects {
diff --git a/vela-templates/definitions/internal/trait/expose.cue b/vela-templates/definitions/internal/trait/expose.cue
index 281640df..528fb57a 100644
--- a/vela-templates/definitions/internal/trait/expose.cue
+++ b/vela-templates/definitions/internal/trait/expose.cue
@@ -13,21 +13,17 @@ expose: {
 		appliesToWorkloads: ["deployments.apps", "statefulsets.apps"]
 		status: {
 			customStatus: #"""
-				message: *"" | string
 				service: context.outputs.service
+				message: *"" | string
 				if service.spec.type == "ClusterIP" {
 					message: "ClusterIP: \(service.spec.clusterIP)"
 				}
 				if service.spec.type == "LoadBalancer" {
 					status: service.status
 					isHealth: *false | bool
+					message: *"ExternalIP: Pending" | string
 					if status != _|_ if status.loadBalancer != _|_ if status.loadBalancer.ingress != _|_ if len(status.loadBalancer.ingress) > 0 if status.loadBalancer.ingress[0].ip != _|_ {
 						isHealth: true
-					}
-					if !isHealth {
-						message: "ExternalIP: Pending"
-					}
-					if isHealth {
 						message: "ExternalIP: \(status.loadBalancer.ingress[0].ip)"
 					}
 				}
diff --git a/vela-templates/definitions/internal/trait/gateway.cue b/vela-templates/definitions/internal/trait/gateway.cue
index 772d252a..955a6608 100644
--- a/vela-templates/definitions/internal/trait/gateway.cue
+++ b/vela-templates/definitions/internal/trait/gateway.cue
@@ -16,13 +16,17 @@ gateway: {
 				  if parameter.name == _|_ { "" }
 				}
 				let ingressMetaName = context.name + nameSuffix
-				let ig  = [for i in context.outputs if (i.kind == "Ingress") && (i.metadata.name == ingressMetaName) {i}][0]
+				let igList = [for i in context.outputs if (i.kind == "Ingress") && (i.metadata.name == ingressMetaName) {i}]
+				ig: *_|_ | _
+				if len(igList) > 0 {
+				  ig: igList[0]
+				}
 				igs: *{} | {}
-				if ig != _|_ if ig.status != _|_ if ig.status.loadbalancer != _|_ {
+				if ig != _|_ if ig.status != _|_ if ig.status.loadbalancer != _|_ if len(ig.status.loadbalancer.ingress) > 0 {
 				  igs: ig.status.loadbalancer.ingress[0]
 				}
 				igr: *{} | {}
-				if ig != _|_ if ig.spec != _|_  {
+				if ig != _|_ if ig.spec != _|_ if len(ig.spec.rules) > 0 {
 				  igr: ig.spec.rules[0]
 				}
 				if igs == _|_ {
diff --git a/vela-templates/definitions/internal/trait/pure-ingress.cue b/vela-templates/definitions/internal/trait/pure-ingress.cue
index adc710b4..84480f08 100644
--- a/vela-templates/definitions/internal/trait/pure-ingress.cue
+++ b/vela-templates/definitions/internal/trait/pure-ingress.cue
@@ -10,11 +10,16 @@
 					message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + " --route'\n"
 				}
 				if len(igs) > 0 {
+					let rules = context.outputs.ingress.spec.rules
+					host: *"" | string
+					if rules != _|_ if len(rules) > 0 if rules[0].host != _|_ {
+						host: rules[0].host
+					}
 					if igs[0].ip != _|_ {
-						message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + igs[0].ip
+						message: "Visiting URL: " + host + ", IP: " + igs[0].ip
 					}
 					if igs[0].ip == _|_ {
-						message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host
+						message: "Visiting URL: " + host
 					}
 				}
 				"""#
diff --git a/vela-templates/definitions/internal/workflowstep/apply-terraform-provider.cue b/vela-templates/definitions/internal/workflowstep/apply-terraform-provider.cue
index 52bb95de..09f31af6 100644
--- a/vela-templates/definitions/internal/workflowstep/apply-terraform-provider.cue
+++ b/vela-templates/definitions/internal/workflowstep/apply-terraform-provider.cue
@@ -86,9 +86,9 @@ template: {
 		}
 	}
 	providerBasic: {
-		accessKey: string
-		secretKey: string
-		region:    string
+		accessKey!: string
+		secretKey!: string
+		region!:    string
 	}
 	#AlibabaProvider: {
 		providerBasic
@@ -140,5 +140,5 @@ template: {
 		type:       "ucloud"
 		name:       *"ucloud-provider" | string
 	}
-	parameter: *#AlibabaProvider | #AWSProvider | #AzureProvider | #BaiduProvider | #ECProvider | #GCPProvider | #TencentProvider | #UCloudProvider
+	parameter: #AlibabaProvider | #AWSProvider | #AzureProvider | #BaiduProvider | #ECProvider | #GCPProvider | #TencentProvider | #UCloudProvider
 }
diff --git a/vela-templates/definitions/internal/workflowstep/vela-cli.cue b/vela-templates/definitions/internal/workflowstep/vela-cli.cue
index 0af351f6..c43f3bd5 100644
--- a/vela-templates/definitions/internal/workflowstep/vela-cli.cue
+++ b/vela-templates/definitions/internal/workflowstep/vela-cli.cue
@@ -133,8 +133,6 @@ template: {
 	}
 
 	parameter: {
-		// +usage=Specify the name of the addon.
-		addonName: string
 		// +usage=Specify the vela command
 		command: [...string]
 		// +usage=Specify the image



Test patch:
diff --git a/cmd/core/app/options/options_test.go b/cmd/core/app/options/options_test.go
index 12557741..04b481f4 100644
--- a/cmd/core/app/options/options_test.go
+++ b/cmd/core/app/options/options_test.go
@@ -20,104 +20,915 @@ import (
 	"testing"
 	"time"
 
-	"github.com/google/go-cmp/cmp"
 	"github.com/kubevela/pkg/cue/cuex"
+	wfTypes "github.com/kubevela/workflow/pkg/types"
 	"github.com/spf13/pflag"
 	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
 
-	oamcontroller "github.com/oam-dev/kubevela/pkg/controller/core.oam.dev"
+	commonconfig "github.com/oam-dev/kubevela/pkg/controller/common"
+	"github.com/oam-dev/kubevela/pkg/oam"
+	"github.com/oam-dev/kubevela/pkg/resourcekeeper"
 )
 
-func TestCoreOptions_Flags(t *testing.T) {
+func TestNewCoreOptions_DefaultValues(t *testing.T) {
+	opt := NewCoreOptions()
+
+	// Test Server defaults
+	assert.Equal(t, ":9440", opt.Server.HealthAddr)
+	assert.Equal(t, "Local", opt.Server.StorageDriver)
+	assert.Equal(t, false, opt.Server.EnableLeaderElection)
+	assert.Equal(t, "", opt.Server.LeaderElectionNamespace)
+	assert.Equal(t, 15*time.Second, opt.Server.LeaseDuration)
+	assert.Equal(t, 10*time.Second, opt.Server.RenewDeadline)
+	assert.Equal(t, 2*time.Second, opt.Server.RetryPeriod)
+
+	// Test Webhook defaults
+	assert.Equal(t, false, opt.Webhook.UseWebhook)
+	assert.Equal(t, "/k8s-webhook-server/serving-certs", opt.Webhook.CertDir)
+	assert.Equal(t, 9443, opt.Webhook.WebhookPort)
+
+	// Test Observability defaults
+	assert.Equal(t, ":8080", opt.Observability.MetricsAddr)
+	assert.Equal(t, false, opt.Observability.LogDebug)
+	assert.Equal(t, "", opt.Observability.LogFilePath)
+	assert.Equal(t, uint64(1024), opt.Observability.LogFileMaxSize)
+
+	// Test Kubernetes defaults
+	assert.Equal(t, 10*time.Hour, opt.Kubernetes.InformerSyncPeriod)
+	assert.Equal(t, float64(50), opt.Kubernetes.QPS)
+	assert.Equal(t, 100, opt.Kubernetes.Burst)
+
+	// Test MultiCluster defaults
+	assert.Equal(t, false, opt.MultiCluster.EnableClusterGateway)
+	assert.Equal(t, false, opt.MultiCluster.EnableClusterMetrics)
+	assert.Equal(t, 15*time.Second, opt.MultiCluster.ClusterMetricsInterval)
+
+	// Test CUE defaults
+	assert.NotNil(t, opt.CUE)
+
+	// Test Application defaults
+	assert.Equal(t, 5*time.Minute, opt.Application.ReSyncPeriod)
+
+	// Test OAM defaults
+	assert.Equal(t, "vela-system", opt.OAM.SystemDefinitionNamespace)
+
+	// Test Performance defaults
+	assert.Equal(t, false, opt.Performance.PerfEnabled)
+
+	// Test Controller defaults
+	assert.Equal(t, 50, opt.Controller.RevisionLimit)
+	assert.Equal(t, 10, opt.Controller.AppRevisionLimit)
+	assert.Equal(t, 20, opt.Controller.DefRevisionLimit)
+	assert.Equal(t, true, opt.Controller.AutoGenWorkloadDefinition)
+	assert.Equal(t, 4, opt.Controller.ConcurrentReconciles)
+	assert.Equal(t, false, opt.Controller.IgnoreAppWithoutControllerRequirement)
+	assert.Equal(t, false, opt.Controller.IgnoreDefinitionWithoutControllerRequirement)
+
+	// Test Workflow defaults
+	assert.Equal(t, 60, opt.Workflow.MaxWaitBackoffTime)
+	assert.Equal(t, 300, opt.Workflow.MaxFailedBackoffTime)
+	assert.Equal(t, 10, opt.Workflow.MaxStepErrorRetryTimes)
+
+	// Test Resource defaults
+	assert.Equal(t, 10, opt.Resource.MaxDispatchConcurrent)
+
+	// Ensure all config modules are initialized
+	assert.NotNil(t, opt.Admission)
+	assert.NotNil(t, opt.Client)
+	assert.NotNil(t, opt.Reconcile)
+	assert.NotNil(t, opt.Sharding)
+	assert.NotNil(t, opt.Feature)
+	assert.NotNil(t, opt.Profiling)
+	assert.NotNil(t, opt.KLog)
+	assert.NotNil(t, opt.Controller)
+}
+
+func TestCoreOptions_FlagsCompleteSet(t *testing.T) {
 	fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
-	opt := &CoreOptions{
-		ControllerArgs: &oamcontroller.Args{},
-	}
+	opt := NewCoreOptions()
 
 	for _, f := range opt.Flags().FlagSets {
 		fs.AddFlagSet(f)
 	}
 
 	args := []string{
-		"--application-re-sync-period=5s",
-		"--cluster-metrics-interval=5s",
-		"--enable-cluster-gateway=true",
-		"--enable-cluster-metrics=true",
-		"--enable-leader-election=true",
+		// Server flags
 		"--health-addr=/healthz",
-		"--informer-sync-period=3s",
-		"--kube-api-burst=500",
-		"--kube-api-qps=200",
-		"--leader-election-lease-duration=3s",
+		"--storage-driver=MongoDB",
+		"--enable-leader-election=true",
 		"--leader-election-namespace=test-namespace",
+		"--leader-election-lease-duration=3s",
 		"--leader-election-renew-deadline=5s",
 		"--leader-election-retry-period=3s",
-		"--log-debug=true",
-		"--log-file-max-size=50",
-		"--log-file-path=/path/to/log",
-		"--max-dispatch-concurrent=5",
-		"--max-workflow-failed-backoff-time=30",
-		"--max-workflow-step-error-retry-times=5",
-		"--max-workflow-wait-backoff-time=5",
-		"--metrics-addr=/metrics",
-		"--perf-enabled=true",
+		// Webhook flags
 		"--use-webhook=true",
 		"--webhook-cert-dir=/path/to/cert",
 		"--webhook-port=8080",
+		// Observability flags
+		"--metrics-addr=/metrics",
+		"--log-debug=true",
+		"--log-file-path=/path/to/log",
+		"--log-file-max-size=50",
+		// Kubernetes flags
+		"--informer-sync-period=3s",
+		"--kube-api-qps=200",
+		"--kube-api-burst=500",
+		// MultiCluster flags
+		"--enable-cluster-gateway=true",
+		"--enable-cluster-metrics=true",
+		"--cluster-metrics-interval=5s",
+		// CUE flags
+		"--enable-external-package-for-default-compiler=true",
+		"--enable-external-package-watch-for-default-compiler=true",
+		// Application flags
+		"--application-re-sync-period=5s",
+		// OAM flags
+		"--system-definition-namespace=custom-namespace",
+		// Performance flags
+		"--perf-enabled=true",
+		// Controller flags
+		"--revision-limit=100",
+		"--application-revision-limit=20",
+		"--definition-revision-limit=30",
+		"--autogen-workload-definition=false",
+		"--concurrent-reconciles=8",
+		"--ignore-app-without-controller-version=true",
+		"--ignore-definition-without-controller-version=true",
+		// Workflow flags
+		"--max-workflow-wait-backoff-time=30",
+		"--max-workflow-failed-backoff-time=150",
+		"--max-workflow-step-error-retry-times=5",
+		// Resource flags
+		"--max-dispatch-concurrent=5",
 	}
 
-	if err := fs.Parse(args); err != nil {
-		t.Errorf("Failed to parse args: %v", err)
+	err := fs.Parse(args)
+	require.NoError(t, err)
+
+	// Verify Server flags
+	assert.Equal(t, "/healthz", opt.Server.HealthAddr)
+	assert.Equal(t, "MongoDB", opt.Server.StorageDriver)
+	assert.Equal(t, true, opt.Server.EnableLeaderElection)
+	assert.Equal(t, "test-namespace", opt.Server.LeaderElectionNamespace)
+	assert.Equal(t, 3*time.Second, opt.Server.LeaseDuration)
+	assert.Equal(t, 5*time.Second, opt.Server.RenewDeadline)
+	assert.Equal(t, 3*time.Second, opt.Server.RetryPeriod)
+
+	// Verify Webhook flags
+	assert.Equal(t, true, opt.Webhook.UseWebhook)
+	assert.Equal(t, "/path/to/cert", opt.Webhook.CertDir)
+	assert.Equal(t, 8080, opt.Webhook.WebhookPort)
+
+	// Verify Observability flags
+	assert.Equal(t, "/metrics", opt.Observability.MetricsAddr)
+	assert.Equal(t, true, opt.Observability.LogDebug)
+	assert.Equal(t, "/path/to/log", opt.Observability.LogFilePath)
+	assert.Equal(t, uint64(50), opt.Observability.LogFileMaxSize)
+
+	// Verify Kubernetes flags
+	assert.Equal(t, 3*time.Second, opt.Kubernetes.InformerSyncPeriod)
+	assert.Equal(t, float64(200), opt.Kubernetes.QPS)
+	assert.Equal(t, 500, opt.Kubernetes.Burst)
+
+	// Verify MultiCluster flags
+	assert.Equal(t, true, opt.MultiCluster.EnableClusterGateway)
+	assert.Equal(t, true, opt.MultiCluster.EnableClusterMetrics)
+	assert.Equal(t, 5*time.Second, opt.MultiCluster.ClusterMetricsInterval)
+
+	// Verify CUE flags
+	assert.True(t, opt.CUE.EnableExternalPackage)
+	assert.True(t, opt.CUE.EnableExternalPackageWatch)
+
+	// Verify Application flags
+	assert.Equal(t, 5*time.Second, opt.Application.ReSyncPeriod)
+
+	// Verify OAM flags
+	assert.Equal(t, "custom-namespace", opt.OAM.SystemDefinitionNamespace)
+
+	// Verify Performance flags
+	assert.Equal(t, true, opt.Performance.PerfEnabled)
+
+	// Verify Controller flags
+	assert.Equal(t, 100, opt.Controller.RevisionLimit)
+	assert.Equal(t, 20, opt.Controller.AppRevisionLimit)
+	assert.Equal(t, 30, opt.Controller.DefRevisionLimit)
+	assert.Equal(t, false, opt.Controller.AutoGenWorkloadDefinition)
+	assert.Equal(t, 8, opt.Controller.ConcurrentReconciles)
+	assert.Equal(t, true, opt.Controller.IgnoreAppWithoutControllerRequirement)
+	assert.Equal(t, true, opt.Controller.IgnoreDefinitionWithoutControllerRequirement)
+
+	// Verify Workflow flags
+	assert.Equal(t, 30, opt.Workflow.MaxWaitBackoffTime)
+	assert.Equal(t, 150, opt.Workflow.MaxFailedBackoffTime)
+	assert.Equal(t, 5, opt.Workflow.MaxStepErrorRetryTimes)
+
+	// Verify Resource flags
+	assert.Equal(t, 5, opt.Resource.MaxDispatchConcurrent)
+}
+
+func TestCuexOptions_SyncToGlobals(t *testing.T) {
+	// Reset globals
+	cuex.EnableExternalPackageForDefaultCompiler = false
+	cuex.EnableExternalPackageWatchForDefaultCompiler = false
+
+	opts := NewCoreOptions()
+	fss := opts.Flags()
+
+	args := []string{
+		"--enable-external-package-for-default-compiler=true",
+		"--enable-external-package-watch-for-default-compiler=true",
 	}
 
-	expected := &CoreOptions{
-		UseWebhook:              true,
-		CertDir:                 "/path/to/cert",
-		WebhookPort:             8080,
-		MetricsAddr:             "/metrics",
-		EnableLeaderElection:    true,
-		LeaderElectionNamespace: "test-namespace",
-		LogFilePath:             "/path/to/log",
-		LogFileMaxSize:          50,
-		LogDebug:                true,
-		ControllerArgs:          &oamcontroller.Args{},
-		HealthAddr:              "/healthz",
-		StorageDriver:           "",
-		InformerSyncPeriod:      3 * time.Second,
-		QPS:                     200,
-		Burst:                   500,
-		LeaseDuration:           3 * time.Second,
-		RenewDeadLine:           5 * time.Second,
-		RetryPeriod:             3 * time.Second,
-		EnableClusterGateway:    true,
-		EnableClusterMetrics:    true,
-		ClusterMetricsInterval:  5 * time.Second,
+	err := fss.FlagSet("cue").Parse(args)
+	require.NoError(t, err)
+
+	// Before sync, globals should still be false
+	assert.False(t, cuex.EnableExternalPackageForDefaultCompiler)
+	assert.False(t, cuex.EnableExternalPackageWatchForDefaultCompiler)
+
+	// After sync, globals should be updated
+	opts.CUE.SyncToCUEGlobals()
+	assert.True(t, cuex.EnableExternalPackageForDefaultCompiler)
+	assert.True(t, cuex.EnableExternalPackageWatchForDefaultCompiler)
+}
+
+func TestWorkflowOptions_SyncToGlobals(t *testing.T) {
+	// Store original values
+	origWait := wfTypes.MaxWorkflowWaitBackoffTime
+	origFailed := wfTypes.MaxWorkflowFailedBackoffTime
+	origRetry := wfTypes.MaxWorkflowStepErrorRetryTimes
+
+	// Restore after test
+	defer func() {
+		wfTypes.MaxWorkflowWaitBackoffTime = origWait
+		wfTypes.MaxWorkflowFailedBackoffTime = origFailed
+		wfTypes.MaxWorkflowStepErrorRetryTimes = origRetry
+	}()
+
+	opts := NewCoreOptions()
+	fss := opts.Flags()
+
+	args := []string{
+		"--max-workflow-wait-backoff-time=120",
+		"--max-workflow-failed-backoff-time=600",
+		"--max-workflow-step-error-retry-times=20",
 	}
 
-	if !cmp.Equal(opt, expected, cmp.AllowUnexported(CoreOptions{})) {
-		t.Errorf("Flags() diff: %v", cmp.Diff(opt, expected, cmp.AllowUnexported(CoreOptions{})))
+	err := fss.FlagSet("workflow").Parse(args)
+	require.NoError(t, err)
+
+	// Verify struct fields are updated
+	assert.Equal(t, 120, opts.Workflow.MaxWaitBackoffTime)
+	assert.Equal(t, 600, opts.Workflow.MaxFailedBackoffTime)
+	assert.Equal(t, 20, opts.Workflow.MaxStepErrorRetryTimes)
+
+	// After sync, globals should be updated
+	opts.Workflow.SyncToWorkflowGlobals()
+	assert.Equal(t, 120, wfTypes.MaxWorkflowWaitBackoffTime)
+	assert.Equal(t, 600, wfTypes.MaxWorkflowFailedBackoffTime)
+	assert.Equal(t, 20, wfTypes.MaxWorkflowStepErrorRetryTimes)
+}
+
+func TestOAMOptions_SyncToGlobals(t *testing.T) {
+	// Store original value
+	origNamespace := oam.SystemDefinitionNamespace
+
+	// Restore after test
+	defer func() {
+		oam.SystemDefinitionNamespace = origNamespace
+	}()
+
+	opts := NewCoreOptions()
+	fss := opts.Flags()
+
+	args := []string{
+		"--system-definition-namespace=custom-system",
 	}
+
+	err := fss.FlagSet("oam").Parse(args)
+	require.NoError(t, err)
+
+	// Verify struct field is updated
+	assert.Equal(t, "custom-system", opts.OAM.SystemDefinitionNamespace)
+
+	// After sync, global should be updated
+	opts.OAM.SyncToOAMGlobals()
+	assert.Equal(t, "custom-system", oam.SystemDefinitionNamespace)
 }
 
-func TestCuexOptions_Flags(t *testing.T) {
-	pflag.NewFlagSet("test", pflag.ContinueOnError)
-	cuex.EnableExternalPackageForDefaultCompiler = false
-	cuex.EnableExternalPackageWatchForDefaultCompiler = false
+func TestPerformanceOptions_SyncToGlobals(t *testing.T) {
+	// Store original value
+	origPerf := commonconfig.PerfEnabled
+
+	// Restore after test
+	defer func() {
+		commonconfig.PerfEnabled = origPerf
+	}()
+
+	opts := NewCoreOptions()
+	fss := opts.Flags()
 
-	opts := &CoreOptions{
-		ControllerArgs: &oamcontroller.Args{},
+	args := []string{
+		"--perf-enabled=true",
 	}
+
+	err := fss.FlagSet("performance").Parse(args)
+	require.NoError(t, err)
+
+	// Verify struct field is updated
+	assert.Equal(t, true, opts.Performance.PerfEnabled)
+
+	// After sync, global should be updated
+	opts.Performance.SyncToPerformanceGlobals()
+	assert.True(t, commonconfig.PerfEnabled)
+}
+
+func TestApplicationOptions_SyncToGlobals(t *testing.T) {
+	// Store original value
+	origPeriod := commonconfig.ApplicationReSyncPeriod
+
+	// Restore after test
+	defer func() {
+		commonconfig.ApplicationReSyncPeriod = origPeriod
+	}()
+
+	opts := NewCoreOptions()
 	fss := opts.Flags()
 
 	args := []string{
+		"--application-re-sync-period=10m",
+	}
+
+	err := fss.FlagSet("application").Parse(args)
+	require.NoError(t, err)
+
+	// Verify struct field is updated
+	assert.Equal(t, 10*time.Minute, opts.Application.ReSyncPeriod)
+
+	// After sync, global should be updated
+	opts.Application.SyncToApplicationGlobals()
+	assert.Equal(t, 10*time.Minute, commonconfig.ApplicationReSyncPeriod)
+}
+
+func TestResourceOptions_SyncToGlobals(t *testing.T) {
+	// Store original value
+	origDispatch := resourcekeeper.MaxDispatchConcurrent
+
+	// Restore after test
+	defer func() {
+		resourcekeeper.MaxDispatchConcurrent = origDispatch
+	}()
+
+	opts := NewCoreOptions()
+	fss := opts.Flags()
+
+	args := []string{
+		"--max-dispatch-concurrent=25",
+	}
+
+	err := fss.FlagSet("resource").Parse(args)
+	require.NoError(t, err)
+
+	// Verify struct field is updated
+	assert.Equal(t, 25, opts.Resource.MaxDispatchConcurrent)
+
+	// After sync, global should be updated
+	opts.Resource.SyncToResourceGlobals()
+	assert.Equal(t, 25, resourcekeeper.MaxDispatchConcurrent)
+}
+
+func TestCoreOptions_InvalidValues(t *testing.T) {
+	tests := []struct {
+		name        string
+		args        []string
+		expectError bool
+		errorMsg    string
+	}{
+		{
+			name: "invalid boolean value",
+			args: []string{
+				"--enable-leader-election=notabool",
+			},
+			expectError: true,
+			errorMsg:    "invalid argument",
+		},
+		{
+			name: "invalid duration value",
+			args: []string{
+				"--leader-election-lease-duration=notaduration",
+			},
+			expectError: true,
+			errorMsg:    "invalid argument",
+		},
+		{
+			name: "invalid int value",
+			args: []string{
+				"--webhook-port=notanint",
+			},
+			expectError: true,
+			errorMsg:    "invalid argument",
+		},
+		{
+			name: "invalid float value",
+			args: []string{
+				"--kube-api-qps=notafloat",
+			},
+			expectError: true,
+			errorMsg:    "invalid argument",
+		},
+		{
+			name: "invalid uint64 value",
+			args: []string{
+				"--log-file-max-size=-100",
+			},
+			expectError: true,
+			errorMsg:    "invalid argument",
+		},
+		{
+			name: "unknown flag",
+			args: []string{
+				"--unknown-flag=value",
+			},
+			expectError: true,
+			errorMsg:    "unknown flag",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
+			opt := NewCoreOptions()
+
+			for _, f := range opt.Flags().FlagSets {
+				fs.AddFlagSet(f)
+			}
+
+			err := fs.Parse(tt.args)
+			if tt.expectError {
+				assert.Error(t, err)
+				assert.Contains(t, err.Error(), tt.errorMsg)
+			} else {
+				assert.NoError(t, err)
+			}
+		})
+	}
+}
+
+func TestCoreOptions_PartialConfiguration(t *testing.T) {
+	// Test that partial configuration works correctly
+	// and doesn't override other defaults
+	fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
+	opt := NewCoreOptions()
+
+	for _, f := range opt.Flags().FlagSets {
+		fs.AddFlagSet(f)
+	}
+
+	// Only set a few flags
+	args := []string{
+		"--enable-leader-election=true",
+		"--log-debug=true",
+		"--perf-enabled=true",
+	}
+
+	err := fs.Parse(args)
+	require.NoError(t, err)
+
+	// Check that specified flags are updated
+	assert.Equal(t, true, opt.Server.EnableLeaderElection)
+	assert.Equal(t, true, opt.Observability.LogDebug)
+	assert.Equal(t, true, opt.Performance.PerfEnabled)
+
+	// Check that unspecified flags retain defaults
+	assert.Equal(t, ":9440", opt.Server.HealthAddr)
+	assert.Equal(t, "Local", opt.Server.StorageDriver)
+	assert.Equal(t, false, opt.Webhook.UseWebhook)
+	assert.Equal(t, ":8080", opt.Observability.MetricsAddr)
+	assert.Equal(t, 10*time.Hour, opt.Kubernetes.InformerSyncPeriod)
+	assert.Equal(t, 10, opt.Resource.MaxDispatchConcurrent)
+}
+
+func TestCoreOptions_FlagSetsOrganization(t *testing.T) {
+	opt := NewCoreOptions()
+	fss := opt.Flags()
+
+	// Verify that all expected flag sets are created
+	expectedFlagSets := []string{
+		"server",
+		"webhook",
+		"observability",
+		"kubernetes",
+		"multicluster",
+		"cue",
+		"application",
+		"oam",
+		"performance",
+		"admission",
+		"resource",
+		"workflow",
+		"controller",
+		"client",
+		"reconcile",
+		"sharding",
+		"feature",
+		"profiling",
+		"klog",
+	}
+
+	for _, name := range expectedFlagSets {
+		fs := fss.FlagSet(name)
+		assert.NotNil(t, fs, "FlagSet %s should exist", name)
+	}
+}
+
+func TestCoreOptions_FlagHelp(t *testing.T) {
+	opt := NewCoreOptions()
+	fss := opt.Flags()
+
+	// Test that flags have proper help messages
+	serverFS := fss.FlagSet("server")
+	flag := serverFS.Lookup("enable-leader-election")
+	assert.NotNil(t, flag)
+	assert.Contains(t, flag.Usage, "Enable leader election")
+
+	webhookFS := fss.FlagSet("webhook")
+	flag = webhookFS.Lookup("use-webhook")
+	assert.NotNil(t, flag)
+	assert.Contains(t, flag.Usage, "Enable Admission Webhook")
+
+	obsFS := fss.FlagSet("observability")
+	flag = obsFS.Lookup("log-debug")
+	assert.NotNil(t, flag)
+	assert.Contains(t, flag.Usage, "Enable debug logs")
+}
+
+func TestCoreOptions_MultipleSyncCalls(t *testing.T) {
+	// Store original values
+	origCUEExternal := cuex.EnableExternalPackageForDefaultCompiler
+	origCUEWatch := cuex.EnableExternalPackageWatchForDefaultCompiler
+	origWait := wfTypes.MaxWorkflowWaitBackoffTime
+	origDispatch := resourcekeeper.MaxDispatchConcurrent
+	origOAMNamespace := oam.SystemDefinitionNamespace
+	origAppPeriod := commonconfig.ApplicationReSyncPeriod
+	origPerf := commonconfig.PerfEnabled
+
+	// Restore after test
+	defer func() {
+		cuex.EnableExternalPackageForDefaultCompiler = origCUEExternal
+		cuex.EnableExternalPackageWatchForDefaultCompiler = origCUEWatch
+		wfTypes.MaxWorkflowWaitBackoffTime = origWait
+		resourcekeeper.MaxDispatchConcurrent = origDispatch
+		oam.SystemDefinitionNamespace = origOAMNamespace
+		commonconfig.ApplicationReSyncPeriod = origAppPeriod
+		commonconfig.PerfEnabled = origPerf
+	}()
+
+	// Test that calling sync multiple times doesn't cause issues
+	opts := NewCoreOptions()
+
+	// Set some values
+	opts.CUE.EnableExternalPackage = true
+	opts.CUE.EnableExternalPackageWatch = false
+	opts.Workflow.MaxWaitBackoffTime = 100
+	opts.Resource.MaxDispatchConcurrent = 20
+	opts.OAM.SystemDefinitionNamespace = "test-system"
+	opts.Application.ReSyncPeriod = 15 * time.Minute
+	opts.Performance.PerfEnabled = true
+
+	// Call sync multiple times
+	opts.CUE.SyncToCUEGlobals()
+	opts.CUE.SyncToCUEGlobals()
+
+	opts.Workflow.SyncToWorkflowGlobals()
+	opts.Workflow.SyncToWorkflowGlobals()
+
+	opts.Resource.SyncToResourceGlobals()
+	opts.Resource.SyncToResourceGlobals()
+
+	opts.OAM.SyncToOAMGlobals()
+	opts.OAM.SyncToOAMGlobals()
+
+	opts.Application.SyncToApplicationGlobals()
+	opts.Application.SyncToApplicationGlobals()
+
+	opts.Performance.SyncToPerformanceGlobals()
+	opts.Performance.SyncToPerformanceGlobals()
+
+	// Verify values are still correct
+	assert.True(t, cuex.EnableExternalPackageForDefaultCompiler)
+	assert.False(t, cuex.EnableExternalPackageWatchForDefaultCompiler)
+	assert.Equal(t, 100, wfTypes.MaxWorkflowWaitBackoffTime)
+	assert.Equal(t, 20, resourcekeeper.MaxDispatchConcurrent)
+	assert.Equal(t, "test-system", oam.SystemDefinitionNamespace)
+	assert.Equal(t, 15*time.Minute, commonconfig.ApplicationReSyncPeriod)
+	assert.True(t, commonconfig.PerfEnabled)
+}
+
+func TestCoreOptions_SpecialCharactersInStrings(t *testing.T) {
+	fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
+	opt := NewCoreOptions()
+
+	for _, f := range opt.Flags().FlagSets {
+		fs.AddFlagSet(f)
+	}
+
+	// Test with special characters and spaces in paths
+	args := []string{
+		`--webhook-cert-dir=/path/with spaces/and-special!@#$%chars`,
+		`--log-file-path=/var/log/kubevela/日本語/логи.log`,
+		`--health-addr=[::1]:8080`,
+		`--metrics-addr=0.0.0.0:9090`,
+	}
+
+	err := fs.Parse(args)
+	require.NoError(t, err)
+
+	assert.Equal(t, `/path/with spaces/and-special!@#$%chars`, opt.Webhook.CertDir)
+	assert.Equal(t, `/var/log/kubevela/日本語/логи.log`, opt.Observability.LogFilePath)
+	assert.Equal(t, `[::1]:8080`, opt.Server.HealthAddr)
+	assert.Equal(t, `0.0.0.0:9090`, opt.Observability.MetricsAddr)
+}
+
+func TestCoreOptions_ConcurrentAccess(t *testing.T) {
+	// Test that the options can be accessed concurrently safely
+	opt := NewCoreOptions()
+
+	// Set some values
+	opt.Server.EnableLeaderElection = true
+	opt.Workflow.MaxWaitBackoffTime = 100
+	opt.Resource.MaxDispatchConcurrent = 20
+
+	// Simulate concurrent access
+	done := make(chan bool, 3)
+
+	go func() {
+		for i := 0; i < 100; i++ {
+			_ = opt.Server.EnableLeaderElection
+		}
+		done <- true
+	}()
+
+	go func() {
+		for i := 0; i < 100; i++ {
+			_ = opt.Workflow.MaxWaitBackoffTime
+		}
+		done <- true
+	}()
+
+	go func() {
+		for i := 0; i < 100; i++ {
+			_ = opt.Resource.MaxDispatchConcurrent
+		}
+		done <- true
+	}()
+
+	// Wait for all goroutines
+	for i := 0; i < 3; i++ {
+		<-done
+	}
+}
+
+func TestCoreOptions_NilPointerSafety(t *testing.T) {
+	// Ensure NewCoreOptions never returns nil pointers
+	opt := NewCoreOptions()
+
+	// All config modules should be non-nil
+	assert.NotNil(t, opt.Server)
+	assert.NotNil(t, opt.Webhook)
+	assert.NotNil(t, opt.Observability)
+	assert.NotNil(t, opt.Kubernetes)
+	assert.NotNil(t, opt.MultiCluster)
+	assert.NotNil(t, opt.CUE)
+	assert.NotNil(t, opt.Application)
+	assert.NotNil(t, opt.OAM)
+	assert.NotNil(t, opt.Performance)
+	assert.NotNil(t, opt.Workflow)
+	assert.NotNil(t, opt.Admission)
+	assert.NotNil(t, opt.Resource)
+	assert.NotNil(t, opt.Client)
+	assert.NotNil(t, opt.Reconcile)
+	assert.NotNil(t, opt.Sharding)
+	assert.NotNil(t, opt.Feature)
+	assert.NotNil(t, opt.Profiling)
+	assert.NotNil(t, opt.KLog)
+	assert.NotNil(t, opt.Controller)
+}
+
+func TestCoreOptions_FlagPrecedence(t *testing.T) {
+	// Test that later flags override earlier ones
+	fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
+	opt := NewCoreOptions()
+
+	for _, f := range opt.Flags().FlagSets {
+		fs.AddFlagSet(f)
+	}
+
+	// Parse with one value, then parse again with different value
+	args1 := []string{"--webhook-port=8080"}
+	err := fs.Parse(args1)
+	require.NoError(t, err)
+	assert.Equal(t, 8080, opt.Webhook.WebhookPort)
+
+	// Reset and parse with different value
+	fs = pflag.NewFlagSet("test", pflag.ContinueOnError)
+	opt = NewCoreOptions()
+	for _, f := range opt.Flags().FlagSets {
+		fs.AddFlagSet(f)
+	}
+
+	args2 := []string{"--webhook-port=9090"}
+	err = fs.Parse(args2)
+	require.NoError(t, err)
+	assert.Equal(t, 9090, opt.Webhook.WebhookPort)
+}
+
+func TestCoreOptions_AllConfigModulesHaveFlags(t *testing.T) {
+	// Ensure every config module registers at least one flag
+	opt := NewCoreOptions()
+	fss := opt.Flags()
+
+	configsWithExpectedFlags := map[string][]string{
+		"server":        {"health-addr", "storage-driver", "enable-leader-election"},
+		"webhook":       {"use-webhook", "webhook-cert-dir", "webhook-port"},
+		"observability": {"metrics-addr", "log-debug", "log-file-path"},
+		"kubernetes":    {"informer-sync-period", "kube-api-qps", "kube-api-burst"},
+		"multicluster":  {"enable-cluster-gateway", "enable-cluster-metrics"},
+		"cue":           {"enable-external-package-for-default-compiler"},
+		"application":   {"application-re-sync-period"},
+		"oam":           {"system-definition-namespace"},
+		"controller":    {"revision-limit", "application-revision-limit", "definition-revision-limit"},
+		"performance":   {"perf-enabled"},
+		"workflow":      {"max-workflow-wait-backoff-time"},
+		"resource":      {"max-dispatch-concurrent"},
+	}
+
+	for setName, expectedFlags := range configsWithExpectedFlags {
+		fs := fss.FlagSet(setName)
+		assert.NotNil(t, fs, "FlagSet %s should exist", setName)
+
+		for _, flagName := range expectedFlags {
+			flag := fs.Lookup(flagName)
+			assert.NotNil(t, flag, "Flag %s should exist in flagset %s", flagName, setName)
+		}
+	}
+}
+
+func TestCoreOptions_CLIOverridesWork(t *testing.T) {
+	// This test verifies that CLI flags correctly override default values
+	// and that the sync methods properly propagate these values to globals
+
+	// Store original globals to restore after test
+	origWait := wfTypes.MaxWorkflowWaitBackoffTime
+	origFailed := wfTypes.MaxWorkflowFailedBackoffTime
+	origRetry := wfTypes.MaxWorkflowStepErrorRetryTimes
+	origDispatch := resourcekeeper.MaxDispatchConcurrent
+	origOAMNamespace := oam.SystemDefinitionNamespace
+	origAppPeriod := commonconfig.ApplicationReSyncPeriod
+	origPerf := commonconfig.PerfEnabled
+	origCUEExternal := cuex.EnableExternalPackageForDefaultCompiler
+	origCUEWatch := cuex.EnableExternalPackageWatchForDefaultCompiler
+
+	defer func() {
+		wfTypes.MaxWorkflowWaitBackoffTime = origWait
+		wfTypes.MaxWorkflowFailedBackoffTime = origFailed
+		wfTypes.MaxWorkflowStepErrorRetryTimes = origRetry
+		resourcekeeper.MaxDispatchConcurrent = origDispatch
+		oam.SystemDefinitionNamespace = origOAMNamespace
+		commonconfig.ApplicationReSyncPeriod = origAppPeriod
+		commonconfig.PerfEnabled = origPerf
+		cuex.EnableExternalPackageForDefaultCompiler = origCUEExternal
+		cuex.EnableExternalPackageWatchForDefaultCompiler = origCUEWatch
+	}()
+
+	opt := NewCoreOptions()
+	fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
+
+	for _, f := range opt.Flags().FlagSets {
+		fs.AddFlagSet(f)
+	}
+
+	// Verify defaults first
+	assert.Equal(t, 60, opt.Workflow.MaxWaitBackoffTime, "Default should be 60")
+	assert.Equal(t, 300, opt.Workflow.MaxFailedBackoffTime, "Default should be 300")
+	assert.Equal(t, 10, opt.Workflow.MaxStepErrorRetryTimes, "Default should be 10")
+	assert.Equal(t, 10, opt.Resource.MaxDispatchConcurrent, "Default should be 10")
+	assert.Equal(t, "vela-system", opt.OAM.SystemDefinitionNamespace, "Default should be vela-system")
+	assert.Equal(t, false, opt.Performance.PerfEnabled, "Default should be false")
+
+	// Parse CLI args with overrides
+	args := []string{
+		"--max-workflow-wait-backoff-time=999",
+		"--max-workflow-failed-backoff-time=888",
+		"--max-workflow-step-error-retry-times=77",
+		"--max-dispatch-concurrent=66",
+		"--system-definition-namespace=custom-ns",
+		"--application-re-sync-period=20m",
+		"--perf-enabled=true",
 		"--enable-external-package-for-default-compiler=true",
 		"--enable-external-package-watch-for-default-compiler=true",
 	}
-	err := fss.FlagSet("generic").Parse(args)
-	if err != nil {
-		return
+
+	err := fs.Parse(args)
+	require.NoError(t, err)
+
+	// Verify struct fields got CLI values (not defaults)
+	assert.Equal(t, 999, opt.Workflow.MaxWaitBackoffTime, "CLI override should be 999")
+	assert.Equal(t, 888, opt.Workflow.MaxFailedBackoffTime, "CLI override should be 888")
+	assert.Equal(t, 77, opt.Workflow.MaxStepErrorRetryTimes, "CLI override should be 77")
+	assert.Equal(t, 66, opt.Resource.MaxDispatchConcurrent, "CLI override should be 66")
+	assert.Equal(t, "custom-ns", opt.OAM.SystemDefinitionNamespace, "CLI override should be custom-ns")
+	assert.Equal(t, 20*time.Minute, opt.Application.ReSyncPeriod, "CLI override should be 20m")
+	assert.Equal(t, true, opt.Performance.PerfEnabled, "CLI override should be true")
+	assert.Equal(t, true, opt.CUE.EnableExternalPackage, "CLI override should be true")
+	assert.Equal(t, true, opt.CUE.EnableExternalPackageWatch, "CLI override should be true")
+
+	// Now sync to globals
+	opt.Workflow.SyncToWorkflowGlobals()
+	opt.Resource.SyncToResourceGlobals()
+	opt.OAM.SyncToOAMGlobals()
+	opt.Application.SyncToApplicationGlobals()
+	opt.Performance.SyncToPerformanceGlobals()
+	opt.CUE.SyncToCUEGlobals()
+
+	// Verify globals got the CLI values
+	assert.Equal(t, 999, wfTypes.MaxWorkflowWaitBackoffTime, "Global should have CLI value")
+	assert.Equal(t, 888, wfTypes.MaxWorkflowFailedBackoffTime, "Global should have CLI value")
+	assert.Equal(t, 77, wfTypes.MaxWorkflowStepErrorRetryTimes, "Global should have CLI value")
+	assert.Equal(t, 66, resourcekeeper.MaxDispatchConcurrent, "Global should have CLI value")
+	assert.Equal(t, "custom-ns", oam.SystemDefinitionNamespace, "Global should have CLI value")
+	assert.Equal(t, 20*time.Minute, commonconfig.ApplicationReSyncPeriod, "Global should have CLI value")
+	assert.Equal(t, true, commonconfig.PerfEnabled, "Global should have CLI value")
+	assert.Equal(t, true, cuex.EnableExternalPackageForDefaultCompiler, "Global should have CLI value")
+	assert.Equal(t, true, cuex.EnableExternalPackageWatchForDefaultCompiler, "Global should have CLI value")
+}
+
+func TestCoreOptions_CompleteIntegration(t *testing.T) {
+	// A comprehensive integration test
+	opt := NewCoreOptions()
+	fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
+
+	for _, f := range opt.Flags().FlagSets {
+		fs.AddFlagSet(f)
 	}
 
-	assert.True(t, cuex.EnableExternalPackageForDefaultCompiler, "The --enable-external-package-for-default-compiler flag should be enabled")
-	assert.True(t, cuex.EnableExternalPackageWatchForDefaultCompiler, "The --enable-external-package-watch-for-default-compiler flag should be enabled")
+	// Simulate a real-world configuration
+	args := []string{
+		// Production-like settings
+		"--enable-leader-election=true",
+		"--leader-election-namespace=vela-system",
+		"--use-webhook=true",
+		"--webhook-port=9443",
+		"--metrics-addr=:8080",
+		"--health-addr=:9440",
+		"--log-debug=false",
+		"--log-file-path=/var/log/vela/core.log",
+		"--log-file-max-size=100",
+		"--kube-api-qps=100",
+		"--kube-api-burst=200",
+		"--enable-cluster-gateway=true",
+		"--enable-cluster-metrics=true",
+		"--cluster-metrics-interval=30s",
+		"--application-re-sync-period=10m",
+		"--perf-enabled=true",
+		"--max-dispatch-concurrent=20",
+		"--max-workflow-wait-backoff-time=120",
+		"--max-workflow-failed-backoff-time=600",
+	}
+
+	err := fs.Parse(args)
+	require.NoError(t, err)
+
+	// Verify the configuration is production-ready
+	assert.True(t, opt.Server.EnableLeaderElection, "Leader election should be enabled in production")
+	assert.Equal(t, "vela-system", opt.Server.LeaderElectionNamespace)
+	assert.True(t, opt.Webhook.UseWebhook, "Webhook should be enabled in production")
+	assert.Equal(t, 9443, opt.Webhook.WebhookPort)
+	assert.False(t, opt.Observability.LogDebug, "Debug logging should be disabled in production")
+	assert.NotEmpty(t, opt.Observability.LogFilePath, "Log file path should be set in production")
+
+	// Verify performance settings
+	assert.True(t, opt.Performance.PerfEnabled)
+	assert.Equal(t, 20, opt.Resource.MaxDispatchConcurrent)
+
+	// Verify cluster settings
+	assert.True(t, opt.MultiCluster.EnableClusterGateway)
+	assert.True(t, opt.MultiCluster.EnableClusterMetrics)
+	assert.Equal(t, 30*time.Second, opt.MultiCluster.ClusterMetricsInterval)
+
+	// Sync all configurations that need it
+	opt.CUE.SyncToCUEGlobals()
+	opt.Workflow.SyncToWorkflowGlobals()
+	opt.Resource.SyncToResourceGlobals()
+	opt.OAM.SyncToOAMGlobals()
+	opt.Application.SyncToApplicationGlobals()
+	opt.Performance.SyncToPerformanceGlobals()
+
+	// Verify sync worked
+	assert.Equal(t, 20, resourcekeeper.MaxDispatchConcurrent)
+	assert.Equal(t, 120, wfTypes.MaxWorkflowWaitBackoffTime)
+	assert.Equal(t, 600, wfTypes.MaxWorkflowFailedBackoffTime)
+	assert.Equal(t, "vela-system", oam.SystemDefinitionNamespace)
+	assert.Equal(t, 10*time.Minute, commonconfig.ApplicationReSyncPeriod)
+	assert.True(t, commonconfig.PerfEnabled)
 }
diff --git a/pkg/addon/error_test.go b/pkg/addon/error_test.go
index 05709d37..d9066211 100644
--- a/pkg/addon/error_test.go
+++ b/pkg/addon/error_test.go
@@ -20,6 +20,8 @@ import (
 	"strings"
 	"testing"
 
+	"github.com/google/go-github/v32/github"
+	"github.com/pkg/errors"
 	"github.com/stretchr/testify/assert"
 )
 
@@ -41,3 +43,13 @@ func TestGetAvailableVersion(t *testing.T) {
 	assert.NotEmpty(t, err)
 	assert.Equal(t, version, "")
 }
+
+func TestWrapErrRateLimit(t *testing.T) {
+	regularErr := errors.New("regular error")
+	wrappedErr := WrapErrRateLimit(regularErr)
+	assert.Equal(t, regularErr, wrappedErr)
+
+	rateLimitErr := &github.RateLimitError{}
+	wrappedErr = WrapErrRateLimit(rateLimitErr)
+	assert.Equal(t, ErrRateLimit, wrappedErr)
+}
diff --git a/pkg/addon/memory_reader_test.go b/pkg/addon/memory_reader_test.go
deleted file mode 100644
index d778b02d..00000000
--- a/pkg/addon/memory_reader_test.go
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
-Copyright 2021 The KubeVela Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package addon
-
-import (
-	"testing"
-
-	"github.com/stretchr/testify/assert"
-	"helm.sh/helm/v3/pkg/chart/loader"
-)
-
-var files = []*loader.BufferedFile{
-	{
-		Name: "metadata.yaml",
-		Data: []byte(`name: test-helm-addon
-version: 1.0.0
-description: This is a addon for test when install addon from helm repo
-icon: https://www.terraform.io/assets/images/logo-text-8c3ba8a6.svg
-url: https://terraform.io/
-
-tags: []
-
-deployTo:
-  control_plane: true
-  runtime_cluster: false
-
-dependencies: []
-
-invisible: false`),
-	},
-	{
-		Name: "/resources/parameter.cue",
-		Data: []byte(`parameter: {
-	// test wrong parameter
-	example: *"default"
-}`),
-	},
-}
-
-func TestMemoryReader(t *testing.T) {
-	m := MemoryReader{
-		Name:  "fluxcd",
-		Files: files,
-	}
-
-	meta, err := m.ListAddonMeta()
-	assert.NoError(t, err)
-	assert.Equal(t, len(meta["fluxcd"].Items), 2)
-
-	metaFile, err := m.ReadFile("metadata.yaml")
-	assert.NoError(t, err)
-	assert.NotEmpty(t, metaFile)
-
-	parameterData, err := m.ReadFile("/resources/parameter.cue")
-	assert.NoError(t, err)
-	assert.NotEmpty(t, parameterData)
-}
diff --git a/pkg/addon/reader_gitee_test.go b/pkg/addon/reader_gitee_test.go
index 2f6f9d02..a242e070 100644
--- a/pkg/addon/reader_gitee_test.go
+++ b/pkg/addon/reader_gitee_test.go
@@ -97,3 +97,155 @@ func TestGiteeReader(t *testing.T) {
 	assert.NoError(t, err)
 
 }
+
+func TestNewGiteeClient(t *testing.T) {
+	defaultURL, _ := url.Parse(DefaultGiteeURL)
+
+	testCases := map[string]struct {
+		httpClient *http.Client
+		baseURL    *url.URL
+		wantClient *http.Client
+		wantURL    *url.URL
+	}{
+		"Nil inputs": {
+			httpClient: nil,
+			baseURL:    nil,
+			wantClient: &http.Client{},
+			wantURL:    defaultURL,
+		},
+		"Custom inputs": {
+			httpClient: &http.Client{Timeout: 10},
+			baseURL:    &url.URL{Host: "my-gitee.com"},
+			wantClient: &http.Client{Timeout: 10},
+			wantURL:    &url.URL{Host: "my-gitee.com"},
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			client := NewGiteeClient(tc.httpClient, tc.baseURL)
+			assert.Equal(t, tc.wantClient.Timeout, client.Client.Timeout)
+			assert.Equal(t, tc.wantURL.Host, client.BaseURL.Host)
+		})
+	}
+}
+
+func TestGiteeReaderRelativePath(t *testing.T) {
+	testCases := map[string]struct {
+		basePath     string
+		itemPath     string
+		expectedPath string
+	}{
+		"No base path": {
+			basePath:     "",
+			itemPath:     "fluxcd/metadata.yaml",
+			expectedPath: "fluxcd/metadata.yaml",
+		},
+		"With base path": {
+			basePath:     "addons",
+			itemPath:     "addons/fluxcd/metadata.yaml",
+			expectedPath: "fluxcd/metadata.yaml",
+		},
+		"With deep base path": {
+			basePath:     "official/addons",
+			itemPath:     "official/addons/fluxcd/template.cue",
+			expectedPath: "fluxcd/template.cue",
+		},
+		"Item at root of base path": {
+			basePath:     "addons",
+			itemPath:     "addons/README.md",
+			expectedPath: "README.md",
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			gith := &giteeHelper{
+				Meta: &utils.Content{GiteeContent: utils.GiteeContent{
+					Path: tc.basePath,
+				}},
+			}
+			r := &giteeReader{h: gith}
+			item := &github.RepositoryContent{Path: &tc.itemPath}
+
+			result := r.RelativePath(item)
+			assert.Equal(t, tc.expectedPath, result)
+		})
+	}
+}
+
+func TestGiteeReader_ListAddonMeta(t *testing.T) {
+	client, mux, teardown := giteeSetup()
+	defer teardown()
+
+	giteePattern := "/repos/o/r/contents/"
+	mux.HandleFunc(giteePattern, func(rw http.ResponseWriter, req *http.Request) {
+		var contents []*github.RepositoryContent
+		queryPath := strings.TrimPrefix(req.URL.Path, giteePattern)
+
+		switch queryPath {
+		case "": // Root directory
+			contents = []*github.RepositoryContent{
+				{Type: String("dir"), Name: String("fluxcd"), Path: String("fluxcd")},
+				{Type: String("dir"), Name: String("velaux"), Path: String("velaux")},
+				{Type: String("file"), Name: String("README.md"), Path: String("README.md")},
+			}
+		case "fluxcd":
+			contents = []*github.RepositoryContent{
+				{Type: String("file"), Name: String("metadata.yaml"), Path: String("fluxcd/metadata.yaml")},
+				{Type: String("dir"), Name: String("resources"), Path: String("fluxcd/resources")},
+			}
+		case "fluxcd/resources":
+			contents = []*github.RepositoryContent{
+				{Type: String("file"), Name: String("parameter.cue"), Path: String("fluxcd/resources/parameter.cue")},
+			}
+		case "velaux":
+			contents = []*github.RepositoryContent{
+				{Type: String("file"), Name: String("metadata.yaml"), Path: String("velaux/metadata.yaml")},
+			}
+		default:
+			rw.WriteHeader(http.StatusNotFound)
+			return
+		}
+		res, _ := json.Marshal(contents)
+		rw.Write(res)
+	})
+
+	gith := &giteeHelper{
+		Client: client,
+		Meta: &utils.Content{GiteeContent: utils.GiteeContent{
+			Owner: "o",
+			Repo:  "r",
+		}},
+	}
+	r := &giteeReader{h: gith}
+
+	meta, err := r.ListAddonMeta()
+	assert.NoError(t, err)
+	assert.NotNil(t, meta)
+	assert.Equal(t, 2, len(meta), "Expected to find 2 addons, root files should be ignored")
+
+	t.Run("fluxcd addon discovery", func(t *testing.T) {
+		addon, ok := meta["fluxcd"]
+		assert.True(t, ok, "fluxcd addon should be discovered")
+		assert.Equal(t, "fluxcd", addon.Name)
+
+		// Should find 2 items recursively: metadata.yaml and resources/parameter.cue
+		assert.Equal(t, 2, len(addon.Items), "fluxcd should contain 2 files")
+
+		foundPaths := make(map[string]bool)
+		for _, item := range addon.Items {
+			foundPaths[item.GetPath()] = true
+		}
+		assert.True(t, foundPaths["fluxcd/metadata.yaml"], "should find fluxcd/metadata.yaml")
+		assert.True(t, foundPaths["fluxcd/resources/parameter.cue"], "should find fluxcd/resources/parameter.cue")
+	})
+
+	t.Run("velaux addon discovery", func(t *testing.T) {
+		addon, ok := meta["velaux"]
+		assert.True(t, ok, "velaux addon should be discovered")
+		assert.Equal(t, "velaux", addon.Name)
+		assert.Equal(t, 1, len(addon.Items), "velaux should contain 1 file")
+		assert.Equal(t, "velaux/metadata.yaml", addon.Items[0].GetPath())
+	})
+}
diff --git a/pkg/addon/reader_github_test.go b/pkg/addon/reader_github_test.go
index 1d971c03..5ef217d4 100644
--- a/pkg/addon/reader_github_test.go
+++ b/pkg/addon/reader_github_test.go
@@ -64,8 +64,10 @@ func setup() (client *github.Client, mux *http.ServeMux, teardown func()) {
 	return client, mux, server.Close
 }
 
-func TestGitHubReader(t *testing.T) {
+func TestGitHubReader_ReadFile(t *testing.T) {
 	client, mux, teardown := setup()
+	defer teardown()
+
 	githubPattern := "/repos/o/r/contents/"
 	mux.HandleFunc(githubPattern, func(rw http.ResponseWriter, req *http.Request) {
 		queryPath := strings.TrimPrefix(req.URL.Path, githubPattern)
@@ -76,6 +78,7 @@ func TestGitHubReader(t *testing.T) {
 			content := &github.RepositoryContent{Type: String("file"), Name: String(path.Base(queryPath)), Size: Int(len(file)), Encoding: String(""), Path: String(queryPath), Content: String(string(file))}
 			res, _ := json.Marshal(content)
 			rw.Write(res)
+			return
 		}
 
 		// otherwise, it could be directory
@@ -91,11 +94,11 @@ func TestGitHubReader(t *testing.T) {
 			}
 			dRes, _ := json.Marshal(contents)
 			rw.Write(dRes)
+			return
 		}
 
-		rw.Write([]byte("invalid github query"))
+		rw.WriteHeader(http.StatusNotFound)
 	})
-	defer teardown()
 
 	gith := &gitHelper{
 		Client: client,
@@ -107,7 +110,95 @@ func TestGitHubReader(t *testing.T) {
 	var r AsyncReader = &gitReader{gith}
 	_, err := r.ReadFile("example/metadata.yaml")
 	assert.NoError(t, err)
+}
+
+func TestGitReader_RelativePath(t *testing.T) {
+	testCases := map[string]struct {
+		basePath     string
+		itemPath     string
+		expectedPath string
+	}{
+		"No base path": {
+			basePath:     "",
+			itemPath:     "fluxcd/metadata.yaml",
+			expectedPath: "fluxcd/metadata.yaml",
+		},
+		"With base path": {
+			basePath:     "addons",
+			itemPath:     "addons/fluxcd/metadata.yaml",
+			expectedPath: "fluxcd/metadata.yaml",
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			gith := &gitHelper{
+				Meta: &utils.Content{GithubContent: utils.GithubContent{
+					Path: tc.basePath,
+				}},
+			}
+			r := &gitReader{h: gith}
+			item := &github.RepositoryContent{Path: &tc.itemPath}
+
+			result := r.RelativePath(item)
+			assert.Equal(t, tc.expectedPath, result)
+		})
+	}
+}
+
+func TestGitReader_ListAddonMeta(t *testing.T) {
+	client, mux, teardown := setup()
+	defer teardown()
+
+	githubPattern := "/repos/o/r/contents/"
+	mux.HandleFunc(githubPattern, func(rw http.ResponseWriter, req *http.Request) {
+		var contents []*github.RepositoryContent
+		queryPath := strings.TrimPrefix(req.URL.Path, githubPattern)
 
+		switch queryPath {
+		case "": // Root directory
+			contents = []*github.RepositoryContent{
+				{Type: String("dir"), Name: String("fluxcd"), Path: String("fluxcd")},
+				{Type: String("file"), Name: String("README.md"), Path: String("README.md")},
+			}
+		case "fluxcd":
+			contents = []*github.RepositoryContent{
+				{Type: String("file"), Name: String("metadata.yaml"), Path: String("fluxcd/metadata.yaml")},
+				{Type: String("dir"), Name: String("resources"), Path: String("fluxcd/resources")},
+				{Type: String("file"), Name: String("template.cue"), Path: String("fluxcd/template.cue")},
+			}
+		case "fluxcd/resources":
+			contents = []*github.RepositoryContent{
+				{Type: String("file"), Name: String("parameter.cue"), Path: String("fluxcd/resources/parameter.cue")},
+			}
+		default:
+			rw.WriteHeader(http.StatusNotFound)
+			return
+		}
+		res, _ := json.Marshal(contents)
+		rw.Write(res)
+	})
+
+	gith := &gitHelper{
+		Client: client,
+		Meta: &utils.Content{GithubContent: utils.GithubContent{
+			Owner: "o",
+			Repo:  "r",
+		}},
+	}
+	r := &gitReader{h: gith}
+
+	meta, err := r.ListAddonMeta()
+	assert.NoError(t, err)
+	assert.NotNil(t, meta)
+	assert.Equal(t, 1, len(meta), "Expected to find 1 addon, root files should be ignored")
+
+	t.Run("fluxcd addon discovery", func(t *testing.T) {
+		addon, ok := meta["fluxcd"]
+		assert.True(t, ok, "fluxcd addon should be discovered")
+		assert.Equal(t, "fluxcd", addon.Name)
+		assert.Equal(t, 3, len(addon.Items), "fluxcd should contain 3 files")
+	})
 }
 
 // Int is a helper routine that allocates a new int value
diff --git a/pkg/addon/reader_gitlab_test.go b/pkg/addon/reader_gitlab_test.go
index e193767a..4c0ace62 100644
--- a/pkg/addon/reader_gitlab_test.go
+++ b/pkg/addon/reader_gitlab_test.go
@@ -21,8 +21,7 @@ import (
 	"encoding/json"
 	"net/http"
 	"net/http/httptest"
-	"path"
-	"strings"
+	"strconv"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
@@ -33,81 +32,190 @@ import (
 
 var baseUrl = "/api/v4"
 
-func gitlabSetup() (client *gitlab.Client, mux *http.ServeMux, teardown func()) {
-	// mux is the HTTP request multiplexer used with the test server.
-	mux = http.NewServeMux()
-
+func gitlabSetup(t *testing.T) (*gitlab.Client, *http.ServeMux, func()) {
+	mux := http.NewServeMux()
 	apiHandler := http.NewServeMux()
 	apiHandler.Handle(baseUrl+"/", http.StripPrefix(baseUrl, mux))
-
-	// server is a test HTTP server used to provide mock API responses.
 	server := httptest.NewServer(apiHandler)
 
-	// client is the Gitlab client being tested and is
-	// configured to use test server.
 	client, err := gitlab.NewClient("", gitlab.WithBaseURL(server.URL+baseUrl+"/"))
-	if err != nil {
-		return
-	}
+	assert.NoError(t, err)
 
 	return client, mux, server.Close
 }
 
-func TestGitlabReader(t *testing.T) {
-	client, mux, teardown := gitlabSetup()
-	gitlabPattern := "/projects/9999/repository/files/"
-	mux.HandleFunc(gitlabPattern, func(rw http.ResponseWriter, req *http.Request) {
-		queryPath := strings.TrimPrefix(req.URL.Path, gitlabPattern)
-		localPath := path.Join(testdataPrefix, queryPath)
-		file, err := testdata.ReadFile(localPath)
-		// test if it's a file
-		if err == nil {
-			content := &gitlab.File{
-				FilePath: localPath,
-				FileName: path.Base(queryPath),
-				Size:     *Int(len(file)),
-				Encoding: "base64",
-				Ref:      "master",
-				Content:  base64.StdEncoding.EncodeToString(file),
-			}
-			res, _ := json.Marshal(content)
-			rw.Write(res)
-			return
+func TestGitlabReader_ReadFile(t *testing.T) {
+	client, mux, teardown := gitlabSetup(t)
+	defer teardown()
+
+	// The gitlab client URL-encodes the file path, so we must match the encoded path.
+	mux.HandleFunc("/projects/9999/repository/files/example%2Fmetadata.yaml", func(rw http.ResponseWriter, req *http.Request) {
+		content := &gitlab.File{
+			Content: base64.StdEncoding.EncodeToString([]byte("hello world")),
 		}
+		res, err := json.Marshal(content)
+		assert.NoError(t, err)
+		_, err = rw.Write(res)
+		assert.NoError(t, err)
+	})
+	mux.HandleFunc("/projects/9999/repository/files/example%2Fnot%2Ffound.yaml", func(rw http.ResponseWriter, req *http.Request) {
+		rw.WriteHeader(http.StatusNotFound)
+	})
+
+	gith := &gitlabHelper{
+		Client: client,
+		Meta:   &utils.Content{GitlabContent: utils.GitlabContent{PId: 9999, Path: "example"}},
+	}
+	var r AsyncReader = &gitlabReader{h: gith}
+
+	t.Run("success case", func(t *testing.T) {
+		content, err := r.ReadFile("metadata.yaml")
+		assert.NoError(t, err)
+		assert.Equal(t, "hello world", content)
+	})
+
+	t.Run("not found case", func(t *testing.T) {
+		_, err := r.ReadFile("not/found.yaml")
+		assert.Error(t, err)
+	})
+}
+
+func TestGitlabReader_ListAddonMeta(t *testing.T) {
+	client, mux, teardown := gitlabSetup(t)
+	defer teardown()
+
+	projectID := 9999
+	projectPath := "addons"
+
+	mux.HandleFunc("/projects/"+strconv.Itoa(projectID)+"/repository/tree", func(rw http.ResponseWriter, req *http.Request) {
+		pathParam := req.URL.Query().Get("path")
+		pageParam := req.URL.Query().Get("page")
+		if pageParam == "" {
+			pageParam = "1"
+		}
+
+		var tree []*gitlab.TreeNode
 
-		// otherwise, it could be directory
-		dir, err := testdata.ReadDir(localPath)
-		if err == nil {
-			contents := make([]*gitlab.TreeNode, 0)
-			for _, item := range dir {
-				tp := "file"
-				if item.IsDir() {
-					tp = "dir"
-				}
-				contents = append(contents, &gitlab.TreeNode{
-					ID:   "",
-					Name: item.Name(),
-					Type: tp,
-					Path: localPath + "/" + item.Name(),
-					Mode: "",
-				})
+		switch pathParam {
+		case projectPath:
+			rw.Header().Set("X-Total-Pages", "2")
+			if pageParam == "1" {
+				tree = []*gitlab.TreeNode{{ID: "1", Name: "fluxcd", Type: "tree", Path: "addons/fluxcd"}}
+			} else if pageParam == "2" {
+				tree = []*gitlab.TreeNode{{ID: "2", Name: "velaux", Type: "tree", Path: "addons/velaux"}}
 			}
-			dRes, _ := json.Marshal(contents)
-			rw.Write(dRes)
+		case "addons/fluxcd":
+			tree = []*gitlab.TreeNode{{ID: "3", Name: "metadata.yaml", Type: "blob", Path: "addons/fluxcd/metadata.yaml"}}
+		case "addons/velaux":
+			tree = []*gitlab.TreeNode{{ID: "4", Name: "template.cue", Type: "blob", Path: "addons/velaux/template.cue"}}
+		default:
+			rw.WriteHeader(http.StatusNotFound)
 			return
 		}
-
-		rw.Write([]byte("invalid gitlab query"))
+		res, err := json.Marshal(tree)
+		assert.NoError(t, err)
+		_, err = rw.Write(res)
+		assert.NoError(t, err)
 	})
-	defer teardown()
 
 	gith := &gitlabHelper{
 		Client: client,
 		Meta: &utils.Content{GitlabContent: utils.GitlabContent{
-			PId: 9999,
+			PId:  projectID,
+			Path: projectPath,
 		}},
 	}
-	var r AsyncReader = &gitlabReader{gith}
-	_, err := r.ReadFile("example/metadata.yaml")
+	r := &gitlabReader{h: gith}
+
+	meta, err := r.ListAddonMeta()
 	assert.NoError(t, err)
+	assert.NotNil(t, meta)
+	assert.Equal(t, 2, len(meta))
+
+	expectedAddons := map[string]struct {
+		itemCount int
+		itemPath  string
+	}{
+		"fluxcd": {itemCount: 1, itemPath: "fluxcd/metadata.yaml"},
+		"velaux": {itemCount: 1, itemPath: "velaux/template.cue"},
+	}
+
+	for name, expected := range expectedAddons {
+		t.Run(name, func(t *testing.T) {
+			addon, ok := meta[name]
+			assert.True(t, ok, "addon not found in result")
+			assert.Equal(t, name, addon.Name)
+			assert.Equal(t, expected.itemCount, len(addon.Items))
+			assert.Equal(t, expected.itemPath, addon.Items[0].GetPath())
+		})
+	}
+}
+
+func TestGitlabReader_Getters(t *testing.T) {
+	t.Run("GetRef", func(t *testing.T) {
+		githWithRef := &gitlabHelper{Meta: &utils.Content{GitlabContent: utils.GitlabContent{Ref: "develop"}}}
+		rWithRef := &gitlabReader{h: githWithRef}
+		assert.Equal(t, "develop", rWithRef.GetRef())
+
+		githWithoutRef := &gitlabHelper{Meta: &utils.Content{GitlabContent: utils.GitlabContent{Ref: ""}}}
+		rWithoutRef := &gitlabReader{h: githWithoutRef}
+		assert.Equal(t, "master", rWithoutRef.GetRef())
+	})
+
+	t.Run("GetProjectID and GetProjectPath", func(t *testing.T) {
+		gith := &gitlabHelper{
+			Meta: &utils.Content{GitlabContent: utils.GitlabContent{
+				PId:  12345,
+				Path: "my/project/path",
+			}},
+		}
+		r := &gitlabReader{h: gith}
+		assert.Equal(t, 12345, r.GetProjectID())
+		assert.Equal(t, "my/project/path", r.GetProjectPath())
+	})
+
+	t.Run("RelativePath", func(t *testing.T) {
+		r := &gitlabReader{}
+		item := &GitLabItem{
+			basePath: "addons",
+			path:     "addons/fluxcd/metadata.yaml",
+		}
+		assert.Equal(t, "fluxcd/metadata.yaml", r.RelativePath(item))
+	})
+}
+
+func TestGitLabItem(t *testing.T) {
+	t.Run("Getters", func(t *testing.T) {
+		item := GitLabItem{
+			tp:   "blob",
+			name: "metadata.yaml",
+		}
+		assert.Equal(t, "blob", item.GetType())
+		assert.Equal(t, "metadata.yaml", item.GetName())
+	})
+
+	t.Run("GetPath", func(t *testing.T) {
+		testCases := map[string]struct {
+			basePath string
+			fullPath string
+			expected string
+		}{
+			"no base path": {
+				basePath: "",
+				fullPath: "fluxcd/metadata.yaml",
+				expected: "fluxcd/metadata.yaml",
+			},
+			"with base path": {
+				basePath: "addons",
+				fullPath: "addons/fluxcd/metadata.yaml",
+				expected: "fluxcd/metadata.yaml",
+			},
+		}
+		for name, tc := range testCases {
+			t.Run(name, func(t *testing.T) {
+				item := GitLabItem{basePath: tc.basePath, path: tc.fullPath}
+				assert.Equal(t, tc.expected, item.GetPath())
+			})
+		}
+	})
 }
diff --git a/pkg/addon/reader_local_test.go b/pkg/addon/reader_local_test.go
index 909fa282..83226603 100644
--- a/pkg/addon/reader_local_test.go
+++ b/pkg/addon/reader_local_test.go
@@ -17,6 +17,7 @@ limitations under the License.
 package addon
 
 import (
+	"path/filepath"
 	"strings"
 	"testing"
 
@@ -25,17 +26,66 @@ import (
 
 func TestLocalReader(t *testing.T) {
 	r := localReader{name: "local", dir: "./testdata/local"}
-	m, err := r.ListAddonMeta()
-	assert.NoError(t, err)
-	assert.Equal(t, len(m["local"].Items), 2)
 
-	file, err := r.ReadFile("metadata.yaml")
-	assert.NoError(t, err)
-	assert.Equal(t, file, metaFile)
+	t.Run("ListAddonMeta", func(t *testing.T) {
+		m, err := r.ListAddonMeta()
+		assert.NoError(t, err)
+		assert.NotNil(t, m["local"])
+		assert.Equal(t, 2, len(m["local"].Items))
 
-	file, err = r.ReadFile("resources/parameter.cue")
-	assert.NoError(t, err)
-	assert.Equal(t, true, strings.Contains(file, parameterFile))
+		// Check that the correct files are found, regardless of order.
+		foundPaths := make(map[string]bool)
+		for _, item := range m["local"].Items {
+			// Normalize path separators for consistent checking
+			foundPaths[filepath.ToSlash(item.GetPath())] = true
+		}
+		assert.True(t, foundPaths[filepath.ToSlash("testdata/local/metadata.yaml")])
+		assert.True(t, foundPaths[filepath.ToSlash("testdata/local/resources/parameter.cue")])
+	})
+
+	t.Run("ReadFile", func(t *testing.T) {
+		t.Run("read root file", func(t *testing.T) {
+			file, err := r.ReadFile("metadata.yaml")
+			assert.NoError(t, err)
+			assert.Equal(t, file, metaFile)
+		})
+		t.Run("read nested file", func(t *testing.T) {
+			file, err := r.ReadFile("resources/parameter.cue")
+			assert.NoError(t, err)
+			assert.True(t, strings.Contains(file, parameterFile))
+		})
+	})
+}
+
+func TestLocalReader_RelativePath(t *testing.T) {
+	testCases := map[string]struct {
+		dir       string
+		addonName string
+		itemPath  string
+		expected  string
+	}{
+		"item in root": {
+			dir:       "./testdata/local",
+			addonName: "my-addon",
+			itemPath:  filepath.Join("./testdata/local", "metadata.yaml"),
+			expected:  filepath.Join("my-addon", "metadata.yaml"),
+		},
+		"item in subdirectory": {
+			dir:       "./testdata/local",
+			addonName: "my-addon",
+			itemPath:  filepath.Join("./testdata/local", "resources", "parameter.cue"),
+			expected:  filepath.Join("my-addon", "resources", "parameter.cue"),
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			r := localReader{name: tc.addonName, dir: tc.dir}
+			item := OSSItem{path: tc.itemPath}
+			result := r.RelativePath(item)
+			assert.Equal(t, tc.expected, result)
+		})
+	}
 }
 
 const (
diff --git a/pkg/addon/reader_memory_test.go b/pkg/addon/reader_memory_test.go
new file mode 100644
index 00000000..19289052
--- /dev/null
+++ b/pkg/addon/reader_memory_test.go
@@ -0,0 +1,116 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package addon
+
+import (
+	"path/filepath"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	"helm.sh/helm/v3/pkg/chart/loader"
+)
+
+var files = []*loader.BufferedFile{
+	{
+		Name: "metadata.yaml",
+		Data: []byte(`name: test-helm-addon
+version: 1.0.0
+description: This is a addon for test when install addon from helm repo
+icon: https://www.terraform.io/assets/images/logo-text-8c3ba8a6.svg
+url: https://terraform.io/
+
+tags: []
+
+deployTo:
+  control_plane: true
+  runtime_cluster: false
+
+dependencies: []
+
+invisible: false`),
+	},
+	{
+		Name: "resources/parameter.cue",
+		Data: []byte(`parameter: {
+	// test wrong parameter
+	example: *"default"
+}`),
+	},
+}
+
+func TestMemoryReader(t *testing.T) {
+	m := MemoryReader{
+		Name:  "fluxcd",
+		Files: files,
+	}
+
+	t.Run("ListAddonMeta", func(t *testing.T) {
+		meta, err := m.ListAddonMeta()
+		assert.NoError(t, err)
+		assert.Equal(t, 2, len(meta["fluxcd"].Items))
+		// Verify the internal fileData map was populated
+		_, metadataExists := m.fileData["metadata.yaml"]
+		assert.True(t, metadataExists, "metadata.yaml should exist in fileData map")
+		_, parameterExists := m.fileData["resources/parameter.cue"]
+		assert.True(t, parameterExists, "resources/parameter.cue should exist in fileData map")
+	})
+
+	t.Run("ReadFile", func(t *testing.T) {
+		// Ensure ListAddonMeta has been called to populate the internal map
+		_, _ = m.ListAddonMeta()
+
+		t.Run("read by exact name", func(t *testing.T) {
+			metaFile, err := m.ReadFile("metadata.yaml")
+			assert.NoError(t, err)
+			assert.NotEmpty(t, metaFile)
+		})
+
+		t.Run("read by prefixed name", func(t *testing.T) {
+			parameterData, err := m.ReadFile("fluxcd/resources/parameter.cue")
+			assert.NoError(t, err)
+			assert.NotEmpty(t, parameterData)
+		})
+	})
+}
+
+func TestMemoryReader_RelativePath(t *testing.T) {
+	testCases := map[string]struct {
+		addonName string
+		itemName  string
+		expected  string
+	}{
+		"name without prefix": {
+			addonName: "my-addon",
+			itemName:  "metadata.yaml",
+			expected:  filepath.Join("my-addon", "metadata.yaml"),
+		},
+		"name with prefix": {
+			addonName: "my-addon",
+			itemName:  "my-addon/template.cue",
+			expected:  "my-addon/template.cue",
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			r := MemoryReader{Name: tc.addonName}
+			item := OSSItem{name: tc.itemName}
+			result := r.RelativePath(item)
+			assert.Equal(t, tc.expected, result)
+		})
+	}
+}
diff --git a/pkg/addon/registry_test.go b/pkg/addon/registry_test.go
new file mode 100644
index 00000000..a7e077b1
--- /dev/null
+++ b/pkg/addon/registry_test.go
@@ -0,0 +1,643 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package addon
+
+import (
+	"context"
+	"encoding/json"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	v1 "k8s.io/api/core/v1"
+	apierrors "k8s.io/apimachinery/pkg/api/errors"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime"
+	"k8s.io/apimachinery/pkg/types"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
+
+	velatypes "github.com/oam-dev/kubevela/apis/types"
+)
+
+func TestAddonRegistry(t *testing.T) {
+	ctx := context.Background()
+	testRegistry := Registry{
+		Name: "test-registry",
+		Git: &GitAddonSource{
+			URL:   "http://github.com/test/repo",
+			Token: "test-token",
+		},
+	}
+	scheme := runtime.NewScheme()
+	assert.NoError(t, v1.AddToScheme(scheme))
+	client := fake.NewClientBuilder().WithScheme(scheme).Build()
+	ds := NewRegistryDataStore(client)
+
+	t.Run("add registry", func(t *testing.T) {
+		err := ds.AddRegistry(ctx, testRegistry)
+		assert.NoError(t, err)
+
+		var cm v1.ConfigMap
+		err = client.Get(ctx, types.NamespacedName{Name: registryConfigMapName, Namespace: velatypes.DefaultKubeVelaNS}, &cm)
+		assert.NoError(t, err)
+		var registries map[string]Registry
+		err = json.Unmarshal([]byte(cm.Data[registriesKey]), &registries)
+		assert.NoError(t, err)
+		assert.Equal(t, 1, len(registries))
+		gotRegistry := registries["test-registry"]
+		assert.Equal(t, "", gotRegistry.Git.Token)
+		assert.Equal(t, "addon-registry-test-registry", gotRegistry.Git.TokenSecretRef)
+
+		var secret v1.Secret
+		err = client.Get(ctx, types.NamespacedName{Name: "addon-registry-test-registry", Namespace: velatypes.DefaultKubeVelaNS}, &secret)
+		assert.NoError(t, err)
+		assert.Equal(t, "test-token", string(secret.Data["token"]))
+	})
+
+	t.Run("update registry", func(t *testing.T) {
+		updatedRegistry := Registry{
+			Name: "test-registry",
+			Git: &GitAddonSource{
+				URL:   "http://github.com/test/repo-updated",
+				Token: "test-token-updated",
+			},
+		}
+		err := ds.UpdateRegistry(ctx, updatedRegistry)
+		assert.NoError(t, err)
+
+		var secret v1.Secret
+		err = client.Get(ctx, types.NamespacedName{Name: "addon-registry-test-registry", Namespace: velatypes.DefaultKubeVelaNS}, &secret)
+		assert.NoError(t, err)
+		assert.Equal(t, "test-token-updated", string(secret.Data["token"]))
+	})
+
+	t.Run("list and get registry", func(t *testing.T) {
+		registries, err := ds.ListRegistries(ctx)
+		assert.NoError(t, err)
+		assert.Equal(t, 1, len(registries))
+		assert.Equal(t, "test-token-updated", registries[0].Git.Token)
+
+		reg, err := ds.GetRegistry(ctx, "test-registry")
+		assert.NoError(t, err)
+		assert.Equal(t, "test-token-updated", reg.Git.Token)
+	})
+
+	t.Run("delete registry", func(t *testing.T) {
+		err := ds.DeleteRegistry(ctx, "test-registry")
+		assert.NoError(t, err)
+
+		var cm v1.ConfigMap
+		err = client.Get(ctx, types.NamespacedName{Name: registryConfigMapName, Namespace: velatypes.DefaultKubeVelaNS}, &cm)
+		assert.NoError(t, err)
+		var registries map[string]Registry
+		err = json.Unmarshal([]byte(cm.Data[registriesKey]), &registries)
+		assert.NoError(t, err)
+		assert.Equal(t, 0, len(registries))
+
+		var secret v1.Secret
+		err = client.Get(ctx, types.NamespacedName{Name: "addon-registry-test-registry", Namespace: velatypes.DefaultKubeVelaNS}, &secret)
+		assert.Error(t, err)
+		assert.True(t, apierrors.IsNotFound(err))
+	})
+}
+
+func TestGetTokenSource(t *testing.T) {
+	gitSource := &GitAddonSource{URL: "https://github.com/kubevela/catalog.git"}
+	giteeSource := &GiteeAddonSource{URL: "https://gitee.com/kubevela/catalog.git"}
+	gitlabSource := &GitlabAddonSource{URL: "https://gitlab.com/kubevela/catalog.git"}
+
+	testCases := []struct {
+		name           string
+		registry       *Registry
+		expectedSource TokenSource
+	}{
+		{
+			name: "git source",
+			registry: &Registry{
+				Git: gitSource,
+			},
+			expectedSource: gitSource,
+		},
+		{
+			name: "gitee source",
+			registry: &Registry{
+				Gitee: giteeSource,
+			},
+			expectedSource: giteeSource,
+		},
+		{
+			name: "gitlab source",
+			registry: &Registry{
+				Gitlab: gitlabSource,
+			},
+			expectedSource: gitlabSource,
+		},
+		{
+			name: "git and gitee source",
+			registry: &Registry{
+				Git:   gitSource,
+				Gitee: giteeSource,
+			},
+			expectedSource: gitSource,
+		},
+		{
+			name: "gitee and gitlab source",
+			registry: &Registry{
+				Gitee:  giteeSource,
+				Gitlab: gitlabSource,
+			},
+			expectedSource: giteeSource,
+		},
+		{
+			name: "all token sources",
+			registry: &Registry{
+				Git:    gitSource,
+				Gitee:  giteeSource,
+				Gitlab: gitlabSource,
+			},
+			expectedSource: gitSource,
+		},
+		{
+			name: "no token source",
+			registry: &Registry{
+				Helm: &HelmSource{},
+			},
+			expectedSource: nil,
+		},
+		{
+			name:           "empty registry",
+			registry:       &Registry{},
+			expectedSource: nil,
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			source := tc.registry.GetTokenSource()
+			assert.Equal(t, tc.expectedSource, source)
+		})
+	}
+}
+
+func TestAddRegistry(t *testing.T) {
+	t.Run("Test adding a registry", func(t *testing.T) {
+		ctx := context.Background()
+		testRegistry := Registry{
+			Name: "test-registry",
+			Git: &GitAddonSource{
+				URL:   "http://github.com/test/repo",
+				Token: "test-token",
+			},
+		}
+		scheme := runtime.NewScheme()
+		assert.NoError(t, v1.AddToScheme(scheme))
+		client := fake.NewClientBuilder().WithScheme(scheme).Build()
+		ds := NewRegistryDataStore(client)
+
+		err := ds.AddRegistry(ctx, testRegistry)
+		assert.NoError(t, err)
+
+		var cm v1.ConfigMap
+		err = client.Get(ctx, types.NamespacedName{Name: registryConfigMapName, Namespace: velatypes.DefaultKubeVelaNS}, &cm)
+		assert.NoError(t, err)
+		var registries map[string]Registry
+		err = json.Unmarshal([]byte(cm.Data[registriesKey]), &registries)
+		assert.NoError(t, err)
+		assert.Equal(t, 1, len(registries))
+		gotRegistry := registries["test-registry"]
+		assert.Equal(t, "", gotRegistry.Git.Token)
+		assert.Equal(t, "addon-registry-test-registry", gotRegistry.Git.TokenSecretRef)
+
+		var secret v1.Secret
+		err = client.Get(ctx, types.NamespacedName{Name: "addon-registry-test-registry", Namespace: velatypes.DefaultKubeVelaNS}, &secret)
+		assert.NoError(t, err)
+		assert.Equal(t, "test-token", string(secret.Data["token"]))
+	})
+}
+
+func TestUpdateRegistry(t *testing.T) {
+	t.Run("Test updating a registry", func(t *testing.T) {
+		ctx := context.Background()
+		updatedRegistry := Registry{
+			Name: "test-registry",
+			Git: &GitAddonSource{
+				URL:   "http://github.com/test/repo-updated",
+				Token: "test-token-updated",
+			},
+		}
+		// Pre-existing state
+		existingRegistry := Registry{
+			Name: "test-registry",
+			Git: &GitAddonSource{
+				URL:            "http://github.com/test/repo",
+				TokenSecretRef: "addon-registry-test-registry",
+			},
+		}
+		registries := map[string]Registry{"test-registry": existingRegistry}
+		registriesBytes, err := json.Marshal(registries)
+		assert.NoError(t, err)
+		cm := &v1.ConfigMap{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      registryConfigMapName,
+				Namespace: velatypes.DefaultKubeVelaNS,
+			},
+			Data: map[string]string{
+				registriesKey: string(registriesBytes),
+			},
+		}
+		secret := &v1.Secret{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      "addon-registry-test-registry",
+				Namespace: velatypes.DefaultKubeVelaNS,
+			},
+			Data: map[string][]byte{
+				"token": []byte("test-token"),
+			},
+		}
+
+		scheme := runtime.NewScheme()
+		assert.NoError(t, v1.AddToScheme(scheme))
+		client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cm, secret).Build()
+		ds := NewRegistryDataStore(client)
+
+		err = ds.UpdateRegistry(ctx, updatedRegistry)
+		assert.NoError(t, err)
+
+		var updatedSecret v1.Secret
+		err = client.Get(ctx, types.NamespacedName{Name: "addon-registry-test-registry", Namespace: velatypes.DefaultKubeVelaNS}, &updatedSecret)
+		assert.NoError(t, err)
+		assert.Equal(t, "test-token-updated", string(updatedSecret.Data["token"]))
+
+		var updatedCm v1.ConfigMap
+		err = client.Get(ctx, types.NamespacedName{Name: registryConfigMapName, Namespace: velatypes.DefaultKubeVelaNS}, &updatedCm)
+		assert.NoError(t, err)
+		var updatedRegistries map[string]Registry
+		err = json.Unmarshal([]byte(updatedCm.Data[registriesKey]), &updatedRegistries)
+		assert.NoError(t, err)
+		assert.Equal(t, "http://github.com/test/repo-updated", updatedRegistries["test-registry"].Git.URL)
+	})
+}
+
+func TestListRegistry(t *testing.T) {
+	t.Run("Test listing registries", func(t *testing.T) {
+		ctx := context.Background()
+		// Pre-existing state
+		existingRegistry := Registry{
+			Name: "test-registry",
+			Git: &GitAddonSource{
+				URL:            "http://github.com/test/repo",
+				TokenSecretRef: "addon-registry-test-registry",
+			},
+		}
+		registries := map[string]Registry{"test-registry": existingRegistry}
+		registriesBytes, err := json.Marshal(registries)
+		assert.NoError(t, err)
+		cm := &v1.ConfigMap{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      registryConfigMapName,
+				Namespace: velatypes.DefaultKubeVelaNS,
+			},
+			Data: map[string]string{
+				registriesKey: string(registriesBytes),
+			},
+		}
+		secret := &v1.Secret{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      "addon-registry-test-registry",
+				Namespace: velatypes.DefaultKubeVelaNS,
+			},
+			Data: map[string][]byte{
+				"token": []byte("test-token"),
+			},
+		}
+
+		scheme := runtime.NewScheme()
+		assert.NoError(t, v1.AddToScheme(scheme))
+		client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cm, secret).Build()
+		ds := NewRegistryDataStore(client)
+
+		// Test List
+		listedRegistries, err := ds.ListRegistries(ctx)
+		assert.NoError(t, err)
+		assert.Equal(t, 1, len(listedRegistries))
+		assert.Equal(t, "test-token", listedRegistries[0].Git.Token)
+		assert.Equal(t, "http://github.com/test/repo", listedRegistries[0].Git.URL)
+	})
+}
+
+func TestGetRegistry(t *testing.T) {
+	t.Run("Test getting a single registry", func(t *testing.T) {
+		ctx := context.Background()
+		// Pre-existing state
+		existingRegistry := Registry{
+			Name: "test-registry",
+			Git: &GitAddonSource{
+				URL:            "http://github.com/test/repo",
+				TokenSecretRef: "addon-registry-test-registry",
+			},
+		}
+		registries := map[string]Registry{"test-registry": existingRegistry}
+		registriesBytes, err := json.Marshal(registries)
+		assert.NoError(t, err)
+		cm := &v1.ConfigMap{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      registryConfigMapName,
+				Namespace: velatypes.DefaultKubeVelaNS,
+			},
+			Data: map[string]string{
+				registriesKey: string(registriesBytes),
+			},
+		}
+		secret := &v1.Secret{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      "addon-registry-test-registry",
+				Namespace: velatypes.DefaultKubeVelaNS,
+			},
+			Data: map[string][]byte{
+				"token": []byte("test-token"),
+			},
+		}
+
+		scheme := runtime.NewScheme()
+		assert.NoError(t, v1.AddToScheme(scheme))
+		client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cm, secret).Build()
+		ds := NewRegistryDataStore(client)
+
+		// Test Get
+		reg, err := ds.GetRegistry(ctx, "test-registry")
+		assert.NoError(t, err)
+		assert.Equal(t, "test-token", reg.Git.Token)
+		assert.Equal(t, "http://github.com/test/repo", reg.Git.URL)
+	})
+}
+
+func TestDeleteRegistry(t *testing.T) {
+	t.Run("Test deleting a registry", func(t *testing.T) {
+		ctx := context.Background()
+		// Pre-existing state
+		existingRegistry := Registry{
+			Name: "test-registry",
+			Git: &GitAddonSource{
+				URL:            "http://github.com/test/repo",
+				TokenSecretRef: "addon-registry-test-registry",
+			},
+		}
+		registries := map[string]Registry{"test-registry": existingRegistry}
+		registriesBytes, err := json.Marshal(registries)
+		assert.NoError(t, err)
+		cm := &v1.ConfigMap{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      registryConfigMapName,
+				Namespace: velatypes.DefaultKubeVelaNS,
+			},
+			Data: map[string]string{
+				registriesKey: string(registriesBytes),
+			},
+		}
+		secret := &v1.Secret{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      "addon-registry-test-registry",
+				Namespace: velatypes.DefaultKubeVelaNS,
+			},
+			Data: map[string][]byte{
+				"token": []byte("test-token"),
+			},
+		}
+
+		scheme := runtime.NewScheme()
+		assert.NoError(t, v1.AddToScheme(scheme))
+		client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cm, secret).Build()
+		ds := NewRegistryDataStore(client)
+
+		err = ds.DeleteRegistry(ctx, "test-registry")
+		assert.NoError(t, err)
+
+		var updatedCm v1.ConfigMap
+		err = client.Get(ctx, types.NamespacedName{Name: registryConfigMapName, Namespace: velatypes.DefaultKubeVelaNS}, &updatedCm)
+		assert.NoError(t, err)
+		var updatedRegistries map[string]Registry
+		err = json.Unmarshal([]byte(updatedCm.Data[registriesKey]), &updatedRegistries)
+		assert.NoError(t, err)
+		assert.Equal(t, 0, len(updatedRegistries))
+
+		var deletedSecret v1.Secret
+		err = client.Get(ctx, types.NamespacedName{Name: "addon-registry-test-registry", Namespace: velatypes.DefaultKubeVelaNS}, &deletedSecret)
+		assert.Error(t, err)
+		assert.True(t, apierrors.IsNotFound(err))
+	})
+}
+
+func TestGetRegistries(t *testing.T) {
+	ctx := context.Background()
+	scheme := runtime.NewScheme()
+	assert.NoError(t, v1.AddToScheme(scheme))
+
+	// valid configmap with one registry
+	validRegistries := map[string]Registry{"test-registry": {Name: "test-registry"}}
+	validRegistriesBytes, err := json.Marshal(validRegistries)
+	assert.NoError(t, err)
+	validCm := &v1.ConfigMap{
+		ObjectMeta: metav1.ObjectMeta{Name: registryConfigMapName, Namespace: velatypes.DefaultKubeVelaNS},
+		Data:       map[string]string{registriesKey: string(validRegistriesBytes)},
+	}
+
+	// configmap with invalid json
+	invalidJSONCm := &v1.ConfigMap{
+		ObjectMeta: metav1.ObjectMeta{Name: registryConfigMapName, Namespace: velatypes.DefaultKubeVelaNS},
+		Data:       map[string]string{registriesKey: "invalid-json"},
+	}
+
+	// configmap with missing key
+	missingKeyCm := &v1.ConfigMap{
+		ObjectMeta: metav1.ObjectMeta{Name: registryConfigMapName, Namespace: velatypes.DefaultKubeVelaNS},
+		Data:       map[string]string{"another-key": "some-data"},
+	}
+
+	testCases := map[string]struct {
+		client       client.Client
+		expectErr    bool
+		expectRegNum int
+	}{
+		"success": {
+			client:       fake.NewClientBuilder().WithScheme(scheme).WithObjects(validCm).Build(),
+			expectErr:    false,
+			expectRegNum: 1,
+		},
+		"configmap not found": {
+			client:    fake.NewClientBuilder().WithScheme(scheme).Build(),
+			expectErr: true,
+		},
+		"invalid json": {
+			client:    fake.NewClientBuilder().WithScheme(scheme).WithObjects(invalidJSONCm).Build(),
+			expectErr: true,
+		},
+		"registries key missing": {
+			client:    fake.NewClientBuilder().WithScheme(scheme).WithObjects(missingKeyCm).Build(),
+			expectErr: true,
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			ds := registryImpl{client: tc.client}
+			registries, _, err := ds.getRegistries(ctx)
+			if tc.expectErr {
+				assert.Error(t, err)
+			} else {
+				assert.NoError(t, err)
+				assert.Equal(t, tc.expectRegNum, len(registries))
+			}
+		})
+	}
+}
+
+func TestLoadTokenFromSecret(t *testing.T) {
+	ctx := context.Background()
+	scheme := runtime.NewScheme()
+	assert.NoError(t, v1.AddToScheme(scheme))
+
+	secret := &v1.Secret{
+		ObjectMeta: metav1.ObjectMeta{Name: "addon-registry-test", Namespace: velatypes.DefaultKubeVelaNS},
+		Data:       map[string][]byte{"token": []byte("test-token")},
+	}
+
+	testCases := map[string]struct {
+		client      client.Client
+		registry    *Registry
+		expectErr   bool
+		expectToken string
+	}{
+		"success": {
+			client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(secret).Build(),
+			registry: &Registry{
+				Name: "test",
+				Git:  &GitAddonSource{URL: "http://github.com/test/repo", TokenSecretRef: "addon-registry-test"},
+			},
+			expectErr:   false,
+			expectToken: "test-token",
+		},
+		"secret not found": {
+			client: fake.NewClientBuilder().WithScheme(scheme).Build(),
+			registry: &Registry{
+				Name: "test",
+				Git:  &GitAddonSource{URL: "http://github.com/test/repo", TokenSecretRef: "addon-registry-test"},
+			},
+			expectErr:   false,
+			expectToken: "",
+		},
+		"no token source": {
+			client:      fake.NewClientBuilder().WithScheme(scheme).Build(),
+			registry:    &Registry{Name: "test"},
+			expectErr:   false,
+			expectToken: "",
+		},
+		"no secret ref": {
+			client:      fake.NewClientBuilder().WithScheme(scheme).Build(),
+			registry:    &Registry{Name: "test", Git: &GitAddonSource{URL: "http://github.com/test/repo"}},
+			expectErr:   false,
+			expectToken: "",
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			err := loadTokenFromSecret(ctx, tc.client, tc.registry)
+			if tc.expectErr {
+				assert.Error(t, err)
+			} else {
+				assert.NoError(t, err)
+				if tc.registry.Git != nil {
+					assert.Equal(t, tc.expectToken, tc.registry.Git.Token)
+				}
+			}
+		})
+	}
+}
+
+func TestCreateOrUpdateTokenSecret(t *testing.T) {
+	ctx := context.Background()
+	scheme := runtime.NewScheme()
+	assert.NoError(t, v1.AddToScheme(scheme))
+
+	existingSecret := &v1.Secret{
+		ObjectMeta: metav1.ObjectMeta{Name: "addon-registry-test", Namespace: velatypes.DefaultKubeVelaNS},
+		Data:       map[string][]byte{"token": []byte("old-token")},
+	}
+
+	testCases := map[string]struct {
+		client       client.Client
+		registry     *Registry
+		expectErr    bool
+		expectToken  string
+		expectSecret bool
+	}{
+		"create new secret": {
+			client: fake.NewClientBuilder().WithScheme(scheme).Build(),
+			registry: &Registry{
+				Name: "test",
+				Git:  &GitAddonSource{Token: "new-token"},
+			},
+			expectErr:    false,
+			expectToken:  "new-token",
+			expectSecret: true,
+		},
+		"update existing secret": {
+			client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(existingSecret).Build(),
+			registry: &Registry{
+				Name: "test",
+				Git:  &GitAddonSource{Token: "updated-token"},
+			},
+			expectErr:    false,
+			expectToken:  "updated-token",
+			expectSecret: true,
+		},
+		"no token source": {
+			client:       fake.NewClientBuilder().WithScheme(scheme).Build(),
+			registry:     &Registry{Name: "test"},
+			expectErr:    false,
+			expectSecret: false,
+		},
+		"empty token": {
+			client:       fake.NewClientBuilder().WithScheme(scheme).Build(),
+			registry:     &Registry{Name: "test", Git: &GitAddonSource{Token: ""}},
+			expectErr:    false,
+			expectSecret: false,
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			err := createOrUpdateTokenSecret(ctx, tc.client, tc.registry)
+			if tc.expectErr {
+				assert.Error(t, err)
+			} else {
+				assert.NoError(t, err)
+				if tc.expectSecret {
+					var secret v1.Secret
+					err := tc.client.Get(ctx, types.NamespacedName{Name: "addon-registry-test", Namespace: velatypes.DefaultKubeVelaNS}, &secret)
+					assert.NoError(t, err)
+					assert.Equal(t, tc.expectToken, string(secret.Data["token"]))
+					assert.Equal(t, "addon-registry-test", tc.registry.GetTokenSource().GetTokenSecretRef())
+				} else {
+					var secret v1.Secret
+					err := tc.client.Get(ctx, types.NamespacedName{Name: "addon-registry-test", Namespace: velatypes.DefaultKubeVelaNS}, &secret)
+					assert.True(t, apierrors.IsNotFound(err))
+				}
+			}
+		})
+	}
+}
diff --git a/pkg/addon/source_test.go b/pkg/addon/source_test.go
index c1033eda..414b5780 100644
--- a/pkg/addon/source_test.go
+++ b/pkg/addon/source_test.go
@@ -22,6 +22,127 @@ import (
 	"github.com/stretchr/testify/assert"
 )
 
+// mockItem implements the Item interface for testing
+type mockItem struct {
+	path     string
+	name     string
+	typeName string
+}
+
+func (m mockItem) GetType() string { return m.typeName }
+func (m mockItem) GetPath() string { return m.path }
+func (m mockItem) GetName() string { return m.name }
+
+// mockReader implements the AsyncReader interface for testing
+type mockReader struct{}
+
+func (m mockReader) ListAddonMeta() (map[string]SourceMeta, error) { return nil, nil }
+func (m mockReader) ReadFile(path string) (string, error)          { return "", nil }
+func (m mockReader) RelativePath(item Item) string                 { return item.GetPath() }
+
+func TestClassifyItemByPattern(t *testing.T) {
+	addonName := "my-addon"
+	meta := &SourceMeta{
+		Name: addonName,
+		Items: []Item{
+			mockItem{path: "my-addon/metadata.yaml"},
+			mockItem{path: "my-addon/template.cue"},
+			mockItem{path: "my-addon/definitions/def.cue"},
+			mockItem{path: "my-addon/resources/res.yaml"},
+			mockItem{path: "my-addon/schemas/schema.cue"},
+			mockItem{path: "my-addon/views/view.cue"},
+			mockItem{path: "my-addon/some-other-file.txt"}, // Should be ignored
+		},
+	}
+
+	r := mockReader{}
+	classified := ClassifyItemByPattern(meta, r)
+
+	assert.Contains(t, classified, MetadataFileName)
+	assert.Len(t, classified[MetadataFileName], 1)
+
+	assert.Contains(t, classified, AppTemplateCueFileName)
+	assert.Len(t, classified[AppTemplateCueFileName], 1)
+
+	assert.Contains(t, classified, DefinitionsDirName)
+	assert.Len(t, classified[DefinitionsDirName], 1)
+
+	assert.Contains(t, classified, ResourcesDirName)
+	assert.Len(t, classified[ResourcesDirName], 1)
+
+	assert.Contains(t, classified, DefSchemaName)
+	assert.Len(t, classified[DefSchemaName], 1)
+
+	assert.Contains(t, classified, ViewDirName)
+	assert.Len(t, classified[ViewDirName], 1)
+
+	assert.NotContains(t, classified, "some-other-file.txt")
+}
+
+func TestNewAsyncReader(t *testing.T) {
+	testCases := map[string]struct {
+		baseURL  string
+		bucket   string
+		repo     string
+		subPath  string
+		token    string
+		rdType   ReaderType
+		wantType interface{}
+		wantErr  bool
+	}{
+		"git type": {
+			baseURL:  "https://github.com/kubevela/catalog",
+			subPath:  "addons",
+			rdType:   gitType,
+			wantType: &gitReader{},
+			wantErr:  false,
+		},
+		"gitee type": {
+			baseURL:  "https://gitee.com/kubevela/catalog",
+			subPath:  "addons",
+			rdType:   giteeType,
+			wantType: &giteeReader{},
+			wantErr:  false,
+		},
+		"oss type": {
+			baseURL:  "oss-cn-hangzhou.aliyuncs.com",
+			bucket:   "kubevela-addons",
+			rdType:   ossType,
+			wantType: &ossReader{},
+			wantErr:  false,
+		},
+		"invalid url": {
+			baseURL: "://invalid-url",
+			rdType:  gitType,
+			wantErr: true,
+		},
+		"invalid type": {
+			baseURL: "https://github.com/kubevela/catalog",
+			rdType:  "invalid",
+			wantErr: true,
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			// Note: This test does not cover the gitlab case as it requires a live API call
+			// or a complex mock setup, which is beyond the scope of this unit test.
+			if tc.rdType == gitlabType {
+				t.Skip("Skipping gitlab test in this unit test suite.")
+			}
+
+			reader, err := NewAsyncReader(tc.baseURL, tc.bucket, tc.repo, tc.subPath, tc.token, tc.rdType)
+
+			if tc.wantErr {
+				assert.Error(t, err)
+			} else {
+				assert.NoError(t, err)
+				assert.IsType(t, tc.wantType, reader)
+			}
+		})
+	}
+}
+
 func TestPathWithParent(t *testing.T) {
 	testCases := []struct {
 		readPath       string
@@ -154,3 +275,47 @@ func TestSafeCopy(t *testing.T) {
 	assert.Empty(t, shelm.Password)
 	assert.Equal(t, "https://hub.vela.com/chartrepo/addons", shelm.URL)
 }
+
+func TestTokenSource(t *testing.T) {
+	t.Run("GitAddonSource", func(t *testing.T) {
+		source := &GitAddonSource{}
+		assert.Equal(t, "", source.GetToken())
+		assert.Equal(t, "", source.GetTokenSecretRef())
+
+		source.SetToken("test-token")
+		assert.Equal(t, "test-token", source.GetToken())
+		assert.Equal(t, "", source.GetTokenSecretRef())
+
+		source.SetTokenSecretRef("test-secret")
+		assert.Equal(t, "test-secret", source.GetTokenSecretRef())
+		assert.Equal(t, "", source.GetToken())
+	})
+
+	t.Run("GiteeAddonSource", func(t *testing.T) {
+		source := &GiteeAddonSource{}
+		assert.Equal(t, "", source.GetToken())
+		assert.Equal(t, "", source.GetTokenSecretRef())
+
+		source.SetToken("test-token")
+		assert.Equal(t, "test-token", source.GetToken())
+		assert.Equal(t, "", source.GetTokenSecretRef())
+
+		source.SetTokenSecretRef("test-secret")
+		assert.Equal(t, "test-secret", source.GetTokenSecretRef())
+		assert.Equal(t, "", source.GetToken())
+	})
+
+	t.Run("GitlabAddonSource", func(t *testing.T) {
+		source := &GitlabAddonSource{}
+		assert.Equal(t, "", source.GetToken())
+		assert.Equal(t, "", source.GetTokenSecretRef())
+
+		source.SetToken("test-token")
+		assert.Equal(t, "test-token", source.GetToken())
+		assert.Equal(t, "", source.GetTokenSecretRef())
+
+		source.SetTokenSecretRef("test-secret")
+		assert.Equal(t, "test-secret", source.GetTokenSecretRef())
+		assert.Equal(t, "", source.GetToken())
+	})
+}
diff --git a/pkg/addon/utils_test.go b/pkg/addon/utils_test.go
index e1c462d1..07fec6c9 100644
--- a/pkg/addon/utils_test.go
+++ b/pkg/addon/utils_test.go
@@ -26,6 +26,7 @@ import (
 	. "github.com/onsi/ginkgo/v2"
 	. "github.com/onsi/gomega"
 	"github.com/stretchr/testify/assert"
+	"helm.sh/helm/v3/pkg/chart"
 	"helm.sh/helm/v3/pkg/chartutil"
 	v1 "k8s.io/api/core/v1"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -116,6 +117,86 @@ var _ = Describe("Test definition check", func() {
 		Expect(err).Should(BeNil())
 		Expect(len(usedApps)).Should(BeEquivalentTo(4))
 	})
+
+	It("Test checkConflictDefs", func() {
+		const appName = "addon-fluxcd"
+		const otherAppName = "addon-other"
+		isController := true
+
+		// A definition that doesn't exist in the cluster
+		nonExistingDef := &unstructured.Unstructured{}
+		nonExistingDef.SetAPIVersion("core.oam.dev/v1beta1")
+		nonExistingDef.SetKind("ComponentDefinition")
+		nonExistingDef.SetName("non-existing-def")
+		nonExistingDef.SetNamespace(velatypes.DefaultKubeVelaNS)
+
+		// A definition that exists but has no owner
+		defWithNoOwner := &unstructured.Unstructured{}
+		defWithNoOwner.SetAPIVersion("core.oam.dev/v1beta1")
+		defWithNoOwner.SetKind("ComponentDefinition")
+		defWithNoOwner.SetName("def-no-owner")
+		defWithNoOwner.SetNamespace(velatypes.DefaultKubeVelaNS)
+		Expect(k8sClient.Create(ctx, defWithNoOwner)).Should(Succeed())
+		defer func() {
+			Expect(k8sClient.Delete(ctx, defWithNoOwner)).Should(Succeed())
+		}()
+
+		// A definition that is owned by another addon
+		defWithOtherOwner := &unstructured.Unstructured{}
+		defWithOtherOwner.SetAPIVersion("core.oam.dev/v1beta1")
+		defWithOtherOwner.SetKind("ComponentDefinition")
+		defWithOtherOwner.SetName("def-other-owner")
+		defWithOtherOwner.SetNamespace(velatypes.DefaultKubeVelaNS)
+		defWithOtherOwner.SetOwnerReferences([]metav1.OwnerReference{
+			{
+				APIVersion: v1beta1.SchemeGroupVersion.String(),
+				Kind:       v1beta1.ApplicationKind,
+				Name:       otherAppName,
+				Controller: &isController,
+				UID:        "test-uid-other",
+			},
+		})
+		Expect(k8sClient.Create(ctx, defWithOtherOwner)).Should(Succeed())
+		defer func() {
+			Expect(k8sClient.Delete(ctx, defWithOtherOwner)).Should(Succeed())
+		}()
+
+		// A definition that is owned by the same addon
+		defWithSameOwner := &unstructured.Unstructured{}
+		defWithSameOwner.SetAPIVersion("core.oam.dev/v1beta1")
+		defWithSameOwner.SetKind("ComponentDefinition")
+		defWithSameOwner.SetName("def-same-owner")
+		defWithSameOwner.SetNamespace(velatypes.DefaultKubeVelaNS)
+		defWithSameOwner.SetOwnerReferences([]metav1.OwnerReference{
+			{
+				APIVersion: v1beta1.SchemeGroupVersion.String(),
+				Kind:       v1beta1.ApplicationKind,
+				Name:       appName,
+				Controller: &isController,
+				UID:        "test-uid-same",
+			},
+		})
+		Expect(k8sClient.Create(ctx, defWithSameOwner)).Should(Succeed())
+		defer func() {
+			Expect(k8sClient.Delete(ctx, defWithSameOwner)).Should(Succeed())
+		}()
+
+		By("Checking a mix of definitions for conflicts")
+		defs := []*unstructured.Unstructured{
+			nonExistingDef,
+			defWithNoOwner,
+			defWithOtherOwner,
+			defWithSameOwner,
+		}
+
+		conflicts, err := checkConflictDefs(ctx, k8sClient, defs, appName)
+		Expect(err).Should(BeNil())
+		Expect(len(conflicts)).Should(Equal(2))
+		Expect(conflicts).Should(HaveKey(defWithNoOwner.GetName()))
+		Expect(conflicts[defWithNoOwner.GetName()]).Should(ContainSubstring("already exist and not belong to any addon"))
+		Expect(conflicts).Should(HaveKey(defWithOtherOwner.GetName()))
+		Expect(conflicts[defWithOtherOwner.GetName()]).Should(ContainSubstring("already exist in other"))
+	})
 })
 
 func TestMerge2Map(t *testing.T) {
@@ -402,6 +483,90 @@ func TestCheckAddonPackageValid(t *testing.T) {
 	}
 }
 
+func TestIsRegistryFuncs(t *testing.T) {
+	t.Run("IsLocalRegistry", func(t *testing.T) {
+		assert.True(t, IsLocalRegistry(Registry{Name: "local"}))
+		assert.False(t, IsLocalRegistry(Registry{Name: "KubeVela"}))
+	})
+	t.Run("IsVersionRegistry", func(t *testing.T) {
+		assert.True(t, IsVersionRegistry(Registry{Helm: &HelmSource{}}))
+		assert.False(t, IsVersionRegistry(Registry{Git: &GitAddonSource{}}))
+		assert.False(t, IsVersionRegistry(Registry{}))
+	})
+}
+
+func TestInstallOptions(t *testing.T) {
+	t.Run("SkipValidateVersion", func(t *testing.T) {
+		installer := &Installer{}
+		SkipValidateVersion(installer)
+		assert.True(t, installer.skipVersionValidate)
+	})
+	t.Run("DryRunAddon", func(t *testing.T) {
+		installer := &Installer{}
+		DryRunAddon(installer)
+		assert.True(t, installer.dryRun)
+	})
+	t.Run("OverrideDefinitions", func(t *testing.T) {
+		installer := &Installer{}
+		OverrideDefinitions(installer)
+		assert.True(t, installer.overrideDefs)
+	})
+}
+
+func TestProduceDefConflictError(t *testing.T) {
+	t.Run("no conflicts", func(t *testing.T) {
+		err := produceDefConflictError(map[string]string{})
+		assert.NoError(t, err)
+	})
+	t.Run("with conflicts", func(t *testing.T) {
+		conflicts := map[string]string{
+			"def1": "error message 1",
+			"def2": "error message 2",
+		}
+		err := produceDefConflictError(conflicts)
+		assert.Error(t, err)
+		assert.Contains(t, err.Error(), "error message 1")
+		assert.Contains(t, err.Error(), "error message 2")
+		assert.Contains(t, err.Error(), "--override-definitions")
+	})
+}
+
+func TestGenerateChartMetadata(t *testing.T) {
+	addonDir := t.TempDir()
+
+	// Corrected YAML content with no leading whitespace
+	metaFileContent := `name: my-addon
+version: 1.2.3
+description: my addon description
+icon: http://my-icon.com
+url: http://my-home.com
+tags:
+  - tag1
+  - tag2
+system:
+  vela: ">=1.5.0"
+  kubernetes: "1.20.0"
+`
+	err := os.WriteFile(filepath.Join(addonDir, MetadataFileName), []byte(metaFileContent), 0644)
+	assert.NoError(t, err)
+
+	chartMeta, err := generateChartMetadata(addonDir)
+	assert.NoError(t, err)
+	assert.NotNil(t, chartMeta)
+
+	assert.Equal(t, "my-addon", chartMeta.Name)
+	assert.Equal(t, "1.2.3", chartMeta.Version)
+	assert.Equal(t, "my addon description", chartMeta.Description)
+	assert.Equal(t, "library", chartMeta.Type)
+	assert.Equal(t, chart.APIVersionV2, chartMeta.APIVersion)
+	assert.Equal(t, "http://my-icon.com", chartMeta.Icon)
+	assert.Equal(t, "http://my-home.com", chartMeta.Home)
+	assert.Equal(t, []string{"tag1", "tag2"}, chartMeta.Keywords)
+	assert.Equal(t, ">=1.5.0", chartMeta.Annotations[velaSystemRequirement])
+	assert.Equal(t, "1.20.0", chartMeta.Annotations[kubernetesSystemRequirement])
+	assert.Equal(t, "my-addon", chartMeta.Annotations[addonSystemRequirement])
+}
+
 const (
 	compDefYaml = `
 apiVersion: core.oam.dev/v1beta1
diff --git a/pkg/addon/versioned_registry_test.go b/pkg/addon/versioned_registry_test.go
index 34abd314..a15f8e67 100644
--- a/pkg/addon/versioned_registry_test.go
+++ b/pkg/addon/versioned_registry_test.go
@@ -17,6 +17,7 @@ limitations under the License.
 package addon
 
 import (
+	"context"
 	"encoding/base64"
 	"net/http"
 	"net/http/httptest"
@@ -28,6 +29,7 @@ import (
 	"helm.sh/helm/v3/pkg/repo"
 
 	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
 
 	"github.com/oam-dev/kubevela/pkg/utils/common"
 	"github.com/oam-dev/kubevela/pkg/utils/helm"
@@ -227,3 +229,159 @@ func TestToVersionedRegistry(t *testing.T) {
 	assert.EqualError(t, err, "registry 'git-based-registry' is not a versioned registry")
 	assert.Nil(t, actual)
 }
+
+func TestResolveAddonListFromIndex(t *testing.T) {
+	r := &versionedRegistry{name: "test-repo"}
+	indexFile := &repo.IndexFile{
+		Entries: map[string]repo.ChartVersions{
+			"addon-good": {
+				{Metadata: &chart.Metadata{Name: "addon-good", Version: "1.0.0", Description: "old desc", Icon: "old_icon", Keywords: []string{"tag1"}}},
+				{Metadata: &chart.Metadata{Name: "addon-good", Version: "1.2.0", Description: "latest desc", Icon: "latest_icon", Keywords: []string{"tag2"}}},
+				{Metadata: &chart.Metadata{Name: "addon-good", Version: "1.1.0", Description: "middle desc", Icon: "middle_icon", Keywords: []string{"tag3"}}},
+			},
+			"addon-empty": {},
+			"addon-single": {
+				{Metadata: &chart.Metadata{Name: "addon-single", Version: "0.1.0", Description: "single desc"}},
+			},
+		},
+	}
+
+	result := r.resolveAddonListFromIndex(r.name, indexFile)
+
+	assert.Equal(t, 2, len(result))
+
+	var addonGood, addonSingle *UIData
+	for _, addon := range result {
+		if addon.Name == "addon-good" {
+			addonGood = addon
+		}
+		if addon.Name == "addon-single" {
+			addonSingle = addon
+		}
+	}
+
+	require.NotNil(t, addonGood)
+	assert.Equal(t, "addon-good", addonGood.Name)
+	assert.Equal(t, "test-repo", addonGood.RegistryName)
+	assert.Equal(t, "1.2.0", addonGood.Version)
+	assert.Equal(t, "latest desc", addonGood.Description)
+	assert.Equal(t, "latest_icon", addonGood.Icon)
+	assert.Equal(t, []string{"tag2"}, addonGood.Tags)
+	assert.Equal(t, []string{"1.2.0", "1.1.0", "1.0.0"}, addonGood.AvailableVersions)
+
+	require.NotNil(t, addonSingle)
+	assert.Equal(t, "addon-single", addonSingle.Name)
+	assert.Equal(t, "0.1.0", addonSingle.Version)
+	assert.Equal(t, []string{"0.1.0"}, addonSingle.AvailableVersions)
+}
+
+// setupAddonTestServer creates a mock HTTP server for testing addon loading.
+// It can simulate success, 404 errors, or serving corrupt data based on the handlerType.
+func setupAddonTestServer(t *testing.T, handlerType string) string {
+	var server *httptest.Server
+	// This handler rewrites URLs in the index file to point to the server it's running on.
+	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if strings.Contains(r.URL.Path, "index.yaml") {
+			content, err := os.ReadFile("./testdata/multiversion-helm-repo/index.yaml")
+			assert.NoError(t, err)
+			newContent := strings.ReplaceAll(string(content), "http://127.0.0.1:18083/multi", server.URL)
+			_, err = w.Write([]byte(newContent))
+			assert.NoError(t, err)
+			return
+		}
+
+		// After serving the index, the next request depends on the handler type.
+		switch handlerType {
+		case "success":
+			multiVersionHandler(w, r)
+		case "notfound":
+			w.WriteHeader(http.StatusNotFound)
+		case "corrupt":
+			_, err := w.Write([]byte("this is not a valid tgz file"))
+			assert.NoError(t, err)
+		default:
+			t.Errorf("unknown handler type: %s", handlerType)
+		}
+	})
+	server = httptest.NewServer(handler)
+	t.Cleanup(server.Close)
+	return server.URL
+}
+
+func TestLoadAddon(t *testing.T) {
+	testCases := []struct {
+		name           string
+		handlerType    string
+		addonName      string
+		addonVersion   string
+		expectErr      bool
+		expectedErrStr string
+		checkFunc      func(t *testing.T, pkg *WholeAddonPackage)
+	}{
+		{
+			name:         "Success case",
+			handlerType:  "success",
+			addonName:    "fluxcd",
+			addonVersion: "1.0.0",
+			expectErr:    false,
+			checkFunc: func(t *testing.T, pkg *WholeAddonPackage) {
+				assert.NotNil(t, pkg)
+				assert.Equal(t, "fluxcd", pkg.Name)
+				assert.Equal(t, "1.0.0", pkg.Version)
+				assert.NotEmpty(t, pkg.YAMLTemplates)
+				assert.Equal(t, []string{"2.0.0", "1.0.0"}, pkg.AvailableVersions)
+			},
+		},
+		{
+			name:           "Version not found",
+			handlerType:    "success",
+			addonName:      "fluxcd",
+			addonVersion:   "3.0.0",
+			expectErr:      true,
+			expectedErrStr: "specified version 3.0.0 for addon fluxcd not exist",
+		},
+		{
+			name:           "Chart download fails",
+			handlerType:    "notfound",
+			addonName:      "fluxcd",
+			addonVersion:   "1.0.0",
+			expectErr:      true,
+			expectedErrStr: ErrFetch.Error(),
+		},
+		{
+			name:           "Corrupt chart file",
+			handlerType:    "corrupt",
+			addonName:      "fluxcd",
+			addonVersion:   "1.0.0",
+			expectErr:      true,
+			expectedErrStr: ErrFetch.Error(),
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			serverURL := setupAddonTestServer(t, tc.handlerType)
+			reg := &versionedRegistry{
+				name: "test-registry",
+				url:  serverURL,
+				h:    helm.NewHelperWithCache(),
+				Opts: nil,
+			}
+
+			pkg, err := reg.loadAddon(context.Background(), tc.addonName, tc.addonVersion)
+
+			if tc.expectErr {
+				assert.Error(t, err)
+				if tc.expectedErrStr != "" {
+					assert.Contains(t, err.Error(), tc.expectedErrStr)
+				}
+			} else {
+				assert.NoError(t, err)
+			}
+
+			if tc.checkFunc != nil {
+				tc.checkFunc(t, pkg)
+			}
+		})
+	}
+}
diff --git a/pkg/appfile/appfile_test.go b/pkg/appfile/appfile_test.go
index 521a5aa9..cca5e852 100644
--- a/pkg/appfile/appfile_test.go
+++ b/pkg/appfile/appfile_test.go
@@ -19,26 +19,33 @@ package appfile
 import (
 	"context"
 	"encoding/json"
+	"strings"
 	"testing"
 
 	"cuelang.org/go/cue/cuecontext"
+	"github.com/crossplane/crossplane-runtime/pkg/fieldpath"
 	"github.com/crossplane/crossplane-runtime/pkg/test"
 	"github.com/google/go-cmp/cmp"
 	terraformtypes "github.com/oam-dev/terraform-controller/api/types/crossplane-runtime"
 	terraformapi "github.com/oam-dev/terraform-controller/api/v1beta2"
-	. "github.com/onsi/ginkgo/v2"
-	. "github.com/onsi/gomega"
 	"github.com/pkg/errors"
 	"github.com/stretchr/testify/assert"
 	appsv1 "k8s.io/api/apps/v1"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
 	"k8s.io/apimachinery/pkg/runtime"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
 	"sigs.k8s.io/yaml"
 
 	"github.com/kubevela/workflow/pkg/cue/model"
 
+	workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
+	corev1 "k8s.io/api/core/v1"
+	kerrors "k8s.io/apimachinery/pkg/api/errors"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+
 	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1"
 	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
 	oamtypes "github.com/oam-dev/kubevela/apis/types"
 	"github.com/oam-dev/kubevela/pkg/cue/definition"
@@ -47,8 +54,9 @@ import (
 	"github.com/oam-dev/kubevela/pkg/oam/util"
 )
 
-var _ = Describe("Test Workflow", func() {
-	It("generate workflow task runners", func() {
+func TestWorkflow(t *testing.T) {
+	k8sClient := fake.NewClientBuilder().Build()
+	t.Run("generate workflow task runners", func(t *testing.T) {
 		workflowStepDef := v1beta1.WorkflowStepDefinition{
 			Spec: v1beta1.WorkflowStepDefinitionSpec{
 				Schematic: &common.Schematic{
@@ -65,7 +73,7 @@ wait: op.#ConditionalWait & {
 		workflowStepDef.Name = "test-wait"
 		workflowStepDef.Namespace = "default"
 		err := k8sClient.Create(context.Background(), &workflowStepDef)
-		Expect(err).To(BeNil())
+		assert.NoError(t, err)
 
 		notCueStepDef := v1beta1.WorkflowStepDefinition{
 			Spec: v1beta1.WorkflowStepDefinitionSpec{
@@ -76,12 +84,12 @@ wait: op.#ConditionalWait & {
 		notCueStepDef.Name = "not-cue"
 		notCueStepDef.Namespace = "default"
 		err = k8sClient.Create(context.Background(), &notCueStepDef)
-		Expect(err).To(BeNil())
+		assert.NoError(t, err)
 	})
-})
+}
 
-var _ = Describe("Test Terraform schematic appfile", func() {
-	It("workload capability is Terraform", func() {
+func TestTerraformSchematicAppfile(t *testing.T) {
+	t.Run("workload capability is Terraform", func(t *testing.T) {
 		var (
 			ns            = "default"
 			compName      = "sample-db"
@@ -202,10 +210,10 @@ variable "password" {
 
 		comps, err := af.GenerateComponentManifests()
 		diff := cmp.Diff(comps[0], expectCompManifest)
-		Expect(diff).ShouldNot(BeEmpty())
-		Expect(err).Should(BeNil())
+		assert.NotEmpty(t, diff)
+		assert.NoError(t, err)
 	})
-})
+}
 
 func TestSetParameterValuesToKubeObj(t *testing.T) {
 	tests := map[string]struct {
@@ -301,18 +309,20 @@ func TestSetParameterValuesToKubeObj(t *testing.T) {
 			obj := tc.obj.DeepCopy()
 			err := setParameterValuesToKubeObj(obj, tc.values)
 			if diff := cmp.Diff(tc.wantObj, *obj); diff != "" {
-				t.Errorf("\nsetParameterValuesToKubeObj(...)error -want +get \nreason:%s\n%s\n", tc.reason, diff)
+				t.Errorf(
+					"\nsetParameterValuesToKubeObj(...)error -want +get \nreason:%s\n%s\n", tc.reason, diff)
 			}
 			if diff := cmp.Diff(tc.wantErr, err, test.EquateErrors()); diff != "" {
-				t.Errorf("\nsetParameterValuesToKubeObj(...)error -want +get \nreason:%s\n%s\n", tc.reason, diff)
+				t.Errorf(
+					"\nsetParameterValuesToKubeObj(...)error -want +get \nreason:%s\n%s\n", tc.reason, diff)
 			}
 		})
 	}
 
 }
 
-var _ = Describe("Test evalWorkloadWithContext", func() {
-	It("workload capability is Terraform", func() {
+func TestEvalWorkloadWithContext(t *testing.T) {
+	t.Run("workload capability is Terraform", func(t *testing.T) {
 		var (
 			ns       = "default"
 			compName = "sample-db"
@@ -404,11 +414,11 @@ variable "password" {
 		}, args.wl.Name)
 		pCtx := NewBasicContext(ctxData, args.wl.Params)
 		comp, err := evalWorkloadWithContext(pCtx, args.wl, ns, args.appName)
-		Expect(comp.ComponentOutput).ShouldNot(BeNil())
-		Expect(comp.Name).Should(Equal(""))
-		Expect(err).Should(BeNil())
+		assert.NotNil(t, comp.ComponentOutput)
+		assert.Equal(t, "", comp.Name)
+		assert.NoError(t, err)
 	})
-})
+}
 
 func TestGenerateTerraformConfigurationWorkload(t *testing.T) {
 	var (
@@ -700,16 +710,16 @@ func TestBaseGenerateComponent(t *testing.T) {
 	}, wlName)
 	pContext := NewBasicContext(ctxData, nil)
 	base := `
-	apiVersion: "apps/v1"
-	kind:       "Deployment"
-	spec: {
-		template: {
-			spec: containers: [{
-				image: "nginx"
-			}]
+		apiVersion: "apps/v1"
+		kind:       "Deployment"
+		spec: {
+			template: {
+				spec: containers: [{
+					image: "nginx"
+				}]
+			}
 		}
-	}
-`
+	`
 	inst := cuecontext.New().CompileString(base)
 	bs, _ := model.NewBase(inst.Value())
 	err := pContext.SetBase(bs)
@@ -738,8 +748,8 @@ if context.componentType == "stateless" {
 	assert.Equal(t, cm.ComponentOutputsAndTraits[0].Object["publishVersion"], publishVersion)
 }
 
-var _ = Describe("Test use context.appLabels& context.appAnnotations in componentDefinition ", func() {
-	It("Test generate AppConfig resources from ", func() {
+func TestAppLabelsAndAnnotationsInComponentDefinition(t *testing.T) {
+	t.Run("generate AppConfig resources", func(t *testing.T) {
 		af := &Appfile{
 			Name:      "app",
 			Namespace: "ns",
@@ -769,7 +779,6 @@ var _ = Describe("Test use context.appLabels& context.appAnnotations in componen
 								selector: matchLabels: {
 									"app.oam.dev/component": context.name
 								}
-						  
 								template: {
 									metadata: {
 										labels: {
@@ -783,47 +792,971 @@ var _ = Describe("Test use context.appLabels& context.appAnnotations in componen
 											}
 										}
 									}
-						  
 									spec: {
-										containers: [{
+										containers: [{ 
 											name:  context.name
 											image: parameter.image
-						  
 											if parameter["cmd"] != _|_ {
 												command: parameter.cmd
 											}
 										}]
 									}
 								}
-						  
 								selector:
 									matchLabels:
 										"app.oam.dev/component": context.name
 							}
 						  }
-						  
-						  parameter: {
+						  parameter: { 
 							// +usage=Which image would you like to use for your service
 							// +short=i
 							image: string
-						  
 							cmd?: [...string]
 						  }`},
 				},
 			},
 		}
-		By("Generate ComponentManifests")
+
+		// Generate ComponentManifests
 		componentManifests, err := af.GenerateComponentManifests()
-		Expect(err).To(BeNil())
-		By("Verify expected ComponentManifest")
+		if err != nil {
+			t.Fatalf("GenerateComponentManifests() error = %v", err)
+		}
+
+		// Verify expected ComponentManifest
 		deployment := &appsv1.Deployment{}
-		runtime.DefaultUnstructuredConverter.FromUnstructured(componentManifests[0].ComponentOutput.Object, deployment)
+		if err := runtime.DefaultUnstructuredConverter.FromUnstructured(
+			componentManifests[0].ComponentOutput.Object, deployment); err != nil {
+			t.Fatalf("Failed to convert to Deployment: %v", err)
+		}
+
 		labels := deployment.Spec.Template.Labels
 		annotations := deployment.Spec.Template.Annotations
-		Expect(cmp.Diff(len(labels), 2)).Should(BeEmpty())
-		Expect(cmp.Diff(len(annotations), 2)).Should(BeEmpty())
-		Expect(cmp.Diff(labels["lk1"], "lv1")).Should(BeEmpty())
-		Expect(cmp.Diff(annotations["ak1"], "av1")).Should(BeEmpty())
+
+		if diff := cmp.Diff(len(labels), 2); diff != "" {
+			t.Errorf("labels length mismatch (-want +got): %s", diff)
+		}
+		if diff := cmp.Diff(len(annotations), 2); diff != "" {
+			t.Errorf("annotations length mismatch (-want +got): %s", diff)
+		}
+		if diff := cmp.Diff(labels["lk1"], "lv1"); diff != "" {
+			t.Errorf("label mismatch (-want +got): %s", diff)
+		}
+		if diff := cmp.Diff(annotations["ak1"], "av1"); diff != "" {
+			t.Errorf("annotation mismatch (-want +got): %s", diff)
+		}
+	})
+}
+
+func TestIsNotFoundInAppFile(t *testing.T) {
+	tests := map[string]struct {
+		err  error
+		want bool
+	}{
+		"ErrorIsNil": {
+			err:  nil,
+			want: false,
+		},
+		"ErrorContainsSubstring": {
+			err:  errors.New("some error not found in appfile"),
+			want: true,
+		},
+		"ErrorNotContainsSubstring": {
+			err:  errors.New("some other error"),
+			want: false,
+		},
+	}
+
+	for name, tc := range tests {
+		t.Run(name, func(t *testing.T) {
+			got := IsNotFoundInAppFile(tc.err)
+			assert.Equal(t, tc.want, got)
+		})
+	}
+}
+
+func TestPrepareProcessContext(t *testing.T) {
+	ctxData := process.ContextData{
+		AppName:   "test-app",
+		Namespace: "test-ns",
+	}
+
+	t.Run("Success case with nil initial context", func(t *testing.T) {
+		comp := &Component{
+			engine: definition.NewWorkloadAbstractEngine("test"),
+			FullTemplate: &Template{
+				TemplateStr: `
+output: {}
+parameter: {name: string}
+`,
+			},
+			Params: map[string]interface{}{"name": "test-name"},
+		}
+		assert.Nil(t, comp.Ctx)
+
+		ctx, err := PrepareProcessContext(comp, ctxData)
+
+		assert.NoError(t, err)
+		assert.NotNil(t, ctx)
+		assert.NotNil(t, comp.Ctx)
+		assert.Equal(t, ctx, comp.Ctx)
+	})
+
+	t.Run("Error case from invalid CUE template", func(t *testing.T) {
+		comp := &Component{
+			engine: definition.NewWorkloadAbstractEngine("test"),
+			FullTemplate: &Template{
+				TemplateStr: `
+output: {}
+parameter: {name: string & int}
+`,
+			},
+			Params: map[string]interface{}{"name": "test-name"},
+		}
+
+		_, err := PrepareProcessContext(comp, ctxData)
+
+		assert.Error(t, err)
+		assert.ErrorContains(t, err, "conflicting values string and int")
 	})
 
-})
+	t.Run("Use existing context if not nil", func(t *testing.T) {
+		comp := &Component{
+			engine: definition.NewWorkloadAbstractEngine("test"),
+			FullTemplate: &Template{
+				TemplateStr: `
+output: {}
+parameter: {name: string}
+`,
+			},
+			Params: map[string]interface{}{"name": "test-name"},
+		}
+
+		// First call to populate context
+		ctx1, err := PrepareProcessContext(comp, ctxData)
+		assert.NoError(t, err)
+		assert.NotNil(t, ctx1)
+
+		// Second call
+		ctx2, err := PrepareProcessContext(comp, ctxData)
+		assert.NoError(t, err)
+		assert.NotNil(t, ctx2)
+
+		// Check if the context object is the same
+		assert.Same(t, ctx1, ctx2)
+	})
+}
+
+func TestLoadDynamicComponent(t *testing.T) {
+	ctx := context.Background()
+	cli := fake.NewClientBuilder().Build()
+
+	t.Run("Non-ref-objects component", func(t *testing.T) {
+		af := &Appfile{}
+		comp := &common.ApplicationComponent{
+			Type: "webservice",
+		}
+		resultComp, err := af.LoadDynamicComponent(ctx, cli, comp)
+		assert.NoError(t, err)
+		assert.Equal(t, comp, resultComp)
+	})
+
+	t.Run("Invalid properties", func(t *testing.T) {
+		af := &Appfile{}
+		comp := &common.ApplicationComponent{
+			Type: v1alpha1.RefObjectsComponentType,
+			Properties: &runtime.RawExtension{
+				Raw: []byte(`{"objects": "not-an-array"}`),
+			},
+		}
+		_, err := af.LoadDynamicComponent(ctx, cli, comp)
+		assert.Error(t, err)
+		assert.Contains(t, err.Error(), "invalid ref-objects component properties")
+	})
+
+	t.Run("Success with URL selectors", func(t *testing.T) {
+		objWithURL := &unstructured.Unstructured{
+			Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "Secret",
+				"metadata": map[string]interface{}{
+					"name":      "secret1",
+					"namespace": "default",
+					"annotations": map[string]interface{}{
+						oam.AnnotationResourceURL: "http://example.com/secret.yaml",
+					},
+				},
+			},
+		}
+		af := &Appfile{
+			Namespace:       "default",
+			ReferredObjects: []*unstructured.Unstructured{objWithURL},
+			app:             &v1beta1.Application{},
+		}
+		comp := &common.ApplicationComponent{
+			Name: "my-comp",
+			Type: v1alpha1.RefObjectsComponentType,
+			Properties: &runtime.RawExtension{
+				Raw: []byte(`{"urls": ["http://example.com/secret.yaml"]}`),
+			},
+		}
+
+		resultComp, err := af.LoadDynamicComponent(ctx, cli, comp)
+		assert.NoError(t, err)
+
+		refObjList := &common.ReferredObjectList{}
+		err = json.Unmarshal(resultComp.Properties.Raw, refObjList)
+		assert.NoError(t, err)
+		assert.Len(t, refObjList.Objects, 1)
+
+		u := &unstructured.Unstructured{}
+		err = u.UnmarshalJSON(refObjList.Objects[0].Raw)
+		assert.NoError(t, err)
+		assert.Equal(t, "Secret", u.GetKind())
+		assert.Equal(t, "secret1", u.GetName())
+	})
+}
+
+func TestPolicyClient(t *testing.T) {
+	ctx := context.Background()
+	policy := &v1alpha1.Policy{
+		ObjectMeta: metav1.ObjectMeta{Name: "my-policy", Namespace: "default"},
+		Type:       "override",
+	}
+	policyKey := client.ObjectKeyFromObject(policy)
+
+	cm := &corev1.ConfigMap{
+		ObjectMeta: metav1.ObjectMeta{Name: "my-cm", Namespace: "default"},
+		Data:       map[string]string{"key": "value"},
+	}
+	cmKey := client.ObjectKeyFromObject(cm)
+
+	t.Run("With AppRevision, policy in cache", func(t *testing.T) {
+		af := &Appfile{
+			AppRevision: &v1beta1.ApplicationRevision{},
+			ExternalPolicies: map[string]*v1alpha1.Policy{
+				policyKey.String(): policy,
+			},
+		}
+		cli := fake.NewClientBuilder().Build()
+		policyClient := af.PolicyClient(cli)
+
+		retrievedPolicy := &v1alpha1.Policy{}
+		err := policyClient.Get(ctx, policyKey, retrievedPolicy)
+		assert.NoError(t, err)
+		assert.Equal(t, policy, retrievedPolicy)
+	})
+
+	t.Run("With AppRevision, policy not in cache", func(t *testing.T) {
+		af := &Appfile{
+			AppRevision:      &v1beta1.ApplicationRevision{},
+			ExternalPolicies: map[string]*v1alpha1.Policy{},
+		}
+		// The policy exists in the client, but it should not be returned
+		cli := fake.NewClientBuilder().WithObjects(policy).Build()
+		policyClient := af.PolicyClient(cli)
+
+		retrievedPolicy := &v1alpha1.Policy{}
+		err := policyClient.Get(ctx, policyKey, retrievedPolicy)
+		assert.Error(t, err)
+		assert.True(t, kerrors.IsNotFound(err))
+	})
+
+	t.Run("With AppRevision, get non-policy object", func(t *testing.T) {
+		af := &Appfile{
+			AppRevision: &v1beta1.ApplicationRevision{},
+		}
+		cli := fake.NewClientBuilder().WithObjects(cm).Build()
+		policyClient := af.PolicyClient(cli)
+
+		retrievedCm := &corev1.ConfigMap{}
+		err := policyClient.Get(ctx, cmKey, retrievedCm)
+		assert.NoError(t, err)
+		assert.Equal(t, cm, retrievedCm)
+	})
+
+	t.Run("Without AppRevision, policy in client", func(t *testing.T) {
+		af := &Appfile{
+			ExternalPolicies: make(map[string]*v1alpha1.Policy),
+		}
+		cli := fake.NewClientBuilder().WithObjects(policy).Build()
+		policyClient := af.PolicyClient(cli)
+
+		retrievedPolicy := &v1alpha1.Policy{}
+		err := policyClient.Get(ctx, policyKey, retrievedPolicy)
+		assert.NoError(t, err)
+		assert.Equal(t, policy, retrievedPolicy)
+
+		// Check if the policy is now cached
+		cachedPolicy, found := af.ExternalPolicies[policyKey.String()]
+		assert.True(t, found)
+		assert.Equal(t, policy, cachedPolicy)
+	})
+
+	t.Run("Without AppRevision, policy not in client", func(t *testing.T) {
+		af := &Appfile{
+			ExternalPolicies: make(map[string]*v1alpha1.Policy),
+		}
+		cli := fake.NewClientBuilder().Build()
+		policyClient := af.PolicyClient(cli)
+
+		retrievedPolicy := &v1alpha1.Policy{}
+		err := policyClient.Get(ctx, policyKey, retrievedPolicy)
+		assert.Error(t, err)
+		assert.True(t, kerrors.IsNotFound(err))
+	})
+
+	t.Run("Without AppRevision, get non-policy object", func(t *testing.T) {
+		af := &Appfile{}
+		cli := fake.NewClientBuilder().WithObjects(cm).Build()
+		policyClient := af.PolicyClient(cli)
+
+		retrievedCm := &corev1.ConfigMap{}
+		err := policyClient.Get(ctx, cmKey, retrievedCm)
+		assert.NoError(t, err)
+		assert.Equal(t, cm, retrievedCm)
+	})
+}
+
+func TestWorkflowClient(t *testing.T) {
+	ctx := context.Background()
+	workflow := &workflowv1alpha1.Workflow{
+		ObjectMeta: metav1.ObjectMeta{Name: "my-workflow", Namespace: "default"},
+	}
+	workflowKey := client.ObjectKeyFromObject(workflow)
+
+	cm := &corev1.ConfigMap{
+		ObjectMeta: metav1.ObjectMeta{Name: "my-cm", Namespace: "default"},
+		Data:       map[string]string{"key": "value"},
+	}
+	cmKey := client.ObjectKeyFromObject(cm)
+
+	t.Run("With AppRevision, workflow in cache", func(t *testing.T) {
+		af := &Appfile{
+			AppRevision:      &v1beta1.ApplicationRevision{},
+			ExternalWorkflow: workflow,
+		}
+		cli := fake.NewClientBuilder().Build()
+		workflowClient := af.WorkflowClient(cli)
+
+		retrievedWorkflow := &workflowv1alpha1.Workflow{}
+		err := workflowClient.Get(ctx, workflowKey, retrievedWorkflow)
+		assert.NoError(t, err)
+		assert.Equal(t, workflow, retrievedWorkflow)
+	})
+
+	t.Run("With AppRevision, workflow not in cache", func(t *testing.T) {
+		af := &Appfile{
+			AppRevision: &v1beta1.ApplicationRevision{},
+		}
+		// The workflow exists in the client, but it should not be returned
+		cli := fake.NewClientBuilder().WithObjects(workflow).Build()
+		workflowClient := af.WorkflowClient(cli)
+
+		retrievedWorkflow := &workflowv1alpha1.Workflow{}
+		err := workflowClient.Get(ctx, workflowKey, retrievedWorkflow)
+		assert.Error(t, err)
+		assert.True(t, kerrors.IsNotFound(err))
+	})
+
+	t.Run("With AppRevision, get non-workflow object", func(t *testing.T) {
+		af := &Appfile{
+			AppRevision: &v1beta1.ApplicationRevision{},
+		}
+		cli := fake.NewClientBuilder().WithObjects(cm).Build()
+		workflowClient := af.WorkflowClient(cli)
+
+		retrievedCm := &corev1.ConfigMap{}
+		err := workflowClient.Get(ctx, cmKey, retrievedCm)
+		assert.NoError(t, err)
+		assert.Equal(t, cm, retrievedCm)
+	})
+
+	t.Run("Without AppRevision, workflow in client", func(t *testing.T) {
+		af := &Appfile{}
+		cli := fake.NewClientBuilder().WithObjects(workflow).Build()
+		workflowClient := af.WorkflowClient(cli)
+
+		retrievedWorkflow := &workflowv1alpha1.Workflow{}
+		err := workflowClient.Get(ctx, workflowKey, retrievedWorkflow)
+		assert.NoError(t, err)
+		assert.Equal(t, workflow, retrievedWorkflow)
+
+		// Check if the workflow is now cached
+		assert.Equal(t, workflow, af.ExternalWorkflow)
+	})
+
+	t.Run("Without AppRevision, workflow not in client", func(t *testing.T) {
+		af := &Appfile{}
+		cli := fake.NewClientBuilder().Build()
+		workflowClient := af.WorkflowClient(cli)
+
+		retrievedWorkflow := &workflowv1alpha1.Workflow{}
+		err := workflowClient.Get(ctx, workflowKey, retrievedWorkflow)
+		assert.Error(t, err)
+		assert.True(t, kerrors.IsNotFound(err))
+	})
+
+	t.Run("Without AppRevision, get non-workflow object", func(t *testing.T) {
+		af := &Appfile{}
+		cli := fake.NewClientBuilder().WithObjects(cm).Build()
+		workflowClient := af.WorkflowClient(cli)
+
+		retrievedCm := &corev1.ConfigMap{}
+		err := workflowClient.Get(ctx, cmKey, retrievedCm)
+		assert.NoError(t, err)
+		assert.Equal(t, cm, retrievedCm)
+	})
+}
+
+func TestSetWorkloadRefToTrait(t *testing.T) {
+	wlRef := corev1.ObjectReference{
+		APIVersion: "apps/v1",
+		Kind:       "Deployment",
+		Name:       "my-workload",
+	}
+
+	tests := map[string]struct {
+		reason    string
+		appfile   *Appfile
+		trait     *unstructured.Unstructured
+		wantTrait *unstructured.Unstructured
+		wantErr   error
+	}{
+		"AuxiliaryWorkloadTrait": {
+			reason:  "Should do nothing for auxiliary-workload traits",
+			appfile: &Appfile{},
+			trait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: definition.AuxiliaryWorkload,
+					},
+				},
+			}},
+			wantTrait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: definition.AuxiliaryWorkload,
+					},
+				},
+			}},
+			wantErr: nil,
+		},
+		"TraitDefinitionNotFound": {
+			reason: "Should return error if TraitDefinition is not found",
+			appfile: &Appfile{
+				RelatedTraitDefinitions: map[string]*v1beta1.TraitDefinition{},
+			},
+			trait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait",
+					},
+				},
+			}},
+			wantTrait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait",
+					},
+				},
+			}},
+			wantErr: errors.Errorf("TraitDefinition %s not found in appfile", "my-trait"),
+		},
+		"WorkloadRefPathIsEmpty": {
+			reason: "Should do nothing if workloadRefPath is empty",
+			appfile: &Appfile{
+				RelatedTraitDefinitions: map[string]*v1beta1.TraitDefinition{
+					"my-trait": {
+						Spec: v1beta1.TraitDefinitionSpec{
+							WorkloadRefPath: "",
+						},
+					},
+				},
+			},
+			trait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait",
+					},
+				},
+			}},
+			wantTrait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait",
+					},
+				},
+			}},
+			wantErr: nil,
+		},
+		"SetWorkloadRefSucceeds": {
+			reason: "Should set workload reference correctly",
+			appfile: &Appfile{
+				RelatedTraitDefinitions: map[string]*v1beta1.TraitDefinition{
+					"my-trait": {
+						Spec: v1beta1.TraitDefinitionSpec{
+							WorkloadRefPath: "spec.workloadRef",
+						},
+					},
+				},
+			},
+			trait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait",
+					},
+				},
+				"spec": map[string]interface{}{},
+			}},
+			wantTrait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait",
+					},
+				},
+				"spec": map[string]interface{}{
+					"workloadRef": map[string]interface{}{
+						"apiVersion": "apps/v1",
+						"kind":       "Deployment",
+						"name":       "my-workload",
+					},
+				},
+			}},
+			wantErr: nil,
+		},
+		"SetWorkloadRefWithSuffixedTraitType": {
+			reason: "Should find the base trait definition and set workload reference",
+			appfile: &Appfile{
+				RelatedTraitDefinitions: map[string]*v1beta1.TraitDefinition{
+					"my-trait": {
+						Spec: v1beta1.TraitDefinitionSpec{
+							WorkloadRefPath: "spec.workloadRef",
+						},
+					},
+				},
+			},
+			trait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait-abcde",
+					},
+				},
+				"spec": map[string]interface{}{},
+			}},
+			wantTrait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait-abcde",
+					},
+				},
+				"spec": map[string]interface{}{
+					"workloadRef": map[string]interface{}{
+						"apiVersion": "apps/v1",
+						"kind":       "Deployment",
+						"name":       "my-workload",
+					},
+				},
+			}},
+			wantErr: nil,
+		},
+		"InvalidWorkloadRefPath": {
+			reason: "Should return an error for an invalid workloadRefPath",
+			appfile: &Appfile{
+				RelatedTraitDefinitions: map[string]*v1beta1.TraitDefinition{
+					"my-trait": {
+						Spec: v1beta1.TraitDefinitionSpec{
+							WorkloadRefPath: "spec[workloadRef", // Invalid path
+						},
+					},
+				},
+			},
+			trait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait",
+					},
+				},
+			}},
+			wantTrait: &unstructured.Unstructured{Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"labels": map[string]interface{}{
+						oam.TraitTypeLabel: "my-trait",
+					},
+				},
+			}},
+			wantErr: fieldpath.Pave(map[string]interface{}{}).SetValue("spec[workloadRef", wlRef),
+		},
+	}
+
+	for name, tc := range tests {
+		t.Run(name, func(t *testing.T) {
+			traitCopy := tc.trait.DeepCopy()
+			err := tc.appfile.setWorkloadRefToTrait(wlRef, traitCopy)
+
+			if diff := cmp.Diff(tc.wantErr, err, test.EquateErrors()); diff != "" {
+				t.Errorf("\n%s\nsetWorkloadRefToTrait(...): -want error, +got error:\n%s\n", tc.reason, diff)
+			}
+			if diff := cmp.Diff(tc.wantTrait, traitCopy); diff != "" {
+				t.Errorf("\n%s\nsetWorkloadRefToTrait(...): -want trait, +got trait:\n%s\n", tc.reason, diff)
+			}
+		})
+	}
+}
+
+func TestSetOAMContract(t *testing.T) {
+	baseAppfile := &Appfile{
+		Name:            "test-app",
+		Namespace:       "test-ns",
+		AppRevisionName: "test-app-v1",
+		AppLabels: map[string]string{
+			"app-label": "app-label-val",
+		},
+		AppAnnotations: map[string]string{
+			"app-annot": "app-annot-val",
+		},
+		RelatedTraitDefinitions: map[string]*v1beta1.TraitDefinition{
+			"my-trait": {
+				Spec: v1beta1.TraitDefinitionSpec{
+					WorkloadRefPath: "spec.workloadRef",
+				},
+			},
+			"no-ref-trait": {
+				Spec: v1beta1.TraitDefinitionSpec{},
+			},
+		},
+	}
+
+	baseWorkload := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "apps/v1",
+			"kind":       "Deployment",
+			"metadata": map[string]interface{}{
+				"name": "my-workload",
+			},
+		},
+	}
+
+	baseTrait := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "v1",
+			"kind":       "Service",
+			"metadata": map[string]interface{}{
+				"labels": map[string]interface{}{
+					oam.TraitTypeLabel: "my-trait",
+				},
+			},
+		},
+	}
+
+	tests := map[string]struct {
+		reason   string
+		appfile  *Appfile
+		comp     *oamtypes.ComponentManifest
+		wantComp *oamtypes.ComponentManifest
+		wantErr  bool
+	}{
+		"SuccessBasic": {
+			reason:  "A basic workload and trait should be assembled correctly",
+			appfile: baseAppfile,
+			comp: &oamtypes.ComponentManifest{
+				Name:            "my-comp",
+				ComponentOutput: baseWorkload.DeepCopy(),
+				ComponentOutputsAndTraits: []*unstructured.Unstructured{
+					baseTrait.DeepCopy(),
+				},
+			},
+			wantComp: &oamtypes.ComponentManifest{
+				Name: "my-comp",
+				ComponentOutput: &unstructured.Unstructured{
+					Object: map[string]interface{}{
+						"apiVersion": "apps/v1",
+						"kind":       "Deployment",
+						"metadata": map[string]interface{}{
+							"name":      "my-workload",
+							"namespace": "test-ns",
+							"labels": map[string]interface{}{
+								"app-label":              "app-label-val",
+								oam.LabelAppName:         "test-app",
+								oam.LabelAppNamespace:    "test-ns",
+								oam.LabelAppRevision:     "test-app-v1",
+								oam.LabelAppComponent:    "my-comp",
+								oam.LabelOAMResourceType: oam.ResourceTypeWorkload,
+							},
+							"annotations": map[string]interface{}{
+								"app-annot": "app-annot-val",
+							},
+						},
+					},
+				},
+				ComponentOutputsAndTraits: []*unstructured.Unstructured{
+					{
+						Object: map[string]interface{}{
+							"apiVersion": "v1",
+							"kind":       "Service",
+							"metadata": map[string]interface{}{
+								"name":      "", // Name will be generated
+								"namespace": "test-ns",
+								"labels": map[string]interface{}{
+									"app-label":              "app-label-val",
+									oam.TraitTypeLabel:       "my-trait",
+									oam.LabelAppName:         "test-app",
+									oam.LabelAppNamespace:    "test-ns",
+									oam.LabelAppRevision:     "test-app-v1",
+									oam.LabelAppComponent:    "my-comp",
+									oam.LabelOAMResourceType: oam.ResourceTypeTrait,
+								},
+								"annotations": map[string]interface{}{
+									"app-annot": "app-annot-val",
+								},
+							},
+							"spec": map[string]interface{}{
+								"workloadRef": map[string]interface{}{
+									"apiVersion": "apps/v1",
+									"kind":       "Deployment",
+									"name":       "my-workload",
+								},
+							},
+						},
+					},
+				},
+			},
+			wantErr: false,
+		},
+	}
+
+	for name, tc := range tests {
+		t.Run(name, func(t *testing.T) {
+			compCopy := deepCopyComponentManifest(tc.comp)
+			err := tc.appfile.SetOAMContract(compCopy)
+
+			if (err != nil) != tc.wantErr {
+				t.Errorf("\n%s\nSetOAMContract(...): want error? %v, got error: %v\n", tc.reason, tc.wantErr, err)
+			}
+
+			if name == "SuccessBasic" || name == "SuccessNameGeneration" {
+				for i, trait := range compCopy.ComponentOutputsAndTraits {
+					gotName := trait.GetName()
+					wantTrait := tc.wantComp.ComponentOutputsAndTraits[i]
+					traitType := trait.GetLabels()[oam.TraitTypeLabel]
+					expectedPrefix := compCopy.Name + "-" + traitType + "-"
+
+					if !strings.HasPrefix(gotName, expectedPrefix) {
+						t.Errorf("\n%s\nSetOAMContract(...): trait name %q does not have expected prefix %q", tc.reason, gotName, expectedPrefix)
+					}
+					trait.SetName("")
+					wantTrait.SetName("")
+				}
+			}
+
+			if !tc.wantErr {
+				if diff := cmp.Diff(tc.wantComp.ComponentOutput, compCopy.ComponentOutput); diff != "" {
+					t.Errorf("\n%s\nSetOAMContract(...): -want workload, +got workload:\n%s\n", tc.reason, diff)
+				}
+				if diff := cmp.Diff(tc.wantComp.ComponentOutputsAndTraits, compCopy.ComponentOutputsAndTraits); diff != "" {
+					t.Errorf("\n%s\nSetOAMContract(...): -want traits, +got traits:\n%s\n", tc.reason, diff)
+				}
+			}
+		})
+	}
+}
+
+func deepCopyComponentManifest(in *oamtypes.ComponentManifest) *oamtypes.ComponentManifest {
+	if in == nil {
+		return nil
+	}
+	out := &oamtypes.ComponentManifest{
+		Name: in.Name,
+	}
+	if in.ComponentOutput != nil {
+		out.ComponentOutput = in.ComponentOutput.DeepCopy()
+	}
+	if in.ComponentOutputsAndTraits != nil {
+		out.ComponentOutputsAndTraits = make([]*unstructured.Unstructured, len(in.ComponentOutputsAndTraits))
+		for i, trait := range in.ComponentOutputsAndTraits {
+			if trait != nil {
+				out.ComponentOutputsAndTraits[i] = trait.DeepCopy()
+			}
+		}
+	}
+	return out
+}
+
+func TestGenerateComponentManifests(t *testing.T) {
+	baseEngine := definition.NewWorkloadAbstractEngine("test-engine")
+	baseTraitEngine := definition.NewTraitAbstractEngine("scaler")
+	baseTemplate := &Template{
+		TemplateStr: `
+			output: {
+				apiVersion: "apps/v1"
+				kind:       "Deployment"
+				spec: {
+					selector: matchLabels: {
+						"app.oam.dev/component": context.name
+					}
+					template: {
+						metadata: labels: {
+							"app.oam.dev/component": context.name
+						}
+						spec: containers: [{
+							name:  context.name
+							image: parameter.image
+						}]
+					}
+				}
+			}
+			parameter: {
+				image: string
+			}`,
+	}
+	baseTraitTemplate := &Trait{
+		Name:   "scaler",
+		engine: baseTraitEngine,
+		Template: `
+			outputs: scaler: {
+				apiVersion: "autoscaling/v2beta2"
+				kind:       "HorizontalPodAutoscaler"
+				spec: {
+					scaleTargetRef: {
+						apiVersion: "apps/v1"
+						kind:       "Deployment"
+						name:       context.name
+					}
+					minReplicas: parameter.min
+					maxReplicas: parameter.max
+				}
+			}
+			parameter: {
+				min: *1 | int
+				max: *10 | int
+			}
+		`,
+		Params: map[string]interface{}{
+			"min": 2,
+			"max": 15,
+		},
+	}
+
+	type fields struct {
+		Appfile *Appfile
+	}
+	tests := []struct {
+		name    string
+		fields  fields
+		wantErr bool
+	}{
+		{
+			name: "Test generate component manifests",
+			fields: fields{
+				Appfile: &Appfile{
+					Name:            "test-app",
+					Namespace:       "test-ns",
+					AppRevisionName: "test-app-v1",
+					ParsedComponents: []*Component{
+						{
+							Name:   "test-comp",
+							Type:   "worker",
+							Params: map[string]interface{}{"image": "nginx:1.10"},
+							engine: baseEngine,
+							FullTemplate: &Template{
+								TemplateStr: baseTemplate.TemplateStr,
+							},
+							Traits: []*Trait{baseTraitTemplate},
+						},
+					},
+					RelatedTraitDefinitions: map[string]*v1beta1.TraitDefinition{
+						"scaler": {
+							Spec: v1beta1.TraitDefinitionSpec{
+								WorkloadRefPath: "spec.scaleTargetRef",
+							},
+						},
+					},
+				},
+			},
+			wantErr: false,
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			af := tt.fields.Appfile
+			got, err := af.GenerateComponentManifests()
+			if (err != nil) != tt.wantErr {
+				t.Errorf("GenerateComponentManifests() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			assert.NoError(t, err)
+			assert.Equal(t, len(af.ParsedComponents), len(got))
+			assert.Equal(t, "test-comp", got[0].Name)
+			assert.Equal(t, "Deployment", got[0].ComponentOutput.GetKind())
+			assert.Equal(t, "test-comp", got[0].ComponentOutput.GetName())
+			assert.Equal(t, "test-ns", got[0].ComponentOutput.GetNamespace())
+			assert.Equal(t, "test-app", got[0].ComponentOutput.GetLabels()[oam.LabelAppName])
+			assert.Equal(t, 1, len(got[0].ComponentOutputsAndTraits))
+			trait := got[0].ComponentOutputsAndTraits[0]
+			assert.Equal(t, "HorizontalPodAutoscaler", trait.GetKind())
+			assert.True(t, strings.HasPrefix(trait.GetName(), "test-comp-scaler-"))
+			paved := fieldpath.Pave(trait.Object)
+			name, err := paved.GetString("spec.scaleTargetRef.name")
+			assert.NoError(t, err)
+			assert.Equal(t, "test-comp", name)
+			assert.Equal(t, af.Artifacts, got)
+		})
+	}
+}
+
+func TestGeneratePolicyManifests(t *testing.T) {
+	policyEngine := definition.NewWorkloadAbstractEngine("test-policy")
+	policyTemplate := &Template{
+		TemplateStr: `
+			output: {
+				apiVersion: "v1"
+				kind:       "ConfigMap"
+				metadata: {
+					name: context.name
+				}
+				data: {
+					key: parameter.value
+				}
+			}
+			parameter: {
+				value: string
+			}
+		`,
+	}
+
+	af := &Appfile{
+		Name:            "test-app",
+		Namespace:       "test-ns",
+		AppRevisionName: "test-app-v1",
+		ParsedPolicies: []*Component{
+			{
+				Name:   "test-policy",
+				Type:   "override",
+				Params: map[string]interface{}{"value": "test-value"},
+				engine: policyEngine,
+				FullTemplate: &Template{
+					TemplateStr: policyTemplate.TemplateStr,
+				},
+			},
+		},
+		AppLabels: map[string]string{
+			"label-key": "label-value",
+		},
+	}
+
+	manifests, err := af.GeneratePolicyManifests(context.Background())
+	assert.NoError(t, err)
+	assert.Equal(t, 1, len(manifests))
+
+	cm := manifests[0]
+	assert.Equal(t, "v1", cm.GetAPIVersion())
+	assert.Equal(t, "ConfigMap", cm.GetKind())
+	assert.Equal(t, "test-policy", cm.GetName())
+	assert.Equal(t, "test-ns", cm.GetNamespace())
+	assert.Equal(t, "test-app", cm.GetLabels()[oam.LabelAppName])
+
+	data, found, err := unstructured.NestedStringMap(cm.Object, "data")
+	assert.NoError(t, err)
+	assert.True(t, found)
+	assert.Equal(t, "test-value", data["key"])
+}
diff --git a/pkg/appfile/parser_test.go b/pkg/appfile/parser_test.go
index 36953f13..6d431b1f 100644
--- a/pkg/appfile/parser_test.go
+++ b/pkg/appfile/parser_test.go
@@ -24,8 +24,7 @@ import (
 	"testing"
 
 	"github.com/crossplane/crossplane-runtime/pkg/test"
-	. "github.com/onsi/ginkgo/v2"
-	. "github.com/onsi/gomega"
+	workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
 	"github.com/stretchr/testify/assert"
 	errors2 "k8s.io/apimachinery/pkg/api/errors"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -34,16 +33,217 @@ import (
 	"sigs.k8s.io/controller-runtime/pkg/client/fake"
 	"sigs.k8s.io/yaml"
 
-	workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
-
 	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
-	"github.com/oam-dev/kubevela/apis/types"
-
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1"
 	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
+	"github.com/oam-dev/kubevela/apis/types"
 	"github.com/oam-dev/kubevela/pkg/oam/util"
 	common2 "github.com/oam-dev/kubevela/pkg/utils/common"
 )
 
+func TestParsePolicies(t *testing.T) {
+	overrideCompDef := &v1beta1.ComponentDefinition{
+		ObjectMeta: metav1.ObjectMeta{Name: "webservice", Namespace: "vela-system"},
+		Spec:       v1beta1.ComponentDefinitionSpec{Workload: common.WorkloadTypeDescriptor{Type: "Deployment"}},
+	}
+	customPolicyDef := &v1beta1.PolicyDefinition{
+		ObjectMeta: metav1.ObjectMeta{Name: "custom-policy", Namespace: "vela-system"},
+		Spec: v1beta1.PolicyDefinitionSpec{
+			Schematic: &common.Schematic{
+				CUE: &common.CUE{Template: "parameter: {name: string}"},
+			},
+		},
+	}
+	schemes := runtime.NewScheme()
+	v1beta1.AddToScheme(schemes)
+
+	testcases := []struct {
+		name           string
+		appfile        *Appfile
+		client         client.Client
+		wantErrContain string
+		assertFunc     func(*testing.T, *Appfile)
+	}{
+		{
+			name: "policy with nil properties",
+			appfile: &Appfile{
+				app: &v1beta1.Application{
+					Spec: v1beta1.ApplicationSpec{
+						Policies: []v1beta1.AppPolicy{
+							{
+								Name:       "gc-policy",
+								Type:       v1alpha1.GarbageCollectPolicyType,
+								Properties: nil,
+							},
+						},
+					},
+				},
+			},
+			client:         fake.NewClientBuilder().WithScheme(schemes).Build(),
+			wantErrContain: "must not have empty properties",
+		},
+		{
+			name: "debug policy",
+			appfile: &Appfile{
+				app: &v1beta1.Application{
+					Spec: v1beta1.ApplicationSpec{
+						Policies: []v1beta1.AppPolicy{
+							{
+								Name: "debug-policy",
+								Type: v1alpha1.DebugPolicyType,
+							},
+						},
+					},
+				},
+			},
+			client: fake.NewClientBuilder().WithScheme(schemes).Build(),
+			assertFunc: func(t *testing.T, af *Appfile) {
+				assert.True(t, af.Debug)
+			},
+		},
+		{
+			name: "override policy fails to get definition",
+			appfile: &Appfile{
+				app: &v1beta1.Application{
+					Spec: v1beta1.ApplicationSpec{
+						Components: []common.ApplicationComponent{
+							{
+								Name: "comp1",
+								Type: "webservice",
+							},
+						},
+						Policies: []v1beta1.AppPolicy{
+							{
+								Name: "override-policy",
+								Type: v1alpha1.OverridePolicyType,
+								Properties: util.Object2RawExtension(v1alpha1.OverridePolicySpec{
+									Components: []v1alpha1.EnvComponentPatch{
+										{
+											Name: "comp1",
+											Type: "webservice",
+										},
+									},
+								}),
+							},
+						},
+					},
+				},
+				RelatedComponentDefinitions: make(map[string]*v1beta1.ComponentDefinition),
+				RelatedTraitDefinitions:     make(map[string]*v1beta1.TraitDefinition),
+			},
+			client: &test.MockClient{
+				MockGet: func(ctx context.Context, key client.ObjectKey, obj client.Object) error {
+					return fmt.Errorf("get definition error")
+				},
+			},
+			wantErrContain: "get definition error",
+		},
+		{
+			name: "override policy success",
+			appfile: &Appfile{
+				app: &v1beta1.Application{
+					Spec: v1beta1.ApplicationSpec{
+						Components: []common.ApplicationComponent{
+							{
+								Name: "comp1",
+								Type: "webservice",
+							},
+						},
+						Policies: []v1beta1.AppPolicy{
+							{
+								Name: "override-policy",
+								Type: v1alpha1.OverridePolicyType,
+								Properties: util.Object2RawExtension(v1alpha1.OverridePolicySpec{
+									Components: []v1alpha1.EnvComponentPatch{
+										{
+											Name: "comp1",
+											Type: "webservice",
+										},
+									},
+								}),
+							},
+						},
+					},
+				},
+				RelatedComponentDefinitions: make(map[string]*v1beta1.ComponentDefinition),
+				RelatedTraitDefinitions:     make(map[string]*v1beta1.TraitDefinition),
+			},
+			client: fake.NewClientBuilder().WithScheme(schemes).WithObjects(overrideCompDef).Build(),
+			assertFunc: func(t *testing.T, af *Appfile) {
+				assert.Contains(t, af.RelatedComponentDefinitions, "webservice")
+			},
+		},
+		{
+			name: "custom policy definition not found",
+			appfile: &Appfile{
+				app: &v1beta1.Application{
+					Spec: v1beta1.ApplicationSpec{
+						Policies: []v1beta1.AppPolicy{
+							{
+								Name:       "my-policy",
+								Type:       "custom-policy",
+								Properties: util.Object2RawExtension(map[string]string{"name": "test"}),
+							},
+						},
+					},
+				},
+			},
+			client: &test.MockClient{
+				MockGet: func(ctx context.Context, key client.ObjectKey, obj client.Object) error {
+					if _, ok := obj.(*v1beta1.PolicyDefinition); ok {
+						return errors2.NewNotFound(v1beta1.Resource("policydefinition"), "custom-policy")
+					}
+					return nil
+				},
+			},
+			wantErrContain: "fetch component/policy type of my-policy",
+		},
+		{
+			name: "custom policy success",
+			appfile: &Appfile{
+				app: &v1beta1.Application{
+					Spec: v1beta1.ApplicationSpec{
+						Policies: []v1beta1.AppPolicy{
+							{
+								Name:       "my-policy",
+								Type:       "custom-policy",
+								Properties: util.Object2RawExtension(map[string]string{"name": "test"}),
+							},
+						},
+					},
+				},
+			},
+			client: fake.NewClientBuilder().WithScheme(schemes).WithObjects(customPolicyDef).Build(),
+			assertFunc: func(t *testing.T, af *Appfile) {
+				assert.Equal(t, 1, len(af.ParsedPolicies))
+				assert.Equal(t, "my-policy", af.ParsedPolicies[0].Name)
+				assert.Equal(t, "custom-policy", af.ParsedPolicies[0].Type)
+			},
+		},
+	}
+
+	for _, tc := range testcases {
+		t.Run(tc.name, func(t *testing.T) {
+			p := NewApplicationParser(tc.client)
+			// This function is tested separated, mock it for parsePolicies
+			if tc.appfile.app != nil {
+				tc.appfile.Policies = tc.appfile.app.Spec.Policies
+			}
+			err := p.parsePolicies(context.Background(), tc.appfile)
+
+			if tc.wantErrContain != "" {
+				assert.Error(t, err)
+				assert.Contains(t, err.Error(), tc.wantErrContain)
+			} else {
+				assert.NoError(t, err)
+				if tc.assertFunc != nil {
+					tc.assertFunc(t, tc.appfile)
+				}
+			}
+		})
+	}
+}
+
 var expectedExceptApp = &Appfile{
 	Name: "application-sample",
 	ParsedComponents: []*Component{
@@ -81,10 +281,10 @@ var expectedExceptApp = &Appfile{
       			}
       		}
       
-      		selector:
-      			matchLabels:
-      				"app.oam.dev/component": context.name
-      	}
+      			selector:
+      				matchLabels:
+      					"app.oam.dev/component": context.name
+      		}
       }
       
       parameter: {
@@ -149,7 +349,7 @@ spec:
       		selector:
       			matchLabels:
       				"app.oam.dev/component": context.name
-      	}
+      		}
       }
 
       parameter: {
@@ -235,11 +435,11 @@ spec:
       properties:
 `
 
-var _ = Describe("Test application parser", func() {
-	It("Test parse an application", func() {
+func TestApplicationParser(t *testing.T) {
+	t.Run("Test parse an application", func(t *testing.T) {
 		o := v1beta1.Application{}
 		err := yaml.Unmarshal([]byte(appfileYaml), &o)
-		Expect(err).ShouldNot(HaveOccurred())
+		assert.NoError(t, err)
 
 		// Create a mock client
 		tclient := test.MockClient{
@@ -266,24 +466,24 @@ var _ = Describe("Test application parser", func() {
 		}
 
 		appfile, err := NewApplicationParser(&tclient).GenerateAppFile(context.TODO(), &o)
-		Expect(err).ShouldNot(HaveOccurred())
-		Expect(equal(expectedExceptApp, appfile)).Should(BeTrue())
+		assert.NoError(t, err)
+		assert.True(t, equal(expectedExceptApp, appfile))
 
 		notfound := v1beta1.Application{}
 		err = yaml.Unmarshal([]byte(appfileYaml2), &notfound)
-		Expect(err).ShouldNot(HaveOccurred())
+		assert.NoError(t, err)
 		_, err = NewApplicationParser(&tclient).GenerateAppFile(context.TODO(), &notfound)
-		Expect(err).Should(HaveOccurred())
+		assert.Error(t, err)
 
-		By("app with empty policy")
+		t.Log("app with empty policy")
 		emptyPolicy := v1beta1.Application{}
 		err = yaml.Unmarshal([]byte(appfileYamlEmptyPolicy), &emptyPolicy)
-		Expect(err).ShouldNot(HaveOccurred())
+		assert.NoError(t, err)
 		_, err = NewApplicationParser(&tclient).GenerateAppFile(context.TODO(), &emptyPolicy)
-		Expect(err).Should(HaveOccurred())
-		Expect(err.Error()).Should(ContainSubstring("have empty properties"))
+		assert.Error(t, err)
+		assert.Contains(t, err.Error(), "have empty properties")
 	})
-})
+}
 
 func equal(af, dest *Appfile) bool {
 	if af.Name != dest.Name || len(af.ParsedComponents) != len(dest.ParsedComponents) {
@@ -313,29 +513,28 @@ func equal(af, dest *Appfile) bool {
 	return true
 }
 
-var _ = Describe("Test application parser", func() {
+func TestApplicationParserWithLegacyRevision(t *testing.T) {
 	var app v1beta1.Application
 	var apprev v1beta1.ApplicationRevision
 	var wsd v1beta1.WorkflowStepDefinition
 	var expectedExceptAppfile *Appfile
 	var mockClient test.MockClient
 
-	BeforeEach(func() {
-		// prepare WorkflowStepDefinition
-		Expect(common2.ReadYamlToObject("testdata/backport-1-2/wsd.yaml", &wsd)).Should(BeNil())
-
-		// prepare verify data
-		expectedExceptAppfile = &Appfile{
-			Name: "backport-1-2-test-demo",
-			ParsedComponents: []*Component{
-				{
-					Name: "backport-1-2-test-demo",
-					Type: "webservice",
-					Params: map[string]interface{}{
-						"image": "nginx",
-					},
-					FullTemplate: &Template{
-						TemplateStr: `
+	// prepare WorkflowStepDefinition
+	assert.NoError(t, common2.ReadYamlToObject("testdata/backport-1-2/wsd.yaml", &wsd))
+
+	// prepare verify data
+	expectedExceptAppfile = &Appfile{
+		Name: "backport-1-2-test-demo",
+		ParsedComponents: []*Component{
+			{
+				Name: "backport-1-2-test-demo",
+				Type: "webservice",
+				Params: map[string]interface{}{
+					"image": "nginx",
+				},
+				FullTemplate: &Template{
+					TemplateStr: `
       output: {
         apiVersion: "apps/v1"
       	kind:       "Deployment"
@@ -361,10 +560,10 @@ var _ = Describe("Test application parser", func() {
       			}
       		}
       
-      		selector:
-      			matchLabels:
-      				"app.oam.dev/component": context.name
-      	}
+      			selector:
+      				matchLabels:
+      					"app.oam.dev/component": context.name
+      		}
       }
       
       parameter: {
@@ -374,14 +573,14 @@ var _ = Describe("Test application parser", func() {
       
       	cmd?: [...string]
       }`,
-					},
-					Traits: []*Trait{
-						{
-							Name: "scaler",
-							Params: map[string]interface{}{
-								"replicas": float64(1),
-							},
-							Template: `
+				},
+				Traits: []*Trait{
+					{
+						Name: "scaler",
+						Params: map[string]interface{}{
+							"replicas": float64(1),
+						},
+						Template: `
 parameter: {
 	// +usage=Specify the number of workload
 	replicas: *1 | int
@@ -390,62 +589,59 @@ parameter: {
 patch: spec: replicas: parameter.replicas
 
 `,
-						},
 					},
 				},
 			},
-			WorkflowSteps: []workflowv1alpha1.WorkflowStep{
-				{
-					WorkflowStepBase: workflowv1alpha1.WorkflowStepBase{
-						Name: "apply",
-						Type: "apply-application",
-					},
+		},
+		WorkflowSteps: []workflowv1alpha1.WorkflowStep{
+			{
+				WorkflowStepBase: workflowv1alpha1.WorkflowStepBase{
+					Name: "apply",
+					Type: "apply-application",
 				},
 			},
-		}
+		},
+	}
 
-		// Create mock client
-		mockClient = test.MockClient{
-			MockGet: func(ctx context.Context, key client.ObjectKey, obj client.Object) error {
-				if strings.Contains(key.Name, "unknown") {
-					return &errors2.StatusError{ErrStatus: metav1.Status{Reason: "NotFound", Message: "not found"}}
-				}
-				switch o := obj.(type) {
-				case *v1beta1.ComponentDefinition:
-					wd, err := util.UnMarshalStringToComponentDefinition(componentDefinition)
-					if err != nil {
-						return err
-					}
-					*o = *wd
-				case *v1beta1.WorkflowStepDefinition:
-					*o = wsd
-				case *v1beta1.ApplicationRevision:
-					*o = apprev
-				default:
-					// skip
+	// Create mock client
+	mockClient = test.MockClient{
+		MockGet: func(ctx context.Context, key client.ObjectKey, obj client.Object) error {
+			if strings.Contains(key.Name, "unknown") {
+				return &errors2.StatusError{ErrStatus: metav1.Status{Reason: "NotFound", Message: "not found"}}
+			}
+			switch o := obj.(type) {
+			case *v1beta1.ComponentDefinition:
+				wd, err := util.UnMarshalStringToComponentDefinition(componentDefinition)
+				if err != nil {
+					return err
 				}
-				return nil
-			},
-		}
-	})
+				*o = *wd
+			case *v1beta1.WorkflowStepDefinition:
+				*o = wsd
+			case *v1beta1.ApplicationRevision:
+				*o = apprev
+			default:
+				// skip
+			}
+			return nil
+		},
+	}
 
-	When("with apply-application workflowStep", func() {
-		BeforeEach(func() {
-			// prepare application
-			Expect(common2.ReadYamlToObject("testdata/backport-1-2/app.yaml", &app)).Should(BeNil())
-			// prepare application revision
-			Expect(common2.ReadYamlToObject("testdata/backport-1-2/apprev1.yaml", &apprev)).Should(BeNil())
-		})
+	t.Run("with apply-application workflowStep", func(t *testing.T) {
+		// prepare application
+		assert.NoError(t, common2.ReadYamlToObject("testdata/backport-1-2/app.yaml", &app))
+		// prepare application revision
+		assert.NoError(t, common2.ReadYamlToObject("testdata/backport-1-2/apprev1.yaml", &apprev))
 
-		It("Test we can parse an application revision to an appFile 1", func() {
+		t.Run("Test we can parse an application revision to an appFile 1", func(t *testing.T) {
 
 			appfile, err := NewApplicationParser(&mockClient).GenerateAppFile(context.TODO(), &app)
-			Expect(err).ShouldNot(HaveOccurred())
-			Expect(equal(expectedExceptAppfile, appfile)).Should(BeTrue())
-			Expect(len(appfile.WorkflowSteps) > 0 &&
-				len(appfile.RelatedWorkflowStepDefinitions) == len(appfile.AppRevision.Spec.WorkflowStepDefinitions)).Should(BeTrue())
+			assert.NoError(t, err)
+			assert.True(t, equal(expectedExceptAppfile, appfile))
+			assert.True(t, len(appfile.WorkflowSteps) > 0 &&
+				len(appfile.RelatedWorkflowStepDefinitions) == len(appfile.AppRevision.Spec.WorkflowStepDefinitions))
 
-			Expect(len(appfile.WorkflowSteps) > 0 && func() bool {
+			assert.True(t, len(appfile.WorkflowSteps) > 0 && func() bool {
 				this := appfile.RelatedWorkflowStepDefinitions
 				that := appfile.AppRevision.Spec.WorkflowStepDefinitions
 				for i, w := range this {
@@ -455,27 +651,25 @@ patch: spec: replicas: parameter.replicas
 					}
 				}
 				return true
-			}()).Should(BeTrue())
+			}())
 		})
 	})
 
-	When("with apply-application and apply-component build-in workflowStep", func() {
-		BeforeEach(func() {
-			// prepare application
-			Expect(common2.ReadYamlToObject("testdata/backport-1-2/app.yaml", &app)).Should(BeNil())
-			// prepare application revision
-			Expect(common2.ReadYamlToObject("testdata/backport-1-2/apprev2.yaml", &apprev)).Should(BeNil())
-		})
+	t.Run("with apply-application and apply-component build-in workflowStep", func(t *testing.T) {
+		// prepare application
+		assert.NoError(t, common2.ReadYamlToObject("testdata/backport-1-2/app.yaml", &app))
+		// prepare application revision
+		assert.NoError(t, common2.ReadYamlToObject("testdata/backport-1-2/apprev2.yaml", &apprev))
 
-		It("Test we can parse an application revision to an appFile 2", func() {
+		t.Run("Test we can parse an application revision to an appFile 2", func(t *testing.T) {
 
 			appfile, err := NewApplicationParser(&mockClient).GenerateAppFile(context.TODO(), &app)
-			Expect(err).ShouldNot(HaveOccurred())
-			Expect(equal(expectedExceptAppfile, appfile)).Should(BeTrue())
-			Expect(len(appfile.WorkflowSteps) > 0 &&
-				len(appfile.RelatedWorkflowStepDefinitions) == len(appfile.AppRevision.Spec.WorkflowStepDefinitions)).Should(BeTrue())
+			assert.NoError(t, err)
+			assert.True(t, equal(expectedExceptAppfile, appfile))
+			assert.True(t, len(appfile.WorkflowSteps) > 0 &&
+				len(appfile.RelatedWorkflowStepDefinitions) == len(appfile.AppRevision.Spec.WorkflowStepDefinitions))
 
-			Expect(len(appfile.WorkflowSteps) > 0 && func() bool {
+			assert.True(t, len(appfile.WorkflowSteps) > 0 && func() bool {
 				this := appfile.RelatedWorkflowStepDefinitions
 				that := appfile.AppRevision.Spec.WorkflowStepDefinitions
 				for i, w := range this {
@@ -486,29 +680,25 @@ patch: spec: replicas: parameter.replicas
 					}
 				}
 				return true
-			}()).Should(BeTrue())
+			}())
 		})
 	})
 
-	When("with unknown workflowStep", func() {
-		BeforeEach(func() {
-			// prepare application
-			Expect(common2.ReadYamlToObject("testdata/backport-1-2/app.yaml", &app)).Should(BeNil())
-			// prepare application revision
-			Expect(common2.ReadYamlToObject("testdata/backport-1-2/apprev3.yaml", &apprev)).Should(BeNil())
-		})
+	t.Run("with unknown workflowStep", func(t *testing.T) {
+		// prepare application
+		assert.NoError(t, common2.ReadYamlToObject("testdata/backport-1-2/app.yaml", &app))
+		// prepare application revision
+		assert.NoError(t, common2.ReadYamlToObject("testdata/backport-1-2/apprev3.yaml", &apprev))
 
-		It("Test we can parse an application revision to an appFile 3", func() {
+		t.Run("Test we can parse an application revision to an appFile 3", func(t *testing.T) {
 
 			_, err := NewApplicationParser(&mockClient).GenerateAppFile(context.TODO(), &app)
-			Expect(err).Should(HaveOccurred())
-			Expect(err.Error()).Should(SatisfyAll(
-				ContainSubstring("failed to get workflow step definition apply-application-unknown: not found"),
-				ContainSubstring("failed to parseWorkflowStepsForLegacyRevision")),
-			)
+			assert.Error(t, err)
+			assert.Contains(t, err.Error(), "failed to get workflow step definition apply-application-unknown: not found")
+			assert.Contains(t, err.Error(), "failed to parseWorkflowStepsForLegacyRevision")
 		})
 	})
-})
+}
 
 func TestParser_parseTraits(t *testing.T) {
 	type args struct {
@@ -707,3 +897,145 @@ func TestParser_parseTraitsFromRevision(t *testing.T) {
 		})
 	}
 }
+
+func TestParseComponentFromRevisionAndClient(t *testing.T) {
+	compDef := &v1beta1.ComponentDefinition{
+		ObjectMeta: metav1.ObjectMeta{Name: "webservice", Namespace: "vela-system"},
+		Spec: v1beta1.ComponentDefinitionSpec{
+			Workload:  common.WorkloadTypeDescriptor{Type: "Deployment"},
+			Schematic: &common.Schematic{CUE: &common.CUE{Template: "parameter: {image: string}"}},
+		},
+	}
+	traitDef := &v1beta1.TraitDefinition{
+		ObjectMeta: metav1.ObjectMeta{Name: "scaler", Namespace: "vela-system"},
+		Spec: v1beta1.TraitDefinitionSpec{
+			Schematic: &common.Schematic{CUE: &common.CUE{Template: "parameter: {replicas: int}"}},
+		},
+	}
+
+	appComp := common.ApplicationComponent{
+		Name:       "my-comp",
+		Type:       "webservice",
+		Properties: util.Object2RawExtension(map[string]string{"image": "nginx"}),
+		Traits: []common.ApplicationTrait{
+			{
+				Type:       "scaler",
+				Properties: util.Object2RawExtension(map[string]int{"replicas": 2}),
+			},
+		},
+	}
+
+	schemes := runtime.NewScheme()
+	v1beta1.AddToScheme(schemes)
+
+	tests := []struct {
+		name       string
+		appRev     *v1beta1.ApplicationRevision
+		client     client.Client
+		wantErr    bool
+		assertFunc func(*testing.T, *Component)
+	}{
+		{
+			name: "component and trait found in revision",
+			appRev: &v1beta1.ApplicationRevision{
+				Spec: v1beta1.ApplicationRevisionSpec{
+					ApplicationRevisionCompressibleFields: v1beta1.ApplicationRevisionCompressibleFields{
+						ComponentDefinitions: map[string]*v1beta1.ComponentDefinition{"webservice": compDef},
+						TraitDefinitions:     map[string]*v1beta1.TraitDefinition{"scaler": traitDef},
+					},
+				},
+			},
+			client:  fake.NewClientBuilder().WithScheme(schemes).Build(),
+			wantErr: false,
+			assertFunc: func(t *testing.T, c *Component) {
+				assert.NotNil(t, c)
+				assert.Equal(t, "my-comp", c.Name)
+				assert.Equal(t, "webservice", c.Type)
+				assert.Equal(t, 1, len(c.Traits))
+				assert.Equal(t, "scaler", c.Traits[0].Name)
+			},
+		},
+		{
+			name: "component not in revision, but in cluster",
+			appRev: &v1beta1.ApplicationRevision{
+				Spec: v1beta1.ApplicationRevisionSpec{
+					ApplicationRevisionCompressibleFields: v1beta1.ApplicationRevisionCompressibleFields{
+						TraitDefinitions: map[string]*v1beta1.TraitDefinition{"scaler": traitDef},
+					},
+				},
+			},
+			client:  fake.NewClientBuilder().WithScheme(schemes).WithObjects(compDef).Build(),
+			wantErr: false,
+			assertFunc: func(t *testing.T, c *Component) {
+				assert.NotNil(t, c)
+				assert.Equal(t, "webservice", c.Type)
+				assert.Equal(t, 1, len(c.Traits))
+				assert.Equal(t, "scaler", c.Traits[0].Name)
+			},
+		},
+		{
+			name: "trait not in revision, but in cluster",
+			appRev: &v1beta1.ApplicationRevision{
+				Spec: v1beta1.ApplicationRevisionSpec{
+					ApplicationRevisionCompressibleFields: v1beta1.ApplicationRevisionCompressibleFields{
+						ComponentDefinitions: map[string]*v1beta1.ComponentDefinition{"webservice": compDef},
+					},
+				},
+			},
+			client:  fake.NewClientBuilder().WithScheme(schemes).WithObjects(traitDef).Build(),
+			wantErr: false,
+			assertFunc: func(t *testing.T, c *Component) {
+				assert.NotNil(t, c)
+				assert.Equal(t, "webservice", c.Type)
+				assert.Equal(t, 1, len(c.Traits))
+				assert.Equal(t, "scaler", c.Traits[0].Name)
+			},
+		},
+		{
+			name:    "component and trait not in revision, but in cluster",
+			appRev:  &v1beta1.ApplicationRevision{},
+			client:  fake.NewClientBuilder().WithScheme(schemes).WithObjects(compDef, traitDef).Build(),
+			wantErr: false,
+			assertFunc: func(t *testing.T, c *Component) {
+				assert.NotNil(t, c)
+				assert.Equal(t, "webservice", c.Type)
+				assert.Equal(t, 1, len(c.Traits))
+				assert.Equal(t, "scaler", c.Traits[0].Name)
+			},
+		},
+		{
+			name:    "component not found anywhere",
+			appRev:  &v1beta1.ApplicationRevision{},
+			client:  fake.NewClientBuilder().WithScheme(schemes).Build(),
+			wantErr: true,
+		},
+		{
+			name: "trait not found anywhere",
+			appRev: &v1beta1.ApplicationRevision{
+				Spec: v1beta1.ApplicationRevisionSpec{
+					ApplicationRevisionCompressibleFields: v1beta1.ApplicationRevisionCompressibleFields{
+						ComponentDefinitions: map[string]*v1beta1.ComponentDefinition{"webservice": compDef},
+					},
+				},
+			},
+			client:  fake.NewClientBuilder().WithScheme(schemes).Build(),
+			wantErr: true,
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			p := NewApplicationParser(tt.client)
+			comp, err := p.ParseComponentFromRevisionAndClient(context.Background(), appComp, tt.appRev)
+
+			if tt.wantErr {
+				assert.Error(t, err)
+			} else {
+				assert.NoError(t, err)
+				if tt.assertFunc != nil {
+					tt.assertFunc(t, comp)
+				}
+			}
+		})
+	}
+}
diff --git a/pkg/appfile/suit_test.go b/pkg/appfile/suit_test.go
deleted file mode 100644
index 871bc309..00000000
--- a/pkg/appfile/suit_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
-Copyright 2021 The KubeVela Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package appfile
-
-import (
-	"path/filepath"
-	"testing"
-	"time"
-
-	. "github.com/onsi/ginkgo/v2"
-	. "github.com/onsi/gomega"
-	v1 "k8s.io/api/apps/v1"
-	"k8s.io/apimachinery/pkg/runtime"
-	clientgoscheme "k8s.io/client-go/kubernetes/scheme"
-	"k8s.io/client-go/rest"
-	"sigs.k8s.io/controller-runtime/pkg/client"
-	"sigs.k8s.io/controller-runtime/pkg/envtest"
-	logf "sigs.k8s.io/controller-runtime/pkg/log"
-	"sigs.k8s.io/controller-runtime/pkg/log/zap"
-
-	coreoam "github.com/oam-dev/kubevela/apis/core.oam.dev"
-	// +kubebuilder:scaffold:imports
-)
-
-var cfg *rest.Config
-var scheme *runtime.Scheme
-var k8sClient client.Client
-var testEnv *envtest.Environment
-
-func TestAppFile(t *testing.T) {
-	RegisterFailHandler(Fail)
-	RunSpecs(t, "Cli Suite")
-}
-
-var _ = BeforeSuite(func() {
-	logf.SetLogger(zap.New(zap.UseDevMode(true), zap.WriteTo(GinkgoWriter)))
-	By("bootstrapping test environment")
-	useExistCluster := false
-	testEnv = &envtest.Environment{
-		ControlPlaneStartTimeout: time.Minute,
-		ControlPlaneStopTimeout:  time.Minute,
-		CRDDirectoryPaths:        []string{filepath.Join("..", "..", "charts", "vela-core", "crds")},
-		UseExistingCluster:       &useExistCluster,
-	}
-
-	var err error
-	cfg, err = testEnv.Start()
-	Expect(err).ToNot(HaveOccurred())
-	Expect(cfg).ToNot(BeNil())
-	scheme = runtime.NewScheme()
-	Expect(coreoam.AddToScheme(scheme)).NotTo(HaveOccurred())
-	Expect(clientgoscheme.AddToScheme(scheme)).NotTo(HaveOccurred())
-	Expect(v1.AddToScheme(scheme)).NotTo(HaveOccurred())
-	k8sClient, err = client.New(cfg, client.Options{Scheme: scheme})
-	Expect(err).ToNot(HaveOccurred())
-	Expect(k8sClient).ToNot(BeNil())
-})
-
-var _ = AfterSuite(func() {
-	By("tearing down the test environment")
-	err := testEnv.Stop()
-	Expect(err).ToNot(HaveOccurred())
-})
diff --git a/pkg/appfile/template_test.go b/pkg/appfile/template_test.go
index c6485664..a87026ab 100644
--- a/pkg/appfile/template_test.go
+++ b/pkg/appfile/template_test.go
@@ -18,14 +18,19 @@ package appfile
 
 import (
 	"context"
+	"errors"
+	"fmt"
 	"testing"
 
 	"cuelang.org/go/cue/cuecontext"
 	"github.com/crossplane/crossplane-runtime/pkg/test"
 	"github.com/google/go-cmp/cmp"
 	"github.com/stretchr/testify/assert"
+	"k8s.io/apimachinery/pkg/api/meta"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
 	"k8s.io/apimachinery/pkg/runtime"
+	"k8s.io/apimachinery/pkg/runtime/schema"
 	ktypes "k8s.io/apimachinery/pkg/types"
 	"sigs.k8s.io/controller-runtime/pkg/client"
 
@@ -35,6 +40,24 @@ import (
 	oamutil "github.com/oam-dev/kubevela/pkg/oam/util"
 )
 
+type fakeRESTMapper struct {
+	meta.RESTMapper
+}
+
+func (f fakeRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
+	if resource.Resource == "deployments" {
+		return schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}, nil
+	}
+	return schema.GroupVersionKind{}, errors.New("no mapping for KindFor")
+}
+
+func (f fakeRESTMapper) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {
+	if resource.Resource == "deployments" {
+		return []schema.GroupVersionKind{{Group: "apps", Version: "v1", Kind: "Deployment"}}, nil
+	}
+	return nil, errors.New("no mapping for KindsFor")
+}
+
 func TestLoadComponentTemplate(t *testing.T) {
 	cueTemplate := `
       context: {
@@ -47,35 +70,35 @@ func TestLoadComponentTemplate(t *testing.T) {
       		selector: matchLabels: {
       			"app.oam.dev/component": context.name
       		}
-      
+
       		template: {
       			metadata: labels: {
       				"app.oam.dev/component": context.name
       			}
-      
+
       			spec: {
       				containers: [{
       					name:  context.name
       					image: parameter.image
-      
+
       					if parameter["cmd"] != _|_ {
       						command: parameter.cmd
       					}
       				}]
       			}
       		}
-      
+
       		selector:
       			matchLabels:
       				"app.oam.dev/component": context.name
       	}
       }
-      
+
       parameter: {
       	// +usage=Which image would you like to use for your service
       	// +short=i
       	image: string
-      
+
       	cmd?: [...string]
       }
       `
@@ -316,7 +339,7 @@ metadata:
 spec:
   status:
     customStatus: testCustomStatus
-    healthPolicy: testHealthPolicy 
+    healthPolicy: testHealthPolicy
   workload:
     definition:
       apiVersion: apps/v1
@@ -333,7 +356,7 @@ metadata:
 spec:
   status:
     customStatus: testCustomStatus
-    healthPolicy: testHealthPolicy 
+    healthPolicy: testHealthPolicy
   appliesToWorkloads:
     - deployments.apps
   schematic:
@@ -385,3 +408,349 @@ spec:
 		t.Fatal("failed load template of trait definition ", diff)
 	}
 }
+
+func TestLoadTemplateFromRevision(t *testing.T) {
+	compDef := v1beta1.ComponentDefinition{
+		TypeMeta: metav1.TypeMeta{
+			Kind:       v1beta1.ComponentDefinitionKind,
+			APIVersion: v1beta1.SchemeGroupVersion.String(),
+		},
+		ObjectMeta: metav1.ObjectMeta{Name: "my-comp"},
+		Spec: v1beta1.ComponentDefinitionSpec{
+			Schematic: &common.Schematic{
+				CUE: &common.CUE{Template: "parameter: {name: string}"},
+			},
+			Workload: common.WorkloadTypeDescriptor{
+				Definition: common.WorkloadGVK{APIVersion: "v1", Kind: "Pod"},
+			},
+		},
+	}
+	traitDef := v1beta1.TraitDefinition{
+		TypeMeta: metav1.TypeMeta{
+			Kind:       v1beta1.TraitDefinitionKind,
+			APIVersion: v1beta1.SchemeGroupVersion.String(),
+		},
+		ObjectMeta: metav1.ObjectMeta{Name: "my-trait"},
+		Spec: v1beta1.TraitDefinitionSpec{
+			Schematic: &common.Schematic{
+				CUE: &common.CUE{Template: "parameter: {port: int}"},
+			},
+		},
+	}
+	policyDef := v1beta1.PolicyDefinition{
+		TypeMeta: metav1.TypeMeta{
+			Kind:       v1beta1.PolicyDefinitionKind,
+			APIVersion: v1beta1.SchemeGroupVersion.String(),
+		},
+		ObjectMeta: metav1.ObjectMeta{Name: "my-policy"},
+		Spec: v1beta1.PolicyDefinitionSpec{
+			Schematic: &common.Schematic{
+				CUE: &common.CUE{Template: "parameter: {replicas: int}"},
+			},
+		},
+	}
+	wfStepDef := v1beta1.WorkflowStepDefinition{
+		TypeMeta: metav1.TypeMeta{
+			Kind:       v1beta1.WorkflowStepDefinitionKind,
+			APIVersion: v1beta1.SchemeGroupVersion.String(),
+		},
+		ObjectMeta: metav1.ObjectMeta{Name: "my-step"},
+		Spec: v1beta1.WorkflowStepDefinitionSpec{
+			Schematic: &common.Schematic{
+				CUE: &common.CUE{Template: "parameter: {image: string}"},
+			},
+		},
+	}
+	wlDef := v1beta1.WorkloadDefinition{
+		TypeMeta: metav1.TypeMeta{
+			Kind:       v1beta1.WorkloadDefinitionKind,
+			APIVersion: v1beta1.SchemeGroupVersion.String(),
+		},
+		ObjectMeta: metav1.ObjectMeta{Name: "my-workload"},
+		Spec: v1beta1.WorkloadDefinitionSpec{
+			Reference: common.DefinitionReference{
+				Name: "deployments.apps",
+			},
+			Schematic: &common.Schematic{
+				CUE: &common.CUE{Template: "output: {apiVersion: 'apps/v1', kind: 'Deployment'}"},
+			},
+		},
+	}
+
+	appRev := &v1beta1.ApplicationRevision{
+		ObjectMeta: metav1.ObjectMeta{Name: "my-app-rev"},
+		Spec: v1beta1.ApplicationRevisionSpec{
+			ApplicationRevisionCompressibleFields: v1beta1.ApplicationRevisionCompressibleFields{
+				ComponentDefinitions: map[string]*v1beta1.ComponentDefinition{
+					"my-comp": &compDef,
+				},
+				TraitDefinitions: map[string]*v1beta1.TraitDefinition{
+					"my-trait": &traitDef,
+				},
+				PolicyDefinitions: map[string]v1beta1.PolicyDefinition{
+					"my-policy": policyDef,
+				},
+				WorkflowStepDefinitions: map[string]*v1beta1.WorkflowStepDefinition{
+					"my-step": &wfStepDef,
+				},
+				WorkloadDefinitions: map[string]v1beta1.WorkloadDefinition{
+					"my-workload": wlDef,
+				},
+			},
+		},
+	}
+
+	mapper := fakeRESTMapper{}
+
+	testCases := map[string]struct {
+		capName   string
+		capType   types.CapType
+		apprev    *v1beta1.ApplicationRevision
+		checkFunc func(t *testing.T, tmpl *Template, err error)
+	}{
+		"load component definition": {
+			capName: "my-comp",
+			capType: types.TypeComponentDefinition,
+			apprev:  appRev,
+			checkFunc: func(t *testing.T, tmpl *Template, err error) {
+				assert.NoError(t, err)
+				assert.NotNil(t, tmpl)
+				assert.Equal(t, "parameter: {name: string}", tmpl.TemplateStr)
+				assert.Equal(t, v1beta1.ComponentDefinitionKind, tmpl.ComponentDefinition.Kind)
+			},
+		},
+		"load trait definition": {
+			capName: "my-trait",
+			capType: types.TypeTrait,
+			apprev:  appRev,
+			checkFunc: func(t *testing.T, tmpl *Template, err error) {
+				assert.NoError(t, err)
+				assert.NotNil(t, tmpl)
+				assert.Equal(t, "parameter: {port: int}", tmpl.TemplateStr)
+				assert.Equal(t, v1beta1.TraitDefinitionKind, tmpl.TraitDefinition.Kind)
+			},
+		},
+		"load policy definition": {
+			capName: "my-policy",
+			capType: types.TypePolicy,
+			apprev:  appRev,
+			checkFunc: func(t *testing.T, tmpl *Template, err error) {
+				assert.NoError(t, err)
+				assert.NotNil(t, tmpl)
+				assert.Equal(t, "parameter: {replicas: int}", tmpl.TemplateStr)
+				assert.Equal(t, v1beta1.PolicyDefinitionKind, tmpl.PolicyDefinition.Kind)
+			},
+		},
+		"load workflow step definition": {
+			capName: "my-step",
+			capType: types.TypeWorkflowStep,
+			apprev:  appRev,
+			checkFunc: func(t *testing.T, tmpl *Template, err error) {
+				assert.NoError(t, err)
+				assert.NotNil(t, tmpl)
+				assert.Equal(t, "parameter: {image: string}", tmpl.TemplateStr)
+				assert.Equal(t, v1beta1.WorkflowStepDefinitionKind, tmpl.WorkflowStepDefinition.Kind)
+			},
+		},
+		"fallback to workload definition": {
+			capName: "my-workload",
+			capType: types.TypeComponentDefinition,
+			apprev:  appRev,
+			checkFunc: func(t *testing.T, tmpl *Template, err error) {
+				assert.NoError(t, err)
+				assert.NotNil(t, tmpl)
+				assert.Equal(t, "output: {apiVersion: 'apps/v1', kind: 'Deployment'}", tmpl.TemplateStr)
+				assert.NotNil(t, tmpl.WorkloadDefinition)
+				assert.Equal(t, v1beta1.WorkloadDefinitionKind, tmpl.WorkloadDefinition.Kind)
+				assert.Equal(t, "apps/v1", tmpl.Reference.Definition.APIVersion)
+				assert.Equal(t, "Deployment", tmpl.Reference.Definition.Kind)
+			},
+		},
+		"definition not found": {
+			capName: "not-exist",
+			capType: types.TypeComponentDefinition,
+			apprev:  appRev,
+			checkFunc: func(t *testing.T, tmpl *Template, err error) {
+				assert.Error(t, err)
+				assert.Nil(t, tmpl)
+				assert.True(t, IsNotFoundInAppRevision(err))
+				assert.Contains(t, err.Error(), "component definition [not-exist] not found in app revision my-app-rev")
+			},
+		},
+		"nil app revision": {
+			capName: "any",
+			capType: types.TypeComponentDefinition,
+			apprev:  nil,
+			checkFunc: func(t *testing.T, tmpl *Template, err error) {
+				assert.Error(t, err)
+				assert.Nil(t, tmpl)
+				assert.Contains(t, err.Error(), "fail to find template for any as app revision is empty")
+			},
+		},
+		"unsupported type": {
+			capName: "any",
+			capType: "unsupported",
+			apprev:  appRev,
+			checkFunc: func(t *testing.T, tmpl *Template, err error) {
+				assert.Error(t, err)
+				assert.Nil(t, tmpl)
+				assert.Contains(t, err.Error(), "kind(unsupported) of any not supported")
+			},
+		},
+		"verify revision name": {
+			capName: "my-comp@my-ns",
+			capType: types.TypeComponentDefinition,
+			apprev:  appRev,
+			checkFunc: func(t *testing.T, tmpl *Template, err error) {
+				assert.NoError(t, err)
+				assert.NotNil(t, tmpl)
+				assert.Equal(t, "parameter: {name: string}", tmpl.TemplateStr)
+			},
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			tmpl, err := LoadTemplateFromRevision(tc.capName, tc.capType, tc.apprev, mapper)
+			tc.checkFunc(t, tmpl, err)
+		})
+	}
+}
+
+func TestConvertTemplateJSON2Object(t *testing.T) {
+	testCases := map[string]struct {
+		capName   string
+		in        *runtime.RawExtension
+		schematic *common.Schematic
+		wantCap   types.Capability
+		wantErr   bool
+	}{
+		"with schematic CUE": {
+			capName: "test-cap",
+			schematic: &common.Schematic{
+				CUE: &common.CUE{Template: "parameter: {name: string}"},
+			},
+			wantCap: types.Capability{
+				Name:        "test-cap",
+				CueTemplate: "parameter: {name: string}",
+			},
+			wantErr: false,
+		},
+		"with RawExtension": {
+			capName: "test-cap-2",
+			in: &runtime.RawExtension{
+				Raw: []byte(`{"template": "parameter: {age: int}"}`),
+			},
+			wantCap: types.Capability{
+				Name:        "test-cap-2",
+				CueTemplate: "parameter: {age: int}",
+			},
+			wantErr: false,
+		},
+		"with both schematic and RawExtension": {
+			capName: "test-cap-3",
+			in: &runtime.RawExtension{
+				Raw: []byte(`{"description": "test"}`),
+			},
+			schematic: &common.Schematic{
+				CUE: &common.CUE{Template: "parameter: {name: string}"},
+			},
+			wantCap: types.Capability{
+				Name:        "test-cap-3",
+				Description: "test",
+				CueTemplate: "parameter: {name: string}",
+			},
+			wantErr: false,
+		},
+		"with invalid JSON in RawExtension": {
+			capName: "test-cap-4",
+			in: &runtime.RawExtension{
+				Raw: []byte(`{"template": "parameter: {age: int}"`),
+			},
+			wantErr: true,
+		},
+		"with no template": {
+			capName: "test-cap-5",
+			in:      &runtime.RawExtension{Raw: []byte(`{"description": "test"}`)},
+			wantCap: types.Capability{
+				Name:        "test-cap-5",
+				Description: "test",
+			},
+			wantErr: false,
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			cap, err := ConvertTemplateJSON2Object(tc.capName, tc.in, tc.schematic)
+			if tc.wantErr {
+				assert.Error(t, err)
+			} else {
+				assert.NoError(t, err)
+				if diff := cmp.Diff(tc.wantCap, cap); diff != "" {
+					t.Errorf("ConvertTemplateJSON2Object() (-want, +got):\n%s", diff)
+				}
+			}
+		})
+	}
+}
+
+func TestTemplateAsStatusRequest(t *testing.T) {
+	tmpl := &Template{
+		Health:       "isHealth: true",
+		CustomStatus: "message: 'Ready'",
+		Details:      "details: 'some details'",
+	}
+	params := map[string]interface{}{
+		"param1": "value1",
+	}
+	statusReq := tmpl.AsStatusRequest(params)
+
+	assert.Equal(t, "isHealth: true", statusReq.Health)
+	assert.Equal(t, "message: 'Ready'", statusReq.Custom)
+	assert.Equal(t, "details: 'some details'", statusReq.Details)
+	assert.Equal(t, params, statusReq.Parameter)
+}
+
+func TestIsNotFoundInAppRevision(t *testing.T) {
+	testCases := map[string]struct {
+		err      error
+		expected bool
+	}{
+		"component definition not found": {
+			err:      fmt.Errorf("component definition [my-comp] not found in app revision [my-app-rev]"),
+			expected: true,
+		},
+		"trait definition not found": {
+			err:      fmt.Errorf("trait definition [my-trait] not found in app revision [my-app-rev]"),
+			expected: true,
+		},
+		"policy definition not found": {
+			err:      fmt.Errorf("policy definition [my-policy] not found in app revision [my-app-rev]"),
+			expected: true,
+		},
+		"workflow step definition not found": {
+			err:      fmt.Errorf("workflow step definition [my-step] not found in app revision [my-app-rev]"),
+			expected: true,
+		},
+		"different error": {
+			err:      errors.New("a completely different error"),
+			expected: false,
+		},
+		"nil error": {
+			err:      nil,
+			expected: false,
+		},
+		"error with similar text but not exactly": {
+			err:      fmt.Errorf("this resource is not found in revision of app"),
+			expected: false,
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			result := IsNotFoundInAppRevision(tc.err)
+			assert.Equal(t, tc.expected, result)
+		})
+	}
+}
diff --git a/pkg/appfile/unit_test.go b/pkg/appfile/unit_test.go
deleted file mode 100644
index 297559c0..00000000
--- a/pkg/appfile/unit_test.go
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
-Copyright 2023 The KubeVela Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-	http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package appfile
-
-import (
-	"context"
-	"fmt"
-	"testing"
-
-	"github.com/stretchr/testify/require"
-	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-	"k8s.io/apimachinery/pkg/runtime"
-	"sigs.k8s.io/controller-runtime/pkg/client/fake"
-
-	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
-	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
-)
-
-func TestIsNotFoundInAppFile(t *testing.T) {
-	require.True(t, IsNotFoundInAppFile(fmt.Errorf("ComponentDefinition XXX not found in appfile")))
-}
-
-func TestIsNotFoundInAppRevision(t *testing.T) {
-	require.True(t, IsNotFoundInAppRevision(fmt.Errorf("ComponentDefinition XXX not found in app revision")))
-}
-
-func TestParseComponentFromRevisionAndClient(t *testing.T) {
-	ctx := context.Background()
-	cli := fake.NewClientBuilder().WithScheme(scheme).Build()
-	p := &Parser{
-		client:     cli,
-		tmplLoader: LoadTemplate,
-	}
-	comp := common.ApplicationComponent{
-		Name:       "test",
-		Type:       "test",
-		Properties: &runtime.RawExtension{Raw: []byte(`{}`)},
-		Traits: []common.ApplicationTrait{{
-			Type:       "tr",
-			Properties: &runtime.RawExtension{Raw: []byte(`{}`)},
-		}, {
-			Type:       "internal",
-			Properties: &runtime.RawExtension{Raw: []byte(`{}`)},
-		}},
-	}
-	appRev := &v1beta1.ApplicationRevision{}
-	cd := &v1beta1.ComponentDefinition{ObjectMeta: metav1.ObjectMeta{Name: "test"}}
-	td := &v1beta1.TraitDefinition{ObjectMeta: metav1.ObjectMeta{Name: "tr"}}
-	require.NoError(t, cli.Create(ctx, cd))
-	require.NoError(t, cli.Create(ctx, td))
-	appRev.Spec.TraitDefinitions = map[string]*v1beta1.TraitDefinition{"internal": {}}
-	_, err := p.ParseComponentFromRevisionAndClient(ctx, comp, appRev)
-	require.NoError(t, err)
-
-	_comp1 := comp.DeepCopy()
-	_comp1.Type = "bad"
-	_, err = p.ParseComponentFromRevisionAndClient(ctx, *_comp1, appRev)
-	require.Error(t, err)
-
-	_comp2 := comp.DeepCopy()
-	_comp2.Traits[0].Type = "bad"
-	_, err = p.ParseComponentFromRevisionAndClient(ctx, *_comp2, appRev)
-	require.Error(t, err)
-
-	_comp3 := comp.DeepCopy()
-	_comp3.Traits[0].Properties = &runtime.RawExtension{Raw: []byte(`bad`)}
-	_, err = p.ParseComponentFromRevisionAndClient(ctx, *_comp3, appRev)
-	require.Error(t, err)
-}
diff --git a/pkg/appfile/validate_test.go b/pkg/appfile/validate_test.go
index 4fe61bc7..7720a799 100644
--- a/pkg/appfile/validate_test.go
+++ b/pkg/appfile/validate_test.go
@@ -17,67 +17,32 @@ limitations under the License.
 package appfile
 
 import (
-	. "github.com/onsi/ginkgo/v2"
-	. "github.com/onsi/gomega"
+	"testing"
+
+	"cuelang.org/go/cue"
+	"github.com/stretchr/testify/assert"
+	utilfeature "k8s.io/apiserver/pkg/util/feature"
 
 	"github.com/oam-dev/kubevela/apis/types"
 	"github.com/oam-dev/kubevela/pkg/cue/definition"
+	"github.com/oam-dev/kubevela/pkg/features"
 )
 
-var _ = Describe("Test validate CUE schematic Appfile", func() {
+func TestTrait_EvalContext_OutputNameUniqueness(t *testing.T) {
 	type SubTestCase struct {
+		name          string
 		compDefTmpl   string
 		traitDefTmpl1 string
 		traitDefTmpl2 string
 		wantErrMsg    string
 	}
 
-	DescribeTable("Test validate outputs name unique", func(tc SubTestCase) {
-		Expect("").Should(BeEmpty())
-		wl := &Component{
-			Name:               "myweb",
-			Type:               "worker",
-			CapabilityCategory: types.CUECategory,
-			Traits: []*Trait{
-				{
-					Name:               "myscaler",
-					CapabilityCategory: types.CUECategory,
-					Template:           tc.traitDefTmpl1,
-					engine:             definition.NewTraitAbstractEngine("myscaler"),
-				},
-				{
-					Name:               "myingress",
-					CapabilityCategory: types.CUECategory,
-					Template:           tc.traitDefTmpl2,
-					engine:             definition.NewTraitAbstractEngine("myingress"),
-				},
-			},
-			FullTemplate: &Template{
-				TemplateStr: tc.compDefTmpl,
-			},
-			engine: definition.NewWorkloadAbstractEngine("myweb"),
-		}
-
-		ctxData := GenerateContextDataFromAppFile(&Appfile{
-			Name:            "myapp",
-			Namespace:       "test-ns",
-			AppRevisionName: "myapp-v1",
-		}, wl.Name)
-		pCtx, err := newValidationProcessContext(wl, ctxData)
-		Expect(err).Should(BeNil())
-		Eventually(func() string {
-			for _, tr := range wl.Traits {
-				if err := tr.EvalContext(pCtx); err != nil {
-					return err.Error()
-				}
-			}
-			return ""
-		}).Should(ContainSubstring(tc.wantErrMsg))
-	},
-		Entry("Succeed", SubTestCase{
+	testCases := []SubTestCase{
+		{
+			name: "Succeed",
 			compDefTmpl: `
 			output: {
-				apiVersion: "apps/v1" 
+				apiVersion: "apps/v1"
 				kind: "Deployment"
 				}
 			outputs: mysvc: {
@@ -98,11 +63,12 @@ var _ = Describe("Test validate CUE schematic Appfile", func() {
 			}
 			`,
 			wantErrMsg: "",
-		}),
-		Entry("CompDef and TraitDef have same outputs", SubTestCase{
+		},
+		{
+			name: "CompDef and TraitDef have same outputs",
 			compDefTmpl: `
 			output: {
-				apiVersion: "apps/v1" 
+				apiVersion: "apps/v1"
 				kind: "Deployment"
 				}
 			outputs: mysvc1: {
@@ -123,11 +89,12 @@ var _ = Describe("Test validate CUE schematic Appfile", func() {
 			}
 			`,
 			wantErrMsg: `auxiliary "mysvc1" already exits`,
-		}),
-		Entry("TraitDefs have same outputs", SubTestCase{
+		},
+		{
+			name: "TraitDefs have same outputs",
 			compDefTmpl: `
 			output: {
-				apiVersion: "apps/v1" 
+				apiVersion: "apps/v1"
 				kind: "Deployment"
 				}
 			outputs: mysvc: {
@@ -148,41 +115,72 @@ var _ = Describe("Test validate CUE schematic Appfile", func() {
 			}
 			`,
 			wantErrMsg: `auxiliary "mysvc1" already exits`,
-		}),
-	)
-})
+		},
+	}
 
-var _ = Describe("Test ValidateComponentParams", func() {
-	type ParamTestCase struct {
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			wl := &Component{
+				Name:               "myweb",
+				Type:               "worker",
+				CapabilityCategory: types.CUECategory,
+				Traits: []*Trait{
+					{
+						Name:               "myscaler",
+						CapabilityCategory: types.CUECategory,
+						Template:           tc.traitDefTmpl1,
+						engine:             definition.NewTraitAbstractEngine("myscaler"),
+					},
+					{
+						Name:               "myingress",
+						CapabilityCategory: types.CUECategory,
+						Template:           tc.traitDefTmpl2,
+						engine:             definition.NewTraitAbstractEngine("myingress"),
+					},
+				},
+				FullTemplate: &Template{
+					TemplateStr: tc.compDefTmpl,
+				},
+				engine: definition.NewWorkloadAbstractEngine("myweb"),
+			}
+
+			ctxData := GenerateContextDataFromAppFile(&Appfile{
+				Name:            "myapp",
+				Namespace:       "test-ns",
+				AppRevisionName: "myapp-v1",
+			}, wl.Name)
+			pCtx, err := newValidationProcessContext(wl, ctxData)
+			assert.NoError(t, err)
+
+			var evalErr error
+			for _, tr := range wl.Traits {
+				if err := tr.EvalContext(pCtx); err != nil {
+					evalErr = err
+					break
+				}
+			}
+
+			if tc.wantErrMsg != "" {
+				assert.Error(t, evalErr)
+				assert.Contains(t, evalErr.Error(), tc.wantErrMsg)
+			} else {
+				assert.NoError(t, evalErr)
+			}
+		})
+	}
+}
+
+func TestParser_ValidateComponentParams(t *testing.T) {
+	testCases := []struct {
 		name     string
+		compName string
 		template string
 		params   map[string]interface{}
 		wantErr  string
-	}
-
-	DescribeTable("ValidateComponentParams cases", func(tc ParamTestCase) {
-		wl := &Component{
-			Name:         tc.name,
-			Type:         "worker",
-			FullTemplate: &Template{TemplateStr: tc.template},
-			Params:       tc.params,
-		}
-		app := &Appfile{
-			Name:      "myapp",
-			Namespace: "test-ns",
-		}
-		ctxData := GenerateContextDataFromAppFile(app, wl.Name)
-		parser := &Parser{}
-		err := parser.ValidateComponentParams(ctxData, wl, app)
-		if tc.wantErr == "" {
-			Expect(err).To(BeNil())
-		} else {
-			Expect(err).To(HaveOccurred())
-			Expect(err.Error()).To(ContainSubstring(tc.wantErr))
-		}
-	},
-		Entry("valid params and template", ParamTestCase{
-			name: "valid",
+	}{
+		{
+			name:     "valid params and template",
+			compName: "valid",
 			template: `
 			parameter: {
 				replicas: int | *1
@@ -196,9 +194,10 @@ var _ = Describe("Test ValidateComponentParams", func() {
 				"replicas": 2,
 			},
 			wantErr: "",
-		}),
-		Entry("invalid CUE in template", ParamTestCase{
-			name: "invalid-cue",
+		},
+		{
+			name:     "invalid CUE in template",
+			compName: "invalid-cue",
 			template: `
 			parameter: {
 				replicas: int | *1
@@ -213,9 +212,10 @@ var _ = Describe("Test ValidateComponentParams", func() {
 				"replicas": 2,
 			},
 			wantErr: "CUE compile error",
-		}),
-		Entry("missing required parameter", ParamTestCase{
-			name: "missing-required",
+		},
+		{
+			name:     "missing required parameter",
+			compName: "missing-required",
 			template: `
 			parameter: {
 				replicas: int
@@ -227,9 +227,10 @@ var _ = Describe("Test ValidateComponentParams", func() {
 			`,
 			params:  map[string]interface{}{},
 			wantErr: "component \"missing-required\": missing parameters: replicas",
-		}),
-		Entry("parameter constraint violation", ParamTestCase{
-			name: "constraint-violation",
+		},
+		{
+			name:     "parameter constraint violation",
+			compName: "constraint-violation",
 			template: `
 			parameter: {
 				replicas: int & >0
@@ -243,9 +244,10 @@ var _ = Describe("Test ValidateComponentParams", func() {
 				"replicas": -1,
 			},
 			wantErr: "parameter constraint violation",
-		}),
-		Entry("invalid parameter block", ParamTestCase{
-			name: "invalid-param-block",
+		},
+		{
+			name:     "invalid parameter block",
+			compName: "invalid-param-block",
 			template: `
 			parameter: {
 				replicas: int | *1
@@ -259,6 +261,340 @@ var _ = Describe("Test ValidateComponentParams", func() {
 				"replicas": "not-an-int",
 			},
 			wantErr: "parameter constraint violation",
-		}),
-	)
-})
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			wl := &Component{
+				Name:         tc.compName,
+				Type:         "worker",
+				FullTemplate: &Template{TemplateStr: tc.template},
+				Params:       tc.params,
+			}
+			app := &Appfile{
+				Name:      "myapp",
+				Namespace: "test-ns",
+			}
+			ctxData := GenerateContextDataFromAppFile(app, wl.Name)
+			parser := &Parser{}
+			err := parser.ValidateComponentParams(ctxData, wl, app)
+			if tc.wantErr == "" {
+				assert.NoError(t, err)
+			} else {
+				assert.Error(t, err)
+				assert.Contains(t, err.Error(), tc.wantErr)
+			}
+		})
+	}
+}
+
+func TestValidationHelpers(t *testing.T) {
+	t.Run("renderTemplate", func(t *testing.T) {
+		tmpl := "output: {}"
+		expected := "output: {}\ncontext: _\nparameter: _\n"
+		assert.Equal(t, expected, renderTemplate(tmpl))
+	})
+
+	t.Run("cueParamBlock", func(t *testing.T) {
+		t.Run("should handle empty params", func(t *testing.T) {
+			out, err := cueParamBlock(map[string]any{})
+			assert.NoError(t, err)
+			assert.Equal(t, "parameter: {}", out)
+		})
+
+		t.Run("should handle valid params", func(t *testing.T) {
+			params := map[string]any{"key": "value"}
+			out, err := cueParamBlock(params)
+			assert.NoError(t, err)
+			assert.Equal(t, `parameter: {"key":"value"}`, out)
+		})
+
+		t.Run("should return error for unmarshallable params", func(t *testing.T) {
+			params := map[string]any{"key": make(chan int)}
+			_, err := cueParamBlock(params)
+			assert.Error(t, err)
+		})
+	})
+
+	t.Run("filterMissing", func(t *testing.T) {
+		t.Run("should filter missing keys", func(t *testing.T) {
+			keys := []string{"a", "b.c", "d"}
+			provided := map[string]any{
+				"a": 1,
+				"b": map[string]any{
+					"c": 2,
+				},
+			}
+			out, err := filterMissing(keys, provided)
+			assert.NoError(t, err)
+			assert.Equal(t, []string{"d"}, out)
+		})
+
+		t.Run("should handle no missing keys", func(t *testing.T) {
+			keys := []string{"a"}
+			provided := map[string]any{"a": 1}
+			out, err := filterMissing(keys, provided)
+			assert.NoError(t, err)
+			assert.Empty(t, out)
+		})
+	})
+
+	t.Run("requiredFields", func(t *testing.T) {
+		t.Run("should identify required fields", func(t *testing.T) {
+			cueStr := `
+			parameter: {
+				name: string
+				age: int
+				nested: {
+					field1: string
+					field2: bool
+				}
+			}
+			`
+			var r cue.Runtime
+			inst, err := r.Compile("", cueStr)
+			assert.NoError(t, err)
+			val := inst.Value()
+			paramVal := val.LookupPath(cue.ParsePath("parameter"))
+
+			fields, err := requiredFields(paramVal)
+			assert.NoError(t, err)
+			assert.ElementsMatch(t, []string{"name", "age", "nested.field1", "nested.field2"}, fields)
+		})
+
+		t.Run("should ignore optional and default fields", func(t *testing.T) {
+			cueStr := `
+			parameter: {
+				name: string
+				age?: int
+				location: string | *"unknown"
+				nested: {
+					field1: string
+					field2?: bool
+				}
+			}
+			`
+			var r cue.Runtime
+			inst, err := r.Compile("", cueStr)
+			assert.NoError(t, err)
+			val := inst.Value()
+			paramVal := val.LookupPath(cue.ParsePath("parameter"))
+
+			fields, err := requiredFields(paramVal)
+			assert.NoError(t, err)
+			assert.ElementsMatch(t, []string{"name", "nested.field1"}, fields)
+		})
+	})
+}
+
+func TestEnforceRequiredParams(t *testing.T) {
+	var r cue.Runtime
+	cueStr := `
+		parameter: {
+			image: string
+			replicas: int
+			port: int
+			data: {
+				key: string
+				value: string
+			}
+		}
+		`
+	inst, err := r.Compile("", cueStr)
+	assert.NoError(t, err)
+	root := inst.Value()
+
+	t.Run("should pass if all params are provided directly", func(t *testing.T) {
+		params := map[string]any{
+			"image":    "nginx",
+			"replicas": 2,
+			"port":     80,
+			"data": map[string]any{
+				"key":   "k",
+				"value": "v",
+			},
+		}
+		app := &Appfile{}
+		err := enforceRequiredParams(root, params, app)
+		assert.NoError(t, err)
+	})
+
+	t.Run("should fail if params are missing", func(t *testing.T) {
+		params := map[string]any{
+			"image": "nginx",
+		}
+		app := &Appfile{}
+		err := enforceRequiredParams(root, params, app)
+		assert.Error(t, err)
+		assert.Contains(t, err.Error(), "missing parameters: replicas,port,data.key,data.value")
+	})
+}
+
+func TestParser_ValidateCUESchematicAppfile(t *testing.T) {
+	assert.NoError(t, utilfeature.DefaultMutableFeatureGate.Set(string(features.EnableCueValidation)+"=true"))
+	t.Cleanup(func() {
+		assert.NoError(t, utilfeature.DefaultMutableFeatureGate.Set(string(features.EnableCueValidation)+"=false"))
+	})
+
+	t.Run("should validate a valid CUE schematic appfile", func(t *testing.T) {
+		appfile := &Appfile{
+			Name:      "test-app",
+			Namespace: "test-ns",
+			ParsedComponents: []*Component{
+				{
+					Name:               "my-comp",
+					Type:               "worker",
+					CapabilityCategory: types.CUECategory,
+					Params: map[string]any{
+						"image": "nginx",
+					},
+					FullTemplate: &Template{
+						TemplateStr: `
+							parameter: {
+								image: string
+							}
+							output: {
+								apiVersion: "apps/v1"
+								kind: "Deployment"
+								spec: {
+									template: {
+										spec: {
+											containers: [{
+												name: "my-container"
+												image: parameter.image
+											}]
+										}
+									}
+								}
+							}
+						`,
+					},
+					engine: definition.NewWorkloadAbstractEngine("my-comp"),
+					Traits: []*Trait{
+						{
+							Name:               "my-trait",
+							CapabilityCategory: types.CUECategory,
+							Template: `
+								parameter: {
+								domain: string
+							}
+							patch: {}
+						`,
+							Params: map[string]any{
+								"domain": "example.com",
+							},
+							engine: definition.NewTraitAbstractEngine("my-trait"),
+						},
+					},
+				},
+			},
+		}
+
+		p := &Parser{}
+		err := p.ValidateCUESchematicAppfile(appfile)
+		assert.NoError(t, err)
+	})
+
+	t.Run("should return error for invalid trait evaluation", func(t *testing.T) {
+		appfile := &Appfile{
+			Name:      "test-app",
+			Namespace: "test-ns",
+			ParsedComponents: []*Component{
+				{
+					Name:               "my-comp",
+					Type:               "worker",
+					CapabilityCategory: types.CUECategory,
+					Params: map[string]any{
+						"image": "nginx",
+					},
+					FullTemplate: &Template{
+						TemplateStr: `
+							parameter: {
+								image: string
+							}
+							output: {
+								apiVersion: "apps/v1"
+								kind: "Deployment"
+							}
+						`,
+					},
+					engine: definition.NewWorkloadAbstractEngine("my-comp"),
+					Traits: []*Trait{
+						{
+							Name:               "my-trait",
+							CapabilityCategory: types.CUECategory,
+							Template: `
+								// invalid CUE template
+								parameter: {
+									domain: string
+								}
+							patch: {
+									invalid: {
+							}
+						`,
+							Params: map[string]any{
+								"domain": "example.com",
+							},
+							engine: definition.NewTraitAbstractEngine("my-trait"),
+						},
+					},
+				},
+			},
+		}
+
+		p := &Parser{}
+		err := p.ValidateCUESchematicAppfile(appfile)
+		assert.Error(t, err)
+		assert.Contains(t, err.Error(), "cannot evaluate trait \"my-trait\"")
+	})
+
+	t.Run("should return error for missing parameters", func(t *testing.T) {
+		appfile := &Appfile{
+			Name:      "test-app",
+			Namespace: "test-ns",
+			ParsedComponents: []*Component{
+				{
+					Name:               "my-comp",
+					Type:               "worker",
+					CapabilityCategory: types.CUECategory,
+					Params:             map[string]any{}, // no params provided
+					FullTemplate: &Template{
+						TemplateStr: `
+							parameter: {
+								image: string
+							}
+							output: {
+								apiVersion: "apps/v1"
+								kind: "Deployment"
+							}
+						`,
+					},
+					engine: definition.NewWorkloadAbstractEngine("my-comp"),
+				},
+			},
+		}
+
+		p := &Parser{}
+		err := p.ValidateCUESchematicAppfile(appfile)
+		assert.Error(t, err)
+		assert.Contains(t, err.Error(), "missing parameters: image")
+	})
+
+	t.Run("should skip non-CUE components", func(t *testing.T) {
+		appfile := &Appfile{
+			Name:      "test-app",
+			Namespace: "test-ns",
+			ParsedComponents: []*Component{
+				{
+					Name:               "my-comp",
+					Type:               "helm",
+					CapabilityCategory: types.TerraformCategory,
+				},
+			},
+		}
+		p := &Parser{}
+		err := p.ValidateCUESchematicAppfile(appfile)
+		assert.NoError(t, err)
+	})
+}
diff --git a/pkg/component/main_test.go b/pkg/component/main_test.go
new file mode 100644
index 00000000..423a9769
--- /dev/null
+++ b/pkg/component/main_test.go
@@ -0,0 +1,66 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package component
+
+import (
+	"log"
+	"math/rand"
+	"os"
+	"testing"
+	"time"
+
+	"k8s.io/client-go/rest"
+	"k8s.io/utils/ptr"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+	"sigs.k8s.io/controller-runtime/pkg/envtest"
+
+	pkgcommon "github.com/oam-dev/kubevela/pkg/utils/common"
+)
+
+var cfg *rest.Config
+var k8sClient client.Client
+var testEnv *envtest.Environment
+
+func TestMain(m *testing.M) {
+	rand.Seed(time.Now().UnixNano())
+
+	testEnv = &envtest.Environment{
+		ControlPlaneStartTimeout: time.Minute * 3,
+		ControlPlaneStopTimeout:  time.Minute,
+		UseExistingCluster:       ptr.To(false),
+		CRDDirectoryPaths:        []string{"./testdata"},
+	}
+
+	var err error
+	cfg, err = testEnv.Start()
+	if err != nil {
+		log.Fatalf("Failed to start test environment: %v", err)
+	}
+
+	cfg.Timeout = time.Minute * 2
+	k8sClient, err = client.New(cfg, client.Options{Scheme: pkgcommon.Scheme})
+	if err != nil {
+		log.Fatalf("Failed to create new kube client: %v", err)
+	}
+
+	code := m.Run()
+
+	if err = testEnv.Stop(); err != nil {
+		log.Printf("Failed to tear down the test environment: %v", err)
+	}
+	os.Exit(code)
+}
diff --git a/pkg/component/ref_objects_suite_test.go b/pkg/component/ref_objects_suite_test.go
deleted file mode 100644
index 21d1a6a7..00000000
--- a/pkg/component/ref_objects_suite_test.go
+++ /dev/null
@@ -1,381 +0,0 @@
-/*
-Copyright 2021 The KubeVela Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-	http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package component
-
-import (
-	"context"
-	"math/rand"
-	"testing"
-	"time"
-
-	. "github.com/onsi/ginkgo/v2"
-	. "github.com/onsi/gomega"
-	corev1 "k8s.io/api/core/v1"
-	rbacv1 "k8s.io/api/rbac/v1"
-	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
-	utilfeature "k8s.io/apiserver/pkg/util/feature"
-	"k8s.io/client-go/rest"
-	featuregatetesting "k8s.io/component-base/featuregate/testing"
-	"k8s.io/utils/ptr"
-	"sigs.k8s.io/controller-runtime/pkg/client"
-	"sigs.k8s.io/controller-runtime/pkg/envtest"
-
-	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1"
-	"github.com/oam-dev/kubevela/pkg/features"
-	pkgcommon "github.com/oam-dev/kubevela/pkg/utils/common"
-)
-
-var cfg *rest.Config
-var k8sClient client.Client
-var testEnv *envtest.Environment
-
-func TestUtils(t *testing.T) {
-	RegisterFailHandler(Fail)
-	RunSpecs(t, "Utils Suite")
-}
-
-var _ = BeforeSuite(func() {
-	rand.Seed(time.Now().UnixNano())
-	By("bootstrapping test environment for utils test")
-
-	testEnv = &envtest.Environment{
-		ControlPlaneStartTimeout: time.Minute * 3,
-		ControlPlaneStopTimeout:  time.Minute,
-		UseExistingCluster:       ptr.To(false),
-		CRDDirectoryPaths:        []string{"./testdata"},
-	}
-
-	By("start kube test env")
-	var err error
-	cfg, err = testEnv.Start()
-	Expect(err).ShouldNot(HaveOccurred())
-	Expect(cfg).ToNot(BeNil())
-
-	By("new kube client")
-	cfg.Timeout = time.Minute * 2
-	k8sClient, err = client.New(cfg, client.Options{Scheme: pkgcommon.Scheme})
-	Expect(err).Should(Succeed())
-})
-
-var _ = AfterSuite(func() {
-	By("tearing down the test environment")
-	err := testEnv.Stop()
-	Expect(err).ToNot(HaveOccurred())
-})
-
-var _ = Describe("Test ref-objects functions", func() {
-	It("Test SelectRefObjectsForDispatch", func() {
-		featuregatetesting.SetFeatureGateDuringTest(GinkgoT(), utilfeature.DefaultFeatureGate, features.LegacyObjectTypeIdentifier, true)
-		featuregatetesting.SetFeatureGateDuringTest(GinkgoT(), utilfeature.DefaultFeatureGate, features.DeprecatedObjectLabelSelector, true)
-		By("Create objects")
-		Expect(k8sClient.Create(context.Background(), &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "test"}})).Should(Succeed())
-		for _, obj := range []client.Object{&corev1.ConfigMap{
-			ObjectMeta: metav1.ObjectMeta{
-				Name:      "dynamic",
-				Namespace: "test",
-			},
-		}, &corev1.Service{
-			ObjectMeta: metav1.ObjectMeta{
-				Name:       "dynamic",
-				Namespace:  "test",
-				Generation: int64(5),
-			},
-			Spec: corev1.ServiceSpec{
-				ClusterIP: "10.0.0.254",
-				Ports:     []corev1.ServicePort{{Port: 80}},
-			},
-		}, &corev1.ConfigMap{
-			ObjectMeta: metav1.ObjectMeta{
-				Name:      "by-label-1",
-				Namespace: "test",
-				Labels:    map[string]string{"key": "value"},
-			},
-		}, &corev1.ConfigMap{
-			ObjectMeta: metav1.ObjectMeta{
-				Name:      "by-label-2",
-				Namespace: "test",
-				Labels:    map[string]string{"key": "value"},
-			},
-		}, &rbacv1.ClusterRole{
-			ObjectMeta: metav1.ObjectMeta{
-				Name: "test-cluster-role",
-			},
-		}} {
-			Expect(k8sClient.Create(context.Background(), obj)).Should(Succeed())
-		}
-		createUnstructured := func(apiVersion string, kind string, name string, namespace string, labels map[string]interface{}) *unstructured.Unstructured {
-			un := &unstructured.Unstructured{
-				Object: map[string]interface{}{
-					"apiVersion": apiVersion,
-					"kind":       kind,
-					"metadata":   map[string]interface{}{"name": name},
-				},
-			}
-			if namespace != "" {
-				un.SetNamespace(namespace)
-			}
-			if labels != nil {
-				un.Object["metadata"].(map[string]interface{})["labels"] = labels
-			}
-			return un
-		}
-		testcases := map[string]struct {
-			Input         v1alpha1.ObjectReferrer
-			compName      string
-			appNs         string
-			Output        []*unstructured.Unstructured
-			Error         string
-			Scope         string
-			IsService     bool
-			IsClusterRole bool
-		}{
-			"normal": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
-				},
-				appNs:  "test",
-				Output: []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
-			},
-			"legacy-type-identifier": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{LegacyObjectTypeIdentifier: v1alpha1.LegacyObjectTypeIdentifier{Kind: "ConfigMap", APIVersion: "v1"}},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
-				},
-				appNs:  "test",
-				Output: []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
-			},
-			"invalid-apiVersion": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{LegacyObjectTypeIdentifier: v1alpha1.LegacyObjectTypeIdentifier{Kind: "ConfigMap", APIVersion: "a/b/v1"}},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
-				},
-				appNs: "test",
-				Error: "invalid APIVersion",
-			},
-			"invalid-type-identifier": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
-				},
-				appNs: "test",
-				Error: "neither resource or apiVersion/kind is set",
-			},
-			"name-and-selector-both-set": {
-				Input: v1alpha1.ObjectReferrer{ObjectSelector: v1alpha1.ObjectSelector{Name: "dynamic", LabelSelector: map[string]string{"key": "value"}}},
-				appNs: "test",
-				Error: "invalid object selector for ref-objects, name and labelSelector cannot be both set",
-			},
-			"empty-ref-object-name": {
-				Input:    v1alpha1.ObjectReferrer{ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"}},
-				compName: "dynamic",
-				appNs:    "test",
-				Output:   []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
-			},
-			"cannot-find-ref-object": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "static"},
-				},
-				appNs: "test",
-				Error: "failed to load ref object",
-			},
-			"modify-service": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "service"},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
-				},
-				appNs:     "test",
-				IsService: true,
-			},
-			"by-labels": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
-					ObjectSelector:       v1alpha1.ObjectSelector{LabelSelector: map[string]string{"key": "value"}},
-				},
-				appNs: "test",
-				Output: []*unstructured.Unstructured{
-					createUnstructured("v1", "ConfigMap", "by-label-1", "test", map[string]interface{}{"key": "value"}),
-					createUnstructured("v1", "ConfigMap", "by-label-2", "test", map[string]interface{}{"key": "value"}),
-				},
-			},
-			"by-deprecated-labels": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
-					ObjectSelector:       v1alpha1.ObjectSelector{DeprecatedLabelSelector: map[string]string{"key": "value"}},
-				},
-				appNs: "test",
-				Output: []*unstructured.Unstructured{
-					createUnstructured("v1", "ConfigMap", "by-label-1", "test", map[string]interface{}{"key": "value"}),
-					createUnstructured("v1", "ConfigMap", "by-label-2", "test", map[string]interface{}{"key": "value"}),
-				},
-			},
-			"no-kind-for-resource": {
-				Input: v1alpha1.ObjectReferrer{ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "unknown"}},
-				appNs: "test",
-				Error: "no matches",
-			},
-			"cross-namespace": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic", Namespace: "test"},
-				},
-				appNs:  "demo",
-				Output: []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
-			},
-			"cross-namespace-forbidden": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic", Namespace: "test"},
-				},
-				appNs: "demo",
-				Scope: RefObjectsAvailableScopeNamespace,
-				Error: "cannot refer to objects outside the application's namespace",
-			},
-			"cross-cluster": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic", Cluster: "demo"},
-				},
-				appNs:  "test",
-				Output: []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
-			},
-			"cross-cluster-forbidden": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic", Cluster: "demo"},
-				},
-				appNs: "test",
-				Scope: RefObjectsAvailableScopeCluster,
-				Error: "cannot refer to objects outside control plane",
-			},
-			"test-cluster-scope-resource": {
-				Input: v1alpha1.ObjectReferrer{
-					ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "clusterrole"},
-					ObjectSelector:       v1alpha1.ObjectSelector{Name: "test-cluster-role"},
-				},
-				appNs:         "test",
-				Scope:         RefObjectsAvailableScopeCluster,
-				Output:        []*unstructured.Unstructured{createUnstructured("rbac.authorization.k8s.io/v1", "ClusterRole", "test-cluster-role", "", nil)},
-				IsClusterRole: true,
-			},
-		}
-		for name, tt := range testcases {
-			By("Test " + name)
-			if tt.Scope == "" {
-				tt.Scope = RefObjectsAvailableScopeGlobal
-			}
-			RefObjectsAvailableScope = tt.Scope
-			output, err := SelectRefObjectsForDispatch(context.Background(), k8sClient, tt.appNs, tt.compName, tt.Input)
-			if tt.Error != "" {
-				Expect(err).ShouldNot(BeNil())
-				Expect(err.Error()).Should(ContainSubstring(tt.Error))
-			} else {
-				Expect(err).Should(Succeed())
-				if tt.IsService {
-					Expect(output[0].Object["kind"]).Should(Equal("Service"))
-					Expect(output[0].Object["spec"].(map[string]interface{})["clusterIP"]).Should(BeNil())
-				} else {
-					if tt.IsClusterRole {
-						delete(output[0].Object, "rules")
-					}
-					Expect(output).Should(Equal(tt.Output))
-				}
-			}
-		}
-	})
-
-	It("Test AppendUnstructuredObjects", func() {
-		testCases := map[string]struct {
-			Inputs  []*unstructured.Unstructured
-			Input   *unstructured.Unstructured
-			Outputs []*unstructured.Unstructured
-		}{
-			"overlap": {
-				Inputs: []*unstructured.Unstructured{{Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "x", "namespace": "default"},
-					"data":       "a",
-				}}, {Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
-					"data":       "b",
-				}}},
-				Input: &unstructured.Unstructured{Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
-					"data":       "c",
-				}},
-				Outputs: []*unstructured.Unstructured{{Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "x", "namespace": "default"},
-					"data":       "a",
-				}}, {Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
-					"data":       "c",
-				}}},
-			},
-			"append": {
-				Inputs: []*unstructured.Unstructured{{Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "x", "namespace": "default"},
-					"data":       "a",
-				}}, {Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
-					"data":       "b",
-				}}},
-				Input: &unstructured.Unstructured{Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "z", "namespace": "default"},
-					"data":       "c",
-				}},
-				Outputs: []*unstructured.Unstructured{{Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "x", "namespace": "default"},
-					"data":       "a",
-				}}, {Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
-					"data":       "b",
-				}}, {Object: map[string]interface{}{
-					"apiVersion": "v1",
-					"kind":       "ConfigMap",
-					"metadata":   map[string]interface{}{"name": "z", "namespace": "default"},
-					"data":       "c",
-				}}},
-			},
-		}
-		for name, tt := range testCases {
-			By("Test " + name)
-			Expect(AppendUnstructuredObjects(tt.Inputs, tt.Input)).Should(Equal(tt.Outputs))
-		}
-	})
-
-})
diff --git a/pkg/component/ref_objects_test.go b/pkg/component/ref_objects_test.go
new file mode 100644
index 00000000..c65bf93d
--- /dev/null
+++ b/pkg/component/ref_objects_test.go
@@ -0,0 +1,748 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package component
+
+import (
+	"context"
+	"encoding/json"
+	"reflect"
+	"strings"
+	"testing"
+
+	corev1 "k8s.io/api/core/v1"
+	rbacv1 "k8s.io/api/rbac/v1"
+	apierrors "k8s.io/apimachinery/pkg/api/errors"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+	"k8s.io/apimachinery/pkg/runtime"
+	"k8s.io/apimachinery/pkg/runtime/schema"
+	utilfeature "k8s.io/apiserver/pkg/util/feature"
+	featuregatetesting "k8s.io/component-base/featuregate/testing"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1"
+	"github.com/oam-dev/kubevela/pkg/features"
+)
+
+func TestGetLabelSelectorFromRefObjectSelector(t *testing.T) {
+	type args struct {
+		selector v1alpha1.ObjectReferrer
+	}
+	tests := []struct {
+		name      string
+		args      args
+		featureOn bool
+		want      map[string]string
+	}{
+		{
+			name: "label selector present",
+			args: args{
+				selector: v1alpha1.ObjectReferrer{
+					ObjectSelector: v1alpha1.ObjectSelector{
+						LabelSelector: map[string]string{"app": "my-app"},
+					},
+				},
+			},
+			want: map[string]string{"app": "my-app"},
+		},
+		{
+			name: "deprecated label selector present and feature on",
+			args: args{
+				selector: v1alpha1.ObjectReferrer{
+					ObjectSelector: v1alpha1.ObjectSelector{
+						DeprecatedLabelSelector: map[string]string{"app": "my-app-deprecated"},
+					},
+				},
+			},
+			featureOn: true,
+			want:      map[string]string{"app": "my-app-deprecated"},
+		},
+		{
+			name: "deprecated label selector present and feature off",
+			args: args{
+				selector: v1alpha1.ObjectReferrer{
+					ObjectSelector: v1alpha1.ObjectSelector{
+						DeprecatedLabelSelector: map[string]string{"app": "my-app-deprecated"},
+					},
+				},
+			},
+			featureOn: false,
+			want:      nil,
+		},
+		{
+			name: "both present, label selector takes precedence",
+			args: args{
+				selector: v1alpha1.ObjectReferrer{
+					ObjectSelector: v1alpha1.ObjectSelector{
+						LabelSelector:           map[string]string{"app": "my-app"},
+						DeprecatedLabelSelector: map[string]string{"app": "my-app-deprecated"},
+					},
+				},
+			},
+			featureOn: true,
+			want:      map[string]string{"app": "my-app"},
+		},
+		{
+			name: "no selector",
+			args: args{
+				selector: v1alpha1.ObjectReferrer{},
+			},
+			want: nil,
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.DeprecatedObjectLabelSelector, tt.featureOn)
+			if got := GetLabelSelectorFromRefObjectSelector(tt.args.selector); !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("GetLabelSelectorFromRefObjectSelector() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestValidateRefObjectSelector(t *testing.T) {
+	type args struct {
+		selector v1alpha1.ObjectReferrer
+	}
+	tests := []struct {
+		name    string
+		args    args
+		wantErr bool
+	}{
+		{
+			name: "name only",
+			args: args{
+				selector: v1alpha1.ObjectReferrer{
+					ObjectSelector: v1alpha1.ObjectSelector{
+						Name: "my-obj",
+					},
+				},
+			},
+			wantErr: false,
+		},
+		{
+			name: "label selector only",
+			args: args{
+				selector: v1alpha1.ObjectReferrer{
+					ObjectSelector: v1alpha1.ObjectSelector{
+						LabelSelector: map[string]string{"app": "my-app"},
+					},
+				},
+			},
+			wantErr: false,
+		},
+		{
+			name: "both name and label selector",
+			args: args{
+				selector: v1alpha1.ObjectReferrer{
+					ObjectSelector: v1alpha1.ObjectSelector{
+						Name:          "my-obj",
+						LabelSelector: map[string]string{"app": "my-app"},
+					},
+				},
+			},
+			wantErr: true,
+		},
+		{
+			name: "empty selector",
+			args: args{
+				selector: v1alpha1.ObjectReferrer{},
+			},
+			wantErr: false,
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := ValidateRefObjectSelector(tt.args.selector); (err != nil) != tt.wantErr {
+				t.Errorf("ValidateRefObjectSelector() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestClearRefObjectForDispatch(t *testing.T) {
+	un := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"metadata": map[string]interface{}{
+				"name":              "test-obj",
+				"namespace":         "default",
+				"resourceVersion":   "12345",
+				"generation":        int64(1),
+				"uid":               "abc-def",
+				"creationTimestamp": "2021-01-01T00:00:00Z",
+				"managedFields":     []interface{}{},
+				"ownerReferences":   []interface{}{},
+			},
+			"status": map[string]interface{}{
+				"phase": "Available",
+			},
+		},
+	}
+	ClearRefObjectForDispatch(un)
+
+	if un.GetResourceVersion() != "" {
+		t.Errorf("resourceVersion should be cleared")
+	}
+	if un.GetGeneration() != 0 {
+		t.Errorf("generation should be cleared")
+	}
+	if len(un.GetOwnerReferences()) != 0 {
+		t.Errorf("ownerReferences should be cleared")
+	}
+	if un.GetDeletionTimestamp() != nil {
+		t.Errorf("deletionTimestamp should be nil")
+	}
+	if len(un.GetManagedFields()) != 0 {
+		t.Errorf("managedFields should be cleared")
+	}
+	if un.GetUID() != "" {
+		t.Errorf("uid should be cleared")
+	}
+	if _, found, _ := unstructured.NestedFieldNoCopy(un.Object, "metadata", "creationTimestamp"); found {
+		t.Errorf("creationTimestamp should be removed")
+	}
+	if _, found, _ := unstructured.NestedFieldNoCopy(un.Object, "status"); found {
+		t.Errorf("status should be removed")
+	}
+
+	// Test for service
+	svc := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "v1",
+			"kind":       "Service",
+			"metadata": map[string]interface{}{
+				"name": "test-svc",
+			},
+			"spec": map[string]interface{}{
+				"clusterIP":  "1.2.3.4",
+				"clusterIPs": []interface{}{"1.2.3.4"},
+			},
+		},
+	}
+	ClearRefObjectForDispatch(svc)
+	if _, found, _ := unstructured.NestedString(svc.Object, "spec", "clusterIP"); found {
+		t.Errorf("service clusterIP should be removed")
+	}
+	if _, found, _ := unstructured.NestedStringSlice(svc.Object, "spec", "clusterIPs"); found {
+		t.Errorf("service clusterIPs should be removed")
+	}
+
+	// Test for service with ClusterIPNone
+	svcNone := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "v1",
+			"kind":       "Service",
+			"metadata": map[string]interface{}{
+				"name": "test-svc-none",
+			},
+			"spec": map[string]interface{}{
+				"clusterIP": corev1.ClusterIPNone,
+			},
+		},
+	}
+	ClearRefObjectForDispatch(svcNone)
+	if ip, found, _ := unstructured.NestedString(svcNone.Object, "spec", "clusterIP"); !found || ip != corev1.ClusterIPNone {
+		t.Errorf("service with clusterIP None should not be removed")
+	}
+}
+
+func TestSelectRefObjectsForDispatch(t *testing.T) {
+	featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.LegacyObjectTypeIdentifier, true)
+	featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.DeprecatedObjectLabelSelector, true)
+	t.Log("Create objects")
+	if err := k8sClient.Create(context.Background(), &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "test"}}); err != nil {
+		t.Fatal(err)
+	}
+	for _, obj := range []client.Object{&corev1.ConfigMap{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "dynamic",
+			Namespace: "test",
+		},
+	}, &corev1.Service{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:       "dynamic",
+			Namespace:  "test",
+			Generation: int64(5),
+		},
+		Spec: corev1.ServiceSpec{
+			ClusterIP: "10.0.0.254",
+			Ports:     []corev1.ServicePort{{Port: 80}},
+		},
+	}, &corev1.ConfigMap{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "by-label-1",
+			Namespace: "test",
+			Labels:    map[string]string{"key": "value"},
+		},
+	}, &corev1.ConfigMap{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "by-label-2",
+			Namespace: "test",
+			Labels:    map[string]string{"key": "value"},
+		},
+	}, &rbacv1.ClusterRole{
+		ObjectMeta: metav1.ObjectMeta{
+			Name: "test-cluster-role",
+		},
+	}} {
+		if err := k8sClient.Create(context.Background(), obj); err != nil {
+			t.Fatal(err)
+		}
+	}
+	createUnstructured := func(apiVersion string, kind string, name string, namespace string, labels map[string]interface{}) *unstructured.Unstructured {
+		un := &unstructured.Unstructured{
+			Object: map[string]interface{}{"apiVersion": apiVersion,
+				"kind":     kind,
+				"metadata": map[string]interface{}{"name": name},
+			},
+		}
+		if namespace != "" {
+			un.SetNamespace(namespace)
+		}
+		if labels != nil {
+			un.Object["metadata"].(map[string]interface{})["labels"] = labels
+		}
+		return un
+	}
+	testcases := map[string]struct {
+		Input         v1alpha1.ObjectReferrer
+		compName      string
+		appNs         string
+		Output        []*unstructured.Unstructured
+		Error         string
+		Scope         string
+		IsService     bool
+		IsClusterRole bool
+	}{
+		"normal": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
+			},
+			appNs:  "test",
+			Output: []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
+		},
+		"legacy-type-identifier": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{LegacyObjectTypeIdentifier: v1alpha1.LegacyObjectTypeIdentifier{Kind: "ConfigMap", APIVersion: "v1"}},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
+			},
+			appNs:  "test",
+			Output: []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
+		},
+		"invalid-apiVersion": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{LegacyObjectTypeIdentifier: v1alpha1.LegacyObjectTypeIdentifier{Kind: "ConfigMap", APIVersion: "a/b/v1"}},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
+			},
+			appNs: "test",
+			Error: "invalid APIVersion",
+		},
+		"invalid-type-identifier": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
+			},
+			appNs: "test",
+			Error: "neither resource or apiVersion/kind is set",
+		},
+		"name-and-selector-both-set": {
+			Input: v1alpha1.ObjectReferrer{ObjectSelector: v1alpha1.ObjectSelector{Name: "dynamic", LabelSelector: map[string]string{"key": "value"}}},
+			appNs: "test",
+			Error: "invalid object selector for ref-objects, name and labelSelector cannot be both set",
+		},
+		"empty-ref-object-name": {
+			Input:    v1alpha1.ObjectReferrer{ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"}},
+			compName: "dynamic",
+			appNs:    "test",
+			Output:   []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
+		},
+		"cannot-find-ref-object": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "static"},
+			},
+			appNs: "test",
+			Error: "failed to load ref object",
+		},
+		"modify-service": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "service"},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic"},
+			},
+			appNs:     "test",
+			IsService: true,
+		},
+		"by-labels": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
+				ObjectSelector:       v1alpha1.ObjectSelector{LabelSelector: map[string]string{"key": "value"}},
+			},
+			appNs: "test",
+			Output: []*unstructured.Unstructured{
+				createUnstructured("v1", "ConfigMap", "by-label-1", "test", map[string]interface{}{"key": "value"}),
+				createUnstructured("v1", "ConfigMap", "by-label-2", "test", map[string]interface{}{"key": "value"}),
+			},
+		},
+		"by-deprecated-labels": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
+				ObjectSelector:       v1alpha1.ObjectSelector{DeprecatedLabelSelector: map[string]string{"key": "value"}},
+			},
+			appNs: "test",
+			Output: []*unstructured.Unstructured{
+				createUnstructured("v1", "ConfigMap", "by-label-1", "test", map[string]interface{}{"key": "value"}),
+				createUnstructured("v1", "ConfigMap", "by-label-2", "test", map[string]interface{}{"key": "value"}),
+			},
+		},
+		"no-kind-for-resource": {
+			Input: v1alpha1.ObjectReferrer{ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "unknown"}},
+			appNs: "test",
+			Error: "no matches",
+		},
+		"cross-namespace": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic", Namespace: "test"},
+			},
+			appNs:  "demo",
+			Output: []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
+		},
+		"cross-namespace-forbidden": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic", Namespace: "test"},
+			},
+			appNs: "demo",
+			Scope: RefObjectsAvailableScopeNamespace,
+			Error: "cannot refer to objects outside the application's namespace",
+		},
+		"cross-cluster": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic", Cluster: "demo"},
+			},
+			appNs:  "test",
+			Output: []*unstructured.Unstructured{createUnstructured("v1", "ConfigMap", "dynamic", "test", nil)},
+		},
+		"cross-cluster-forbidden": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "configmap"},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "dynamic", Cluster: "demo"},
+			},
+			appNs: "test",
+			Scope: RefObjectsAvailableScopeCluster,
+			Error: "cannot refer to objects outside control plane",
+		},
+		"test-cluster-scope-resource": {
+			Input: v1alpha1.ObjectReferrer{
+				ObjectTypeIdentifier: v1alpha1.ObjectTypeIdentifier{Resource: "clusterrole"},
+				ObjectSelector:       v1alpha1.ObjectSelector{Name: "test-cluster-role"},
+			},
+			appNs:         "test",
+			Scope:         RefObjectsAvailableScopeCluster,
+			Output:        []*unstructured.Unstructured{createUnstructured("rbac.authorization.k8s.io/v1", "ClusterRole", "test-cluster-role", "", nil)},
+			IsClusterRole: true,
+		},
+	}
+	for name, tt := range testcases {
+		t.Run(name, func(t *testing.T) {
+			if tt.Scope == "" {
+				tt.Scope = RefObjectsAvailableScopeGlobal
+			}
+			RefObjectsAvailableScope = tt.Scope
+			output, err := SelectRefObjectsForDispatch(context.Background(), k8sClient, tt.appNs, tt.compName, tt.Input)
+			if tt.Error != "" {
+				if err == nil {
+					t.Fatalf("expected error, got nil")
+				}
+				if !strings.Contains(err.Error(), tt.Error) {
+					t.Fatalf("expected error message to contain %q, got %q", tt.Error, err.Error())
+				}
+			} else {
+				if err != nil {
+					t.Fatal(err)
+				}
+				if tt.IsService {
+					if output[0].Object["kind"] != "Service" {
+						t.Fatalf(`expected kind to be "Service", got %q`, output[0].Object["kind"])
+					}
+					if output[0].Object["spec"].(map[string]interface{})["clusterIP"] != nil {
+						t.Fatalf(`expected clusterIP to be nil, got %v`, output[0].Object["spec"].(map[string]interface{})["clusterIP"])
+					}
+				} else {
+					if tt.IsClusterRole {
+						delete(output[0].Object, "rules")
+					}
+					if !reflect.DeepEqual(output, tt.Output) {
+						t.Fatalf("expected output to be %v, got %v", tt.Output, output)
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestReferredObjectsDelegatingClient(t *testing.T) {
+	objs := []*unstructured.Unstructured{
+		{
+			Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata": map[string]interface{}{
+					"name":      "cm-1",
+					"namespace": "ns-1",
+					"labels":    map[string]interface{}{"app": "app-1"},
+				},
+			},
+		},
+		{
+			Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata": map[string]interface{}{
+					"name":      "cm-2",
+					"namespace": "ns-1",
+					"labels":    map[string]interface{}{"app": "app-2"},
+				},
+			},
+		},
+		{
+			Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "Secret",
+				"metadata": map[string]interface{}{
+					"name":      "secret-1",
+					"namespace": "ns-1",
+					"labels":    map[string]interface{}{"app": "app-1"},
+				},
+			},
+		},
+	}
+
+	delegatingClient := ReferredObjectsDelegatingClient(k8sClient, objs)
+
+	t.Run("Get", func(t *testing.T) {
+		t.Run("should get existing object", func(t *testing.T) {
+			obj := &unstructured.Unstructured{}
+			obj.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMap"})
+			err := delegatingClient.Get(context.Background(), client.ObjectKey{Name: "cm-1", Namespace: "ns-1"}, obj)
+			if err != nil {
+				t.Fatalf("unexpected error: %v", err)
+			}
+			if obj.GetName() != "cm-1" {
+				t.Errorf("expected object name cm-1, got %s", obj.GetName())
+			}
+		})
+
+		t.Run("should return not found for non-existing object", func(t *testing.T) {
+			obj := &unstructured.Unstructured{}
+			obj.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMap"})
+			err := delegatingClient.Get(context.Background(), client.ObjectKey{Name: "cm-non-existent", Namespace: "ns-1"}, obj)
+			if !apierrors.IsNotFound(err) {
+				t.Errorf("expected not found error, got %v", err)
+			}
+		})
+
+		t.Run("should return not found for different kind", func(t *testing.T) {
+			obj := &unstructured.Unstructured{}
+			obj.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"})
+			err := delegatingClient.Get(context.Background(), client.ObjectKey{Name: "cm-1", Namespace: "ns-1"}, obj)
+			if !apierrors.IsNotFound(err) {
+				t.Errorf("expected not found error, got %v", err)
+			}
+		})
+	})
+
+	t.Run("List", func(t *testing.T) {
+		t.Run("should list all objects of a kind", func(t *testing.T) {
+			list := &unstructured.UnstructuredList{}
+			list.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMapList"})
+			err := delegatingClient.List(context.Background(), list)
+			if err != nil {
+				t.Fatalf("unexpected error: %v", err)
+			}
+			if len(list.Items) != 2 {
+				t.Errorf("expected 2 items, got %d", len(list.Items))
+			}
+		})
+
+		t.Run("should list with namespace", func(t *testing.T) {
+			list := &unstructured.UnstructuredList{}
+			list.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMapList"})
+			err := delegatingClient.List(context.Background(), list, client.InNamespace("ns-1"))
+			if err != nil {
+				t.Fatalf("unexpected error: %v", err)
+			}
+			if len(list.Items) != 2 {
+				t.Errorf("expected 2 items, got %d", len(list.Items))
+			}
+
+			list.Items = []unstructured.Unstructured{}
+			err = delegatingClient.List(context.Background(), list, client.InNamespace("ns-2"))
+			if err != nil {
+				t.Fatalf("unexpected error: %v", err)
+			}
+			if len(list.Items) != 0 {
+				t.Errorf("expected 0 items, got %d", len(list.Items))
+			}
+		})
+
+		t.Run("should list with label selector", func(t *testing.T) {
+			list := &unstructured.UnstructuredList{}
+			list.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMapList"})
+			err := delegatingClient.List(context.Background(), list, client.MatchingLabels{"app": "app-1"})
+			if err != nil {
+				t.Fatalf("unexpected error: %v", err)
+			}
+			if len(list.Items) != 1 {
+				t.Errorf("expected 1 item, got %d", len(list.Items))
+			}
+			if list.Items[0].GetName() != "cm-1" {
+				t.Errorf("expected cm-1, got %s", list.Items[0].GetName())
+			}
+		})
+	})
+}
+
+func TestAppendUnstructuredObjects(t *testing.T) {
+	testCases := map[string]struct {
+		Inputs  []*unstructured.Unstructured
+		Input   *unstructured.Unstructured
+		Outputs []*unstructured.Unstructured
+	}{
+		"overlap": {
+			Inputs: []*unstructured.Unstructured{{Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "x", "namespace": "default"},
+				"data":       "a",
+			}}, {Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
+				"data":       "b",
+			}}},
+			Input: &unstructured.Unstructured{Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
+				"data":       "c",
+			}},
+			Outputs: []*unstructured.Unstructured{{Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "x", "namespace": "default"},
+				"data":       "a",
+			}}, {Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
+				"data":       "c",
+			}}},
+		},
+		"append": {
+			Inputs: []*unstructured.Unstructured{{Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "x", "namespace": "default"},
+				"data":       "a",
+			}}, {Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
+				"data":       "b",
+			}}},
+			Input: &unstructured.Unstructured{Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "z", "namespace": "default"},
+				"data":       "c",
+			}},
+			Outputs: []*unstructured.Unstructured{{Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "x", "namespace": "default"},
+				"data":       "a",
+			}}, {Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "y", "namespace": "default"},
+				"data":       "b",
+			}}, {Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata":   map[string]interface{}{"name": "z", "namespace": "default"},
+				"data":       "c",
+			}}},
+		},
+	}
+	for name, tt := range testCases {
+		t.Run(name, func(t *testing.T) {
+			got := AppendUnstructuredObjects(tt.Inputs, tt.Input)
+			if !reflect.DeepEqual(got, tt.Outputs) {
+				t.Fatalf("expected output to be %v, got %v", tt.Outputs, got)
+			}
+		})
+	}
+}
+
+func TestConvertUnstructuredsToReferredObjects(t *testing.T) {
+	uns := []*unstructured.Unstructured{
+		{
+			Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "ConfigMap",
+				"metadata": map[string]interface{}{
+					"name": "cm-1",
+				},
+			},
+		},
+		{
+			Object: map[string]interface{}{
+				"apiVersion": "apps/v1",
+				"kind":       "Deployment",
+				"metadata": map[string]interface{}{
+					"name": "deploy-1",
+				},
+			},
+		},
+	}
+
+	refObjs, err := ConvertUnstructuredsToReferredObjects(uns)
+	if err != nil {
+		t.Fatalf("unexpected error: %v", err)
+	}
+
+	if len(refObjs) != 2 {
+		t.Fatalf("expected 2 referred objects, got %d", len(refObjs))
+	}
+
+	for i, un := range uns {
+		raw, err := json.Marshal(un)
+		if err != nil {
+			t.Fatalf("failed to marshal unstructured: %v", err)
+		}
+		expected := common.ReferredObject{
+			RawExtension: runtime.RawExtension{Raw: raw},
+		}
+		if !reflect.DeepEqual(refObjs[i], expected) {
+			t.Errorf("expected refObj %v, got %v", expected, refObjs[i])
+		}
+	}
+}
diff --git a/pkg/controller/core.oam.dev/v1beta1/application/application_controller_test.go b/pkg/controller/core.oam.dev/v1beta1/application/application_controller_test.go
index fc09f335..19cd3bef 100644
--- a/pkg/controller/core.oam.dev/v1beta1/application/application_controller_test.go
+++ b/pkg/controller/core.oam.dev/v1beta1/application/application_controller_test.go
@@ -1477,7 +1477,7 @@ var _ = Describe("Test Application Controller", func() {
 								Outputs: workflowv1alpha1.StepOutputs{
 									{
 										Name:      "output",
-										ValueFrom: "context.name",
+										ValueFrom: `"app-with-skip-output"`,
 									},
 								},
 								Properties: &runtime.RawExtension{Raw: []byte(`{"component":"myweb1"}`)},
@@ -1492,7 +1492,7 @@ var _ = Describe("Test Application Controller", func() {
 										ParameterKey: "",
 									},
 								},
-								If:         `inputs.output == "app-with-timeout-output"`,
+								If:         `inputs.output == "app-with-skip-output"`,
 								Type:       "apply-component",
 								Properties: &runtime.RawExtension{Raw: []byte(`{"component":"myweb2"}`)},
 							},
diff --git a/pkg/controller/core.oam.dev/v1beta1/application/testdata/definitions/panic.yaml b/pkg/controller/core.oam.dev/v1beta1/application/testdata/definitions/panic.yaml
index 33e68af8..27313191 100644
--- a/pkg/controller/core.oam.dev/v1beta1/application/testdata/definitions/panic.yaml
+++ b/pkg/controller/core.oam.dev/v1beta1/application/testdata/definitions/panic.yaml
@@ -8,6 +8,8 @@ spec:
   schematic:
     cue:
       template: |
+        import "list"
+        
         pvcVolumesList: *[
                         for v in parameter.pvc if v.mountPath != _|_ {
                         {
@@ -24,7 +26,7 @@ spec:
                         }
                 },
         ] | []
-        volumesList: pvcVolumesList + configMapVolumesList
+        volumesList: list.Concat([pvcVolumesList, configMapVolumesList])
         deDupVolumesArray: [
                 for val in [
                         for i, vi in volumesList {
diff --git a/pkg/cue/convert_test.go b/pkg/cue/convert_test.go
index 7cf0da08..496b3c26 100644
--- a/pkg/cue/convert_test.go
+++ b/pkg/cue/convert_test.go
@@ -78,4 +78,25 @@ func TestGetParameter(t *testing.T) {
 		}
 	}
 	assert.Equal(t, flag, true)
+
+	// Test pattern parameter selectors which would cause panic with Unquoted()
+	data, _ = os.ReadFile("testdata/workloads/pattern-params.cue")
+	params, err = GetParameters(string(data))
+	assert.NoError(t, err) // Should not panic
+	// We should get the regular parameters but pattern selectors are handled safely
+	assert.GreaterOrEqual(t, len(params), 2) // At least name and port
+	foundName := false
+	foundPort := false
+	for _, p := range params {
+		if p.Name == "name" {
+			foundName = true
+			assert.Equal(t, cue.StringKind, p.Type)
+		}
+		if p.Name == "port" {
+			foundPort = true
+			assert.Equal(t, int64(8080), p.Default)
+		}
+	}
+	assert.True(t, foundName, "Should find 'name' parameter")
+	assert.True(t, foundPort, "Should find 'port' parameter")
 }
diff --git a/pkg/cue/definition/health/health_test.go b/pkg/cue/definition/health/health_test.go
index 7420baaa..f7319ed2 100644
--- a/pkg/cue/definition/health/health_test.go
+++ b/pkg/cue/definition/health/health_test.go
@@ -476,11 +476,11 @@ func TestContextPassing(t *testing.T) {
 				statusCtx := ctx["status"].(map[string]interface{})
 				details := statusCtx["details"].(map[string]interface{})
 
-				assert.Equal(t, 3, details["replicas"])
-				assert.Equal(t, 8080, details["port"])
+				assert.Equal(t, int64(3), details["replicas"])
+				assert.Equal(t, int64(8080), details["port"])
 				assert.Equal(t, true, details["isReady"])
 				assert.Equal(t, true, details["configEnabled"])
-				assert.Equal(t, 30, details["configTimeout"])
+				assert.Equal(t, int64(30), details["configTimeout"])
 
 				assert.Nil(t, details["config"])
 			},
@@ -518,9 +518,9 @@ func TestContextPassing(t *testing.T) {
 
 				ports := details["$ports"].([]interface{})
 				assert.Len(t, ports, 3)
-				assert.Equal(t, 80, ports[0])
-				assert.Equal(t, 443, ports[1])
-				assert.Equal(t, 8080, ports[2])
+				assert.Equal(t, int64(80), ports[0])
+				assert.Equal(t, int64(443), ports[1])
+				assert.Equal(t, int64(8080), ports[2])
 
 				protocols := details["$protocols"].([]interface{})
 				assert.Len(t, protocols, 3)
@@ -530,8 +530,8 @@ func TestContextPassing(t *testing.T) {
 				mappings := details["$mappings"].([]interface{})
 				assert.Len(t, mappings, 2)
 
-				assert.Equal(t, 3, details["portCount"])
-				assert.Equal(t, 80, details["firstPort"])
+				assert.Equal(t, int64(3), details["portCount"])
+				assert.Equal(t, int64(80), details["firstPort"])
 				assert.Equal(t, "http", details["mainProtocol"])
 				assert.Equal(t, "80,443,8080", details["portsString"])
 			},
@@ -631,9 +631,9 @@ func TestContextPassing(t *testing.T) {
 				statusCtx := ctx["status"].(map[string]interface{})
 				details := statusCtx["details"].(map[string]interface{})
 
-				assert.Equal(t, 2, details["$multiplier"])
-				assert.Equal(t, 5, details["$offset"])
-				assert.Equal(t, 25, details["result"])
+				assert.Equal(t, int64(2), details["$multiplier"])
+				assert.Equal(t, int64(5), details["$offset"])
+				assert.Equal(t, int64(25), details["result"])
 				assert.Equal(t, "Result is 25", details["displayText"])
 			},
 		},
@@ -670,8 +670,8 @@ func TestContextPassing(t *testing.T) {
 				statusCtx := ctx["status"].(map[string]interface{})
 				assert.Equal(t, false, statusCtx["healthy"])
 				details := statusCtx["details"].(map[string]interface{})
-				assert.Equal(t, 5, details["replicas"])
-				assert.Equal(t, 3, details["readyReplicas"])
+				assert.Equal(t, int64(5), details["replicas"])
+				assert.Equal(t, int64(3), details["readyReplicas"])
 			},
 		},
 		"message-references-health-and-details": {
@@ -781,3 +781,185 @@ func TestContextPassing(t *testing.T) {
 		})
 	}
 }
+
+func TestGetStatusWithDefinitionAndHiddenLabels(t *testing.T) {
+	testCases := []struct {
+		name            string
+		templateContext map[string]interface{}
+		statusFields    string
+		wantNoErr       bool
+		description     string
+	}{
+		{
+			name: "handles definition labels without panic",
+			templateContext: map[string]interface{}{
+				"output": map[string]interface{}{
+					"metadata": map[string]interface{}{
+						"name": "test",
+					},
+				},
+			},
+			statusFields: `
+#SomeDefinition: {
+	name: string
+	type: string
+}
+
+status: #SomeDefinition & {
+	name: "test"
+	type: "healthy"
+}
+`,
+			wantNoErr:   true,
+			description: "Should handle definition labels (#SomeDefinition) without panicking",
+		},
+		{
+			name: "handles hidden labels without panic",
+			templateContext: map[string]interface{}{
+				"output": map[string]interface{}{
+					"metadata": map[string]interface{}{
+						"name": "test",
+					},
+				},
+			},
+			statusFields: `
+_hiddenField: "internal"
+
+status: {
+	name: "test"
+	internal: _hiddenField
+}
+`,
+			wantNoErr:   true,
+			description: "Should handle hidden labels (_hiddenField) without panicking",
+		},
+		{
+			name: "handles pattern labels without panic",
+			templateContext: map[string]interface{}{
+				"output": map[string]interface{}{
+					"metadata": map[string]interface{}{
+						"name": "test",
+					},
+				},
+			},
+			statusFields: `
+[string]: _
+
+status: {
+	name: "test"
+	healthy: true
+}
+`,
+			wantNoErr:   true,
+			description: "Should handle pattern labels ([string]: _) without panicking",
+		},
+		{
+			name: "handles mixed label types without panic",
+			templateContext: map[string]interface{}{
+				"output": map[string]interface{}{
+					"metadata": map[string]interface{}{
+						"name": "test",
+					},
+				},
+			},
+			statusFields: `
+#Definition: {
+	field: string
+}
+
+_hidden: "value"
+
+normalField: "visible"
+
+status: {
+	name: normalField
+	type: _hidden
+	def: #Definition & {field: "test"}
+}
+`,
+			wantNoErr:   true,
+			description: "Should handle mixed label types without panicking",
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			request := &StatusRequest{
+				Details:   tc.statusFields,
+				Parameter: map[string]interface{}{},
+			}
+
+			// This should not panic even with definition or hidden labels
+			result, err := GetStatus(tc.templateContext, request)
+
+			if tc.wantNoErr {
+				// We expect no panic and a valid result
+				assert.NotNil(t, result, tc.description)
+				// The function may return an error for invalid CUE, but it shouldn't panic
+				if err != nil {
+					t.Logf("Got expected error (non-panic): %v", err)
+				}
+			} else {
+				assert.Error(t, err, tc.description)
+			}
+		})
+	}
+}
+
+func TestGetStatusMapWithComplexSelectors(t *testing.T) {
+	// Test that getStatusMap doesn't panic with various selector types
+	testCases := []struct {
+		name            string
+		statusFields    string
+		templateContext map[string]interface{}
+		shouldNotPanic  bool
+	}{
+		{
+			name: "definition selector in context",
+			statusFields: `
+#Config: {
+	enabled: bool
+}
+
+config: #Config & {
+	enabled: true
+}
+`,
+			templateContext: map[string]interface{}{},
+			shouldNotPanic:  true,
+		},
+		{
+			name: "hidden field selector",
+			statusFields: `
+_internal: {
+	secret: "hidden"
+}
+
+public: _internal.secret
+`,
+			templateContext: map[string]interface{}{},
+			shouldNotPanic:  true,
+		},
+		{
+			name: "optional field selector",
+			statusFields: `
+optional?: string
+
+required: string | *"default"
+`,
+			templateContext: map[string]interface{}{},
+			shouldNotPanic:  true,
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			if tc.shouldNotPanic {
+				// The function should not panic
+				assert.NotPanics(t, func() {
+					_, _, _ = getStatusMap(tc.templateContext, tc.statusFields, nil)
+				}, "getStatusMap should not panic with %s", tc.name)
+			}
+		})
+	}
+}
diff --git a/pkg/cue/testdata/workloads/pattern-params.cue b/pkg/cue/testdata/workloads/pattern-params.cue
new file mode 100644
index 00000000..74a2fe69
--- /dev/null
+++ b/pkg/cue/testdata/workloads/pattern-params.cue
@@ -0,0 +1,16 @@
+// Test template with pattern parameter selectors
+parameter: {
+	// Regular string parameter
+	name: string
+
+	// Pattern parameter selector - this would cause Unquoted() to panic
+	[string]: _
+
+	// Another regular parameter
+	port: *8080 | int
+}
+
+output: {
+	apiVersion: "apps/v1"
+	kind:       "Deployment"
+}
\ No newline at end of file
diff --git a/pkg/definition/gen_sdk/testdata/apply-terraform-provider.cue b/pkg/definition/gen_sdk/testdata/apply-terraform-provider.cue
index 4404d389..37cf9991 100644
--- a/pkg/definition/gen_sdk/testdata/apply-terraform-provider.cue
+++ b/pkg/definition/gen_sdk/testdata/apply-terraform-provider.cue
@@ -83,9 +83,9 @@ template: {
 		}
 	}
 	providerBasic: {
-		accessKey: string
-		secretKey: string
-		region:    string
+		accessKey!: string
+		secretKey!: string
+		region!:    string
 	}
 	#AlibabaProvider: {
 		providerBasic
@@ -137,5 +137,5 @@ template: {
 		type:       "ucloud"
 		name:       *"ucloud-provider" | string
 	}
-	parameter: *#AlibabaProvider | #AWSProvider | #AzureProvider | #BaiduProvider | #ECProvider | #GCPProvider | #TencentProvider | #UCloudProvider
+	parameter: #AlibabaProvider | #AWSProvider | #AzureProvider | #BaiduProvider | #ECProvider | #GCPProvider | #TencentProvider | #UCloudProvider
 }
diff --git a/pkg/monitor/watcher/application_test.go b/pkg/monitor/watcher/application_test.go
new file mode 100644
index 00000000..fd86c706
--- /dev/null
+++ b/pkg/monitor/watcher/application_test.go
@@ -0,0 +1,261 @@
+/*
+Copyright 2022 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package watcher
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+
+	workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
+
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
+)
+
+func TestApplicationMetricsWatcher(t *testing.T) {
+	t.Parallel()
+
+	appRunning := &v1beta1.Application{
+		ObjectMeta: metav1.ObjectMeta{Name: "app-running"},
+		Status: common.AppStatus{
+			Phase: common.ApplicationRunning,
+		},
+	}
+	appRendering := &v1beta1.Application{
+		ObjectMeta: metav1.ObjectMeta{Name: "app-rendering"},
+		Status: common.AppStatus{
+			Phase: common.ApplicationRendering,
+		},
+	}
+	appWithWorkflow := &v1beta1.Application{
+		ObjectMeta: metav1.ObjectMeta{Name: "app-with-workflow"},
+		Status: common.AppStatus{
+			Phase: common.ApplicationRunning,
+			Workflow: &common.WorkflowStatus{
+				Steps: []workflowv1alpha1.WorkflowStepStatus{
+					{
+						StepStatus: workflowv1alpha1.StepStatus{
+							Name:  "step1",
+							Type:  "apply-component",
+							Phase: workflowv1alpha1.WorkflowStepPhaseSucceeded,
+						},
+					},
+				},
+			},
+		},
+	}
+	appWithMixedWorkflow := &v1beta1.Application{
+		ObjectMeta: metav1.ObjectMeta{Name: "app-with-mixed-workflow"},
+		Status: common.AppStatus{
+			Phase: common.ApplicationRunning,
+			Workflow: &common.WorkflowStatus{
+				Steps: []workflowv1alpha1.WorkflowStepStatus{
+					{
+						StepStatus: workflowv1alpha1.StepStatus{
+							Name:  "step1",
+							Type:  "apply-component",
+							Phase: workflowv1alpha1.WorkflowStepPhaseSucceeded,
+						},
+					},
+					{
+						StepStatus: workflowv1alpha1.StepStatus{
+							Name:  "step2",
+							Type:  "apply-component",
+							Phase: workflowv1alpha1.WorkflowStepPhaseFailed,
+						},
+					},
+					{
+						StepStatus: workflowv1alpha1.StepStatus{
+							Name:  "step3",
+							Type:  "suspend",
+							Phase: workflowv1alpha1.WorkflowStepPhaseRunning,
+						},
+					},
+				},
+			},
+		},
+	}
+
+	testCases := map[string]struct {
+		app    *v1beta1.Application
+		op     int
+		wantPC map[string]int
+		wantSC map[string]int
+		wantPD map[string]struct{}
+		wantSD map[string]struct{}
+	}{
+		"Add an application": {
+			app:    appRunning,
+			op:     1,
+			wantPC: map[string]int{"running": 1},
+			wantSC: map[string]int{},
+			wantPD: map[string]struct{}{"running": {}},
+			wantSD: map[string]struct{}{},
+		},
+		"Add an application with workflow": {
+			app:    appWithWorkflow,
+			op:     1,
+			wantPC: map[string]int{"running": 1},
+			wantSC: map[string]int{"apply-component/succeeded#": 1},
+			wantPD: map[string]struct{}{"running": {}},
+			wantSD: map[string]struct{}{"apply-component/succeeded#": {}},
+		},
+		"Delete an application": {
+			app:    appRunning,
+			op:     -1,
+			wantPC: map[string]int{"running": -1},
+			wantSC: map[string]int{},
+			wantPD: map[string]struct{}{"running": {}},
+			wantSD: map[string]struct{}{},
+		},
+		"Update an application": {
+			app:    appRendering,
+			op:     -1,
+			wantPC: map[string]int{"rendering": -1},
+			wantSC: map[string]int{},
+			wantPD: map[string]struct{}{"rendering": {}},
+			wantSD: map[string]struct{}{},
+		},
+		"Nil app status": {
+			app:    &v1beta1.Application{},
+			op:     1,
+			wantPC: map[string]int{"-": 1},
+			wantSC: map[string]int{},
+			wantPD: map[string]struct{}{"-": {}},
+			wantSD: map[string]struct{}{},
+		},
+		"Add an application with mixed workflow": {
+			app:    appWithMixedWorkflow,
+			op:     1,
+			wantPC: map[string]int{"running": 1},
+			wantSC: map[string]int{
+				"apply-component/succeeded#": 1,
+				"apply-component/failed#":    1,
+				"suspend/running#":           1,
+			},
+			wantPD: map[string]struct{}{"running": {}},
+			wantSD: map[string]struct{}{
+				"apply-component/succeeded#": {},
+				"apply-component/failed#":    {},
+				"suspend/running#":           {},
+			},
+		},
+		"Empty workflow steps": {
+			app: &v1beta1.Application{
+				ObjectMeta: metav1.ObjectMeta{Name: "app-empty-workflow"},
+				Status: common.AppStatus{
+					Phase: common.ApplicationRunning,
+					Workflow: &common.WorkflowStatus{
+						Steps: []workflowv1alpha1.WorkflowStepStatus{},
+					},
+				},
+			},
+			op:     1,
+			wantPC: map[string]int{"running": 1},
+			wantSC: map[string]int{},
+			wantPD: map[string]struct{}{"running": {}},
+			wantSD: map[string]struct{}{},
+		},
+		"Unknown phase": {
+			app: &v1beta1.Application{
+				ObjectMeta: metav1.ObjectMeta{Name: "app-unknown-phase"},
+				Status: common.AppStatus{
+					Phase: "unknown",
+				},
+			},
+			op:     1,
+			wantPC: map[string]int{"unknown": 1},
+			wantSC: map[string]int{},
+			wantPD: map[string]struct{}{"unknown": {}},
+			wantSD: map[string]struct{}{},
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			t.Parallel()
+			watcher := &applicationMetricsWatcher{
+				phaseCounter:     map[string]int{},
+				stepPhaseCounter: map[string]int{},
+				phaseDirty:       map[string]struct{}{},
+				stepPhaseDirty:   map[string]struct{}{},
+			}
+			watcher.inc(tc.app, tc.op)
+			assert.Equal(t, tc.wantPC, watcher.phaseCounter)
+			assert.Equal(t, tc.wantSC, watcher.stepPhaseCounter)
+			assert.Equal(t, tc.wantPD, watcher.phaseDirty)
+			assert.Equal(t, tc.wantSD, watcher.stepPhaseDirty)
+		})
+	}
+
+	t.Run("Idempotence", func(t *testing.T) {
+		t.Parallel()
+		watcher := &applicationMetricsWatcher{
+			phaseCounter:     map[string]int{},
+			stepPhaseCounter: map[string]int{},
+			phaseDirty:       map[string]struct{}{},
+			stepPhaseDirty:   map[string]struct{}{},
+		}
+		watcher.inc(appRunning, 1)
+		watcher.inc(appRunning, 1)
+		assert.Equal(t, map[string]int{"running": 2}, watcher.phaseCounter)
+		assert.Equal(t, map[string]struct{}{"running": {}}, watcher.phaseDirty)
+	})
+
+	t.Run("Report should clear dirty flags", func(t *testing.T) {
+		t.Parallel()
+		watcher := &applicationMetricsWatcher{
+			phaseCounter:     map[string]int{"running": 1},
+			stepPhaseCounter: map[string]int{"apply-component/succeeded#": 1},
+			phaseDirty:       map[string]struct{}{"running": {}},
+			stepPhaseDirty:   map[string]struct{}{"apply-component/succeeded#": {}},
+		}
+		watcher.report()
+		assert.Empty(t, watcher.phaseDirty)
+		assert.Empty(t, watcher.stepPhaseDirty)
+		assert.Equal(t, map[string]int{"running": 1}, watcher.phaseCounter)
+		assert.Equal(t, map[string]int{"apply-component/succeeded#": 1}, watcher.stepPhaseCounter)
+	})
+
+	t.Run("getPhase helper function", func(t *testing.T) {
+		t.Parallel()
+		watcher := &applicationMetricsWatcher{}
+		assert.Equal(t, "-", watcher.getPhase(""))
+		assert.Equal(t, "running", watcher.getPhase("running"))
+	})
+
+	t.Run("getApp helper function", func(t *testing.T) {
+		t.Parallel()
+		watcher := &applicationMetricsWatcher{}
+		inputApp := &v1beta1.Application{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      "test-app",
+				Namespace: "test-ns",
+			},
+			Status: common.AppStatus{
+				Phase: common.ApplicationRunning,
+			},
+		}
+		resultApp := watcher.getApp(inputApp)
+		assert.NotNil(t, resultApp)
+		assert.Equal(t, "test-app", resultApp.Name)
+		assert.Equal(t, "test-ns", resultApp.Namespace)
+		assert.Equal(t, common.ApplicationRunning, resultApp.Status.Phase)
+	})
+}
diff --git a/pkg/velaql/parse_test.go b/pkg/velaql/parse_test.go
index a8d446e5..3ce0e5a9 100644
--- a/pkg/velaql/parse_test.go
+++ b/pkg/velaql/parse_test.go
@@ -17,13 +17,19 @@
 package velaql
 
 import (
+	"context"
+	"fmt"
+	"os"
+	"path/filepath"
 	"testing"
 
 	"github.com/pkg/errors"
 	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
 )
 
 func TestParseVelaQL(t *testing.T) {
+	t.Parallel()
 	testcases := []struct {
 		ql    string
 		query QueryView
@@ -67,19 +73,22 @@ func TestParseVelaQL(t *testing.T) {
 		err: nil,
 	}}
 
-	for _, testcase := range testcases {
-		q, err := ParseVelaQL(testcase.ql)
-		assert.Equal(t, testcase.err != nil, err != nil)
-		if err == nil {
-			assert.Equal(t, testcase.query.View, q.View)
-			assert.Equal(t, testcase.query.Export, q.Export)
-		} else {
-			assert.Equal(t, testcase.err.Error(), err.Error())
-		}
+	for i, testcase := range testcases {
+		t.Run(fmt.Sprintf("testcase-%d", i), func(t *testing.T) {
+			q, err := ParseVelaQL(testcase.ql)
+			if testcase.err != nil {
+				assert.EqualError(t, testcase.err, err.Error())
+			} else {
+				assert.NoError(t, err)
+				assert.Equal(t, testcase.query.View, q.View)
+				assert.Equal(t, testcase.query.Export, q.Export)
+			}
+		})
 	}
 }
 
 func TestParseParameter(t *testing.T) {
+	t.Parallel()
 	testcases := []struct {
 		parameter    string
 		parameterMap map[string]interface{}
@@ -122,15 +131,114 @@ func TestParseParameter(t *testing.T) {
 		err: nil,
 	}}
 
-	for _, testcase := range testcases {
-		result, err := ParseParameter(testcase.parameter)
-		assert.Equal(t, testcase.err != nil, err != nil)
-		if err == nil {
-			for k, v := range result {
-				assert.Equal(t, testcase.parameterMap[k], v)
+	for i, testcase := range testcases {
+		t.Run(fmt.Sprintf("testcase-%d", i), func(t *testing.T) {
+			result, err := ParseParameter(testcase.parameter)
+			if testcase.err != nil {
+				assert.EqualError(t, testcase.err, err.Error())
+			} else {
+				assert.NoError(t, err)
+				for k, v := range result {
+					assert.Equal(t, testcase.parameterMap[k], v)
+				}
+			}
+		})
+	}
+}
+
+func TestParseVelaQLFromPath(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+
+	testdataDir := "testdata"
+
+	testcases := []struct {
+		name           string
+		path           string
+		expectedExport string
+		expectError    bool
+		errorContains  string
+	}{
+		{
+			name:           "Simple valid CUE file with export field",
+			path:           filepath.Join(testdataDir, "simple-valid.cue"),
+			expectedExport: "output.message",
+			expectError:    false,
+		},
+		{
+			name:           "Simple valid CUE file without export field",
+			path:           filepath.Join(testdataDir, "simple-no-export.cue"),
+			expectedExport: DefaultExportValue,
+			expectError:    false,
+		},
+		{
+			name:          "Nonexistent file path",
+			path:          filepath.Join(testdataDir, "nonexistent.cue"),
+			expectError:   true,
+			errorContains: "read view file from",
+		},
+		{
+			name:          "Empty file path",
+			path:          "",
+			expectError:   true,
+			errorContains: "read view file from",
+		},
+		{
+			name:          "Invalid CUE content",
+			path:          filepath.Join(testdataDir, "invalid-cue-content.cue"),
+			expectError:   true,
+			errorContains: "error when parsing view",
+		},
+		{
+			name:           "File with invalid export type - should fallback to default",
+			path:           filepath.Join(testdataDir, "invalid-export.cue"),
+			expectedExport: DefaultExportValue,
+			expectError:    false,
+		},
+		{
+			name:           "Empty CUE file",
+			path:           filepath.Join(testdataDir, "empty.cue"),
+			expectedExport: DefaultExportValue,
+			expectError:    false,
+		},
+		{
+			name:           "File with leading/trailing whitespace",
+			path:           filepath.Join(testdataDir, "whitespace.cue"),
+			expectedExport: "output.message",
+			expectError:    false,
+		},
+		{
+			name:          "Relative path",
+			path:          "testdata/nonexistent.cue",
+			expectError:   true,
+			errorContains: "read view file from",
+		},
+	}
+
+	for _, tc := range testcases {
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			result, err := ParseVelaQLFromPath(ctx, tc.path)
+
+			if tc.expectError {
+				assert.Error(t, err)
+				assert.Nil(t, result)
+				if tc.errorContains != "" {
+					assert.Contains(t, err.Error(), tc.errorContains)
+				}
+			} else {
+				assert.NoError(t, err)
+				assert.NotNil(t, result)
+
+				if tc.path != "" {
+					expectedContent, readErr := os.ReadFile(tc.path)
+					require.NoError(t, readErr)
+					assert.Equal(t, string(expectedContent), result.View)
+				}
+
+				assert.Equal(t, tc.expectedExport, result.Export)
+				assert.Nil(t, result.Parameter)
 			}
-		} else {
-			assert.Equal(t, testcase.err.Error(), err.Error())
-		}
+		})
 	}
 }
diff --git a/pkg/velaql/testdata/empty.cue b/pkg/velaql/testdata/empty.cue
new file mode 100644
index 00000000..e69de29b
diff --git a/pkg/velaql/testdata/invalid-cue-content.cue b/pkg/velaql/testdata/invalid-cue-content.cue
new file mode 100644
index 00000000..f3ad0c1a
--- /dev/null
+++ b/pkg/velaql/testdata/invalid-cue-content.cue
@@ -0,0 +1,4 @@
+invalid cue syntax [
+    missing: colon
+    invalid: brackets
+}
diff --git a/pkg/velaql/testdata/invalid-export.cue b/pkg/velaql/testdata/invalid-export.cue
new file mode 100644
index 00000000..4811f40a
--- /dev/null
+++ b/pkg/velaql/testdata/invalid-export.cue
@@ -0,0 +1,9 @@
+parameter: {
+    name: "test"
+}
+
+output: {
+    message: "hello " + parameter.name
+}
+
+export: 123  // Invalid export type (should be string)
diff --git a/pkg/velaql/testdata/simple-no-export.cue b/pkg/velaql/testdata/simple-no-export.cue
new file mode 100644
index 00000000..e4b80167
--- /dev/null
+++ b/pkg/velaql/testdata/simple-no-export.cue
@@ -0,0 +1,7 @@
+parameter: {
+    name: "test"
+}
+
+output: {
+    message: "hello " + parameter.name
+}
diff --git a/pkg/velaql/testdata/simple-valid.cue b/pkg/velaql/testdata/simple-valid.cue
new file mode 100644
index 00000000..5a293efe
--- /dev/null
+++ b/pkg/velaql/testdata/simple-valid.cue
@@ -0,0 +1,9 @@
+parameter: {
+    name: "test"
+}
+
+output: {
+    message: "hello " + parameter.name
+}
+
+export: "output.message"
diff --git a/pkg/velaql/testdata/whitespace.cue b/pkg/velaql/testdata/whitespace.cue
new file mode 100644
index 00000000..2e9b035a
--- /dev/null
+++ b/pkg/velaql/testdata/whitespace.cue
@@ -0,0 +1,12 @@
+
+
+parameter: {
+    name: "test"
+}
+
+output: {
+    message: "hello " + parameter.name
+}
+
+export: "output.message"  
+
diff --git a/pkg/webhook/utils/utils_test.go b/pkg/webhook/utils/utils_test.go
index 037dc7bb..32379f56 100644
--- a/pkg/webhook/utils/utils_test.go
+++ b/pkg/webhook/utils/utils_test.go
@@ -29,12 +29,132 @@ import (
 	dynamicfake "k8s.io/client-go/dynamic/fake"
 
 	"cuelang.org/go/cue/errors"
-	"github.com/crossplane/crossplane-runtime/pkg/test"
-	"github.com/google/go-cmp/cmp"
 	"github.com/stretchr/testify/assert"
+
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/types"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
+
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
+	"github.com/oam-dev/kubevela/pkg/controller/core.oam.dev/v1beta1/core"
 )
 
+func TestValidateDefinitionRevision(t *testing.T) {
+	t.Parallel()
+	scheme := runtime.NewScheme()
+	v1beta1.AddToScheme(scheme)
+
+	baseCompDef := &v1beta1.ComponentDefinition{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-def",
+			Namespace: "default",
+		},
+		Spec: v1beta1.ComponentDefinitionSpec{
+			Workload: common.WorkloadTypeDescriptor{
+				Definition: common.WorkloadGVK{
+					APIVersion: "apps/v1",
+					Kind:       "Deployment",
+				},
+			},
+			Schematic: &common.Schematic{
+				CUE: &common.CUE{
+					Template: `
+output: {
+	apiVersion: "apps/v1"
+	kind: "Deployment"
+	metadata: name: context.name
+}`,
+				},
+			},
+		},
+	}
+
+	expectedDefRev, _, err := core.GatherRevisionInfo(baseCompDef)
+	assert.NoError(t, err, "Setup: failed to gather revision info")
+	expectedDefRev.Name = "test-def-v1"
+	expectedDefRev.Namespace = "default"
+
+	mismatchedHashDefRev := expectedDefRev.DeepCopy()
+	mismatchedHashDefRev.Spec.RevisionHash = "different-hash"
+
+	mismatchedSpecDefRev := expectedDefRev.DeepCopy()
+	mismatchedSpecDefRev.Spec.ComponentDefinition.Spec.Workload.Definition.Kind = "StatefulSet"
+
+	// tweakedCompDef := baseCompDef.DeepCopy()
+	// tweakedCompDef.Spec.Schematic.CUE.Template = `
+	// output: {
+	// 	apiVersion: "apps/v1"
+	// 	kind: "Deployment"
+	// 	metadata: name: context.name
+	// 	// a tweak
+	// }`
+	testCases := map[string]struct {
+		def                 runtime.Object
+		defRevName          types.NamespacedName
+		existingObjs        []runtime.Object
+		expectErr           bool
+		expectedErrContains string
+	}{
+		"Success with matching definition revision": {
+			def:          baseCompDef,
+			defRevName:   types.NamespacedName{Name: "test-def-v1", Namespace: "default"},
+			existingObjs: []runtime.Object{expectedDefRev},
+			expectErr:    false,
+		},
+		"Success when definition revision does not exist": {
+			def:          baseCompDef,
+			defRevName:   types.NamespacedName{Name: "test-def-v1", Namespace: "default"},
+			existingObjs: []runtime.Object{},
+			expectErr:    false,
+		},
+		"Failure with revision hash mismatch": {
+			def:                 baseCompDef,
+			defRevName:          types.NamespacedName{Name: "test-def-v1", Namespace: "default"},
+			existingObjs:        []runtime.Object{mismatchedHashDefRev},
+			expectErr:           true,
+			expectedErrContains: "the definition's spec is different with existing definitionRevision's spec",
+		},
+		"Failure with spec mismatch (DeepEqual)": {
+			def:                 baseCompDef,
+			defRevName:          types.NamespacedName{Name: "test-def-v1", Namespace: "default"},
+			existingObjs:        []runtime.Object{mismatchedSpecDefRev},
+			expectErr:           true,
+			expectedErrContains: "the definition's spec is different with existing definitionRevision's spec",
+		},
+		"Failure with invalid definition revision name": {
+			def:                 baseCompDef,
+			defRevName:          types.NamespacedName{Name: "invalid!name", Namespace: "default"},
+			existingObjs:        []runtime.Object{},
+			expectErr:           true,
+			expectedErrContains: "invalid definitionRevision name",
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			t.Parallel()
+			cli := fake.NewClientBuilder().
+				WithScheme(scheme).
+				WithRuntimeObjects(tc.existingObjs...).
+				Build()
+
+			err := ValidateDefinitionRevision(context.Background(), cli, tc.def, tc.defRevName)
+
+			if tc.expectErr {
+				assert.Error(t, err)
+				if tc.expectedErrContains != "" {
+					assert.Contains(t, err.Error(), tc.expectedErrContains)
+				}
+			} else {
+				assert.NoError(t, err)
+			}
+		})
+	}
+}
+
 func TestValidateCueTemplate(t *testing.T) {
+	t.Parallel()
 	cases := map[string]struct {
 		cueTemplate string
 		want        error
@@ -66,19 +186,31 @@ func TestValidateCueTemplate(t *testing.T) {
 				}`,
 			want: errors.New("output.hello: reference \"world\" not found"),
 		},
+		"emptyCueTemp": {
+			cueTemplate: "",
+			want:        nil,
+		},
+		"malformedCueTemp": {
+			cueTemplate: "output: { metadata: { name: context.name, label: context.label, annotation: \"default\" }, hello: world ",
+			want:        errors.New("expected '}', found 'EOF'"),
+		},
 	}
 
 	for caseName, cs := range cases {
 		t.Run(caseName, func(t *testing.T) {
+			t.Parallel()
 			err := ValidateCueTemplate(cs.cueTemplate)
-			if diff := cmp.Diff(cs.want, err, test.EquateErrors()); diff != "" {
-				t.Errorf("\n%s\nValidateCueTemplate: -want , +got \n%s\n", cs.want, diff)
+			if cs.want != nil {
+				assert.EqualError(t, cs.want, err.Error())
+			} else {
+				assert.NoError(t, err)
 			}
 		})
 	}
 }
 
 func TestValidateCuexTemplate(t *testing.T) {
+	t.Parallel()
 	cases := map[string]struct {
 		cueTemplate string
 		want        error
@@ -164,15 +296,19 @@ func TestValidateCuexTemplate(t *testing.T) {
 
 	for caseName, cs := range cases {
 		t.Run(caseName, func(t *testing.T) {
+			t.Parallel()
 			err := ValidateCuexTemplate(context.Background(), cs.cueTemplate)
-			if diff := cmp.Diff(cs.want, err, test.EquateErrors()); diff != "" {
-				t.Errorf("\n%s\nValidateCueTemplate: -want , +got \n%s\n", cs.want, diff)
+			if cs.want != nil {
+				assert.Equal(t, cs.want.Error(), err.Error())
+			} else {
+				assert.NoError(t, err)
 			}
 		})
 	}
 }
 
 func TestValidateSemanticVersion(t *testing.T) {
+	t.Parallel()
 	cases := map[string]struct {
 		version string
 		want    error
@@ -192,18 +328,20 @@ func TestValidateSemanticVersion(t *testing.T) {
 	}
 	for caseName, cs := range cases {
 		t.Run(caseName, func(t *testing.T) {
+			t.Parallel()
 			err := ValidateSemanticVersion(cs.version)
 			if cs.want != nil {
-				assert.Equal(t, err.Error(), cs.want.Error())
+				assert.Error(t, err)
+				assert.EqualError(t, cs.want, err.Error())
 			} else {
-				assert.Equal(t, err, cs.want)
+				assert.NoError(t, err)
 			}
-
 		})
 	}
 }
 
 func TestValidateMultipleDefVersionsNotPresent(t *testing.T) {
+	t.Parallel()
 	cases := map[string]struct {
 		version      string
 		revisionName string
@@ -227,11 +365,13 @@ func TestValidateMultipleDefVersionsNotPresent(t *testing.T) {
 	}
 	for caseName, cs := range cases {
 		t.Run(caseName, func(t *testing.T) {
+			t.Parallel()
 			err := ValidateMultipleDefVersionsNotPresent(cs.version, cs.revisionName, "ComponentDefinition")
 			if cs.want != nil {
-				assert.Equal(t, err.Error(), cs.want.Error())
+				assert.Error(t, err)
+				assert.EqualError(t, cs.want, err.Error())
 			} else {
-				assert.Equal(t, err, cs.want)
+				assert.NoError(t, err)
 			}
 
 		})
diff --git a/pkg/workflow/providers/oam/apply_test.go b/pkg/workflow/providers/oam/apply_test.go
index 2ea5aa2d..2fded91d 100644
--- a/pkg/workflow/providers/oam/apply_test.go
+++ b/pkg/workflow/providers/oam/apply_test.go
@@ -48,6 +48,7 @@ func setupClient(ctx context.Context, t *testing.T) client.Client {
 }
 
 func TestParser(t *testing.T) {
+	t.Parallel()
 	r := require.New(t)
 	ctx := context.Background()
 	act := &mock.Action{}
@@ -106,7 +107,67 @@ func TestParser(t *testing.T) {
 	r.Equal(act.Phase, "Wait")
 }
 
+func TestRenderComponent(t *testing.T) {
+	t.Parallel()
+	r := require.New(t)
+	ctx := context.Background()
+	cuectx := cuecontext.New()
+	cli := setupClient(ctx, t)
+
+	v := cuectx.CompileString(`$params: {
+	value: {
+		name: "test-render",
+		type: "webservice",
+	}
+}`)
+	r.NoError(v.Err())
+
+	mockComponentRender := func(ctx context.Context, comp common.ApplicationComponent, patcher *cue.Value, clusterName string, overrideNamespace string) (*unstructured.Unstructured, []*unstructured.Unstructured, error) {
+		r.Equal("test-render", comp.Name)
+		workload := &unstructured.Unstructured{
+			Object: map[string]interface{}{
+				"apiVersion": "apps/v1",
+				"kind":       "Deployment",
+				"metadata": map[string]interface{}{
+					"name": "test-workload",
+				},
+			},
+		}
+		trait := &unstructured.Unstructured{
+			Object: map[string]interface{}{
+				"apiVersion": "v1",
+				"kind":       "Service",
+				"metadata": map[string]interface{}{
+					"name": "test-trait",
+					"labels": map[string]interface{}{
+						"trait.oam.dev/resource": "mytrait",
+					},
+				},
+			},
+		}
+		return workload, []*unstructured.Unstructured{trait}, nil
+	}
+
+	res, err := RenderComponent(ctx, &oamprovidertypes.Params[cue.Value]{
+		Params: v,
+		RuntimeParams: oamprovidertypes.RuntimeParams{
+			KubeClient:      cli,
+			ComponentRender: mockComponentRender,
+		},
+	})
+	r.NoError(err)
+
+	output, err := res.LookupPath(cue.ParsePath("$returns.output.metadata.name")).String()
+	r.NoError(err)
+	r.Equal("test-workload", output)
+
+	outputs, err := res.LookupPath(cue.ParsePath("$returns.outputs.mytrait.metadata.name")).String()
+	r.NoError(err)
+	r.Equal("test-workload", outputs)
+}
+
 func TestLoadComponent(t *testing.T) {
+	t.Parallel()
 	r := require.New(t)
 	ctx := context.Background()
 	act := &mock.Action{}
@@ -171,6 +232,7 @@ func TestLoadComponent(t *testing.T) {
 }
 
 func TestLoadComponentInOrder(t *testing.T) {
+	t.Parallel()
 	r := require.New(t)
 	ctx := context.Background()
 	act := &mock.Action{}
diff --git a/pkg/workflow/providers/query/utils_test.go b/pkg/workflow/providers/query/utils_test.go
index 31708704..240517c3 100644
--- a/pkg/workflow/providers/query/utils_test.go
+++ b/pkg/workflow/providers/query/utils_test.go
@@ -15,3 +15,317 @@
 */
 
 package query
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+
+	"github.com/oam-dev/kubevela/pkg/oam"
+	querytypes "github.com/oam-dev/kubevela/pkg/utils/types"
+)
+
+func TestBuildResourceArray(t *testing.T) {
+	t.Parallel()
+	// Define common objects used across tests
+	pod1 := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "v1",
+			"kind":       "Pod",
+			"metadata": map[string]interface{}{
+				"name": "pod1",
+			},
+		},
+	}
+	pod2 := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "v1",
+			"kind":       "Pod",
+			"metadata": map[string]interface{}{
+				"name": "pod2",
+				"annotations": map[string]interface{}{
+					oam.AnnotationPublishVersion: "v2.0.0-pod",
+					oam.AnnotationDeployVersion:  "rev2-pod",
+				},
+			},
+		},
+	}
+	deployment := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "apps/v1",
+			"kind":       "Deployment",
+			"metadata": map[string]interface{}{
+				"name": "my-app",
+			},
+		},
+	}
+
+	// Define common tree nodes
+	parentWorkloadNode := &querytypes.ResourceTreeNode{
+		APIVersion: "apps/v1",
+		Kind:       "Deployment",
+		Name:       "my-app",
+		Namespace:  "default",
+		Object:     deployment,
+	}
+
+	pod1Node := &querytypes.ResourceTreeNode{
+		APIVersion: "v1",
+		Kind:       "Pod",
+		Name:       "pod1",
+		Namespace:  "default",
+		Object:     pod1,
+	}
+
+	pod2Node := &querytypes.ResourceTreeNode{
+		APIVersion: "v1",
+		Kind:       "Pod",
+		Name:       "pod2",
+		Namespace:  "default",
+		Object:     pod2,
+	}
+
+	replicaSetNode := &querytypes.ResourceTreeNode{
+		APIVersion: "apps/v1",
+		Kind:       "ReplicaSet",
+		Name:       "my-app-rs",
+		Namespace:  "default",
+		LeafNodes:  []*querytypes.ResourceTreeNode{pod1Node, pod2Node},
+	}
+
+	// Define test cases
+	testCases := map[string]struct {
+		res        querytypes.AppliedResource
+		parent     *querytypes.ResourceTreeNode
+		node       *querytypes.ResourceTreeNode
+		kind       string
+		apiVersion string
+		expected   []querytypes.ResourceItem
+	}{
+		"simple case with one matching pod": {
+			res: querytypes.AppliedResource{
+				Cluster:        "local",
+				Component:      "my-comp",
+				PublishVersion: "v1.0.0",
+				DeployVersion:  "rev1",
+			},
+			parent:     parentWorkloadNode,
+			node:       pod1Node,
+			kind:       "Pod",
+			apiVersion: "v1",
+			expected: []querytypes.ResourceItem{
+				{
+					Cluster:   "local",
+					Component: "my-comp",
+					Workload: querytypes.Workload{
+						APIVersion: "apps/v1",
+						Kind:       "Deployment",
+						Name:       "my-app",
+						Namespace:  "default",
+					},
+					Object:         pod1,
+					PublishVersion: "v1.0.0",
+					DeployVersion:  "rev1",
+				},
+			},
+		},
+		"nested case with multiple matching pods": {
+			res: querytypes.AppliedResource{
+				Cluster:        "remote",
+				Component:      "my-comp-2",
+				PublishVersion: "v2.0.0",
+				DeployVersion:  "rev2",
+			},
+			parent:     parentWorkloadNode,
+			node:       replicaSetNode,
+			kind:       "Pod",
+			apiVersion: "v1",
+			expected: []querytypes.ResourceItem{
+				{
+					Cluster:   "remote",
+					Component: "my-comp-2",
+					Workload: querytypes.Workload{
+						APIVersion: "apps/v1",
+						Kind:       "ReplicaSet",
+						Name:       "my-app-rs",
+						Namespace:  "default",
+					},
+					Object:         pod1,
+					PublishVersion: "v2.0.0",
+					DeployVersion:  "rev2",
+				},
+				{
+					Cluster:   "remote",
+					Component: "my-comp-2",
+					Workload: querytypes.Workload{
+						APIVersion: "apps/v1",
+						Kind:       "ReplicaSet",
+						Name:       "my-app-rs",
+						Namespace:  "default",
+					},
+					Object:         pod2,
+					PublishVersion: "v2.0.0-pod", // From annotation
+					DeployVersion:  "rev2-pod",   // From annotation
+				},
+			},
+		},
+		"no matching nodes": {
+			res:        querytypes.AppliedResource{},
+			parent:     parentWorkloadNode,
+			node:       pod1Node,
+			kind:       "Service",
+			apiVersion: "v1",
+			expected:   nil,
+		},
+		"empty node": {
+			res:        querytypes.AppliedResource{},
+			parent:     parentWorkloadNode,
+			node:       &querytypes.ResourceTreeNode{},
+			kind:       "Pod",
+			apiVersion: "v1",
+			expected:   nil,
+		},
+		"complex tree with mixed resources": {
+			res: querytypes.AppliedResource{
+				Cluster:        "local",
+				Component:      "my-comp",
+				PublishVersion: "v1.0.0",
+				DeployVersion:  "rev1",
+			},
+			parent: parentWorkloadNode,
+			node: &querytypes.ResourceTreeNode{
+				APIVersion: "apps/v1",
+				Kind:       "ReplicaSet",
+				Name:       "my-app-rs",
+				Namespace:  "default",
+				LeafNodes: []*querytypes.ResourceTreeNode{
+					pod1Node,
+					{
+						APIVersion: "v1",
+						Kind:       "Service",
+						Name:       "my-service",
+					},
+					pod2Node,
+				},
+			},
+			kind:       "Pod",
+			apiVersion: "v1",
+			expected: []querytypes.ResourceItem{
+				{
+					Cluster:   "local",
+					Component: "my-comp",
+					Workload: querytypes.Workload{
+						APIVersion: "apps/v1",
+						Kind:       "ReplicaSet",
+						Name:       "my-app-rs",
+						Namespace:  "default",
+					},
+					Object:         pod1,
+					PublishVersion: "v1.0.0",
+					DeployVersion:  "rev1",
+				},
+				{
+					Cluster:   "local",
+					Component: "my-comp",
+					Workload: querytypes.Workload{
+						APIVersion: "apps/v1",
+						Kind:       "ReplicaSet",
+						Name:       "my-app-rs",
+						Namespace:  "default",
+					},
+					Object:         pod2,
+					PublishVersion: "v2.0.0-pod",
+					DeployVersion:  "rev2-pod",
+				},
+			},
+		},
+		"case-insensitive matching": {
+			res: querytypes.AppliedResource{
+				Cluster:        "local",
+				Component:      "my-comp",
+				PublishVersion: "v1.0.0",
+				DeployVersion:  "rev1",
+			},
+			parent:     parentWorkloadNode,
+			node:       pod1Node,
+			kind:       "pod",
+			apiVersion: "V1",
+			expected:   nil,
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			t.Parallel()
+			result := buildResourceArray(tc.res, tc.parent, tc.node, tc.kind, tc.apiVersion)
+			assert.ElementsMatch(t, tc.expected, result, "The returned resource items should match the expected ones")
+		})
+	}
+}
+
+func TestBuildResourceItem(t *testing.T) {
+	t.Parallel()
+	pod := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "v1",
+			"kind":       "Pod",
+			"metadata": map[string]interface{}{
+				"name": "test-pod",
+			},
+		},
+	}
+	podWithAnnotations := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "v1",
+			"kind":       "Pod",
+			"metadata": map[string]interface{}{
+				"name": "test-pod-annotated",
+				"annotations": map[string]interface{}{
+					oam.AnnotationPublishVersion: "v2.0.0-annotated",
+					oam.AnnotationDeployVersion:  "rev2-annotated",
+				},
+			},
+		},
+	}
+	res := querytypes.AppliedResource{
+		Cluster:        "test-cluster",
+		Component:      "test-comp",
+		PublishVersion: "v1.0.0-res",
+		DeployVersion:  "rev1-res",
+	}
+	workload := querytypes.Workload{
+		APIVersion: "apps/v1",
+		Kind:       "Deployment",
+		Name:       "test-workload",
+		Namespace:  "test-ns",
+	}
+
+	t.Run("without annotations", func(t *testing.T) {
+		t.Parallel()
+		item := buildResourceItem(res, workload, pod)
+		assert.Equal(t, "test-cluster", item.Cluster)
+		assert.Equal(t, "test-comp", item.Component)
+		assert.Equal(t, workload, item.Workload)
+		assert.Equal(t, pod, item.Object)
+		assert.Equal(t, "v1.0.0-res", item.PublishVersion)
+		assert.Equal(t, "rev1-res", item.DeployVersion)
+	})
+
+	t.Run("with annotations", func(t *testing.T) {
+		t.Parallel()
+		item := buildResourceItem(res, workload, podWithAnnotations)
+		assert.Equal(t, "test-cluster", item.Cluster)
+		assert.Equal(t, "test-comp", item.Component)
+		assert.Equal(t, workload, item.Workload)
+		assert.Equal(t, podWithAnnotations, item.Object)
+		assert.Equal(t, "v2.0.0-annotated", item.PublishVersion)
+		assert.Equal(t, "rev2-annotated", item.DeployVersion)
+	})
+
+	t.Run("annotation override", func(t *testing.T) {
+		item := buildResourceItem(res, workload, podWithAnnotations)
+		assert.Equal(t, "v2.0.0-annotated", item.PublishVersion)
+		assert.Equal(t, "rev2-annotated", item.DeployVersion)
+	})
+}
diff --git a/references/appfile/addon_suit_test.go b/references/appfile/addon_suit_test.go
deleted file mode 100644
index 02ae8086..00000000
--- a/references/appfile/addon_suit_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
-Copyright 2021 The KubeVela Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package appfile
-
-import (
-	"context"
-	"os"
-	"path/filepath"
-	"testing"
-	"time"
-
-	. "github.com/onsi/ginkgo/v2"
-	. "github.com/onsi/gomega"
-	corev1 "k8s.io/api/core/v1"
-	crdv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
-	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-	"k8s.io/apimachinery/pkg/runtime"
-	clientgoscheme "k8s.io/client-go/kubernetes/scheme"
-	"k8s.io/client-go/rest"
-	"sigs.k8s.io/controller-runtime/pkg/client"
-	"sigs.k8s.io/controller-runtime/pkg/envtest"
-	logf "sigs.k8s.io/controller-runtime/pkg/log"
-	"sigs.k8s.io/controller-runtime/pkg/log/zap"
-	"sigs.k8s.io/yaml"
-
-	coreoam "github.com/oam-dev/kubevela/apis/core.oam.dev"
-	corev1beta1 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
-	"github.com/oam-dev/kubevela/pkg/oam/util"
-	"github.com/oam-dev/kubevela/pkg/utils/system"
-	// +kubebuilder:scaffold:imports
-)
-
-var cfg *rest.Config
-var scheme *runtime.Scheme
-var k8sClient client.Client
-var testEnv *envtest.Environment
-var definitionDir string
-var wd corev1beta1.WorkloadDefinition
-var addonNamespace = "test-addon"
-
-func TestAppFile(t *testing.T) {
-	RegisterFailHandler(Fail)
-	RunSpecs(t, "Cli Suite")
-}
-
-var _ = BeforeSuite(func() {
-	logf.SetLogger(zap.New(zap.UseDevMode(true), zap.WriteTo(GinkgoWriter)))
-	ctx := context.Background()
-	By("bootstrapping test environment")
-	useExistCluster := false
-	testEnv = &envtest.Environment{
-		ControlPlaneStartTimeout: time.Minute,
-		ControlPlaneStopTimeout:  time.Minute,
-		CRDDirectoryPaths:        []string{filepath.Join("..", "..", "charts", "vela-core", "crds")},
-		UseExistingCluster:       &useExistCluster,
-	}
-
-	var err error
-	cfg, err = testEnv.Start()
-	Expect(err).ToNot(HaveOccurred())
-	Expect(cfg).ToNot(BeNil())
-	scheme = runtime.NewScheme()
-	Expect(coreoam.AddToScheme(scheme)).NotTo(HaveOccurred())
-	Expect(clientgoscheme.AddToScheme(scheme)).NotTo(HaveOccurred())
-	Expect(crdv1.AddToScheme(scheme)).NotTo(HaveOccurred())
-	k8sClient, err = client.New(cfg, client.Options{Scheme: scheme})
-	Expect(err).ToNot(HaveOccurred())
-	Expect(k8sClient).ToNot(BeNil())
-
-	definitionDir, err = system.GetCapabilityDir()
-	Expect(err).Should(BeNil())
-	Expect(os.MkdirAll(definitionDir, 0755)).Should(BeNil())
-
-	Expect(k8sClient.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: addonNamespace}})).Should(SatisfyAny(BeNil(), &util.AlreadyExistMatcher{}))
-
-	workloadData, err := os.ReadFile("testdata/workloadDef.yaml")
-	Expect(err).Should(BeNil())
-
-	Expect(yaml.Unmarshal(workloadData, &wd)).Should(BeNil())
-
-	wd.Namespace = addonNamespace
-	logf.Log.Info("Creating workload definition", "data", wd)
-	Expect(k8sClient.Create(ctx, &wd)).Should(SatisfyAny(BeNil(), &util.AlreadyExistMatcher{}))
-
-	def, err := os.ReadFile("testdata/terraform-aliyun-oss-workloadDefinition.yaml")
-	Expect(err).Should(BeNil())
-	var terraformDefinition corev1beta1.WorkloadDefinition
-	Expect(yaml.Unmarshal(def, &terraformDefinition)).Should(BeNil())
-	terraformDefinition.Namespace = addonNamespace
-	logf.Log.Info("Creating workload definition", "data", terraformDefinition)
-	Expect(k8sClient.Create(ctx, &terraformDefinition)).Should(SatisfyAny(BeNil(), &util.AlreadyExistMatcher{}))
-})
-
-var _ = AfterSuite(func() {
-	By("tearing down the test environment")
-	_ = k8sClient.Delete(context.Background(), &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: addonNamespace}})
-	_ = k8sClient.Delete(context.Background(), &wd)
-	err := testEnv.Stop()
-	Expect(err).ToNot(HaveOccurred())
-})
diff --git a/references/appfile/addon_test.go b/references/appfile/addon_test.go
index 93939c8f..3bd59d68 100644
--- a/references/appfile/addon_test.go
+++ b/references/appfile/addon_test.go
@@ -19,9 +19,9 @@ package appfile
 import (
 	"fmt"
 	"os"
+	"testing"
 
-	. "github.com/onsi/ginkgo/v2"
-	. "github.com/onsi/gomega"
+	"github.com/stretchr/testify/assert"
 	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 	"k8s.io/apimachinery/pkg/runtime"
 
@@ -31,7 +31,7 @@ import (
 	"github.com/oam-dev/kubevela/pkg/utils/util"
 )
 
-var _ = It("Test ApplyTerraform", func() {
+func TestApplyTerraform(t *testing.T) {
 	app := &v1beta1.Application{
 		ObjectMeta: v1.ObjectMeta{Name: "test-terraform-app"},
 		Spec: v1beta1.ApplicationSpec{Components: []commontype.ApplicationComponent{{
@@ -46,27 +46,29 @@ var _ = It("Test ApplyTerraform", func() {
 		Schema: scheme,
 	}
 	err := arg.SetConfig(cfg)
-	Expect(err).Should(BeNil())
+	assert.NoError(t, err)
 	_, err = ApplyTerraform(app, k8sClient, ioStream, addonNamespace, arg)
-	Expect(err).Should(BeNil())
-})
+	assert.NoError(t, err)
+}
 
-var _ = Describe("Test generateSecretFromTerraformOutput", func() {
+func TestGenerateSecretFromTerraformOutput(t *testing.T) {
 	var name = "test-addon-secret"
-	It("namespace doesn't exist", func() {
+
+	t.Run("namespace doesn't exist", func(t *testing.T) {
 		badNamespace := "a-not-existed-namespace"
-		err := generateSecretFromTerraformOutput(k8sClient, nil, name, badNamespace)
-		Expect(err).Should(Equal(fmt.Errorf("namespace %s doesn't exist", badNamespace)))
+		err := generateSecretFromTerraformOutput(k8sClient, "", name, badNamespace)
+		assert.EqualError(t, err, fmt.Sprintf("namespace %s doesn't exist", badNamespace))
 	})
-	It("valid output list", func() {
-		outputList := []string{"name=aaa", "age=1"}
-		err := generateSecretFromTerraformOutput(k8sClient, outputList, name, addonNamespace)
-		Expect(err).Should(BeNil())
+
+	t.Run("valid output list", func(t *testing.T) {
+		rawOutput := "name=aaa\nage=1"
+		err := generateSecretFromTerraformOutput(k8sClient, rawOutput, name, addonNamespace)
+		assert.NoError(t, err)
 	})
 
-	It("invalid output list", func() {
-		outputList := []string{"name"}
-		err := generateSecretFromTerraformOutput(k8sClient, outputList, name, addonNamespace)
-		Expect(err).Should(Equal(fmt.Errorf("terraform output isn't in the right format")))
+	t.Run("invalid output list", func(t *testing.T) {
+		rawOutput := "name"
+		err := generateSecretFromTerraformOutput(k8sClient, rawOutput, name, addonNamespace)
+		assert.EqualError(t, err, fmt.Sprintf("terraform output isn't in the right format: %q", rawOutput))
 	})
-})
+}
diff --git a/references/appfile/api/appfile_test.go b/references/appfile/api/appfile_test.go
index 074b874e..fad50b01 100644
--- a/references/appfile/api/appfile_test.go
+++ b/references/appfile/api/appfile_test.go
@@ -34,6 +34,58 @@ import (
 	"github.com/oam-dev/kubevela/references/appfile/template"
 )
 
+func TestNewAppFile(t *testing.T) {
+	appFile := NewAppFile()
+	assert.NotNil(t, appFile)
+	assert.NotNil(t, appFile.Services)
+	assert.NotNil(t, appFile.Secrets)
+	assert.Empty(t, appFile.Name)
+}
+
+func TestJSONToYaml(t *testing.T) {
+	t.Run("valid json", func(t *testing.T) {
+		jsonData := `{"name":"test-app","services":{"my-svc":{"image":"nginx"}}}`
+		appFile := NewAppFile()
+		_, err := JSONToYaml([]byte(jsonData), appFile)
+		assert.NoError(t, err)
+		assert.Equal(t, "test-app", appFile.Name)
+		assert.Contains(t, appFile.Services, "my-svc")
+		assert.Equal(t, "nginx", appFile.Services["my-svc"]["image"])
+	})
+
+	t.Run("invalid json", func(t *testing.T) {
+		jsonData := `{"name":"test-app"`
+		appFile := NewAppFile()
+		_, err := JSONToYaml([]byte(jsonData), appFile)
+		assert.Error(t, err)
+	})
+}
+
+func TestLoadFromBytes(t *testing.T) {
+	t.Run("valid yaml", func(t *testing.T) {
+		yamlData := `
+name: test-yaml-app
+services:
+  main:
+    image: httpd
+`
+		appFile, err := LoadFromBytes([]byte(yamlData))
+		assert.NoError(t, err)
+		assert.Equal(t, "test-yaml-app", appFile.Name)
+		assert.Len(t, appFile.Services, 1)
+		assert.Equal(t, "httpd", appFile.Services["main"]["image"])
+	})
+
+	t.Run("valid json", func(t *testing.T) {
+		jsonData := `{"name":"test-json-app","services":{"sidecar":{"image":"redis"}}}`
+		appFile, err := LoadFromBytes([]byte(jsonData))
+		assert.NoError(t, err)
+		assert.Equal(t, "test-json-app", appFile.Name)
+		assert.Len(t, appFile.Services, 1)
+		assert.Equal(t, "redis", appFile.Services["sidecar"]["image"])
+	})
+}
+
 func TestBuildOAMApplication2(t *testing.T) {
 	expectNs := "test-ns"
 
diff --git a/references/appfile/api/service_test.go b/references/appfile/api/service_test.go
index aa0289ff..8bf59fbf 100644
--- a/references/appfile/api/service_test.go
+++ b/references/appfile/api/service_test.go
@@ -36,3 +36,85 @@ func TestGetType(t *testing.T) {
 	got = svc2.GetType()
 	assert.Equal(t, workload2, got)
 }
+
+func TestGetUserConfigName(t *testing.T) {
+	t.Run("config name exists", func(t *testing.T) {
+		svc := Service{"config": "my-config"}
+		assert.Equal(t, "my-config", svc.GetUserConfigName())
+	})
+
+	t.Run("config name does not exist", func(t *testing.T) {
+		svc := Service{"image": "nginx"}
+		assert.Equal(t, "", svc.GetUserConfigName())
+	})
+}
+
+func TestGetApplicationConfig(t *testing.T) {
+	svc := Service{
+		"image":  "nginx",
+		"port":   80,
+		"type":   "webservice",
+		"build":  "./",
+		"config": "my-config",
+	}
+
+	config := svc.GetApplicationConfig()
+
+	assert.Contains(t, config, "image")
+	assert.Contains(t, config, "port")
+	assert.NotContains(t, config, "type")
+	assert.NotContains(t, config, "build")
+	assert.NotContains(t, config, "config")
+	assert.Len(t, config, 2)
+}
+
+func TestToStringSlice(t *testing.T) {
+	testCases := []struct {
+		name     string
+		input    interface{}
+		expected []string
+	}{
+		{
+			name:     "string",
+			input:    "one",
+			expected: []string{"one"},
+		},
+		{
+			name:     "[]string",
+			input:    []string{"one", "two"},
+			expected: []string{"one", "two"},
+		},
+		{
+			name:     "[]interface{} of strings",
+			input:    []interface{}{"one", "two"},
+			expected: []string{"one", "two"},
+		},
+		{
+			name:     "[]interface{} of mixed types",
+			input:    []interface{}{"one", 2, "three"},
+			expected: []string{"one", "three"},
+		},
+		{
+			name:     "nil input",
+			input:    nil,
+			expected: nil,
+		},
+		{
+			name:     "empty []string",
+			input:    []string{},
+			expected: []string{},
+		},
+		{
+			name:     "other type (int)",
+			input:    123,
+			expected: nil,
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			result := toStringSlice(tc.input)
+			assert.Equal(t, tc.expected, result)
+		})
+	}
+}
diff --git a/references/appfile/app_test.go b/references/appfile/app_test.go
index fb35d9f9..9289ae77 100644
--- a/references/appfile/app_test.go
+++ b/references/appfile/app_test.go
@@ -22,14 +22,18 @@ import (
 	"testing"
 
 	"github.com/stretchr/testify/assert"
+	"k8s.io/apimachinery/pkg/runtime"
 	"sigs.k8s.io/yaml"
 
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
 	"github.com/oam-dev/kubevela/apis/types"
+	"github.com/oam-dev/kubevela/references/appfile/api"
 	"github.com/oam-dev/kubevela/references/appfile/template"
 )
 
-func TestApplication(t *testing.T) {
-	yamlNormal := `name: myapp
+const (
+	yamlNormal = `name: myapp
 services:
   frontend:
     image: inanimate/echo-server
@@ -45,55 +49,207 @@ services:
     type: cloneset
     image: "back:v1"
 `
-	yamlNoService := `name: myapp`
-	yamlNoName := `services:
+	yamlNoService = `name: myapp`
+	yamlNoName    = `services:
   frontend:
     image: inanimate/echo-server
     env:
       PORT: 8080`
-	yamlTraitNotMap := `name: myapp
+	yamlTraitNotMap = `name: myapp
 services:
   frontend:
     image: inanimate/echo-server
     env:
       PORT: 8080
     autoscaling: 10`
+)
+
+func TestNewApplication(t *testing.T) {
+	tm := template.NewFakeTemplateManager()
+	app := NewApplication(nil, tm)
+	assert.NotNil(t, app)
+	assert.Equal(t, tm, app.Tm)
+	assert.NotNil(t, app.AppFile)
+
+	appfile := api.NewAppFile()
+	appfile.Name = "test-app"
+	app = NewApplication(appfile, tm)
+	assert.NotNil(t, app)
+	assert.Equal(t, "test-app", app.Name)
+}
 
-	cases := map[string]struct {
-		raw             string
-		InValid         bool
-		InvalidReason   error
-		ExpName         string
-		ExpComponents   []string
-		WantWorkload    string
-		ExpWorkload     map[string]interface{}
-		ExpWorkloadType string
-		ExpTraits       map[string]map[string]interface{}
+func TestValidate(t *testing.T) {
+	testCases := map[string]struct {
+		raw     string
+		expErr  error
+		addFake bool
 	}{
-		"normal case backend": {
-			raw:           yamlNormal,
-			ExpName:       "myapp",
-			ExpComponents: []string{"backend", "frontend"},
-			WantWorkload:  "backend",
-			ExpWorkload: map[string]interface{}{
-				"image": "back:v1",
+		"normal": {
+			raw:    yamlNormal,
+			expErr: nil,
+		},
+		"no service": {
+			raw:    yamlNoService,
+			expErr: errors.New("at least one service is required"),
+		},
+		"no name": {
+			raw:    yamlNoName,
+			expErr: errors.New("name is required"),
+		},
+		"trait not map": {
+			raw:     yamlTraitNotMap,
+			expErr:  fmt.Errorf("trait autoscaling in 'frontend' must be map"),
+			addFake: true,
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			tm := template.NewFakeTemplateManager()
+			if tc.addFake {
+				tm.Templates["autoscaling"] = &template.Template{
+					Captype: types.TypeTrait,
+				}
+			}
+			app := NewApplication(nil, tm)
+			err := yaml.Unmarshal([]byte(tc.raw), &app)
+			assert.NoError(t, err)
+			err = Validate(app)
+			assert.Equal(t, tc.expErr, err)
+		})
+	}
+}
+
+func TestGetComponents(t *testing.T) {
+	app := &v1beta1.Application{
+		Spec: v1beta1.ApplicationSpec{
+			Components: []common.ApplicationComponent{
+				{Name: "c"},
+				{Name: "a"},
+				{Name: "b"},
 			},
-			ExpWorkloadType: "cloneset",
-			ExpTraits:       map[string]map[string]interface{}{},
 		},
-		"normal case frontend": {
-			raw:           yamlNormal,
-			ExpName:       "myapp",
-			ExpComponents: []string{"backend", "frontend"},
-			WantWorkload:  "frontend",
-			ExpWorkload: map[string]interface{}{
+	}
+	comps := GetComponents(app)
+	assert.Equal(t, []string{"a", "b", "c"}, comps)
+}
+
+func TestGetServiceConfig(t *testing.T) {
+	tm := template.NewFakeTemplateManager()
+	app := NewApplication(nil, tm)
+	err := yaml.Unmarshal([]byte(yamlNormal), &app)
+	assert.NoError(t, err)
+
+	tp, cfg := GetServiceConfig(app, "frontend")
+	assert.Equal(t, "webservice", tp)
+	assert.NotEmpty(t, cfg)
+	assert.Contains(t, cfg, "image")
+
+	tp, cfg = GetServiceConfig(app, "backend")
+	assert.Equal(t, "cloneset", tp)
+	assert.NotEmpty(t, cfg)
+	assert.Contains(t, cfg, "image")
+
+	tp, cfg = GetServiceConfig(app, "non-existent")
+	assert.Equal(t, "", tp)
+	assert.Empty(t, cfg)
+}
+
+func TestGetApplicationSettings(t *testing.T) {
+	app := &v1beta1.Application{
+		Spec: v1beta1.ApplicationSpec{
+			Components: []common.ApplicationComponent{
+				{
+					Name: "comp-1",
+					Type: "worker",
+					Properties: &runtime.RawExtension{
+						Raw: []byte(`{"image":"my-image"}`),
+					},
+				},
+			},
+		},
+	}
+
+	tp, settings := GetApplicationSettings(app, "comp-1")
+	assert.Equal(t, "worker", tp)
+	assert.Equal(t, map[string]interface{}{"image": "my-image"}, settings)
+
+	tp, settings = GetApplicationSettings(app, "non-existent")
+	assert.Equal(t, "", tp)
+	assert.Empty(t, settings)
+}
+
+func TestGetWorkload(t *testing.T) {
+	tm := template.NewFakeTemplateManager()
+	tm.Templates["autoscaling"] = &template.Template{Captype: types.TypeTrait}
+	tm.Templates["rollout"] = &template.Template{Captype: types.TypeTrait}
+
+	app := NewApplication(nil, tm)
+	err := yaml.Unmarshal([]byte(yamlNormal), &app)
+	assert.NoError(t, err)
+
+	testCases := map[string]struct {
+		componentName   string
+		expWorkloadType string
+		expWorkload     map[string]interface{}
+	}{
+		"frontend": {
+			componentName:   "frontend",
+			expWorkloadType: "webservice",
+			expWorkload: map[string]interface{}{
 				"image": "inanimate/echo-server",
 				"env": map[string]interface{}{
 					"PORT": float64(8080),
 				},
 			},
-			ExpWorkloadType: "webservice",
-			ExpTraits: map[string]map[string]interface{}{
+		},
+		"backend": {
+			componentName:   "backend",
+			expWorkloadType: "cloneset",
+			expWorkload: map[string]interface{}{
+				"image": "back:v1",
+			},
+		},
+		"non-existent": {
+			componentName:   "non-existent",
+			expWorkloadType: "",
+			expWorkload:     map[string]interface{}{},
+		},
+	}
+
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			workloadType, workload := GetWorkload(app, tc.componentName)
+			assert.Equal(t, tc.expWorkloadType, workloadType)
+			assert.Equal(t, tc.expWorkload, workload)
+		})
+	}
+}
+
+func TestGetTraits(t *testing.T) {
+	tm := template.NewFakeTemplateManager()
+	tm.Templates["autoscaling"] = &template.Template{Captype: types.TypeTrait}
+	tm.Templates["rollout"] = &template.Template{Captype: types.TypeTrait}
+
+	app := NewApplication(nil, tm)
+	err := yaml.Unmarshal([]byte(yamlNormal), &app)
+	assert.NoError(t, err)
+
+	// Test case with invalid trait format
+	invalidTraitApp := NewApplication(nil, tm)
+	err = yaml.Unmarshal([]byte(yamlTraitNotMap), &invalidTraitApp)
+	assert.NoError(t, err)
+
+	testCases := map[string]struct {
+		app      *api.Application
+		compName string
+		exp      map[string]map[string]interface{}
+		expErr   string
+	}{
+		"frontend traits": {
+			app:      app,
+			compName: "frontend",
+			exp: map[string]map[string]interface{}{
 				"autoscaling": {
 					"max": float64(10),
 					"min": float64(1),
@@ -104,50 +260,33 @@ services:
 				},
 			},
 		},
-		"no component": {
-			raw:           yamlNoService,
-			ExpName:       "myapp",
-			InValid:       true,
-			InvalidReason: errors.New("at least one service is required"),
+		"backend traits (none)": {
+			app:      app,
+			compName: "backend",
+			exp:      map[string]map[string]interface{}{},
 		},
-		"no name": {
-			raw:           yamlNoName,
-			ExpName:       "",
-			InValid:       true,
-			InvalidReason: errors.New("name is required"),
+		"non-existent component": {
+			app:      app,
+			compName: "non-existent",
+			exp:      map[string]map[string]interface{}{},
 		},
-		"trait must be map": {
-			raw: yamlTraitNotMap,
-			ExpTraits: map[string]map[string]interface{}{
-				"autoscaling": {},
-			},
-			ExpName:       "myapp",
-			InValid:       true,
-			InvalidReason: fmt.Errorf("trait autoscaling in 'frontend' must be map"),
+		"invalid trait format": {
+			app:      invalidTraitApp,
+			compName: "frontend",
+			exp:      nil,
+			expErr:   "autoscaling is trait, but with invalid format float64, should be map[string]interface{}",
 		},
 	}
 
-	for caseName, c := range cases {
-		tm := template.NewFakeTemplateManager()
-		for k := range c.ExpTraits {
-			tm.Templates[k] = &template.Template{
-				Captype: types.TypeTrait,
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			traits, err := GetTraits(tc.app, tc.compName)
+			if tc.expErr != "" {
+				assert.EqualError(t, err, tc.expErr)
+			} else {
+				assert.NoError(t, err)
+				assert.Equal(t, tc.exp, traits)
 			}
-		}
-		app := NewApplication(nil, tm)
-		err := yaml.Unmarshal([]byte(c.raw), &app)
-		assert.NoError(t, err, caseName)
-		err = Validate(app)
-		if c.InValid {
-			assert.Equal(t, c.InvalidReason, err)
-			continue
-		}
-		assert.Equal(t, c.ExpName, app.Name, caseName)
-		workloadType, workload := GetWorkload(app, c.WantWorkload)
-		assert.Equal(t, c.ExpWorkload, workload, caseName)
-		assert.Equal(t, c.ExpWorkloadType, workloadType, caseName)
-		traits, err := GetTraits(app, c.WantWorkload)
-		assert.NoError(t, err, caseName)
-		assert.Equal(t, c.ExpTraits, traits, caseName)
+		})
 	}
 }
diff --git a/references/appfile/main_test.go b/references/appfile/main_test.go
new file mode 100644
index 00000000..0cd1aa65
--- /dev/null
+++ b/references/appfile/main_test.go
@@ -0,0 +1,161 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package appfile
+
+import (
+	"context"
+	"fmt"
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+
+	corev1 "k8s.io/api/core/v1"
+	crdv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
+	"k8s.io/apimachinery/pkg/api/errors"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime"
+	clientgoscheme "k8s.io/client-go/kubernetes/scheme"
+	"k8s.io/client-go/rest"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+	"sigs.k8s.io/controller-runtime/pkg/envtest"
+	logf "sigs.k8s.io/controller-runtime/pkg/log"
+	"sigs.k8s.io/controller-runtime/pkg/log/zap"
+	"sigs.k8s.io/yaml"
+
+	coreoam "github.com/oam-dev/kubevela/apis/core.oam.dev"
+	corev1beta1 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
+	"github.com/oam-dev/kubevela/pkg/utils/system"
+)
+
+var cfg *rest.Config
+var scheme *runtime.Scheme
+var k8sClient client.Client
+var testEnv *envtest.Environment
+var definitionDir string
+var wd corev1beta1.WorkloadDefinition
+var addonNamespace = "test-addon"
+
+func TestMain(m *testing.M) {
+	logf.SetLogger(zap.New(zap.UseDevMode(true)))
+	ctx := context.Background()
+
+	useExistCluster := false
+	testEnv = &envtest.Environment{
+		ControlPlaneStartTimeout: time.Minute,
+		ControlPlaneStopTimeout:  time.Minute,
+		CRDDirectoryPaths:        []string{filepath.Join("..", "..", "charts", "vela-core", "crds")},
+		UseExistingCluster:       &useExistCluster,
+	}
+
+	var err error
+	cfg, err = testEnv.Start()
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to start test environment: %v\n", err)
+		os.Exit(1)
+	}
+
+	// cleanupAndExit stops the test environment and exits with the given code.
+	cleanupAndExit := func(code int) {
+		// Clean up other resources before stopping the environment
+		if k8sClient != nil {
+			_ = k8sClient.Delete(context.Background(), &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: addonNamespace}})
+			_ = k8sClient.Delete(context.Background(), &wd)
+		}
+		if err := testEnv.Stop(); err != nil {
+			fmt.Fprintf(os.Stderr, "Failed to stop test environment: %v\n", err)
+		}
+		os.Exit(code)
+	}
+
+	scheme = runtime.NewScheme()
+	if err := coreoam.AddToScheme(scheme); err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to add coreoam to scheme: %v\n", err)
+		cleanupAndExit(1)
+	}
+	if err := clientgoscheme.AddToScheme(scheme); err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to add clientgoscheme to scheme: %v\n", err)
+		cleanupAndExit(1)
+	}
+	if err := crdv1.AddToScheme(scheme); err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to add crdv1 to scheme: %v\n", err)
+		cleanupAndExit(1)
+	}
+
+	k8sClient, err = client.New(cfg, client.Options{Scheme: scheme})
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to create k8sClient: %v\n", err)
+		cleanupAndExit(1)
+	}
+
+	definitionDir, err = system.GetCapabilityDir()
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to get capability dir: %v\n", err)
+		cleanupAndExit(1)
+	}
+	if err := os.MkdirAll(definitionDir, 0755); err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to create capability dir: %v\n", err)
+		cleanupAndExit(1)
+	}
+
+	if err := k8sClient.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: addonNamespace}}); err != nil {
+		if !errors.IsAlreadyExists(err) {
+			fmt.Fprintf(os.Stderr, "Failed to create test namespace: %v\n", err)
+			cleanupAndExit(1)
+		}
+	}
+
+	workloadData, err := os.ReadFile("testdata/workloadDef.yaml")
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to read workloadDef.yaml: %v\n", err)
+		cleanupAndExit(1)
+	}
+
+	if err := yaml.Unmarshal(workloadData, &wd); err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to unmarshal workloadDef.yaml: %v\n", err)
+		cleanupAndExit(1)
+	}
+
+	wd.Namespace = addonNamespace
+	if err := k8sClient.Create(ctx, &wd); err != nil {
+		if !errors.IsAlreadyExists(err) {
+			fmt.Fprintf(os.Stderr, "Failed to create workload definition: %v\n", err)
+			cleanupAndExit(1)
+		}
+	}
+
+	def, err := os.ReadFile("testdata/terraform-aliyun-oss-workloadDefinition.yaml")
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to read terraform-aliyun-oss-workloadDefinition.yaml: %v\n", err)
+		cleanupAndExit(1)
+	}
+	var terraformDefinition corev1beta1.WorkloadDefinition
+	if err := yaml.Unmarshal(def, &terraformDefinition); err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to unmarshal terraformDefinition: %v\n", err)
+		cleanupAndExit(1)
+	}
+	terraformDefinition.Namespace = addonNamespace
+	if err := k8sClient.Create(ctx, &terraformDefinition); err != nil {
+		if !errors.IsAlreadyExists(err) {
+			fmt.Fprintf(os.Stderr, "Failed to create terraform workload definition: %v\n", err)
+			cleanupAndExit(1)
+		}
+	}
+
+	code := m.Run()
+	cleanupAndExit(code)
+}
diff --git a/references/appfile/modify_test.go b/references/appfile/modify_test.go
new file mode 100644
index 00000000..c284e6c1
--- /dev/null
+++ b/references/appfile/modify_test.go
@@ -0,0 +1,91 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package appfile
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+
+	"github.com/oam-dev/kubevela/references/appfile/api"
+	"github.com/oam-dev/kubevela/references/appfile/template"
+)
+
+func TestSetWorkload(t *testing.T) {
+	tm := template.NewFakeTemplateManager()
+
+	t.Run("app is nil", func(t *testing.T) {
+		err := SetWorkload(nil, "comp", "worker", nil)
+		assert.EqualError(t, err, errorAppNilPointer.Error())
+	})
+
+	t.Run("add new component", func(t *testing.T) {
+		app := NewApplication(nil, tm)
+		app.Name = "test-app"
+		workloadData := map[string]interface{}{"image": "test-image", "cmd": []string{"sleep", "1000"}}
+		err := SetWorkload(app, "my-comp", "worker", workloadData)
+		assert.NoError(t, err)
+
+		assert.Len(t, app.Services, 1)
+		svc, ok := app.Services["my-comp"]
+		assert.True(t, ok)
+		assert.NotNil(t, svc)
+		assert.Equal(t, "worker", svc["type"])
+		assert.Equal(t, "test-image", svc["image"])
+		assert.Equal(t, []string{"sleep", "1000"}, svc["cmd"])
+	})
+
+	t.Run("update existing component", func(t *testing.T) {
+		app := NewApplication(nil, tm)
+		app.Name = "test-app"
+		app.Services["my-comp"] = api.Service{
+			"type":  "worker",
+			"image": "initial-image",
+		}
+
+		updatedWorkloadData := map[string]interface{}{"image": "updated-image", "port": 8080}
+		err := SetWorkload(app, "my-comp", "webservice", updatedWorkloadData)
+		assert.NoError(t, err)
+
+		assert.Len(t, app.Services, 1)
+		svc, ok := app.Services["my-comp"]
+		assert.True(t, ok)
+		assert.NotNil(t, svc)
+		assert.Equal(t, "webservice", svc["type"])
+		assert.Equal(t, "updated-image", svc["image"])
+		assert.Equal(t, 8080, svc["port"])
+	})
+
+	t.Run("add to existing services", func(t *testing.T) {
+		app := NewApplication(nil, tm)
+		app.Name = "test-app"
+		app.Services["comp-1"] = api.Service{
+			"type": "worker",
+		}
+
+		workloadData := map[string]interface{}{"image": "test-image"}
+		err := SetWorkload(app, "comp-2", "task", workloadData)
+		assert.NoError(t, err)
+
+		assert.Len(t, app.Services, 2)
+		assert.Contains(t, app.Services, "comp-1")
+		assert.Contains(t, app.Services, "comp-2")
+		svc2 := app.Services["comp-2"]
+		assert.Equal(t, "task", svc2["type"])
+		assert.Equal(t, "test-image", svc2["image"])
+	})
+}
diff --git a/references/appfile/run_test.go b/references/appfile/run_test.go
new file mode 100644
index 00000000..dd8ec811
--- /dev/null
+++ b/references/appfile/run_test.go
@@ -0,0 +1,161 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package appfile
+
+import (
+	"context"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
+
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
+	"github.com/oam-dev/kubevela/pkg/oam"
+)
+
+func TestCreateOrUpdateApplication(t *testing.T) {
+	scheme := runtime.NewScheme()
+	assert.NoError(t, v1beta1.AddToScheme(scheme))
+
+	app := &v1beta1.Application{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-app",
+			Namespace: "default",
+		},
+	}
+
+	t.Run("create application", func(t *testing.T) {
+		builder := fake.NewClientBuilder().WithScheme(scheme)
+		fakeClient := builder.Build()
+		err := CreateOrUpdateApplication(context.Background(), fakeClient, app)
+		assert.NoError(t, err)
+
+		var created v1beta1.Application
+		err = fakeClient.Get(context.Background(), client.ObjectKeyFromObject(app), &created)
+		assert.NoError(t, err)
+		assert.Equal(t, "test-app", created.Name)
+	})
+
+	t.Run("update application", func(t *testing.T) {
+		appToUpdate := app.DeepCopy()
+		appToUpdate.SetAnnotations(map[string]string{"key": "val"})
+
+		builder := fake.NewClientBuilder().WithScheme(scheme).WithObjects(app)
+		fakeClient := builder.Build()
+
+		err := CreateOrUpdateApplication(context.Background(), fakeClient, appToUpdate)
+		assert.NoError(t, err)
+
+		var updated v1beta1.Application
+		err = fakeClient.Get(context.Background(), client.ObjectKeyFromObject(app), &updated)
+		assert.NoError(t, err)
+		assert.Equal(t, "val", updated.Annotations["key"])
+	})
+}
+
+func TestCreateOrUpdateObjects(t *testing.T) {
+	scheme := runtime.NewScheme()
+	assert.NoError(t, corev1.AddToScheme(scheme))
+
+	cm := &corev1.ConfigMap{
+		TypeMeta: metav1.TypeMeta{
+			APIVersion: "v1",
+			Kind:       "ConfigMap",
+		},
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-cm",
+			Namespace: "default",
+		},
+		Data: map[string]string{
+			"initial": "true",
+		},
+	}
+
+	t.Run("create object", func(t *testing.T) {
+		builder := fake.NewClientBuilder().WithScheme(scheme)
+		fakeClient := builder.Build()
+		objects := []oam.Object{cm}
+
+		err := CreateOrUpdateObjects(context.Background(), fakeClient, objects)
+		assert.NoError(t, err)
+
+		var created corev1.ConfigMap
+		err = fakeClient.Get(context.Background(), client.ObjectKeyFromObject(cm), &created)
+		assert.NoError(t, err)
+		assert.Equal(t, "true", created.Data["initial"])
+	})
+
+	t.Run("update object", func(t *testing.T) {
+		cmToUpdate := cm.DeepCopy()
+		cmToUpdate.Data["initial"] = "false"
+
+		builder := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cm)
+		fakeClient := builder.Build()
+		objects := []oam.Object{cmToUpdate}
+
+		err := CreateOrUpdateObjects(context.Background(), fakeClient, objects)
+		assert.NoError(t, err)
+
+		var updated corev1.ConfigMap
+		err = fakeClient.Get(context.Background(), client.ObjectKeyFromObject(cm), &updated)
+		assert.NoError(t, err)
+		assert.Equal(t, "false", updated.Data["initial"])
+	})
+}
+
+func TestRun(t *testing.T) {
+	scheme := runtime.NewScheme()
+	assert.NoError(t, v1beta1.AddToScheme(scheme))
+	assert.NoError(t, corev1.AddToScheme(scheme))
+
+	app := &v1beta1.Application{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-app-run",
+			Namespace: "default",
+		},
+	}
+	cm := &corev1.ConfigMap{
+		TypeMeta: metav1.TypeMeta{
+			APIVersion: "v1",
+			Kind:       "ConfigMap",
+		},
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-cm-run",
+			Namespace: "default",
+		},
+	}
+
+	builder := fake.NewClientBuilder().WithScheme(scheme)
+	fakeClient := builder.Build()
+
+	err := Run(context.Background(), fakeClient, app, []oam.Object{cm})
+	assert.NoError(t, err)
+
+	var createdApp v1beta1.Application
+	err = fakeClient.Get(context.Background(), client.ObjectKeyFromObject(app), &createdApp)
+	assert.NoError(t, err)
+	assert.Equal(t, "test-app-run", createdApp.Name)
+
+	var createdCM corev1.ConfigMap
+	err = fakeClient.Get(context.Background(), client.ObjectKeyFromObject(cm), &createdCM)
+	assert.NoError(t, err)
+	assert.Equal(t, "test-cm-run", createdCM.Name)
+}
diff --git a/references/cli/revision_test.go b/references/cli/revision_test.go
index 8cbf53db..fb79fa4a 100644
--- a/references/cli/revision_test.go
+++ b/references/cli/revision_test.go
@@ -59,9 +59,9 @@ metadata:
 spec:
   schematic:
     cue:
-      template: "import (\n\t\"strconv\"\n)\n\nmountsArray: {\n\tpvc: *[\n\t\tfor
-        v in parameter.volumeMounts.pvc {\n\t\t\t{\n\t\t\t\tmountPath: v.mountPath\n\t\t\t\tif
-        v.subPath != _|_ {\n\t\t\t\t\tsubPath: v.subPath\n\t\t\t\t}\n\t\t\t\tname:
+      template: "import (\n\t\"strconv\"\n\t\"list\"\n)\n\nmountsArray: {\n\tpvc:
+        *[\n\t\tfor v in parameter.volumeMounts.pvc {\n\t\t\t{\n\t\t\t\tmountPath:
+        v.mountPath\n\t\t\t\tif v.subPath != _|_ {\n\t\t\t\t\tsubPath: v.subPath\n\t\t\t\t}\n\t\t\t\tname:
         v.name\n\t\t\t}\n\t\t},\n\t] | []\n\n\tconfigMap: *[\n\t\t\tfor v in parameter.volumeMounts.configMap
         {\n\t\t\t{\n\t\t\t\tmountPath: v.mountPath\n\t\t\t\tif v.subPath != _|_ {\n\t\t\t\t\tsubPath:
         v.subPath\n\t\t\t\t}\n\t\t\t\tname: v.name\n\t\t\t}\n\t\t},\n\t] | []\n\n\tsecret:
@@ -85,11 +85,11 @@ spec:
         v.name\n\t\t\t\temptyDir: medium: v.medium\n\t\t\t}\n\t\t},\n\t] | []\n\n\thostPath:
         *[\n\t\t\tfor v in parameter.volumeMounts.hostPath {\n\t\t\t{\n\t\t\t\tname:
         v.name\n\t\t\t\thostPath: path: v.path\n\t\t\t}\n\t\t},\n\t] | []\n}\nvolumesList:
-        volumesArray.pvc + volumesArray.configMap + volumesArray.secret + volumesArray.emptyDir
-        + volumesArray.hostPath\ndeDupVolumesArray: [\n\tfor val in [\n\t\tfor i,
-        vi in volumesList {\n\t\t\tfor j, vj in volumesList if j < i && vi.name ==
-        vj.name {\n\t\t\t\t_ignore: true\n\t\t\t}\n\t\t\tvi\n\t\t},\n\t] if val._ignore
-        == _|_ {\n\t\tval\n\t},\n]\noutput: {\n\tapiVersion: \"apps/v1\"\n\tkind:
+        list.Concat([volumesArray.pvc, volumesArray.configMap, volumesArray.secret,
+        volumesArray.emptyDir, volumesArray.hostPath])\ndeDupVolumesArray: [\n\tfor
+        val in [\n\t\tfor i, vi in volumesList {\n\t\t\tfor j, vj in volumesList if
+        j < i && vi.name == vj.name {\n\t\t\t\t_ignore: true\n\t\t\t}\n\t\t\tvi\n\t\t},\n\t]
+        if val._ignore == _|_ {\n\t\tval\n\t},\n]\noutput: {\n\tapiVersion: \"apps/v1\"\n\tkind:
         \      \"Deployment\"\n\tspec: {\n\t\tselector: matchLabels: \"app.oam.dev/component\":
         context.name\n\n\t\ttemplate: {\n\t\t\tmetadata: {\n\t\t\t\tlabels: {\n\t\t\t\t\tif
         parameter.labels != _|_ {\n\t\t\t\t\t\tparameter.labels\n\t\t\t\t\t}\n\t\t\t\t\tif
@@ -115,8 +115,8 @@ spec:
         parameter[\"volumes\"] != _|_ && parameter[\"volumeMounts\"] == _|_ {\n\t\t\t\t\t\tvolumeMounts:
         [ for v in parameter.volumes {\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmountPath:
         v.mountPath\n\t\t\t\t\t\t\t\tname:      v.name\n\t\t\t\t\t\t\t}}]\n\t\t\t\t\t}\n\n\t\t\t\t\tif
-        parameter[\"volumeMounts\"] != _|_ {\n\t\t\t\t\t\tvolumeMounts: mountsArray.pvc
-        + mountsArray.configMap + mountsArray.secret + mountsArray.emptyDir + mountsArray.hostPath\n\t\t\t\t\t}\n\n\t\t\t\t\tif
+        parameter[\"volumeMounts\"] != _|_ {\n\t\t\t\t\t\tvolumeMounts: list.Concat([mountsArray.pvc,
+        mountsArray.configMap, mountsArray.secret, mountsArray.emptyDir, mountsArray.hostPath])\n\t\t\t\t\t}\n\n\t\t\t\t\tif
         parameter[\"livenessProbe\"] != _|_ {\n\t\t\t\t\t\tlivenessProbe: parameter.livenessProbe\n\t\t\t\t\t}\n\n\t\t\t\t\tif
         parameter[\"readinessProbe\"] != _|_ {\n\t\t\t\t\t\treadinessProbe: parameter.readinessProbe\n\t\t\t\t\t}\n\n\t\t\t\t}]\n\n\t\t\t\tif
         parameter[\"hostAliases\"] != _|_ {\n\t\t\t\t\t// +patchKey=ip\n\t\t\t\t\thostAliases:
@@ -305,7 +305,7 @@ spec:
       spec:
         schematic:
           cue:
-            template: "import (\n\t\"strconv\"\n)\n\nmountsArray: {\n\tpvc: *[\n\t\tfor
+            template: "import (\n\t\"strconv\"\n\t\"list\"\n)\n\nmountsArray: {\n\tpvc: *[\n\t\tfor
               v in parameter.volumeMounts.pvc {\n\t\t\t{\n\t\t\t\tmountPath: v.mountPath\n\t\t\t\tif
               v.subPath != _|_ {\n\t\t\t\t\tsubPath: v.subPath\n\t\t\t\t}\n\t\t\t\tname:
               v.name\n\t\t\t}\n\t\t},\n\t] | []\n\n\tconfigMap: *[\n\t\t\tfor v in
@@ -333,8 +333,7 @@ spec:
               {\n\t\t\t{\n\t\t\t\tname: v.name\n\t\t\t\temptyDir: medium: v.medium\n\t\t\t}\n\t\t},\n\t]
               | []\n\n\thostPath: *[\n\t\t\tfor v in parameter.volumeMounts.hostPath
               {\n\t\t\t{\n\t\t\t\tname: v.name\n\t\t\t\thostPath: path: v.path\n\t\t\t}\n\t\t},\n\t]
-              | []\n}\nvolumesList: volumesArray.pvc + volumesArray.configMap + volumesArray.secret
-              + volumesArray.emptyDir + volumesArray.hostPath\ndeDupVolumesArray:
+              | []\n}\nvolumesList: list.Concat([volumesArray.pvc, volumesArray.configMap, volumesArray.secret, volumesArray.emptyDir, volumesArray.hostPath])\ndeDupVolumesArray:
               [\n\tfor val in [\n\t\tfor i, vi in volumesList {\n\t\t\tfor j, vj in
               volumesList if j < i && vi.name == vj.name {\n\t\t\t\t_ignore: true\n\t\t\t}\n\t\t\tvi\n\t\t},\n\t]
               if val._ignore == _|_ {\n\t\tval\n\t},\n]\noutput: {\n\tapiVersion:
@@ -365,9 +364,7 @@ spec:
               parameter[\"volumes\"] != _|_ && parameter[\"volumeMounts\"] == _|_
               {\n\t\t\t\t\t\tvolumeMounts: [ for v in parameter.volumes {\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmountPath:
               v.mountPath\n\t\t\t\t\t\t\t\tname:      v.name\n\t\t\t\t\t\t\t}}]\n\t\t\t\t\t}\n\n\t\t\t\t\tif
-              parameter[\"volumeMounts\"] != _|_ {\n\t\t\t\t\t\tvolumeMounts: mountsArray.pvc
-              + mountsArray.configMap + mountsArray.secret + mountsArray.emptyDir
-              + mountsArray.hostPath\n\t\t\t\t\t}\n\n\t\t\t\t\tif parameter[\"livenessProbe\"]
+              parameter[\"volumeMounts\"] != _|_ {\n\t\t\t\t\t\tvolumeMounts: list.Concat([mountsArray.pvc, mountsArray.configMap, mountsArray.secret, mountsArray.emptyDir, mountsArray.hostPath])\n\t\t\t\t\t}\n\n\t\t\t\t\tif parameter[\"livenessProbe\"]
               != _|_ {\n\t\t\t\t\t\tlivenessProbe: parameter.livenessProbe\n\t\t\t\t\t}\n\n\t\t\t\t\tif
               parameter[\"readinessProbe\"] != _|_ {\n\t\t\t\t\t\treadinessProbe:
               parameter.readinessProbe\n\t\t\t\t\t}\n\n\t\t\t\t}]\n\n\t\t\t\tif parameter[\"hostAliases\"]
diff --git a/references/cli/top/config/color_test.go b/references/cli/top/config/color_test.go
index 0c69b3e0..10313b91 100644
--- a/references/cli/top/config/color_test.go
+++ b/references/cli/top/config/color_test.go
@@ -18,6 +18,7 @@ package config
 
 import (
 	"os"
+	"path/filepath"
 	"strings"
 	"testing"
 
@@ -27,15 +28,82 @@ import (
 )
 
 func TestString(t *testing.T) {
-	c := Color("red")
-	assert.Equal(t, c.String(), "#ff0000")
+	testCases := map[string]struct {
+		color    Color
+		expected string
+	}{
+		"named color": {
+			color:    "red",
+			expected: "#ff0000",
+		},
+		"hex color": {
+			color:    "#aabbcc",
+			expected: "#aabbcc",
+		},
+		"default color": {
+			color:    DefaultColor,
+			expected: "-",
+		},
+		"invalid color": {
+			color:    "invalidColor",
+			expected: "-",
+		},
+	}
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			assert.Equal(t, tc.expected, tc.color.String())
+		})
+	}
 }
 
 func TestColor(t *testing.T) {
 	c1 := Color("#ff0000")
-	assert.Equal(t, c1.Color(), tcell.GetColor("#ff0000"))
+	assert.Equal(t, tcell.GetColor("#ff0000"), c1.Color())
 	c2 := Color("red")
-	assert.Equal(t, c2.Color(), tcell.GetColor("red").TrueColor())
+	assert.Equal(t, tcell.GetColor("red").TrueColor(), c2.Color())
+	c3 := Color(DefaultColor)
+	assert.Equal(t, tcell.ColorDefault, c3.Color())
+}
+
+func TestIsHex(t *testing.T) {
+	testCases := map[string]struct {
+		color    Color
+		expected bool
+	}{
+		"is hex": {
+			color:    "#aabbcc",
+			expected: true,
+		},
+		"not hex (too short)": {
+			color:    "#aabbc",
+			expected: false,
+		},
+		"not hex (too long)": {
+			color:    "#aabbccd",
+			expected: false,
+		},
+		"not hex (no #)": {
+			color:    "aabbcc",
+			expected: false,
+		},
+		"not hex (named color)": {
+			color:    "red",
+			expected: false,
+		},
+	}
+	for name, tc := range testCases {
+		t.Run(name, func(t *testing.T) {
+			assert.Equal(t, tc.expected, tc.color.isHex())
+		})
+	}
+}
+
+func TestDefaultTheme(t *testing.T) {
+	theme := defaultTheme()
+	assert.NotNil(t, theme)
+	assert.Equal(t, Color("royalblue"), theme.Info.Title)
+	assert.Equal(t, Color("green"), theme.Status.Healthy)
+	assert.Equal(t, Color("red"), theme.Status.UnHealthy)
 }
 
 func TestPersistentThemeConfig(t *testing.T) {
@@ -45,3 +113,101 @@ func TestPersistentThemeConfig(t *testing.T) {
 	assert.Nil(t, err)
 	assert.True(t, strings.Contains(string(bytes), "foo"))
 }
+
+func TestMakeThemeConfigFileIfNotExist(t *testing.T) {
+	tmpDir, err := os.MkdirTemp("", "vela-theme-test")
+	assert.NoError(t, err)
+	defer os.RemoveAll(tmpDir)
+
+	originalHomePath := homePath
+	originalThemeConfigFilePath := themeConfigFilePath
+	homePath = tmpDir
+	themeConfigFilePath = filepath.Join(tmpDir, themeHomeDirPath, themeConfigFile)
+	defer func() {
+		homePath = originalHomePath
+		themeConfigFilePath = originalThemeConfigFilePath
+	}()
+
+	t.Run("should create file if it does not exist", func(t *testing.T) {
+		os.Remove(themeConfigFilePath)
+
+		exists := makeThemeConfigFileIfNotExist()
+		assert.False(t, exists, "should return false as file was created")
+
+		_, err := os.Stat(themeConfigFilePath)
+		assert.NoError(t, err, "expected theme config file to be created")
+		content, err := os.ReadFile(themeConfigFilePath)
+		assert.NoError(t, err)
+		assert.Equal(t, "name : "+DefaultTheme, string(content))
+	})
+
+	t.Run("should not modify file if it already exists", func(t *testing.T) {
+		customContent := "name : custom"
+		err := os.WriteFile(themeConfigFilePath, []byte(customContent), 0600)
+		assert.NoError(t, err)
+
+		exists := makeThemeConfigFileIfNotExist()
+		assert.True(t, exists, "should return true as file already exists")
+
+		content, err := os.ReadFile(themeConfigFilePath)
+		assert.NoError(t, err)
+		assert.Equal(t, customContent, string(content))
+	})
+}
+
+func TestLoadThemeConfig(t *testing.T) {
+	tmpDir, err := os.MkdirTemp("", "vela-theme-test-load")
+	assert.NoError(t, err)
+	defer os.RemoveAll(tmpDir)
+
+	originalHomePath := homePath
+	originalThemeConfigFilePath := themeConfigFilePath
+	originalDiyThemeDirPath := diyThemeDirPath
+	homePath = tmpDir
+	themeConfigFilePath = filepath.Join(tmpDir, themeHomeDirPath, themeConfigFile)
+	diyThemeDirPath = filepath.Join(tmpDir, themeHomeDirPath, diyThemeDir)
+	defer func() {
+		homePath = originalHomePath
+		themeConfigFilePath = originalThemeConfigFilePath
+		diyThemeDirPath = originalDiyThemeDirPath
+	}()
+
+	ThemeMap["custom"] = ThemeConfig{
+		Info: struct {
+			Title Color `yaml:"title"`
+			Text  Color `yaml:"text"`
+		}{Title: "custom-title"},
+	}
+	defer delete(ThemeMap, "custom")
+
+	t.Run("config file not exist", func(t *testing.T) {
+		os.Remove(themeConfigFilePath)
+		cfg := LoadThemeConfig()
+		assert.Equal(t, defaultTheme().Info.Title, cfg.Info.Title)
+	})
+
+	t.Run("config file with default theme", func(t *testing.T) {
+		PersistentThemeConfig(DefaultTheme)
+		cfg := LoadThemeConfig()
+		assert.Equal(t, defaultTheme().Info.Title, cfg.Info.Title)
+	})
+
+	t.Run("config file with custom theme", func(t *testing.T) {
+		PersistentThemeConfig("custom")
+		cfg := LoadThemeConfig()
+		assert.Equal(t, Color("custom-title"), cfg.Info.Title)
+	})
+
+	t.Run("config file with unknown theme", func(t *testing.T) {
+		PersistentThemeConfig("unknown")
+		cfg := LoadThemeConfig()
+		assert.Equal(t, defaultTheme().Info.Title, cfg.Info.Title)
+	})
+
+	t.Run("config file with invalid content", func(t *testing.T) {
+		err := os.WriteFile(themeConfigFilePath, []byte("name: [invalid"), 0600)
+		assert.NoError(t, err)
+		cfg := LoadThemeConfig()
+		assert.Equal(t, defaultTheme().Info.Title, cfg.Info.Title)
+	})
+}
diff --git a/references/cli/top/model/application_test.go b/references/cli/top/model/application_test.go
index f3c78975..8c76ad82 100644
--- a/references/cli/top/model/application_test.go
+++ b/references/cli/top/model/application_test.go
@@ -20,15 +20,14 @@ import (
 	"context"
 	"testing"
 
+	workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
 	. "github.com/onsi/ginkgo/v2"
 	. "github.com/onsi/gomega"
 	"github.com/stretchr/testify/assert"
-)
 
-func TestApplicationList_ToTableBody(t *testing.T) {
-	appList := &ApplicationList{{"Name", "Namespace", "Phase", "", "", "", "CreateTime"}}
-	assert.Equal(t, appList.ToTableBody(), [][]string{{"Name", "Namespace", "Phase", "", "", "", "CreateTime"}})
-}
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
+)
 
 var _ = Describe("test Application", func() {
 	ctx := context.Background()
@@ -66,3 +65,164 @@ var _ = Describe("test Application", func() {
 		Expect(len(topology)).To(Equal(4))
 	})
 })
+
+func TestApplicationList_ToTableBody(t *testing.T) {
+	testCases := []struct {
+		name     string
+		list     ApplicationList
+		expected [][]string
+	}{
+		{
+			name:     "empty list",
+			list:     ApplicationList{},
+			expected: make([][]string, 0),
+		},
+		{
+			name: "single item list",
+			list: ApplicationList{
+				{name: "app1", namespace: "ns1", phase: "running", workflowMode: "DAG", workflow: "1/1", service: "1/1", createTime: "now"},
+			},
+			expected: [][]string{
+				{"app1", "ns1", "running", "DAG", "1/1", "1/1", "now"},
+			},
+		},
+		{
+			name: "multiple item list",
+			list: ApplicationList{
+				{name: "app1", namespace: "ns1", phase: "running", workflowMode: "DAG", workflow: "1/1", service: "1/1", createTime: "now"},
+				{name: "app2", namespace: "ns2", phase: "failed", workflowMode: "StepByStep", workflow: "0/1", service: "0/1", createTime: "then"},
+			},
+			expected: [][]string{
+				{"app1", "ns1", "running", "DAG", "1/1", "1/1", "now"},
+				{"app2", "ns2", "failed", "StepByStep", "0/1", "0/1", "then"},
+			},
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			result := tc.list.ToTableBody()
+			if len(tc.expected) == 0 {
+				assert.Empty(t, result)
+			} else {
+				assert.Equal(t, tc.expected, result)
+			}
+		})
+	}
+}
+
+func TestServiceNum(t *testing.T) {
+	testCases := []struct {
+		name     string
+		app      v1beta1.Application
+		expected string
+	}{
+		{
+			name:     "no services",
+			app:      v1beta1.Application{Status: common.AppStatus{Services: []common.ApplicationComponentStatus{}}},
+			expected: "0/0",
+		},
+		{
+			name: "one healthy, one unhealthy",
+			app: v1beta1.Application{Status: common.AppStatus{Services: []common.ApplicationComponentStatus{
+				{Healthy: true},
+				{Healthy: false},
+			}}},
+			expected: "1/2",
+		},
+		{
+			name: "all healthy",
+			app: v1beta1.Application{Status: common.AppStatus{Services: []common.ApplicationComponentStatus{
+				{Healthy: true},
+				{Healthy: true},
+			}}},
+			expected: "2/2",
+		},
+	}
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			assert.Equal(t, tc.expected, serviceNum(tc.app))
+		})
+	}
+}
+
+func TestWorkflowMode(t *testing.T) {
+	testCases := []struct {
+		name     string
+		app      v1beta1.Application
+		expected string
+	}{
+		{
+			name:     "workflow is nil",
+			app:      v1beta1.Application{Status: common.AppStatus{Workflow: nil}},
+			expected: Unknown,
+		},
+		{
+			name:     "workflow mode is DAG",
+			app:      v1beta1.Application{Status: common.AppStatus{Workflow: &common.WorkflowStatus{Mode: "DAG"}}},
+			expected: "DAG",
+		},
+	}
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			assert.Equal(t, tc.expected, workflowMode(tc.app))
+		})
+	}
+}
+
+func TestWorkflowStepNum(t *testing.T) {
+	testCases := []struct {
+		name     string
+		app      v1beta1.Application
+		expected string
+	}{
+		{
+			name:     "workflow is nil",
+			app:      v1beta1.Application{Status: common.AppStatus{Workflow: nil}},
+			expected: "N/A",
+		},
+		{
+			name: "empty workflow steps",
+			app: v1beta1.Application{Status: common.AppStatus{Workflow: &common.WorkflowStatus{
+				Steps: []workflowv1alpha1.WorkflowStepStatus{},
+			}}},
+			expected: "0/0",
+		},
+		{
+			name: "all steps succeeded",
+			app: v1beta1.Application{Status: common.AppStatus{Workflow: &common.WorkflowStatus{
+				Steps: []workflowv1alpha1.WorkflowStepStatus{
+					{StepStatus: workflowv1alpha1.StepStatus{Phase: workflowv1alpha1.WorkflowStepPhaseSucceeded}},
+					{StepStatus: workflowv1alpha1.StepStatus{Phase: workflowv1alpha1.WorkflowStepPhaseSucceeded}},
+				},
+			}}},
+			expected: "2/2",
+		},
+		{
+			name: "some steps succeeded, some failed/running",
+			app: v1beta1.Application{Status: common.AppStatus{Workflow: &common.WorkflowStatus{
+				Steps: []workflowv1alpha1.WorkflowStepStatus{
+					{StepStatus: workflowv1alpha1.StepStatus{Phase: workflowv1alpha1.WorkflowStepPhaseSucceeded}},
+					{StepStatus: workflowv1alpha1.StepStatus{Phase: workflowv1alpha1.WorkflowStepPhaseFailed}},
+					{StepStatus: workflowv1alpha1.StepStatus{Phase: workflowv1alpha1.WorkflowStepPhaseRunning}},
+				},
+			}}},
+			expected: "1/3",
+		},
+		{
+			name: "all steps failed/running",
+			app: v1beta1.Application{Status: common.AppStatus{Workflow: &common.WorkflowStatus{
+				Steps: []workflowv1alpha1.WorkflowStepStatus{
+					{StepStatus: workflowv1alpha1.StepStatus{Phase: workflowv1alpha1.WorkflowStepPhaseFailed}},
+					{StepStatus: workflowv1alpha1.StepStatus{Phase: workflowv1alpha1.WorkflowStepPhaseRunning}},
+				},
+			}}},
+			expected: "0/2",
+		},
+	}
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			assert.Equal(t, tc.expected, workflowStepNum(tc.app))
+		})
+	}
+}
diff --git a/references/cli/top/utils/time_test.go b/references/cli/top/utils/time_test.go
index 24c61a4c..bf7839d9 100644
--- a/references/cli/top/utils/time_test.go
+++ b/references/cli/top/utils/time_test.go
@@ -24,19 +24,43 @@ import (
 )
 
 func TestTimeFormat(t *testing.T) {
-	t1, err1 := time.ParseDuration("1.5h")
-	assert.NoError(t, err1)
-	assert.Equal(t, TimeFormat(t1), "1h30m0s")
-	t2, err2 := time.ParseDuration("25h")
-	assert.NoError(t, err2)
-	assert.Equal(t, TimeFormat(t2), "1d1h0m0s")
-	t3, err3 := time.ParseDuration("0.1h")
-	assert.NoError(t, err3)
-	assert.Equal(t, TimeFormat(t3), "6m0s")
-	t4, err4 := time.ParseDuration("0.001h")
-	assert.NoError(t, err4)
-	assert.Equal(t, TimeFormat(t4), "3s")
-	t5, err5 := time.ParseDuration("0.00001h")
-	assert.NoError(t, err5)
-	assert.Equal(t, TimeFormat(t5), "36ms")
+	testCases := []struct {
+		name     string
+		in       string
+		expected string
+	}{
+		{
+			name:     "1.5h",
+			in:       "1.5h",
+			expected: "1h30m0s",
+		},
+		{
+			name:     "25h",
+			in:       "25h",
+			expected: "1d1h0m0s",
+		},
+		{
+			name:     "0.1h",
+			in:       "0.1h",
+			expected: "6m0s",
+		},
+		{
+			name:     "0.001h",
+			in:       "0.001h",
+			expected: "3s",
+		},
+		{
+			name:     "0.00001h",
+			in:       "0.00001h",
+			expected: "36ms",
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			d, err := time.ParseDuration(tc.in)
+			assert.NoError(t, err)
+			assert.Equal(t, tc.expected, TimeFormat(d))
+		})
+	}
 }
diff --git a/references/common/application_test.go b/references/common/application_test.go
index e8da691d..86c88a3f 100644
--- a/references/common/application_test.go
+++ b/references/common/application_test.go
@@ -16,22 +16,111 @@ limitations under the License.
 package common
 
 import (
+	"bytes"
 	"context"
+	"os"
 	"testing"
 
 	terraformapi "github.com/oam-dev/terraform-controller/api/v1beta2"
 	"github.com/stretchr/testify/assert"
 	corev1 "k8s.io/api/core/v1"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
 	"k8s.io/apimachinery/pkg/runtime"
-	"sigs.k8s.io/controller-runtime/pkg/client"
+	sigs "sigs.k8s.io/controller-runtime/pkg/client"
 	"sigs.k8s.io/controller-runtime/pkg/client/fake"
 
 	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
 	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
 	"github.com/oam-dev/kubevela/apis/types"
+	"github.com/oam-dev/kubevela/references/appfile/api"
+
+	utilcommon "github.com/oam-dev/kubevela/pkg/utils/common"
+	querytypes "github.com/oam-dev/kubevela/pkg/utils/types"
+	cmdutil "github.com/oam-dev/kubevela/pkg/utils/util"
 )
 
+func TestExportFromAppFile(t *testing.T) {
+	s := runtime.NewScheme()
+	assert.NoError(t, v1beta1.AddToScheme(s))
+	clt := fake.NewClientBuilder().WithScheme(s).Build()
+	var out bytes.Buffer
+	ioStream := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+
+	o := &AppfileOptions{
+		Kubecli:   clt,
+		IO:        ioStream,
+		Namespace: "default",
+	}
+
+	appFile := &api.AppFile{
+		Name: "test-app-export-from",
+	}
+
+	c := utilcommon.Args{}
+	c.SetClient(clt)
+
+	result, data, err := o.ExportFromAppFile(appFile, "default", true, c)
+	assert.NoError(t, err)
+	assert.NotNil(t, result)
+	assert.NotNil(t, data)
+	assert.Contains(t, string(data), "name: test-app-export-from")
+	assert.Equal(t, "test-app-export-from", result.application.Name)
+}
+
+func TestApplyApp(t *testing.T) {
+	s := runtime.NewScheme()
+	v1beta1.AddToScheme(s)
+
+	t.Run("create app if not exist", func(t *testing.T) {
+		cltCreate := fake.NewClientBuilder().WithScheme(s).Build()
+		var outCreate bytes.Buffer
+		ioStreamCreate := cmdutil.IOStreams{In: os.Stdin, Out: &outCreate, ErrOut: &outCreate}
+		oCreate := &AppfileOptions{
+			Kubecli:   cltCreate,
+			IO:        ioStreamCreate,
+			Namespace: "default",
+		}
+		appCreate := &v1beta1.Application{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      "test-app-apply",
+				Namespace: "default",
+			},
+		}
+		err := oCreate.ApplyApp(appCreate, nil)
+		assert.NoError(t, err)
+		assert.Contains(t, outCreate.String(), "App has not been deployed, creating a new deployment...")
+		assert.Contains(t, outCreate.String(), "vela port-forward test-app-apply")
+	})
+
+	t.Run("update app if exists", func(t *testing.T) {
+		existingApp := &v1beta1.Application{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      "test-app-apply",
+				Namespace: "default",
+			},
+		}
+		cltUpdate := fake.NewClientBuilder().WithScheme(s).WithObjects(existingApp).Build()
+		var outUpdate bytes.Buffer
+		ioStreamUpdate := cmdutil.IOStreams{In: os.Stdin, Out: &outUpdate, ErrOut: &outUpdate}
+		oUpdate := &AppfileOptions{
+			Kubecli:   cltUpdate,
+			IO:        ioStreamUpdate,
+			Namespace: "default",
+		}
+		appUpdate := &v1beta1.Application{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      "test-app-apply",
+				Namespace: "default",
+			},
+		}
+		err := oUpdate.ApplyApp(appUpdate, nil)
+		assert.NoError(t, err)
+		assert.Contains(t, outUpdate.String(), "App exists, updating existing deployment...")
+		assert.Contains(t, outUpdate.String(), "vela port-forward test-app-apply")
+	})
+}
+
 func TestPrepareToForceDeleteTerraformComponents(t *testing.T) {
 	ctx := context.Background()
 	s := runtime.NewScheme()
@@ -95,7 +184,7 @@ func TestPrepareToForceDeleteTerraformComponents(t *testing.T) {
 
 	k8sClient5 := fake.NewClientBuilder().WithScheme(s).WithObjects(app2, def2, conf2).Build()
 	type args struct {
-		k8sClient client.Client
+		k8sClient sigs.Client
 		namespace string
 		name      string
 	}
@@ -176,5 +265,115 @@ func TestPrepareToForceDeleteTerraformComponents(t *testing.T) {
 			}
 		})
 	}
+}
+
+func TestIsAppfile(t *testing.T) {
+	testCases := []struct {
+		name     string
+		data     []byte
+		expected bool
+	}{
+		{
+			name:     "valid appfile json",
+			data:     []byte(`{"name": "test"}`),
+			expected: true,
+		},
+		{
+			name:     "invalid json",
+			data:     []byte(`{"name": "test"`),
+			expected: false,
+		},
+		{
+			name: "application yaml",
+			data: []byte(`
+apiVersion: core.oam.dev/v1beta1
+kind: Application
+metadata:
+  name: test-app
+`),
+			expected: false,
+		},
+		{
+			name: "appfile yaml",
+			data: []byte(`
+name: test-app
+`),
+			expected: true,
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			result := IsAppfile(tc.data)
+			assert.Equal(t, tc.expected, result)
+		})
+	}
+}
+
+func TestInfo(t *testing.T) {
+	app := &v1beta1.Application{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-app",
+			Namespace: "test-ns",
+		},
+	}
+	info := Info(app)
+	assert.Contains(t, info, "vela port-forward test-app -n test-ns")
+	assert.Contains(t, info, "vela exec test-app -n test-ns")
+	assert.Contains(t, info, "vela logs test-app -n test-ns")
+	assert.Contains(t, info, "vela status test-app -n test-ns")
+	assert.Contains(t, info, "vela status test-app -n test-ns --endpoint")
+}
 
+func TestSonLeafResource(t *testing.T) {
+	node := &querytypes.ResourceTreeNode{
+		LeafNodes: []*querytypes.ResourceTreeNode{
+			{
+				Object: &unstructured.Unstructured{
+					Object: map[string]interface{}{
+						"kind":       "Deployment",
+						"apiVersion": "apps/v1",
+					},
+				},
+				Kind:       "Deployment",
+				APIVersion: "apps/v1",
+			},
+		},
+	}
+	resources := sonLeafResource(node, "Deployment", "apps/v1")
+	assert.Equal(t, 1, len(resources))
+	assert.Equal(t, "Deployment", resources[0].GetKind())
+}
+
+func TestLoadAppFile(t *testing.T) {
+	content := "name: test-app"
+	tmpFile, err := os.CreateTemp("", "appfile-*.yaml")
+	assert.NoError(t, err)
+	defer os.Remove(tmpFile.Name())
+
+	_, err = tmpFile.WriteString(content)
+	assert.NoError(t, err)
+	assert.NoError(t, tmpFile.Close())
+
+	appFile, err := LoadAppFile(tmpFile.Name())
+	assert.NoError(t, err)
+	assert.NotNil(t, appFile)
+	assert.Equal(t, "test-app", appFile.Name)
+}
+
+func TestApplyApplication(t *testing.T) {
+	s := runtime.NewScheme()
+	v1beta1.AddToScheme(s)
+	clt := fake.NewClientBuilder().WithScheme(s).Build()
+	app := v1beta1.Application{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-app",
+			Namespace: "default",
+		},
+	}
+	var out bytes.Buffer
+	ioStream := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+	err := ApplyApplication(app, ioStream, clt)
+	assert.NoError(t, err)
+	assert.Contains(t, out.String(), "Applying an application in vela K8s object format...")
 }
diff --git a/references/common/metrics_test.go b/references/common/metrics_test.go
index e751aa90..5ab7044c 100644
--- a/references/common/metrics_test.go
+++ b/references/common/metrics_test.go
@@ -18,39 +18,50 @@ package common
 
 import (
 	"testing"
-	"time"
-
-	"k8s.io/utils/ptr"
-	"sigs.k8s.io/controller-runtime/pkg/client"
-	"sigs.k8s.io/controller-runtime/pkg/envtest"
-
-	"github.com/oam-dev/kubevela/pkg/utils/common"
 
 	"github.com/stretchr/testify/assert"
 	v1 "k8s.io/api/core/v1"
 	"k8s.io/apimachinery/pkg/api/resource"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+	"k8s.io/apimachinery/pkg/runtime"
 	"k8s.io/metrics/pkg/apis/metrics/v1beta1"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
+
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
+	appv1beta1 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
 )
 
 func TestToPercentageStr(t *testing.T) {
-	var v1, v2 int64
-	v1, v2 = 10, 100
-	assert.Equal(t, ToPercentageStr(v1, v2), "10%")
-	v1, v2 = 10, 0
-	assert.Equal(t, ToPercentageStr(v1, v2), "N/A")
+	t.Run("valid percentage", func(t *testing.T) {
+		var v1, v2 int64 = 10, 100
+		assert.Equal(t, "10%", ToPercentageStr(v1, v2))
+	})
+	t.Run("division by zero", func(t *testing.T) {
+		var v1, v2 int64 = 10, 0
+		assert.Equal(t, "N/A", ToPercentageStr(v1, v2))
+	})
 }
 
-func TestGetPodResourceSpecAndUsage(t *testing.T) {
-	testEnv := &envtest.Environment{
-		ControlPlaneStartTimeout: time.Minute * 3,
-		ControlPlaneStopTimeout:  time.Minute,
-		UseExistingCluster:       ptr.To(false),
-	}
-	cfg, err := testEnv.Start()
-	assert.NoError(t, err)
+func TestToPercentage(t *testing.T) {
+	t.Run("valid percentage", func(t *testing.T) {
+		var v1, v2 int64 = 10, 100
+		assert.Equal(t, 10, ToPercentage(v1, v2))
+	})
+	t.Run("division by zero", func(t *testing.T) {
+		var v1, v2 int64 = 10, 0
+		assert.Equal(t, 0, ToPercentage(v1, v2))
+	})
+	t.Run("floor", func(t *testing.T) {
+		var v1, v2 int64 = 1, 3
+		assert.Equal(t, 33, ToPercentage(v1, v2))
+	})
+}
 
-	k8sClient, err := client.New(cfg, client.Options{Scheme: common.Scheme})
-	assert.NoError(t, err)
+func TestGetPodResourceSpecAndUsage(t *testing.T) {
+	s := runtime.NewScheme()
+	v1.AddToScheme(s)
+	k8sClient := fake.NewClientBuilder().WithScheme(s).Build()
 
 	quantityLimitsCPU, _ := resource.ParseQuantity("10m")
 	quantityLimitsMemory, _ := resource.ParseQuantity("10Mi")
@@ -83,10 +94,157 @@ func TestGetPodResourceSpecAndUsage(t *testing.T) {
 	}
 
 	spec, usage := GetPodResourceSpecAndUsage(k8sClient, pod, podMetric)
-	assert.Equal(t, usage.CPU, int64(8))
-	assert.Equal(t, usage.Mem, int64(20971520))
-	assert.Equal(t, spec.Lcpu, int64(10))
-	assert.Equal(t, spec.Lmem, int64(10485760))
-	assert.Equal(t, spec.Rcpu, int64(100))
-	assert.Equal(t, spec.Rmem, int64(52428800))
+	assert.Equal(t, int64(8), usage.CPU)
+	assert.Equal(t, int64(20971520), usage.Mem)
+	assert.Equal(t, int64(10), spec.Lcpu)
+	assert.Equal(t, int64(10485760), spec.Lmem)
+	assert.Equal(t, int64(100), spec.Rcpu)
+	assert.Equal(t, int64(52428800), spec.Rmem)
+}
+
+func TestGetPodStorage(t *testing.T) {
+	s := runtime.NewScheme()
+	v1.AddToScheme(s)
+
+	pvc := &v1.PersistentVolumeClaim{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-pvc",
+			Namespace: "default",
+		},
+	}
+	k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(pvc).Build()
+
+	podWithPVC := &v1.Pod{
+		ObjectMeta: metav1.ObjectMeta{
+			Namespace: "default",
+		},
+		Spec: v1.PodSpec{
+			Volumes: []v1.Volume{
+				{
+					Name: "test-storage",
+					VolumeSource: v1.VolumeSource{
+						PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
+							ClaimName: "test-pvc",
+						},
+					},
+				},
+			},
+		},
+	}
+
+	podWithoutPVC := &v1.Pod{
+		Spec: v1.PodSpec{
+			Volumes: []v1.Volume{
+				{
+					Name: "test-emptydir",
+					VolumeSource: v1.VolumeSource{
+						EmptyDir: &v1.EmptyDirVolumeSource{},
+					},
+				},
+			},
+		},
+	}
+
+	podWithNonExistentPVC := &v1.Pod{
+		ObjectMeta: metav1.ObjectMeta{
+			Namespace: "default",
+		},
+		Spec: v1.PodSpec{
+			Volumes: []v1.Volume{
+				{
+					Name: "test-storage",
+					VolumeSource: v1.VolumeSource{
+						PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
+							ClaimName: "non-existent-pvc",
+						},
+					},
+				},
+			},
+		},
+	}
+
+	t.Run("pod with pvc", func(t *testing.T) {
+		storages := GetPodStorage(k8sClient, podWithPVC)
+		assert.Equal(t, 1, len(storages))
+		assert.Equal(t, "test-pvc", storages[0].Name)
+	})
+
+	t.Run("pod without pvc", func(t *testing.T) {
+		storages := GetPodStorage(k8sClient, podWithoutPVC)
+		assert.Equal(t, 0, len(storages))
+	})
+
+	t.Run("pod with non-existent pvc", func(t *testing.T) {
+		storages := GetPodStorage(k8sClient, podWithNonExistentPVC)
+		assert.Equal(t, 0, len(storages))
+	})
+}
+
+func TestGetPodOfManagedResource(t *testing.T) {
+	s := runtime.NewScheme()
+	v1.AddToScheme(s)
+	appv1beta1.AddToScheme(s)
+
+	app := &appv1beta1.Application{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-app",
+			Namespace: "default",
+		},
+	}
+
+	pod := &v1.Pod{
+		TypeMeta: metav1.TypeMeta{
+			Kind:       "Pod",
+			APIVersion: "v1",
+		},
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-pod",
+			Namespace: "default",
+		},
+	}
+	podUnstructured, err := runtime.DefaultUnstructuredConverter.ToUnstructured(pod)
+	assert.NoError(t, err)
+
+	rt := &appv1beta1.ResourceTracker{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-app-v1", // A tracker name
+			Namespace: "default",
+			Labels: map[string]string{
+				"app.oam.dev/name":      "test-app",
+				"app.oam.dev/namespace": "default",
+			},
+		},
+		Spec: appv1beta1.ResourceTrackerSpec{
+			Type: appv1beta1.ResourceTrackerTypeRoot,
+			ManagedResources: []appv1beta1.ManagedResource{
+				{
+					ClusterObjectReference: common.ClusterObjectReference{
+						ObjectReference: v1.ObjectReference{
+							Kind:       "Pod",
+							APIVersion: "v1",
+							Name:       "test-pod",
+							Namespace:  "default",
+						},
+					},
+					OAMObjectReference: common.OAMObjectReference{
+						Component: "test-component",
+					},
+				},
+			},
+		},
+	}
+
+	k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(app, rt, &unstructured.Unstructured{Object: podUnstructured}).Build()
+
+	t.Run("get existing pod", func(t *testing.T) {
+		pods := GetPodOfManagedResource(k8sClient, app, "test-component")
+		assert.Equal(t, 2, len(pods))
+		assert.Equal(t, "test-pod", pods[0].Name)
+		assert.Equal(t, "test-pod", pods[1].Name)
+	})
+
+	t.Run("get pod for non-existent component", func(t *testing.T) {
+		pods := GetPodOfManagedResource(k8sClient, app, "non-existent-component")
+		assert.Equal(t, 0, len(pods))
+	})
 }
diff --git a/references/common/registry_test.go b/references/common/registry_test.go
index 44c6fe79..d484ad08 100644
--- a/references/common/registry_test.go
+++ b/references/common/registry_test.go
@@ -17,16 +17,178 @@ limitations under the License.
 package common
 
 import (
+	"bytes"
+	"context"
 	"encoding/json"
+	"os"
 	"reflect"
 	"testing"
 
+	"github.com/pkg/errors"
 	"github.com/stretchr/testify/assert"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 	"k8s.io/apimachinery/pkg/runtime"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
+	"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
 
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
 	"github.com/oam-dev/kubevela/apis/types"
+	cmdutil "github.com/oam-dev/kubevela/pkg/utils/util"
 )
 
+func TestInstallComponentDefinition(t *testing.T) {
+	s := runtime.NewScheme()
+	assert.NoError(t, v1beta1.AddToScheme(s))
+
+	validComponentData := []byte(`
+apiVersion: core.oam.dev/v1beta1
+kind: ComponentDefinition
+metadata:
+  name: test-component
+spec:
+  workload:
+    definition:
+      apiVersion: apps/v1
+      kind: Deployment
+`)
+
+	existingComponent := &v1beta1.ComponentDefinition{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-component",
+			Namespace: types.DefaultKubeVelaNS,
+		},
+	}
+
+	t.Run("success", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).Build()
+		var out bytes.Buffer
+		ioStreams := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+
+		err := InstallComponentDefinition(k8sClient, validComponentData, ioStreams)
+		assert.NoError(t, err)
+		assert.Contains(t, out.String(), "Installing component: test-component")
+
+		var cd v1beta1.ComponentDefinition
+		err = k8sClient.Get(context.Background(), client.ObjectKey{Name: "test-component", Namespace: types.DefaultKubeVelaNS}, &cd)
+		assert.NoError(t, err)
+		assert.Equal(t, "test-component", cd.Name)
+	})
+
+	t.Run("already exists", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(existingComponent).Build()
+		var out bytes.Buffer
+		ioStreams := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+
+		err := InstallComponentDefinition(k8sClient, validComponentData, ioStreams)
+		assert.NoError(t, err)
+	})
+
+	t.Run("client error", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).WithInterceptorFuncs(interceptor.Funcs{
+			Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
+				return errors.New("client create error")
+			},
+		}).Build()
+		var out bytes.Buffer
+		ioStreams := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+
+		err := InstallComponentDefinition(k8sClient, validComponentData, ioStreams)
+		assert.Error(t, err)
+		assert.EqualError(t, err, "client create error")
+	})
+
+	t.Run("invalid data", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).Build()
+		var out bytes.Buffer
+		ioStreams := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+		invalidData := []byte(`{"invalid": "yaml"`)
+
+		err := InstallComponentDefinition(k8sClient, invalidData, ioStreams)
+		assert.Error(t, err)
+	})
+
+	t.Run("nil data", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).Build()
+		var out bytes.Buffer
+		ioStreams := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+
+		err := InstallComponentDefinition(k8sClient, nil, ioStreams)
+		assert.Error(t, err)
+		assert.Equal(t, "componentData is nil", err.Error())
+	})
+}
+
+func TestInstallTraitDefinition(t *testing.T) {
+	s := runtime.NewScheme()
+	v1beta1.AddToScheme(s)
+
+	validTraitData := []byte(`
+apiVersion: core.oam.dev/v1beta1
+kind: TraitDefinition
+metadata:
+  name: test-trait
+spec:
+  appliesToWorkloads:
+    - deployments.apps
+`)
+
+	existingTrait := &v1beta1.TraitDefinition{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "test-trait",
+			Namespace: types.DefaultKubeVelaNS,
+		},
+	}
+
+	t.Run("success", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).Build()
+		var out bytes.Buffer
+		ioStreams := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+
+		err := InstallTraitDefinition(k8sClient, validTraitData, ioStreams)
+		assert.NoError(t, err)
+		assert.Contains(t, out.String(), "Installing trait test-trait")
+
+		var td v1beta1.TraitDefinition
+		err = k8sClient.Get(context.Background(), client.ObjectKey{Name: "test-trait", Namespace: types.DefaultKubeVelaNS}, &td)
+		assert.NoError(t, err)
+		assert.Equal(t, "test-trait", td.Name)
+	})
+
+	t.Run("already exists", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(existingTrait).Build()
+		var out bytes.Buffer
+		ioStreams := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+
+		err := InstallTraitDefinition(k8sClient, validTraitData, ioStreams)
+		assert.NoError(t, err)
+	})
+
+	t.Run("client error", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).WithInterceptorFuncs(interceptor.Funcs{
+			Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
+				return errors.New("client create error")
+			},
+		}).Build()
+		var out bytes.Buffer
+		ioStreams := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+
+		err := InstallTraitDefinition(k8sClient, validTraitData, ioStreams)
+		assert.Error(t, err)
+		assert.Equal(t, "client create error", err.Error())
+	})
+
+	t.Run("invalid data", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).Build()
+		var out bytes.Buffer
+		ioStreams := cmdutil.IOStreams{In: os.Stdin, Out: &out, ErrOut: &out}
+		invalidData := []byte(`{"invalid": "yaml"`)
+
+		err := InstallTraitDefinition(k8sClient, invalidData, ioStreams)
+		assert.Error(t, err)
+	})
+}
+
 func TestAddSourceIntoDefinition(t *testing.T) {
 	caseJson := []byte(`{"template":""}`)
 	wantJson := []byte(`{"source":{"repoName":"foo"},"template":""}`)
diff --git a/references/common/trait_test.go b/references/common/trait_test.go
new file mode 100644
index 00000000..20879c10
--- /dev/null
+++ b/references/common/trait_test.go
@@ -0,0 +1,90 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package common
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
+
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
+	"github.com/oam-dev/kubevela/pkg/oam"
+	"github.com/oam-dev/kubevela/pkg/utils/common"
+)
+
+func TestListRawWorkloadDefinitions(t *testing.T) {
+	s := runtime.NewScheme()
+	v1beta1.AddToScheme(s)
+
+	sysWorkload := v1beta1.WorkloadDefinition{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "sys-worker",
+			Namespace: oam.SystemDefinitionNamespace,
+		},
+	}
+	userWorkload := v1beta1.WorkloadDefinition{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "user-worker",
+			Namespace: "my-ns",
+		},
+	}
+
+	t.Run("list from both user and system namespaces", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(&sysWorkload, &userWorkload).Build()
+		c := common.Args{}
+		c.SetClient(k8sClient)
+
+		defs, err := ListRawWorkloadDefinitions("my-ns", c)
+		assert.NoError(t, err)
+		assert.Equal(t, 2, len(defs))
+	})
+
+	t.Run("list from only system namespace", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(&sysWorkload).Build()
+		c := common.Args{}
+		c.SetClient(k8sClient)
+
+		defs, err := ListRawWorkloadDefinitions("my-ns", c)
+		assert.NoError(t, err)
+		assert.Equal(t, 1, len(defs))
+		assert.Equal(t, "sys-worker", defs[0].Name)
+	})
+
+	t.Run("list from only user namespace", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(&userWorkload).Build()
+		c := common.Args{}
+		c.SetClient(k8sClient)
+
+		defs, err := ListRawWorkloadDefinitions("my-ns", c)
+		assert.NoError(t, err)
+		assert.Equal(t, 1, len(defs))
+		assert.Equal(t, "user-worker", defs[0].Name)
+	})
+
+	t.Run("no definitions found", func(t *testing.T) {
+		k8sClient := fake.NewClientBuilder().WithScheme(s).Build()
+		c := common.Args{}
+		c.SetClient(k8sClient)
+
+		defs, err := ListRawWorkloadDefinitions("my-ns", c)
+		assert.NoError(t, err)
+		assert.Equal(t, 0, len(defs))
+	})
+}
diff --git a/references/common/workload_test.go b/references/common/workload_test.go
new file mode 100644
index 00000000..4549d95a
--- /dev/null
+++ b/references/common/workload_test.go
@@ -0,0 +1,106 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package common
+
+import (
+	"testing"
+
+	"github.com/spf13/pflag"
+	"github.com/stretchr/testify/assert"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
+
+	corecommon "github.com/oam-dev/kubevela/apis/core.oam.dev/common"
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
+	"github.com/oam-dev/kubevela/apis/types"
+	"github.com/oam-dev/kubevela/pkg/oam"
+	"github.com/oam-dev/kubevela/pkg/utils/common"
+)
+
+func TestInitApplication(t *testing.T) {
+	c := common.Args{}
+	c.SetClient(fake.NewClientBuilder().Build())
+
+	t.Run("with appGroup", func(t *testing.T) {
+		app, err := InitApplication("default", c, "my-workload", "my-app")
+		assert.NoError(t, err)
+		assert.NotNil(t, app)
+		assert.Equal(t, "my-app", app.Name)
+	})
+
+	t.Run("without appGroup", func(t *testing.T) {
+		app, err := InitApplication("default", c, "my-workload", "")
+		assert.NoError(t, err)
+		assert.NotNil(t, app)
+		assert.Equal(t, "my-workload", app.Name)
+	})
+}
+
+func TestBaseComplete(t *testing.T) {
+	s := runtime.NewScheme()
+	assert.NoError(t, v1beta1.AddToScheme(s))
+
+	template := &v1beta1.ComponentDefinition{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "worker",
+			Namespace: oam.SystemDefinitionNamespace,
+		},
+		Spec: v1beta1.ComponentDefinitionSpec{
+			Workload: corecommon.WorkloadTypeDescriptor{
+				Type: types.AutoDetectWorkloadDefinition,
+			},
+			Schematic: &corecommon.Schematic{
+				CUE: &corecommon.CUE{
+					Template: `
+parameter: {
+	image: string
+	port: *8080 | int
+}
+`,
+				},
+			},
+		},
+	}
+	k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(template).Build()
+	c := common.Args{}
+	c.SetClient(k8sClient)
+
+	t.Run("success", func(t *testing.T) {
+		flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
+		flagSet.String("image", "my-image", "")
+		flagSet.Int64("port", 80, "")
+
+		app, err := BaseComplete(oam.SystemDefinitionNamespace, c, "my-workload", "my-app", flagSet, "worker")
+		assert.NoError(t, err)
+		assert.NotNil(t, app)
+
+		workload, ok := app.Services["my-workload"]
+		assert.True(t, ok)
+		assert.Equal(t, "my-image", workload["image"])
+		assert.Equal(t, int64(80), workload["port"])
+	})
+
+	t.Run("missing required flag", func(t *testing.T) {
+		flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
+		// not setting the required "image" flag
+
+		_, err := BaseComplete(oam.SystemDefinitionNamespace, c, "my-workload", "my-app", flagSet, "worker")
+		assert.Error(t, err)
+		assert.Contains(t, err.Error(), `required flag(s) "image" not set`)
+	})
+}
diff --git a/references/cuegen/convert_test.go b/references/cuegen/convert_test.go
index 9a5721d4..6b5a5aa3 100644
--- a/references/cuegen/convert_test.go
+++ b/references/cuegen/convert_test.go
@@ -19,11 +19,16 @@ package cuegen
 import (
 	"bytes"
 	goast "go/ast"
+	"go/importer"
+	"go/parser"
+	"go/token"
+	"go/types"
 	"os"
 	"path/filepath"
 	"strings"
 	"testing"
 
+	cueast "cuelang.org/go/cue/ast"
 	"github.com/stretchr/testify/assert"
 )
 
@@ -88,3 +93,200 @@ func TestConvertNullable(t *testing.T) {
 
 	assert.Equal(t, got.String(), string(want))
 }
+
+func TestMakeComment(t *testing.T) {
+	cases := []struct {
+		name string
+		in   *goast.CommentGroup
+		out  []string
+	}{
+		{
+			name: "nil comment",
+			in:   nil,
+			out:  nil,
+		},
+		{
+			name: "empty comment",
+			in:   &goast.CommentGroup{},
+			out:  nil,
+		},
+		{
+			name: "line comment",
+			in: &goast.CommentGroup{
+				List: []*goast.Comment{
+					{Text: "// hello"},
+					{Text: "// world"},
+				},
+			},
+			out: []string{"// hello", "// world"},
+		},
+		{
+			name: "block comment",
+			in: &goast.CommentGroup{
+				List: []*goast.Comment{
+					{Text: "/* hello world */"},
+				},
+			},
+			out: []string{"// hello world "},
+		},
+		{
+			name: "multiline block comment",
+			in: &goast.CommentGroup{
+				List: []*goast.Comment{
+					{Text: `/*
+ * hello
+ * world
+ */`},
+				},
+			},
+			out: []string{"// * hello", "// * world", "//"},
+		},
+		{
+			name: "multiline block comment with no space",
+			in: &goast.CommentGroup{
+				List: []*goast.Comment{
+					{Text: `/*
+hello
+world
+*/`},
+				},
+			},
+			out: []string{"// hello", "// world", "//"},
+		},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			cg := makeComment(tc.in)
+			if cg == nil {
+				assert.Nil(t, tc.out)
+				return
+			}
+			var comments []string
+			for _, c := range cg.List {
+				comments = append(comments, c.Text)
+			}
+			assert.Equal(t, tc.out, comments)
+		})
+	}
+}
+
+func typeFromSource(t *testing.T, src string) types.Type {
+	fset := token.NewFileSet()
+	fullSrc := "package p\n\n" + src
+	f, err := parser.ParseFile(fset, "src.go", fullSrc, 0)
+	assert.NoError(t, err)
+
+	conf := types.Config{Importer: importer.Default()}
+	pkg, err := conf.Check("p", fset, []*goast.File{f}, nil)
+	assert.NoError(t, err)
+
+	obj := pkg.Scope().Lookup("T")
+	assert.NotNil(t, obj, "type T not found in source")
+	return obj.Type()
+}
+
+func TestSupportedType(t *testing.T) {
+	cases := []struct {
+		name          string
+		src           string
+		shouldError   bool
+		errorContains string
+	}{
+		{name: "string", src: "type T string", shouldError: false},
+		{name: "pointer", src: "type T *string", shouldError: false},
+		{name: "slice", src: "type T []int", shouldError: false},
+		{name: "map", src: "type T map[string]bool", shouldError: false},
+		{name: "struct", src: "type T struct{ F string }", shouldError: false},
+		{name: "interface", src: "type T interface{}", shouldError: false},
+		{name: "recursive pointer", src: "type T *T", shouldError: true, errorContains: "recursive type"},
+		{name: "recursive struct field", src: "type T struct{ F *T }", shouldError: true, errorContains: "recursive type"},
+		{name: "map with non-string key", src: "type T map[int]string", shouldError: true, errorContains: "unsupported map key type"},
+		{name: "map with struct key", src: `type U struct{}
+		type T map[U]string`, shouldError: true, errorContains: "unsupported map key type"}}
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			typ := typeFromSource(t, tc.src)
+			err := supportedType(nil, typ)
+
+			if tc.shouldError {
+				assert.Error(t, err)
+				if tc.errorContains != "" {
+					assert.Contains(t, err.Error(), tc.errorContains)
+				}
+			} else {
+				assert.NoError(t, err)
+			}
+		})
+	}
+}
+
+func TestEnumField(t *testing.T) {
+	// Create a dummy generator. The actual fields of Generator are not used by enumField
+	// except for g.opts.types, which is empty here.
+	g := &Generator{}
+
+	defVal1 := "val1"
+	def1 := "1"
+
+	cases := []struct {
+		name        string
+		typSrc      string
+		opts        *tagOptions
+		expectedErr bool
+		expectedCue cueast.Expr
+	}{
+		{
+			name:        "string enum",
+			typSrc:      "type T string",
+			opts:        &tagOptions{Enum: []string{"val1", "val2"}},
+			expectedErr: true,
+		},
+		{
+			name:        "int enum",
+			typSrc:      "type T int",
+			opts:        &tagOptions{Enum: []string{"1", "2"}},
+			expectedErr: true,
+		},
+		{
+			name:        "string enum with default",
+			typSrc:      "type T string",
+			opts:        &tagOptions{Enum: []string{"val1", "val2"}, Default: &defVal1},
+			expectedErr: true,
+		},
+		{
+			name:        "int enum with default",
+			typSrc:      "type T int",
+			opts:        &tagOptions{Enum: []string{"1", "2"}, Default: &def1},
+			expectedErr: true,
+		},
+		{
+			name:        "unsupported type for enum",
+			typSrc:      "type T struct{}",
+			opts:        &tagOptions{Enum: []string{"val1"}},
+			expectedErr: true,
+		},
+		{
+			name:        "invalid enum value for int type",
+			typSrc:      "type T int",
+			opts:        &tagOptions{Enum: []string{"not_an_int"}},
+			expectedErr: true,
+		},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			typ := typeFromSource(t, tc.typSrc)
+			expr, err := g.enumField(typ, tc.opts)
+
+			if tc.expectedErr {
+				assert.Error(t, err)
+				assert.Nil(t, expr)
+			} else {
+				assert.NoError(t, err)
+				assert.Equal(t, tc.expectedCue, expr)
+			}
+		})
+	}
+}
diff --git a/references/cuegen/generator_test.go b/references/cuegen/generator_test.go
index 180da376..5e1d5489 100644
--- a/references/cuegen/generator_test.go
+++ b/references/cuegen/generator_test.go
@@ -18,12 +18,21 @@ package cuegen
 
 import (
 	"io"
+	"os"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 )
 
+// errorWriter is an io.Writer that always returns an error.
+type errorWriter struct{}
+
+func (ew *errorWriter) Write(p []byte) (n int, err error) {
+	return 0, assert.AnError
+}
+
+// testGenerator is a helper function to create a valid Generator for tests.
 func testGenerator(t *testing.T) *Generator {
 	g, err := NewGenerator("testdata/valid.go")
 	require.NoError(t, err)
@@ -34,16 +43,47 @@ func testGenerator(t *testing.T) *Generator {
 }
 
 func TestNewGenerator(t *testing.T) {
-	g := testGenerator(t)
+	cases := []struct {
+		name        string
+		path        string
+		expectedErr bool
+		errContains string
+	}{
+		{
+			name:        "valid package",
+			path:        "testdata/valid.go",
+			expectedErr: false,
+		},
+		{
+			name:        "non-existent package",
+			path:        "testdata/non_existent.go",
+			expectedErr: true,
+			errContains: "could not load Go packages",
+		},
+	}
 
-	assert.NotNil(t, g.pkg)
-	assert.NotNil(t, g.types)
-	assert.Equal(t, g.opts.types, newDefaultOptions().types)
-	assert.Equal(t, g.opts.nullable, newDefaultOptions().nullable)
-	// assert can't compare function
-	assert.True(t, g.opts.typeFilter(nil))
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			g, err := NewGenerator(tc.path)
 
-	assert.Greater(t, len(g.types), 0)
+			if tc.expectedErr {
+				assert.Error(t, err)
+				assert.Nil(t, g)
+				if tc.errContains != "" {
+					assert.Contains(t, err.Error(), tc.errContains)
+				}
+			} else {
+				assert.NoError(t, err)
+				assert.NotNil(t, g)
+				assert.NotNil(t, g.pkg)
+				assert.NotNil(t, g.types)
+				assert.Equal(t, g.opts.types, newDefaultOptions().types)
+				assert.Equal(t, g.opts.nullable, newDefaultOptions().nullable)
+				assert.True(t, g.opts.typeFilter(nil))
+				assert.Greater(t, len(g.types), 0)
+			}
+		})
+	}
 }
 
 func TestGeneratorPackage(t *testing.T) {
@@ -55,41 +95,180 @@ func TestGeneratorPackage(t *testing.T) {
 func TestGeneratorGenerate(t *testing.T) {
 	g := testGenerator(t)
 
-	decls, err := g.Generate(WithTypes(map[string]Type{
-		"foo": TypeAny,
-		"bar": TypeAny,
-	}), nil)
-	assert.NoError(t, err)
-	assert.NotNil(t, decls)
+	cases := []struct {
+		name        string
+		opts        []Option
+		expectedErr bool
+		expectedLen int // Expected number of Decls
+	}{
+		{
+			name:        "no options",
+			opts:        nil,
+			expectedErr: false,
+			expectedLen: 26,
+		},
+		{
+			name: "with types option",
+			opts: []Option{WithTypes(map[string]Type{
+				"foo": TypeAny,
+				"bar": TypeAny,
+			})},
+			expectedErr: false,
+			expectedLen: 26,
+		},
+	}
 
-	decls, err = g.Generate()
-	assert.NoError(t, err)
-	assert.NotNil(t, decls)
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			decls, err := g.Generate(tc.opts...)
+
+			if tc.expectedErr {
+				assert.Error(t, err)
+				assert.Nil(t, decls)
+			} else {
+				assert.NoError(t, err)
+				assert.NotNil(t, decls)
+				assert.Len(t, decls, tc.expectedLen)
+			}
+		})
+	}
 }
 
 func TestGeneratorFormat(t *testing.T) {
 	g := testGenerator(t)
 
 	decls, err := g.Generate()
-	assert.NoError(t, err)
+	require.NoError(t, err)
+	require.NotNil(t, decls)
+
+	cases := []struct {
+		name        string
+		writer      io.Writer
+		decls       []Decl
+		expectedErr bool
+		errContains string
+	}{
+		{
+			name:        "valid format",
+			writer:      io.Discard,
+			decls:       decls,
+			expectedErr: false,
+		},
+		{
+			name:        "nil writer",
+			writer:      nil,
+			decls:       decls,
+			expectedErr: true,
+			errContains: "nil writer",
+		},
+		{
+			name:        "empty decls",
+			writer:      io.Discard,
+			decls:       []Decl{},
+			expectedErr: true,
+			errContains: "invalid decls",
+		},
+		{
+			name:        "writer error",
+			writer:      &errorWriter{},
+			decls:       decls,
+			expectedErr: true,
+			errContains: assert.AnError.Error(),
+		},
+	}
 
-	assert.NoError(t, g.Format(io.Discard, decls))
-	assert.NoError(t, g.Format(io.Discard, []Decl{nil, nil}))
-	assert.Error(t, g.Format(nil, decls))
-	assert.Error(t, g.Format(io.Discard, nil))
-	assert.Error(t, g.Format(io.Discard, []Decl{}))
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			err := g.Format(tc.writer, tc.decls)
+
+			if tc.expectedErr {
+				assert.Error(t, err)
+				if tc.errContains != "" {
+					assert.Contains(t, err.Error(), tc.errContains)
+				}
+			} else {
+				assert.NoError(t, err)
+			}
+		})
+	}
 }
 
 func TestLoadPackage(t *testing.T) {
-	pkg, err := loadPackage("testdata/valid.go")
+	cases := []struct {
+		name        string
+		path        string
+		expectedErr bool
+		errContains string
+	}{
+		{
+			name:        "valid package",
+			path:        "testdata/valid.go",
+			expectedErr: false,
+		},
+		{
+			name:        "non-existent package",
+			path:        "testdata/non_existent.go",
+			expectedErr: true,
+			errContains: "could not load Go packages",
+		},
+		{
+			name:        "package with syntax error",
+			path:        "testdata/invalid_syntax.go",
+			expectedErr: true,
+			errContains: "could not load Go packages",
+		},
+	}
+
+	// Create a temporary file with syntax errors for "package with syntax error" case
+	invalidGoContent := `package main
+
+func main { // Missing parentheses
+	fmt.Println("Hello")
+}`
+	err := os.WriteFile("testdata/invalid_syntax.go", []byte(invalidGoContent), 0644)
 	require.NoError(t, err)
-	require.NotNil(t, pkg)
-	require.Len(t, pkg.Errors, 0)
+	t.Cleanup(func() {
+		os.Remove("testdata/invalid_syntax.go")
+	})
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			pkg, err := loadPackage(tc.path)
+
+			if tc.expectedErr {
+				assert.Error(t, err)
+				assert.Nil(t, pkg)
+				if tc.errContains != "" {
+					assert.Contains(t, err.Error(), tc.errContains)
+				}
+			} else {
+				assert.NoError(t, err)
+				assert.NotNil(t, pkg)
+				assert.Len(t, pkg.Errors, 0)
+			}
+		})
+	}
 }
 
 func TestGetTypeInfo(t *testing.T) {
-	pkg, err := loadPackage("testdata/valid.go")
-	require.NoError(t, err)
+	cases := []struct {
+		name        string
+		path        string
+		expectedLen int
+	}{
+		{
+			name:        "valid package",
+			path:        "testdata/valid.go",
+			expectedLen: 40,
+		}}
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			pkg, err := loadPackage(tc.path)
+			require.NoError(t, err)
 
-	require.Greater(t, len(getTypeInfo(pkg)), 0)
+			typeInfo := getTypeInfo(pkg)
+			assert.Len(t, typeInfo, tc.expectedLen)
+		})
+	}
 }
diff --git a/references/cuegen/generators/provider/provider_test.go b/references/cuegen/generators/provider/provider_test.go
index b5b6c382..eab234a1 100644
--- a/references/cuegen/generators/provider/provider_test.go
+++ b/references/cuegen/generators/provider/provider_test.go
@@ -23,6 +23,7 @@ import (
 	"path/filepath"
 	"testing"
 
+	cueast "cuelang.org/go/cue/ast"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 
@@ -30,51 +31,124 @@ import (
 )
 
 func TestGenerate(t *testing.T) {
-	got := bytes.Buffer{}
-	err := Generate(Options{
-		File:   "testdata/valid.go",
-		Writer: &got,
-		Types: map[string]cuegen.Type{
-			"*k8s.io/apimachinery/pkg/apis/meta/v1/unstructured.Unstructured":     cuegen.TypeEllipsis,
-			"*k8s.io/apimachinery/pkg/apis/meta/v1/unstructured.UnstructuredList": cuegen.TypeEllipsis,
-		},
-		Nullable: false,
+	t.Run("valid", func(t *testing.T) {
+		got := bytes.Buffer{}
+		err := Generate(Options{
+			File:   "testdata/valid.go",
+			Writer: &got,
+			Types: map[string]cuegen.Type{
+				"*k8s.io/apimachinery/pkg/apis/meta/v1/unstructured.Unstructured":     cuegen.TypeEllipsis,
+				"*k8s.io/apimachinery/pkg/apis/meta/v1/unstructured.UnstructuredList": cuegen.TypeEllipsis,
+			},
+			Nullable: false,
+		})
+		require.NoError(t, err)
+
+		expected, err := os.ReadFile("testdata/valid.cue")
+		assert.NoError(t, err)
+		assert.Equal(t, string(expected), got.String())
 	})
-	require.NoError(t, err)
 
-	expected, err := os.ReadFile("testdata/valid.cue")
-	assert.NoError(t, err)
+	t.Run("invalid", func(t *testing.T) {
+		if err := filepath.Walk("testdata/invalid", func(path string, info os.FileInfo, e error) error {
+			if e != nil {
+				return e
+			}
 
-	assert.NoError(t, err)
-	assert.Equal(t, string(expected), got.String())
-}
+			if info.IsDir() {
+				return nil
+			}
 
-func TestGenerateInvalid(t *testing.T) {
-	if err := filepath.Walk("testdata/invalid", func(path string, info os.FileInfo, e error) error {
-		if e != nil {
-			return e
-		}
+			err := Generate(Options{
+				File:   path,
+				Writer: io.Discard,
+			})
+			assert.Error(t, err)
 
-		if info.IsDir() {
 			return nil
+		}); err != nil {
+			t.Error(err)
 		}
+	})
 
+	t.Run("empty file", func(t *testing.T) {
 		err := Generate(Options{
-			File:   path,
+			File:   "",
 			Writer: io.Discard,
 		})
 		assert.Error(t, err)
+	})
+}
 
-		return nil
-	}); err != nil {
-		t.Error(err)
+func TestExtractProviders(t *testing.T) {
+	t.Run("valid", func(t *testing.T) {
+		g, err := cuegen.NewGenerator("testdata/valid.go")
+		require.NoError(t, err)
+		providers, err := extractProviders(g.Package())
+		require.NoError(t, err)
+		require.Len(t, providers, 4)
+		assert.Equal(t, `"apply"`, providers[0].name)
+		assert.Equal(t, "ResourceParams", providers[0].params)
+		assert.Equal(t, "ResourceReturns", providers[0].returns)
+		assert.Equal(t, "Apply", providers[0].do)
+	})
+
+	t.Run("no provider map", func(t *testing.T) {
+		g, err := cuegen.NewGenerator("testdata/invalid/no_provider_map.go")
+		require.NoError(t, err)
+		_, err = extractProviders(g.Package())
+		assert.EqualError(t, err, "no provider function map found like 'map[string]github.com/kubevela/pkg/cue/cuex/runtime.ProviderFn'")
+	})
+}
+
+func TestModifyDecls(t *testing.T) {
+	tests := []struct {
+		name      string
+		decls     []cuegen.Decl
+		providers []provider
+		wantLen   int
+	}{
+		{
+			name: "valid",
+			decls: []cuegen.Decl{
+				&cuegen.Struct{CommonFields: cuegen.CommonFields{Name: "Params", Expr: &cueast.StructLit{Elts: []cueast.Decl{&cueast.Field{Label: cueast.NewIdent("p"), Value: cueast.NewIdent("string")}}}}},
+				&cuegen.Struct{CommonFields: cuegen.CommonFields{Name: "Returns", Expr: &cueast.StructLit{Elts: []cueast.Decl{&cueast.Field{Label: cueast.NewIdent("r"), Value: cueast.NewIdent("string")}}}}},
+			},
+			providers: []provider{
+				{name: `"my-do"`, params: "Params", returns: "Returns", do: "MyDo"},
+			},
+			wantLen: 1,
+		},
+		{
+			name:      "no providers",
+			decls:     []cuegen.Decl{},
+			providers: []provider{},
+			wantLen:   0,
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			newDecls, err := modifyDecls("my-provider", tt.decls, tt.providers)
+			require.NoError(t, err)
+			require.Len(t, newDecls, tt.wantLen)
+			if tt.wantLen > 0 {
+				s, ok := newDecls[0].(*cuegen.Struct)
+				require.True(t, ok)
+				assert.Equal(t, "#MyDo", s.Name)
+				require.Len(t, s.Expr.(*cueast.StructLit).Elts, 4)
+			}
+		})
 	}
 }
 
-func TestGenerateEmptyError(t *testing.T) {
-	err := Generate(Options{
-		File:   "",
-		Writer: io.Discard,
+func TestRecoverAssert(t *testing.T) {
+	t.Run("panic recovery", func(t *testing.T) {
+		var err error
+		func() {
+			defer recoverAssert(&err, "test panic")
+			panic("panic message")
+		}()
+		assert.EqualError(t, err, "panic message: panic: test panic")
 	})
-	assert.Error(t, err)
 }
diff --git a/references/docgen/console_test.go b/references/docgen/console_test.go
new file mode 100644
index 00000000..227b7b68
--- /dev/null
+++ b/references/docgen/console_test.go
@@ -0,0 +1,187 @@
+/*
+Copyright 2021 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package docgen
+
+import (
+	"os"
+	"testing"
+
+	"github.com/google/go-cmp/cmp"
+	"github.com/stretchr/testify/require"
+	"sigs.k8s.io/yaml"
+
+	"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
+	"github.com/oam-dev/kubevela/apis/types"
+)
+
+func TestGenerateCUETemplateProperties(t *testing.T) {
+	// Read componentDef for a valid capability
+	componentDefYAML, err := os.ReadFile("testdata/componentDef.yaml")
+	require.NoError(t, err)
+	var componentDef v1beta1.ComponentDefinition
+	err = yaml.Unmarshal(componentDefYAML, &componentDef)
+	require.NoError(t, err)
+
+	// Define a struct to unmarshal the raw extension
+	type extensionSpec struct {
+		Template string `json:"template"`
+	}
+	var extSpec extensionSpec
+	err = yaml.Unmarshal(componentDef.Spec.Extension.Raw, &extSpec)
+	require.NoError(t, err)
+
+	// Define test cases
+	testCases := []struct {
+		name           string
+		capability     *types.Capability
+		expectedTables int
+		expectErr      bool
+	}{
+		{
+			name: "valid component definition",
+			capability: &types.Capability{
+				Name:        "test-component",
+				CueTemplate: extSpec.Template,
+			},
+			expectedTables: 2,
+			expectErr:      false,
+		},
+		{
+			name: "invalid cue template",
+			capability: &types.Capability{
+				Name:        "invalid-cue",
+				CueTemplate: `parameter: { image: }`,
+			},
+			expectErr: true,
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			ref := &ConsoleReference{}
+			doc, console, err := ref.GenerateCUETemplateProperties(tc.capability)
+
+			if tc.expectErr {
+				require.Error(t, err)
+				return
+			}
+
+			require.NoError(t, err)
+			require.NotNil(t, doc)
+			require.Len(t, console, tc.expectedTables)
+		})
+	}
+}
+
+func TestGenerateTerraformCapabilityProperties(t *testing.T) {
+	ref := &ConsoleReference{}
+	type args struct {
+		cap types.Capability
+	}
+
+	type want struct {
+		tableName1 string
+		tableName2 string
+		errMsg     string
+	}
+	testcases := map[string]struct {
+		args args
+		want want
+	}{
+		"normal": {
+			args: args{
+				cap: types.Capability{
+					TerraformConfiguration: `
+resource "alicloud_oss_bucket" "bucket-acl" {
+  bucket = var.bucket
+  acl = var.acl
+}
+
+output "BUCKET_NAME" {
+  value = "${alicloud_oss_bucket.bucket-acl.bucket}.${alicloud_oss_bucket.bucket-acl.extranet_endpoint}"
+}
+
+variable "bucket" {
+  description = "OSS bucket name"
+  default = "vela-website"
+  type = string
+}
+
+variable "acl" {
+  description = "OSS bucket ACL, supported 'private', 'public-read', 'public-read-write'"
+  default = "private"
+  type = string
+}
+`,
+				},
+			},
+			want: want{
+				errMsg:     "",
+				tableName1: "",
+				tableName2: "#### writeConnectionSecretToRef",
+			},
+		},
+		"configuration is in git remote": {
+			args: args{
+				cap: types.Capability{
+					Name:                   "ecs",
+					TerraformConfiguration: "https://github.com/wonderflow/terraform-alicloud-ecs-instance.git",
+					ConfigurationType:      "remote",
+				},
+			},
+			want: want{
+				errMsg:     "",
+				tableName1: "",
+				tableName2: "#### writeConnectionSecretToRef",
+			},
+		},
+		"configuration is not valid": {
+			args: args{
+				cap: types.Capability{
+					TerraformConfiguration: `abc`,
+				},
+			},
+			want: want{
+				errMsg: "failed to generate capability properties: :1,1-4: Argument or block definition required; An " +
+					"argument or block definition is required here. To set an argument, use the equals sign \"=\" to " +
+					"introduce the argument value.",
+			},
+		},
+	}
+	for name, tc := range testcases {
+		t.Run(name, func(t *testing.T) {
+			consoleRef, err := ref.GenerateTerraformCapabilityProperties(tc.args.cap)
+			var errMsg string
+			if err != nil {
+				errMsg = err.Error()
+				if diff := cmp.Diff(tc.want.errMsg, errMsg); diff != "" {
+					t.Errorf("\n%s\nGenerateTerraformCapabilityProperties(...): -want error, +got error:\n%s\n", name, diff)
+				}
+			} else {
+				if diff := cmp.Diff(2, len(consoleRef)); diff != "" {
+					t.Errorf("\n%s\nGenerateTerraformCapabilityProperties(...): -want, +got:\n%s\n", name, diff)
+				}
+				if diff := cmp.Diff(tc.want.tableName1, consoleRef[0].TableName); diff != "" {
+					t.Errorf("\n%s\nGenerateTerraformCapabilityProperties(...): -want, +got:\n%s\n", name, diff)
+				}
+				if diff := cmp.Diff(tc.want.tableName2, consoleRef[1].TableName); diff != "" {
+					t.Errorf("\n%s\nGenerateTerraformCapabilityProperties(...): -want, +got:\n%s\n", name, diff)
+				}
+			}
+		})
+	}
+}
diff --git a/references/docgen/convert_test.go b/references/docgen/convert_test.go
new file mode 100644
index 00000000..1d95f72f
--- /dev/null
+++ b/references/docgen/convert_test.go
@@ -0,0 +1,186 @@
+/*
+ Copyright 2022 The KubeVela Authors.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ 	http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+package docgen
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/require"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+
+	"github.com/oam-dev/kubevela/apis/types"
+)
+
+func TestParseCapabilityFromUnstructured(t *testing.T) {
+	testCases := []struct {
+		name       string
+		obj        unstructured.Unstructured
+		wantCap    types.Capability
+		wantErr    bool
+		wantErrMsg string
+	}{
+		{
+			name: "trait definition",
+			obj: unstructured.Unstructured{
+				Object: map[string]interface{}{
+					"apiVersion": "core.oam.dev/v1beta1",
+					"kind":       "TraitDefinition",
+					"metadata": map[string]interface{}{
+						"name": "my-trait",
+					},
+					"spec": map[string]interface{}{
+						"appliesToWorkloads": []interface{}{"webservice", "worker"},
+						"schematic": map[string]interface{}{
+							"cue": map[string]interface{}{
+								"template": "parameter: {}",
+							},
+						},
+					},
+				},
+			},
+			wantCap: types.Capability{
+				Name:      "my-trait",
+				Type:      types.TypeTrait,
+				AppliesTo: []string{"webservice", "worker"},
+			},
+			wantErr: false,
+		},
+		{
+			name: "component definition",
+			obj: unstructured.Unstructured{
+				Object: map[string]interface{}{
+					"apiVersion": "core.oam.dev/v1beta1",
+					"kind":       "ComponentDefinition",
+					"metadata": map[string]interface{}{
+						"name": "my-comp",
+					},
+					"spec": map[string]interface{}{
+						"workload": map[string]interface{}{
+							"type": "worker",
+						},
+						"schematic": map[string]interface{}{
+							"cue": map[string]interface{}{
+								"template": "parameter: {}",
+							},
+						},
+					},
+				},
+			}, wantCap: types.Capability{
+				Name: "my-comp",
+				Type: types.TypeComponentDefinition,
+			},
+			wantErr: false,
+		},
+		{
+			name: "policy definition",
+			obj: unstructured.Unstructured{
+				Object: map[string]interface{}{
+					"apiVersion": "core.oam.dev/v1beta1",
+					"kind":       "PolicyDefinition",
+					"metadata": map[string]interface{}{
+						"name": "my-policy",
+					},
+					"spec": map[string]interface{}{
+						"schematic": map[string]interface{}{
+							"cue": map[string]interface{}{
+								"template": "parameter: {}",
+							},
+						},
+					},
+				},
+			},
+			wantCap: types.Capability{
+				Name: "my-policy",
+				Type: types.TypePolicy,
+			},
+			wantErr: false,
+		},
+		{
+			name: "workflow step definition",
+			obj: unstructured.Unstructured{
+				Object: map[string]interface{}{
+					"apiVersion": "core.oam.dev/v1beta1",
+					"kind":       "WorkflowStepDefinition",
+					"metadata": map[string]interface{}{
+						"name": "my-step",
+					},
+					"spec": map[string]interface{}{
+						"schematic": map[string]interface{}{
+							"cue": map[string]interface{}{
+								"template": "parameter: {}",
+							},
+						},
+					},
+				},
+			},
+			wantCap: types.Capability{
+				Name: "my-step",
+				Type: types.TypeWorkflowStep,
+			},
+			wantErr: false,
+		},
+		{
+			name: "unknown kind",
+			obj: unstructured.Unstructured{
+				Object: map[string]interface{}{
+					"apiVersion": "core.oam.dev/v1beta1",
+					"kind":       "UnknownKind",
+					"metadata": map[string]interface{}{
+						"name": "my-unknown",
+					},
+				},
+			},
+			wantErr:    true,
+			wantErrMsg: "unknown definition Type UnknownKind",
+		},
+		{
+			name: "malformed spec",
+			obj: unstructured.Unstructured{
+				Object: map[string]interface{}{
+					"apiVersion": "core.oam.dev/v1beta1",
+					"kind":       "TraitDefinition",
+					"metadata": map[string]interface{}{
+						"name": "my-trait",
+					},
+					"spec": "this-should-be-a-map",
+				},
+			},
+			wantErr: true,
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			// The mapper is nil for these cases as they don't rely on it.
+			// A separate test would be needed for the mapper-dependent path.
+			cap, err := ParseCapabilityFromUnstructured(nil, tc.obj)
+
+			if tc.wantErr {
+				require.Error(t, err)
+				if tc.wantErrMsg != "" {
+					require.Contains(t, err.Error(), tc.wantErrMsg)
+				}
+				return
+			}
+
+			require.NoError(t, err)
+			require.Equal(t, tc.wantCap.Name, cap.Name)
+			require.Equal(t, tc.wantCap.Type, cap.Type)
+			require.Equal(t, tc.wantCap.AppliesTo, cap.AppliesTo)
+		})
+	}
+}
diff --git a/references/docgen/i18n_test.go b/references/docgen/i18n_test.go
index b728f4df..26fe4a4a 100644
--- a/references/docgen/i18n_test.go
+++ b/references/docgen/i18n_test.go
@@ -21,34 +21,83 @@ import (
 	"net/http"
 	"net/http/httptest"
 	"testing"
-	"time"
 
 	"github.com/stretchr/testify/assert"
 )
 
-func TestLoad(t *testing.T) {
-	svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprintf(w, `{"Outputs":{"Chinese":"输出"}}`)
-	}))
-	defer svr.Close()
-	time.Sleep(time.Millisecond)
-	assert.Equal(t, En.Language(), Language("English"))
-	assert.Equal(t, En.Get("nihaoha"), "nihaoha")
-	assert.Equal(t, En.Get("AlibabaCloud"), "Alibaba Cloud")
-	var ni *I18n
-	assert.Equal(t, ni.Get("AlibabaCloud"), "Alibaba Cloud")
-	assert.Equal(t, ni.Get("AlibabaCloud."), "Alibaba Cloud")
-	assert.Equal(t, ni.Get("AlibabaCloud。"), "Alibaba Cloud")
-	assert.Equal(t, ni.Get("AlibabaCloud。 "), "Alibaba Cloud")
-	assert.Equal(t, ni.Get("AlibabaCloud 。 "), "Alibaba Cloud")
-	assert.Equal(t, ni.Get("AlibabaCloud \n "), "Alibaba Cloud")
-	assert.Equal(t, ni.Get(" A\n "), "A")
-	assert.Equal(t, ni.Get(" \n "), "")
-
-	assert.Equal(t, Zh.Language(), Language("Chinese"))
-	assert.Equal(t, Zh.Get("nihaoha"), "nihaoha")
-	assert.Equal(t, Zh.Get("AlibabaCloud"), "阿里云")
-
-	LoadI18nData(svr.URL)
-	assert.Equal(t, Zh.Get("Outputs"), "输出")
+func TestI18n(t *testing.T) {
+	t.Run("English defaults", func(t *testing.T) {
+		assert.Equal(t, En.Language(), Language("English"))
+		assert.Equal(t, En.Get("nihaoha"), "nihaoha")
+		assert.Equal(t, En.Get("AlibabaCloud"), "Alibaba Cloud")
+	})
+
+	t.Run("Chinese defaults", func(t *testing.T) {
+		assert.Equal(t, Zh.Language(), Language("Chinese"))
+		assert.Equal(t, Zh.Get("nihaoha"), "nihaoha")
+		assert.Equal(t, Zh.Get("AlibabaCloud"), "阿里云")
+	})
+
+	t.Run("nil receiver", func(t *testing.T) {
+		var ni *I18n
+		assert.Equal(t, ni.Get("AlibabaCloud"), "Alibaba Cloud")
+		assert.Equal(t, ni.Get("AlibabaCloud."), "Alibaba Cloud")
+		assert.Equal(t, ni.Get("AlibabaCloud。"), "Alibaba Cloud")
+		assert.Equal(t, ni.Get("AlibabaCloud。 "), "Alibaba Cloud")
+		assert.Equal(t, ni.Get("AlibabaCloud 。 "), "Alibaba Cloud")
+		assert.Equal(t, ni.Get("AlibabaCloud \n "), "Alibaba Cloud")
+		assert.Equal(t, ni.Get(" A\n "), "A")
+		assert.Equal(t, ni.Get(" \n "), "")
+	})
+
+	t.Run("Get with fallback logic", func(t *testing.T) {
+		// Test suffix trimming
+		assert.Equal(t, "Description", En.Get("Description."))
+		assert.Equal(t, "描述", Zh.Get("描述。"))
+
+		// Test lowercase fallback (Note: this reveals a bug, as it doesn't find the capitalized key)
+		assert.Equal(t, "description", En.Get("description"))
+		assert.Equal(t, "description", Zh.Get("description"))
+	})
+}
+
+func TestLoadI18nData(t *testing.T) {
+	t.Run("Load external data", func(t *testing.T) {
+		svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			_, _ = fmt.Fprintf(w, `{"Outputs":{"Chinese":"输出"}}`)
+		}))
+		defer svr.Close()
+		LoadI18nData(svr.URL)
+		assert.Equal(t, "输出", Zh.Get("Outputs"))
+	})
+}
+
+func TestLoadI18nDataErrors(t *testing.T) {
+	t.Run("http error", func(t *testing.T) {
+		// Check that a non-existent key is not translated before the call
+		assert.Equal(t, "TestKey", Zh.Get("TestKey"))
+
+		svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			w.WriteHeader(http.StatusNotFound)
+		}))
+		defer svr.Close()
+		LoadI18nData(svr.URL)
+
+		// Assert that the key is still not translated
+		assert.Equal(t, "TestKey", Zh.Get("TestKey"))
+	})
+
+	t.Run("malformed json", func(t *testing.T) {
+		// Check that another non-existent key is not translated
+		assert.Equal(t, "AnotherKey", Zh.Get("AnotherKey"))
+
+		svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			_, _ = fmt.Fprint(w, `this-is-not-json`)
+		}))
+		defer svr.Close()
+		LoadI18nData(svr.URL)
+
+		// Assert that the key is still not translated
+		assert.Equal(t, "AnotherKey", Zh.Get("AnotherKey"))
+	})
 }
diff --git a/references/docgen/openapi_test.go b/references/docgen/openapi_test.go
new file mode 100644
index 00000000..5bb2aec2
--- /dev/null
+++ b/references/docgen/openapi_test.go
@@ -0,0 +1,126 @@
+/*
+Copyright 2022 The KubeVela Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package docgen
+
+import (
+	"sort"
+	"strings"
+	"testing"
+
+	"github.com/getkin/kin-openapi/openapi3"
+	"github.com/stretchr/testify/require"
+)
+
+func TestGenerateConsoleDocument(t *testing.T) {
+	testCases := []struct {
+		name       string
+		title      string
+		schema     *openapi3.Schema
+		wantOutput string
+		wantErr    bool
+	}{
+		{
+			name:       "empty schema",
+			title:      "Test",
+			schema:     &openapi3.Schema{},
+			wantOutput: "",
+		},
+		{
+			name:  "simple schema",
+			title: "",
+			schema: &openapi3.Schema{
+				Properties: map[string]*openapi3.SchemaRef{
+					"name": {
+						Value: &openapi3.Schema{
+							Title:       "name",
+							Description: "The name of the resource.",
+							Type:        &openapi3.Types{openapi3.TypeString},
+						},
+					},
+					"port": {
+						Value: &openapi3.Schema{
+							Title:       "port",
+							Description: "The port to expose.",
+							Type:        &openapi3.Types{openapi3.TypeInteger},
+						},
+					},
+				},
+			},
+			wantOutput: `
++------+---------+---------------------------+----------+---------+---------+
+| NAME |  TYPE   |        DESCRIPTION        | REQUIRED | OPTIONS | DEFAULT |
++------+---------+---------------------------+----------+---------+---------+
+| name | string  | The name of the resource. | false    |         |         |
+| port | integer | The port to expose.       | false    |         |         |
++------+---------+---------------------------+----------+---------+---------+
+`,
+		},
+		{
+			name:  "nested schema",
+			title: "parent",
+			schema: &openapi3.Schema{
+				Required: []string{"child"},
+				Properties: map[string]*openapi3.SchemaRef{
+					"child": {
+						Value: &openapi3.Schema{
+							Title: "child",
+							Type:  &openapi3.Types{openapi3.TypeObject},
+							Properties: map[string]*openapi3.SchemaRef{
+								"leaf": {
+									Value: &openapi3.Schema{
+										Title: "leaf",
+										Type:  &openapi3.Types{openapi3.TypeString},
+									},
+								},
+							},
+						},
+					},
+				},
+			},
+			wantOutput: `parent
++----------------+--------+-------------+----------+---------+---------+
+|      NAME      |  TYPE  | DESCRIPTION | REQUIRED | OPTIONS | DEFAULT |
++----------------+--------+-------------+----------+---------+---------+
+| (parent).child | object |             | true     |         |         |
++----------------+--------+-------------+----------+---------+---------+
+parent.child
++---------------------+--------+-------------+----------+---------+---------+
+|        NAME         |  TYPE  | DESCRIPTION | REQUIRED | OPTIONS | DEFAULT |
++---------------------+--------+-------------+----------+---------+---------+
+| (parent.child).leaf | string |             | false    |         |         |
++---------------------+--------+-------------+----------+---------+---------+
+`,
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			doc, err := GenerateConsoleDocument(tc.title, tc.schema)
+			if tc.wantErr {
+				require.Error(t, err)
+				return
+			}
+			require.NoError(t, err)
+			// Trim whitespace for consistent comparison and sort lines to avoid flakiness
+			expectedLines := strings.Split(strings.TrimSpace(tc.wantOutput), "\n")
+			actualLines := strings.Split(strings.TrimSpace(doc), "\n")
+			sort.Strings(expectedLines)
+			sort.Strings(actualLines)
+			require.Equal(t, expectedLines, actualLines)
+		})
+	}
+}
diff --git a/references/docgen/parser_test.go b/references/docgen/parser_test.go
index c01c48b4..38ad0c4e 100644
--- a/references/docgen/parser_test.go
+++ b/references/docgen/parser_test.go
@@ -24,7 +24,6 @@ import (
 	"reflect"
 	"testing"
 
-	"github.com/crossplane/crossplane-runtime/pkg/test"
 	"github.com/getkin/kin-openapi/openapi3"
 	"github.com/google/go-cmp/cmp"
 	"github.com/stretchr/testify/assert"
@@ -262,103 +261,6 @@ func TestWalkParameterSchema(t *testing.T) {
 	}
 }
 
-func TestGenerateTerraformCapabilityProperties(t *testing.T) {
-	ref := &ConsoleReference{}
-	type args struct {
-		cap types.Capability
-	}
-
-	type want struct {
-		tableName1 string
-		tableName2 string
-		errMsg     string
-	}
-	testcases := map[string]struct {
-		args args
-		want want
-	}{
-		"normal": {
-			args: args{
-				cap: types.Capability{
-					TerraformConfiguration: `
-resource "alicloud_oss_bucket" "bucket-acl" {
-  bucket = var.bucket
-  acl = var.acl
-}
-
-output "BUCKET_NAME" {
-  value = "${alicloud_oss_bucket.bucket-acl.bucket}.${alicloud_oss_bucket.bucket-acl.extranet_endpoint}"
-}
-
-variable "bucket" {
-  description = "OSS bucket name"
-  default = "vela-website"
-  type = string
-}
-
-variable "acl" {
-  description = "OSS bucket ACL, supported 'private', 'public-read', 'public-read-write'"
-  default = "private"
-  type = string
-}
-`,
-				},
-			},
-			want: want{
-				errMsg:     "",
-				tableName1: "",
-				tableName2: "#### writeConnectionSecretToRef",
-			},
-		},
-		"configuration is in git remote": {
-			args: args{
-				cap: types.Capability{
-					Name:                   "ecs",
-					TerraformConfiguration: "https://github.com/wonderflow/terraform-alicloud-ecs-instance.git",
-					ConfigurationType:      "remote",
-				},
-			},
-			want: want{
-				errMsg:     "",
-				tableName1: "",
-				tableName2: "#### writeConnectionSecretToRef",
-			},
-		},
-		"configuration is not valid": {
-			args: args{
-				cap: types.Capability{
-					TerraformConfiguration: `abc`,
-				},
-			},
-			want: want{
-				errMsg: "failed to generate capability properties: :1,1-4: Argument or block definition required; An " +
-					"argument or block definition is required here. To set an argument, use the equals sign \"=\" to " +
-					"introduce the argument value.",
-			},
-		},
-	}
-	for name, tc := range testcases {
-		consoleRef, err := ref.GenerateTerraformCapabilityProperties(tc.args.cap)
-		var errMsg string
-		if err != nil {
-			errMsg = err.Error()
-			if diff := cmp.Diff(tc.want.errMsg, errMsg, test.EquateErrors()); diff != "" {
-				t.Errorf("\n%s\nGenerateTerraformCapabilityProperties(...): -want error, +got error:\n%s\n", name, diff)
-			}
-		} else {
-			if diff := cmp.Diff(len(consoleRef), 2); diff != "" {
-				t.Errorf("\n%s\nGenerateTerraformCapabilityProperties(...): -want, +got:\n%s\n", name, diff)
-			}
-			if diff := cmp.Diff(tc.want.tableName1, consoleRef[0].TableName); diff != "" {
-				t.Errorf("\n%s\nGenerateTerraformCapabilityProperties(...): -want, +got:\n%s\n", name, diff)
-			}
-			if diff := cmp.Diff(tc.want.tableName2, consoleRef[1].TableName); diff != "" {
-				t.Errorf("\n%s\nGexnerateTerraformCapabilityProperties(...): -want, +got:\n%s\n", name, diff)
-			}
-		}
-	}
-}
-
 func TestPrepareTerraformOutputs(t *testing.T) {
 	type args struct {
 		tableName     string
@@ -749,7 +651,7 @@ func TestExtractParameterFromFiles(t *testing.T) {
  containerName | Specify the name of the target container, if not set, use the component name. | string | false | empty 
  replace | Specify if replacing the whole environment settings for the container. | bool | false | false 
  env | Specify the  environment variables to merge, if key already existing, override its value. | map[string]string | true |  
- unset | Specify which existing environment variables to unset. | []string | true |  
+ unset | Specify which existing environment variables to unset. | list | true |  
 
 
 #### type-option-2
@@ -766,7 +668,7 @@ func TestExtractParameterFromFiles(t *testing.T) {
  containerName | Specify the name of the target container, if not set, use the component name. | string | false | empty 
  replace | Specify if replacing the whole environment settings for the container. | bool | false | false 
  env | Specify the  environment variables to merge, if key already existing, override its value. | map[string]string | true |  
- unset | Specify which existing environment variables to unset. | []string | true |`,
+ unset | Specify which existing environment variables to unset. | list | true |`,
 		},
 		"command": {
 			path: "testdata/parameter/command.cue",
@@ -819,8 +721,8 @@ func TestExtractParameterFromFiles(t *testing.T) {
  Name | Description | Type | Required | Default 
  ---- | ----------- | ---- | -------- | ------- 
  name |  | string | true |  
- defaultMode | only works when type equals configmap. | int | false | 420 
- type |  | "configMap" or "secret" or "emptyDir" or "ephemeral" | false | configMap`,
+ type |  | "configMap" or "secret" or "emptyDir" or "ephemeral" | false | configMap 
+ defaultMode | only works when type equals configmap. | int | false | 420 `,
 		},
 	}
 	for key, ca := range testcases {
diff --git a/test/e2e-multicluster-test/multicluster_standalone_test.go b/test/e2e-multicluster-test/multicluster_standalone_test.go
index 882a827a..1eb44e2a 100644
--- a/test/e2e-multicluster-test/multicluster_standalone_test.go
+++ b/test/e2e-multicluster-test/multicluster_standalone_test.go
@@ -291,28 +291,28 @@ var _ = Describe("Test multicluster standalone scenario", func() {
 		Eventually(func(g Gomega) {
 			g.Expect(k8sClient.Get(hubCtx, appKey, app)).Should(Succeed())
 			g.Expect(app.Status.Phase).Should(Equal(oamcomm.ApplicationRunning))
-		}).WithTimeout(5 * time.Minute).WithPolling(5 * time.Second).Should(Succeed())
+		}).WithTimeout(10 * time.Minute).WithPolling(5 * time.Second).Should(Succeed())
 
 		By("Verify deployment image rollback")
 		Eventually(func(g Gomega) {
 			deploy := &v1.Deployment{}
 			g.Expect(k8sClient.Get(workerCtx, types.NamespacedName{Namespace: namespace, Name: "busybox"}, deploy)).Should(Succeed())
 			g.Expect(deploy.Spec.Template.Spec.Containers[0].Image).Should(Equal("busybox"))
-		}).WithTimeout(5 * time.Minute).WithPolling(5 * time.Second).Should(Succeed())
+		}).WithTimeout(10 * time.Minute).WithPolling(5 * time.Second).Should(Succeed())
 
 		By("Verify referred object state rollback")
 		Eventually(func(g Gomega) {
 			deploy := &v1.Deployment{}
 			g.Expect(k8sClient.Get(workerCtx, types.NamespacedName{Namespace: namespace, Name: "busybox-ref"}, deploy)).Should(Succeed())
 			g.Expect(deploy.Spec.Replicas).Should(Equal(ptr.To(int32(0))))
-		}).WithTimeout(5 * time.Minute).WithPolling(5 * time.Second).Should(Succeed())
+		}).WithTimeout(10 * time.Minute).WithPolling(5 * time.Second).Should(Succeed())
 
 		By("Verify application revisions")
 		Eventually(func(g Gomega) {
 			revs, err := application.GetSortedAppRevisions(hubCtx, k8sClient, app.Name, namespace)
 			g.Expect(err).Should(Succeed())
 			g.Expect(len(revs)).Should(BeNumerically(">=", 1))
-		}).WithTimeout(5 * time.Minute).WithPolling(5 * time.Second).Should(Succeed())
+		}).WithTimeout(10 * time.Minute).WithPolling(5 * time.Second).Should(Succeed())
 	})
 
 	It("Test large application parallel apply and delete", func() {
diff --git a/test/e2e-test/testdata/definition/replica-webservice.yaml b/test/e2e-test/testdata/definition/replica-webservice.yaml
index e4857370..559575d9 100644
--- a/test/e2e-test/testdata/definition/replica-webservice.yaml
+++ b/test/e2e-test/testdata/definition/replica-webservice.yaml
@@ -14,6 +14,7 @@ spec:
       template: |
         import (
         	"strconv"
+        	"list"
         )
 
         mountsArray: {
@@ -135,7 +136,7 @@ spec:
         		},
         	] | []
         }
-        volumesList: volumesArray.pvc + volumesArray.configMap + volumesArray.secret + volumesArray.emptyDir + volumesArray.hostPath
+        volumesList: list.Concat([volumesArray.pvc, volumesArray.configMap, volumesArray.secret, volumesArray.emptyDir, volumesArray.hostPath])
         deDupVolumesArray: [
         	for val in [
         		for i, vi in volumesList {
@@ -250,7 +251,7 @@ spec:
         					}
 
         					if parameter["volumeMounts"] != _|_ {
-        						volumeMounts: mountsArray.pvc + mountsArray.configMap + mountsArray.secret + mountsArray.emptyDir + mountsArray.hostPath
+        						volumeMounts: list.Concat([mountsArray.pvc, mountsArray.configMap, mountsArray.secret, mountsArray.emptyDir, mountsArray.hostPath])
         					}
 
         					if parameter["livenessProbe"] != _|_ {