← Back to Pull requests

✨ (helm/v2-alpha): Helm charts now include optional NetworkPolicy resources by default when none are defined in the informed Kustomize file. #5708

Merged
mattsu2020 merged 32 files (1242 lines) on May 29, 2026 05:28 UTC
View on GitHub
mattsu2020 mattsu2020 commented on May 21, 2026 12:25 UTC
Author

Summary

Fixes #5471

The helm/v2-alpha plugin has inconsistent handling between prometheus and network-policy options. Prometheus always emits prometheus.enable: false in values.yaml with conditional template guards, but NetworkPolicy resources get no values.yaml entry and no conditional wrapper — making it impossible to toggle NetworkPolicy via Helm values alone.

This PR adds NetworkPolicy support following the same pattern as prometheus and certManager:

  • Parser: Recognizes kind: NetworkPolicy with apiVersion: networking.k8s.io/v1

  • Feature detection: HasNetworkPolicy flag set when NetworkPolicy resources exist

  • Categorizer: Groups NetworkPolicy resources into "network-policy" template directory

  • Conditional wrapper: Wraps templates with {{- if .Values.networkPolicy.enable }}

  • values.yaml: Emits networkPolicy.enable — defaults to true when NetworkPolicy resources are present in kustomize input, false otherwise (matching the certManager pattern)

  • Generator: Splits network-policy group into individual files
  • Changes

    | File | Change |
    |---|---|
    | consts.go | Add KindNetworkPolicy + APIVersionNetworking constants |
    | parser.go | Add NetworkPolicies field + switch case |
    | extractor.go | Add NetworkPolicies to ResourceSet |
    | features.go | Add HasNetworkPolicy flag + detection |
    | chart_scaffolder.go | Map NetworkPolicies to extractor |
    | categorizer.go | Add "network-policy" group |
    | conditionals.go | Add conditional wrapper with apiVersion check |
    | values.go | Add dynamic networkPolicy.enable section |
    | generator.go | Add "network-policy" to shouldSplitFiles |

    Test plan

  • Unit tests: parser recognizes NetworkPolicy resources

  • Unit tests: values.yaml emits networkPolicy:\n enable: true when detected

  • Unit tests: values.yaml emits networkPolicy:\n enable: false when absent

  • Unit tests: conditional wrapper applied for correct apiVersion

  • Unit tests: conditional wrapper NOT applied for wrong apiVersion

  • All existing tests continue to pass

  • Integration test with kubebuilder init --plugins=helm/v2-alpha + kubebuilder edit (requires integration tag)
  • Diff: 1242 lines (+1218 / -24) across 32 files Reviewer: mattsu2020 Review duration: 11103m
    All Vouch review confidence checks passed
    Residual risk 0.19 = Change Risk (0.96) × (1 − Review Confidence (0.80)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.96 · 1242 lines diff across 32 files
    0.96
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.90 · 5 substantive comment(s)
    0.90
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    79%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Sensitive Paths sensitive_paths
    0.096
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    52 items
    k8s-ci-robot k8s-ci-robot commented on May 21, 2026 12:25 UTC
    Contributor

    Hi @mattsu2020. Thanks for your PR.

    I'm waiting for a kubernetes-sigs member to verify that this patch is reasonable to test. If it is, they should reply with /ok-to-test on its own line. Until that is done, I will not automatically test new commits in this PR, but the usual testing commands by org members will still work.

    Regular contributors should join the org to skip this step.

    Once the patch is verified, the new status will be reflected by the ok-to-test label.

    I understand the commands that are listed here.

    <details>

    Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
    </details>

    Copilot Copilot commented on code on May 21, 2026 15:11 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go:1
    @@ -93,6 +93,7 @@ func (s *ChartScaffolder) PrepareTemplates(_ machinery.Filesystem) ([]machinery.
     		Certificates:              resources.Certificates,
     		Issuer:                    resources.Issuer,
     		ServiceMonitors:           resources.ServiceMonitors,
    +		NetworkPolicies:           resources.NetworkPolicies,
     		Other:                     resources.Other,

    This change wires NetworkPolicies into extraction/categorization, but the chart generation flow still won’t emit any NetworkPolicy templates when the input manifests don’t contain NetworkPolicy resources (e.g., the default scaffolding has ../network-policy commented out in config/default/kustomization). In that common case, values.yaml will now expose networkPolicy.enable but toggling it can’t enable anything because there are no templates to render. To actually make NetworkPolicy optional via Helm values alone (as described in the PR summary/issue), consider generating a default NetworkPolicy template when none are detected (similar to the existing generic ServiceMonitor behavior) or otherwise sourcing NetworkPolicy manifests even when excluded from the kustomize output.

    Copilot Copilot commented on code on May 21, 2026 15:11 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/categorizer.go:1
    @@ -77,6 +77,11 @@ func (c *ResourceCategorizer) CategorizeByFunction() map[string][]*unstructured.
     		groups["prometheus"] = prometheusResources
     	}
     
    +	networkPolicyResources := c.collectNetworkPolicyResources()
    +	if len(networkPolicyResources) > 0 {
    +		groups["network-policy"] = networkPolicyResources
    +	}

    The ResourceCategorizer doc comment lists the supported groups but doesn’t include the newly added "network-policy" group, so it’s now inaccurate. Please update the comment to reflect the full set of groups so future maintainers don’t miss this category.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on May 21, 2026 15:11 UTC
    Reviewer

    Pull request overview

    This PR extends the helm/v2-alpha plugin’s Helm chart generation pipeline to recognize NetworkPolicy resources and treat them as an optional feature, mirroring the existing conditional-templating approach used for Prometheus.

    Changes:

  • Add NetworkPolicy parsing, feature detection (HasNetworkPolicy), and categorization into a dedicated network-policy template group.

  • Wrap generated NetworkPolicy templates with {{- if .Values.networkPolicy.enable }} guards and emit a networkPolicy.enable value in values.yaml.

  • Update template generation behavior to split network-policy resources into individual template files.
  • Reviewed changes

    Copilot reviewed 12 out of 12 changed files in this pull request and generated 2 comments.

    <details>
    <summary>Show a summary per file</summary>

    | File | Description |
    | ---- | ----------- |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/values.go | Emit networkPolicy.enable in values.yaml based on detected resources. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/values_test.go | Add unit coverage for networkPolicy.enable value emission behavior. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/templater/templater_test.go | Add tests ensuring conditional wrapping is applied (or not) for NetworkPolicy based on apiVersion. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/templater/appliers/conditionals.go | Add NetworkPolicy conditional wrapper logic keyed off kind/apiVersion. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/parser.go | Parse networking.k8s.io/v1 NetworkPolicy resources into a dedicated slice. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/parser_test.go | Add parser coverage for NetworkPolicy documents. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/generator.go | Split network-policy resources into separate files. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/categorizer.go | Categorize NetworkPolicy resources into the network-policy group. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/extractor/features.go | Detect HasNetworkPolicy based on extracted NetworkPolicy resources. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/extractor/extractor.go | Extend ResourceSet with NetworkPolicies. |
    | pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go | Wire parsed NetworkPolicies into the extractor ResourceSet. |
    | pkg/plugins/optional/helm/v2alpha/internal/common/consts.go | Add NetworkPolicy kind and networking API version constants. |
    </details>

    mattsu2020 mattsu2020 commented on code on May 23, 2026 06:22 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go:1
    @@ -93,6 +93,7 @@ func (s *ChartScaffolder) PrepareTemplates(_ machinery.Filesystem) ([]machinery.
     		Certificates:              resources.Certificates,
     		Issuer:                    resources.Issuer,
     		ServiceMonitors:           resources.ServiceMonitors,
    +		NetworkPolicies:           resources.NetworkPolicies,
     		Other:                     resources.Other,

    I implemented this by wiring the NetworkPolicy resources into the extractor ResourceSet as NetworkPolicies: resources.NetworkPolicies.

    mattsu2020 mattsu2020 commented on code on May 23, 2026 06:26 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/categorizer.go:1
    @@ -77,6 +77,11 @@ func (c *ResourceCategorizer) CategorizeByFunction() map[string][]*unstructured.
     		groups["prometheus"] = prometheusResources
     	}
     
    +	networkPolicyResources := c.collectNetworkPolicyResources()
    +	if len(networkPolicyResources) > 0 {
    +		groups["network-policy"] = networkPolicyResources
    +	}

    not included in extras.

    camilamacedo86 camilamacedo86 commented on code on May 24, 2026 08:11 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go:1
    @@ -93,6 +93,7 @@ func (s *ChartScaffolder) PrepareTemplates(_ machinery.Filesystem) ([]machinery.
     		Certificates:              resources.Certificates,
     		Issuer:                    resources.Issuer,
     		ServiceMonitors:           resources.ServiceMonitors,
    +		NetworkPolicies:           resources.NetworkPolicies,
     		Other:                     resources.Other,

    This one should be implemented at the same way of ServiceMonitor right?
    If not added by default because was not find in the kustomize you wnat to have the NP scaffold in the chart. Are it done in this way? if so, why we have no change in the testdata samples? Why are we not seen the new NPs in the samples scaffolded?

    camilamacedo86 camilamacedo86 commented on code on May 24, 2026 08:11 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go:1
    @@ -146,6 +147,21 @@ func (s *ChartScaffolder) PrepareTemplates(_ machinery.Filesystem) ([]machinery.
     		})
     	}
     
    +	// Add generic NetworkPolicy only if kustomize output doesn't provide one
    +	if !extraction.Features.HasNetworkPolicy {
    +		builders = append(builders, &charttemplates.NetworkPolicy{
    +			OutputDir: s.config.OutputDir,
    +			Force:     s.config.Force,
    +		})
    +		if extraction.Features.HasWebhooks {

    Why do we need to have the condition HasWebhook here?
    What is the relation of NPs with webhooks?

    camilamacedo86 camilamacedo86 commented on code on May 24, 2026 08:13 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder_test.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 internal
    +
    +import (
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"testing"
    +
    +	"github.com/spf13/afero"
    +
    +	cfgv3 "sigs.k8s.io/kubebuilder/v4/pkg/config/v3"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +)
    +
    +func TestPrepareTemplatesAddsGenericNetworkPolicyWhenMissing(t *testing.T) {
    +	manifestsPath := filepath.Join(t.TempDir(), "install.yaml")
    +	if err := os.WriteFile(manifestsPath, []byte(manifestsWithoutNetworkPolicy), 0o600); err != nil {
    +		t.Fatalf("failed to write manifests: %v", err)
    +	}

    See all tests implemeted in the project.
    All of them use

    	. "github.com/onsi/ginkgo/v2"
    	. "github.com/onsi/gomega"
    

    We should follow BBD style.
    Could you please fix this one?

    Copilot Copilot commented on code on May 24, 2026 08:19 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool
    +}
    +
    +// SetTemplateDefaults implements machinery.Template.
    +func (f *NetworkPolicy) SetTemplateDefaults() error {
    +	if f.Path == "" {
    +		outputDir := f.OutputDir
    +		if outputDir == "" {
    +			outputDir = common.DefaultOutputDir
    +		}
    +		filename := "allow-metrics-traffic.yaml"
    +		if f.Webhook {
    +			filename = "allow-webhook-traffic.yaml"
    +		}
    +		f.Path = filepath.Join(outputDir, "chart", "templates", "network-policy", filename)
    +	}
    +
    +	chartName := f.ProjectName
    +	if f.Webhook {
    +		f.TemplateBody = fmt.Sprintf(webhookNetworkPolicyTemplate, chartName, chartName)
    +	} else {
    +		f.TemplateBody = fmt.Sprintf(networkPolicyTemplate, chartName, chartName)
    +	}
    +
    +	f.IfExistsAction = machinery.OverwriteFile
    +
    +	return nil
    +}
    +
    +const networkPolicyTemplate = `{{` + "`" + `{{- if .Values.networkPolicy.enable }}` + "`" + `}}
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-metrics-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}
    +spec:
    +  podSelector:
    +    matchLabels:
    +      control-plane: controller-manager
    +      app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  policyTypes:
    +    - Ingress
    +  ingress:
    +    - from:
    +      - namespaceSelector:
    +          matchLabels:
    +            metrics: enabled
    +      ports:
    +        - port: 8443

    In this template the ingress port is hard-coded to 8443. Since the chart already exposes metrics.port and templates the metrics Service/Deployment ports via .Values.metrics.port, the NetworkPolicy should use the same value; otherwise changing metrics.port will break connectivity (policy will allow a different destination port than the pod is actually listening on).

    Copilot Copilot commented on code on May 24, 2026 08:19 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool
    +}
    +
    +// SetTemplateDefaults implements machinery.Template.
    +func (f *NetworkPolicy) SetTemplateDefaults() error {
    +	if f.Path == "" {
    +		outputDir := f.OutputDir
    +		if outputDir == "" {
    +			outputDir = common.DefaultOutputDir
    +		}
    +		filename := "allow-metrics-traffic.yaml"
    +		if f.Webhook {
    +			filename = "allow-webhook-traffic.yaml"
    +		}
    +		f.Path = filepath.Join(outputDir, "chart", "templates", "network-policy", filename)
    +	}
    +
    +	chartName := f.ProjectName
    +	if f.Webhook {
    +		f.TemplateBody = fmt.Sprintf(webhookNetworkPolicyTemplate, chartName, chartName)
    +	} else {
    +		f.TemplateBody = fmt.Sprintf(networkPolicyTemplate, chartName, chartName)
    +	}
    +
    +	f.IfExistsAction = machinery.OverwriteFile
    +
    +	return nil
    +}
    +
    +const networkPolicyTemplate = `{{` + "`" + `{{- if .Values.networkPolicy.enable }}` + "`" + `}}
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-metrics-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}
    +spec:
    +  podSelector:
    +    matchLabels:
    +      control-plane: controller-manager
    +      app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  policyTypes:
    +    - Ingress
    +  ingress:
    +    - from:
    +      - namespaceSelector:
    +          matchLabels:
    +            metrics: enabled
    +      ports:
    +        - port: 8443
    +          protocol: TCP
    +{{` + "`" + `{{- end }}` + "`" + `}}
    +`
    +
    +const webhookNetworkPolicyTemplate = `{{` + "`" +
    +	`{{- if and .Values.networkPolicy.enable .Values.webhook.enable }}` + "`" + `}}
    +---
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-webhook-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}
    +spec:
    +  podSelector:
    +    matchLabels:
    +      control-plane: controller-manager
    +      app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  policyTypes:
    +    - Ingress
    +  ingress:
    +    - from:
    +      - namespaceSelector:
    +          matchLabels:
    +            webhook: enabled
    +      ports:
    +        - port: 443

    The webhook NetworkPolicy allows port 443, but the chart templates the webhook server/container port via .Values.webhook.port (default 9443) and the Service typically uses targetPort: 9443. NetworkPolicy port matching is against the pod’s destination port (post-Service DNAT), so this should align with the webhook pod port (and be templated from .Values.webhook.port), otherwise enabling the policy will block webhook traffic.

    Copilot Copilot commented on code on May 24, 2026 08:19 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool
    +}
    +
    +// SetTemplateDefaults implements machinery.Template.
    +func (f *NetworkPolicy) SetTemplateDefaults() error {
    +	if f.Path == "" {
    +		outputDir := f.OutputDir
    +		if outputDir == "" {
    +			outputDir = common.DefaultOutputDir
    +		}
    +		filename := "allow-metrics-traffic.yaml"
    +		if f.Webhook {
    +			filename = "allow-webhook-traffic.yaml"
    +		}
    +		f.Path = filepath.Join(outputDir, "chart", "templates", "network-policy", filename)
    +	}
    +
    +	chartName := f.ProjectName
    +	if f.Webhook {
    +		f.TemplateBody = fmt.Sprintf(webhookNetworkPolicyTemplate, chartName, chartName)
    +	} else {
    +		f.TemplateBody = fmt.Sprintf(networkPolicyTemplate, chartName, chartName)
    +	}
    +
    +	f.IfExistsAction = machinery.OverwriteFile
    +
    +	return nil
    +}
    +
    +const networkPolicyTemplate = `{{` + "`" + `{{- if .Values.networkPolicy.enable }}` + "`" + `}}
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-metrics-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}

    Both policies use fixed metadata.name values (e.g. allow-metrics-traffic). That can cause name collisions when multiple Helm releases of the same chart are installed into the same namespace, and is inconsistent with other generated resources that use the chart’s helper naming (<chart>.resourceName / <chart>.fullname). Consider generating these names via the existing helper templates so they are release-scoped.

    Copilot Copilot commented on code on May 24, 2026 08:19 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool

    Force is defined on the template struct but is not used: SetTemplateDefaults always sets IfExistsAction = machinery.OverwriteFile regardless of Force, and the field comment implies conditional behavior. Either honor Force (like other templates do) or remove the field/comment to avoid misleading callers.

    Copilot Copilot commented on code on May 24, 2026 08:19 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool
    +}
    +
    +// SetTemplateDefaults implements machinery.Template.
    +func (f *NetworkPolicy) SetTemplateDefaults() error {
    +	if f.Path == "" {
    +		outputDir := f.OutputDir
    +		if outputDir == "" {
    +			outputDir = common.DefaultOutputDir
    +		}
    +		filename := "allow-metrics-traffic.yaml"
    +		if f.Webhook {
    +			filename = "allow-webhook-traffic.yaml"
    +		}
    +		f.Path = filepath.Join(outputDir, "chart", "templates", "network-policy", filename)
    +	}
    +
    +	chartName := f.ProjectName
    +	if f.Webhook {
    +		f.TemplateBody = fmt.Sprintf(webhookNetworkPolicyTemplate, chartName, chartName)
    +	} else {
    +		f.TemplateBody = fmt.Sprintf(networkPolicyTemplate, chartName, chartName)
    +	}
    +
    +	f.IfExistsAction = machinery.OverwriteFile
    +
    +	return nil
    +}
    +
    +const networkPolicyTemplate = `{{` + "`" + `{{- if .Values.networkPolicy.enable }}` + "`" + `}}
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-metrics-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}
    +spec:
    +  podSelector:
    +    matchLabels:
    +      control-plane: controller-manager
    +      app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  policyTypes:
    +    - Ingress
    +  ingress:
    +    - from:
    +      - namespaceSelector:
    +          matchLabels:
    +            metrics: enabled
    +      ports:
    +        - port: 8443
    +          protocol: TCP
    +{{` + "`" + `{{- end }}` + "`" + `}}
    +`
    +
    +const webhookNetworkPolicyTemplate = `{{` + "`" +
    +	`{{- if and .Values.networkPolicy.enable .Values.webhook.enable }}` + "`" + `}}
    +---
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-webhook-traffic

    This webhook policy also uses a fixed metadata.name (allow-webhook-traffic). As with the metrics policy, this can collide across multiple Helm releases installed into the same namespace. Prefer generating the resource name via the existing helper templates so it is release-scoped and consistent with other chart resources.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on May 24, 2026 08:19 UTC
    Reviewer

    Pull request overview

    Copilot reviewed 15 out of 15 changed files in this pull request and generated 5 comments.

    mattsu2020 mattsu2020 commented on code on May 24, 2026 13:07 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go:1
    @@ -146,6 +147,21 @@ func (s *ChartScaffolder) PrepareTemplates(_ machinery.Filesystem) ([]machinery.
     		})
     	}
     
    +	// Add generic NetworkPolicy only if kustomize output doesn't provide one
    +	if !extraction.Features.HasNetworkPolicy {
    +		builders = append(builders, &charttemplates.NetworkPolicy{
    +			OutputDir: s.config.OutputDir,
    +			Force:     s.config.Force,
    +		})
    +		if extraction.Features.HasWebhooks {

    The relation is that the generic NetworkPolicy selects the controller-manager Pod and restricts ingress. If the project has webhooks, allowing only the metrics port would block webhook traffic, so we need to generate an additional webhook-specific allow policy when webhooks are detected.

    the current code does not make this relationship clear enough. I will improve the comment and add/adjust tests to cover the webhook case explicitly.

    mattsu2020 mattsu2020 commented on code on May 24, 2026 13:46 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool
    +}
    +
    +// SetTemplateDefaults implements machinery.Template.
    +func (f *NetworkPolicy) SetTemplateDefaults() error {
    +	if f.Path == "" {
    +		outputDir := f.OutputDir
    +		if outputDir == "" {
    +			outputDir = common.DefaultOutputDir
    +		}
    +		filename := "allow-metrics-traffic.yaml"
    +		if f.Webhook {
    +			filename = "allow-webhook-traffic.yaml"
    +		}
    +		f.Path = filepath.Join(outputDir, "chart", "templates", "network-policy", filename)
    +	}
    +
    +	chartName := f.ProjectName
    +	if f.Webhook {
    +		f.TemplateBody = fmt.Sprintf(webhookNetworkPolicyTemplate, chartName, chartName)
    +	} else {
    +		f.TemplateBody = fmt.Sprintf(networkPolicyTemplate, chartName, chartName)
    +	}
    +
    +	f.IfExistsAction = machinery.OverwriteFile
    +
    +	return nil
    +}
    +
    +const networkPolicyTemplate = `{{` + "`" + `{{- if .Values.networkPolicy.enable }}` + "`" + `}}
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-metrics-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}
    +spec:
    +  podSelector:
    +    matchLabels:
    +      control-plane: controller-manager
    +      app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  policyTypes:
    +    - Ingress
    +  ingress:
    +    - from:
    +      - namespaceSelector:
    +          matchLabels:
    +            metrics: enabled
    +      ports:
    +        - port: 8443

    We will correct the fixed value due to the issue.

    mattsu2020 mattsu2020 commented on code on May 24, 2026 13:52 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool
    +}
    +
    +// SetTemplateDefaults implements machinery.Template.
    +func (f *NetworkPolicy) SetTemplateDefaults() error {
    +	if f.Path == "" {
    +		outputDir := f.OutputDir
    +		if outputDir == "" {
    +			outputDir = common.DefaultOutputDir
    +		}
    +		filename := "allow-metrics-traffic.yaml"
    +		if f.Webhook {
    +			filename = "allow-webhook-traffic.yaml"
    +		}
    +		f.Path = filepath.Join(outputDir, "chart", "templates", "network-policy", filename)
    +	}
    +
    +	chartName := f.ProjectName
    +	if f.Webhook {
    +		f.TemplateBody = fmt.Sprintf(webhookNetworkPolicyTemplate, chartName, chartName)
    +	} else {
    +		f.TemplateBody = fmt.Sprintf(networkPolicyTemplate, chartName, chartName)
    +	}
    +
    +	f.IfExistsAction = machinery.OverwriteFile
    +
    +	return nil
    +}
    +
    +const networkPolicyTemplate = `{{` + "`" + `{{- if .Values.networkPolicy.enable }}` + "`" + `}}
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-metrics-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}
    +spec:
    +  podSelector:
    +    matchLabels:
    +      control-plane: controller-manager
    +      app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  policyTypes:
    +    - Ingress
    +  ingress:
    +    - from:
    +      - namespaceSelector:
    +          matchLabels:
    +            metrics: enabled
    +      ports:
    +        - port: 8443
    +          protocol: TCP
    +{{` + "`" + `{{- end }}` + "`" + `}}
    +`
    +
    +const webhookNetworkPolicyTemplate = `{{` + "`" +
    +	`{{- if and .Values.networkPolicy.enable .Values.webhook.enable }}` + "`" + `}}
    +---
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-webhook-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}
    +spec:
    +  podSelector:
    +    matchLabels:
    +      control-plane: controller-manager
    +      app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  policyTypes:
    +    - Ingress
    +  ingress:
    +    - from:
    +      - namespaceSelector:
    +          matchLabels:
    +            webhook: enabled
    +      ports:
    +        - port: 443

    I will make the necessary changes to use variables.

    mattsu2020 mattsu2020 commented on code on May 24, 2026 14:02 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool
    +}
    +
    +// SetTemplateDefaults implements machinery.Template.
    +func (f *NetworkPolicy) SetTemplateDefaults() error {
    +	if f.Path == "" {
    +		outputDir := f.OutputDir
    +		if outputDir == "" {
    +			outputDir = common.DefaultOutputDir
    +		}
    +		filename := "allow-metrics-traffic.yaml"
    +		if f.Webhook {
    +			filename = "allow-webhook-traffic.yaml"
    +		}
    +		f.Path = filepath.Join(outputDir, "chart", "templates", "network-policy", filename)
    +	}
    +
    +	chartName := f.ProjectName
    +	if f.Webhook {
    +		f.TemplateBody = fmt.Sprintf(webhookNetworkPolicyTemplate, chartName, chartName)
    +	} else {
    +		f.TemplateBody = fmt.Sprintf(networkPolicyTemplate, chartName, chartName)
    +	}
    +
    +	f.IfExistsAction = machinery.OverwriteFile
    +
    +	return nil
    +}
    +
    +const networkPolicyTemplate = `{{` + "`" + `{{- if .Values.networkPolicy.enable }}` + "`" + `}}
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-metrics-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}

    We will make the necessary corrections to prevent any conflicts.

    mattsu2020 mattsu2020 commented on code on May 24, 2026 14:10 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool

    Referenced other code and modified it so that Force can use it

    mattsu2020 mattsu2020 commented on code on May 24, 2026 14:23 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder_test.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 internal
    +
    +import (
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"testing"
    +
    +	"github.com/spf13/afero"
    +
    +	cfgv3 "sigs.k8s.io/kubebuilder/v4/pkg/config/v3"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +)
    +
    +func TestPrepareTemplatesAddsGenericNetworkPolicyWhenMissing(t *testing.T) {
    +	manifestsPath := filepath.Join(t.TempDir(), "install.yaml")
    +	if err := os.WriteFile(manifestsPath, []byte(manifestsWithoutNetworkPolicy), 0o600); err != nil {
    +		t.Fatalf("failed to write manifests: %v", err)
    +	}

    I made the necessary adjustments to ensure consistency in formatting

    mattsu2020 mattsu2020 commented on code on May 24, 2026 14:24 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool
    +}
    +
    +// SetTemplateDefaults implements machinery.Template.
    +func (f *NetworkPolicy) SetTemplateDefaults() error {
    +	if f.Path == "" {
    +		outputDir := f.OutputDir
    +		if outputDir == "" {
    +			outputDir = common.DefaultOutputDir
    +		}
    +		filename := "allow-metrics-traffic.yaml"
    +		if f.Webhook {
    +			filename = "allow-webhook-traffic.yaml"
    +		}
    +		f.Path = filepath.Join(outputDir, "chart", "templates", "network-policy", filename)
    +	}
    +
    +	chartName := f.ProjectName
    +	if f.Webhook {
    +		f.TemplateBody = fmt.Sprintf(webhookNetworkPolicyTemplate, chartName, chartName)
    +	} else {
    +		f.TemplateBody = fmt.Sprintf(networkPolicyTemplate, chartName, chartName)
    +	}
    +
    +	f.IfExistsAction = machinery.OverwriteFile
    +
    +	return nil
    +}
    +
    +const networkPolicyTemplate = `{{` + "`" + `{{- if .Values.networkPolicy.enable }}` + "`" + `}}
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-metrics-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}
    +spec:
    +  podSelector:
    +    matchLabels:
    +      control-plane: controller-manager
    +      app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  policyTypes:
    +    - Ingress
    +  ingress:
    +    - from:
    +      - namespaceSelector:
    +          matchLabels:
    +            metrics: enabled
    +      ports:
    +        - port: 8443
    +          protocol: TCP
    +{{` + "`" + `{{- end }}` + "`" + `}}
    +`
    +
    +const webhookNetworkPolicyTemplate = `{{` + "`" +
    +	`{{- if and .Values.networkPolicy.enable .Values.webhook.enable }}` + "`" + `}}
    +---
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-webhook-traffic

    I’ve updated the code.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on May 25, 2026 07:14 UTC
    Reviewer

    Pull request overview

    Copilot reviewed 16 out of 16 changed files in this pull request and generated no new comments.

    camilamacedo86 camilamacedo86 commented on code on May 25, 2026 07:20 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go:1
    @@ -146,6 +147,21 @@ func (s *ChartScaffolder) PrepareTemplates(_ machinery.Filesystem) ([]machinery.
     		})
     	}
     
    +	// Add generic NetworkPolicy only if kustomize output doesn't provide one
    +	if !extraction.Features.HasNetworkPolicy {
    +		builders = append(builders, &charttemplates.NetworkPolicy{
    +			OutputDir: s.config.OutputDir,
    +			Force:     s.config.Force,
    +		})
    +		if extraction.Features.HasWebhooks {

    Do we do the same for kustomize?

    mattsu2020 mattsu2020 commented on code on May 25, 2026 12:42 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go:1
    @@ -146,6 +147,21 @@ func (s *ChartScaffolder) PrepareTemplates(_ machinery.Filesystem) ([]machinery.
     		})
     	}
     
    +	// Add generic NetworkPolicy only if kustomize output doesn't provide one
    +	if !extraction.Features.HasNetworkPolicy {
    +		builders = append(builders, &charttemplates.NetworkPolicy{
    +			OutputDir: s.config.OutputDir,
    +			Force:     s.config.Force,
    +		})
    +		if extraction.Features.HasWebhooks {

    @camilamacedo86

    Not yet on the kustomize side.
    The standard config/network-policy/allow-metrics-traffic.yaml only allows the metrics port.

    We're generating the extra webhook allow policy only in Helm for now (when webhooks exist).
    I'll make it match Kustomize

    mattsu2020 mattsu2020 commented on code on May 25, 2026 13:14 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go:1
    @@ -93,6 +93,7 @@ func (s *ChartScaffolder) PrepareTemplates(_ machinery.Filesystem) ([]machinery.
     		Certificates:              resources.Certificates,
     		Issuer:                    resources.Issuer,
     		ServiceMonitors:           resources.ServiceMonitors,
    +		NetworkPolicies:           resources.NetworkPolicies,
     		Other:                     resources.Other,

    Yes, NetworkPolicy should follow the ServiceMonitor fallback pattern. I updated the scaffolder to generate fallback NetworkPolicies when the kustomize output does not provide them, and regenerated the chart testdata so the samples now include the generated NetworkPolicy templates.

    camilamacedo86 camilamacedo86 commented on May 25, 2026 20:39 UTC
    Contributor

    /ok-to-test

    camilamacedo86 camilamacedo86 commented on May 25, 2026 20:42 UTC
    Contributor

    Hi @mattsu2020

    Thank you for the nice work.
    Could you please squash all commits in one commit?
    Also, can you please rebase with master?

    Beyond that, I think is missing we check

  • a) docs, do we need update regards the NP

  • b) the help for the command in the cobra . We might need to update it
  • mattsu2020 mattsu2020 commented on May 25, 2026 22:16 UTC
    Author

    Hi @mattsu2020

    > Thank you for the nice work. Could you please squash all commits in one commit? Also, can you please rebase with master?

    > Beyond that, I think is missing we check

    > a) docs, do we need update regards the NP

    b) the help for the command in the cobra . We might need to update it

    Added the missing documentation update.

    mattsu2020 mattsu2020 commented on May 25, 2026 22:24 UTC
    Author

    @mattsu2020: The following test failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

    > Test name Commit Details Required Rerun command

    pull-kubebuilder-e2e-k8s-1-36-0 6d5a7f4 link true /test pull-kubebuilder-e2e-k8s-1-36-0

    Full PR test history. Your PR dashboard. Please help us cut down on flakes by linking to an open issue when you hit one in your PR.

    > Details

    @camilamacedo86
    ~~Should we address the missing 1.36 support in this PR, or should it be handled in a separate PR?~~

    I found the PR below, so I’ll wait for it to be addressed.
    https://github.com/kubernetes-sigs/kubebuilder/pull/5674

    https://github.com/kubernetes-sigs/kubebuilder/blob/e6b337e1bbdc9f36d3e87eed67daf08bc7851600/test/common.sh#L19-L45

    camilamacedo86 camilamacedo86 commented on May 26, 2026 04:44 UTC
    Contributor

    Hi @mattsu2020

    Regards /test pull-kubebuilder-e2e-k8s-1-36-0 do not worry about it.
    It will not pass until we have a release from kind supporting 1.36. See: https://github.com/kubernetes-sigs/kubebuilder/pull/5674

    We do not need to pass on this one to allow this one get merged. We can overwrite

    camilamacedo86 camilamacedo86 commented on code on May 26, 2026 04:46 UTC
    Code Review
    docs/book/src/plugins/available/helm-v2-alpha.md:1
    @@ -112,6 +113,9 @@ The plugin generates a chart layout that mirrors your `config/` directory:
         │   └── webhook-service.yaml
         ├── monitoring/
         │   └── servicemonitor.yaml
    +    ├── network-policy/
    +    │   ├── allow-metrics-traffic.yaml
    +    │   └── allow-webhook-traffic.yaml

    We need a comment here ( This file should ONLY be scaffolded when the project HasWebhooks).
    Something like

        │   └── allow-webhook-traffic.yaml # When webhooks are found
    

    camilamacedo86 camilamacedo86 commented on code on May 26, 2026 04:51 UTC
    Code Review
    docs/book/src/plugins/available/helm-v2-alpha.md:1
    @@ -225,6 +235,12 @@ The `metrics-auth-role` and `metrics-reader` are always ClusterRoles, even when
     
     </aside>
     
    +### NetworkPolicy configuration
    +
    +Set `networkPolicy.enable: true` to install NetworkPolicy resources for the manager pod.
    +
    +When your kustomize output includes NetworkPolicy resources, the plugin converts them into chart templates and sets `networkPolicy.enable: true`. When kustomize output does not include them, the plugin adds default templates for metrics traffic, and for webhook traffic when webhooks are enabled.

    When the kustomize output includes `NetworkPolicy` resources, the plugin converts them into chart templates and sets `networkPolicy.enable: true`. When no `NetworkPolicy` resources are present in the kustomize output, the plugin generates default templates for metrics traffic, and also for webhook traffic when webhooks are detected in the provided kustomize input files.
    

    camilamacedo86 camilamacedo86 commented on code on May 26, 2026 04:53 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/templater/templater_test.go:1
    @@ -526,6 +526,44 @@ metadata:
     			Expect(result).To(ContainSubstring("{{- end }}"))
     		})
     
    +		It("should add networkPolicy conditional for NetworkPolicy resources", func() {
    +			networkPolicyResource := &unstructured.Unstructured{}
    +			networkPolicyResource.SetAPIVersion("networking.k8s.io/v1")
    +			networkPolicyResource.SetKind("NetworkPolicy")
    +			networkPolicyResource.SetName("allow-metrics-traffic")
    +
    +			content := `apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  name: allow-metrics-traffic
    +  namespace: test-system
    +spec:
    +  podSelector:
    +    matchLabels:
    +      control-plane: controller-manager`
    +
    +			result := templater.ApplyHelmSubstitutions(content, networkPolicyResource)
    +
    +			Expect(result).To(ContainSubstring("{{- if .Values.networkPolicy.enable }}"))
    +			Expect(result).To(ContainSubstring("{{- end }}"))
    +		})
    +
    +		It("should not wrap NetworkPolicy with wrong apiVersion", func() {

    I think this test is not required
    But we need ensure that:

    a) If has webhooks then we have NP for webhooks scaffolded
    b) If has not webhooks then we have only for metrics
    c) if we found NPs in the kustomize all of them indeed others defined will end up in the np folder under the helm charts
    d) If we scaffolded the default ones and then we found in the kustomize file new NPS all should go to the np dir as well.

    camilamacedo86 camilamacedo86 commented on code on May 26, 2026 04:54 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/categorizer.go:1
    @@ -77,6 +77,11 @@ func (c *ResourceCategorizer) CategorizeByFunction() map[string][]*unstructured.
     		groups["prometheus"] = prometheusResources
     	}
     
    +	networkPolicyResources := c.collectNetworkPolicyResources()
    +	if len(networkPolicyResources) > 0 {
    +		groups["network-policy"] = networkPolicyResources
    +	}

    Any NP should go to np file dir so it seems right

    camilamacedo86 camilamacedo86 commented on code on May 26, 2026 04:57 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool

    See from docs and cobra commands so, I think we will need to add NP here as well.
    Would that really make sense ? if so we need to add here and also update the info in the COBRA help for this command. ServiceMonitors should follow the same configuration as well, but align fix there is out of scope.

    So, the first question is should we preserve the end users customizations on this one?
    If not we can remove the force

    Never overwrites Chart.yaml; preserves values.yaml, NOTES.txt, _helpers.tpl, .helmignore, and test-chart.yml unless you use --force
    

    camilamacedo86 camilamacedo86 commented on code on May 26, 2026 04:59 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/chart-templates/networkpolicy.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2026 The Kubernetes 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 charttemplates
    +
    +import (
    +	"fmt"
    +	"path/filepath"
    +
    +	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
    +	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
    +)
    +
    +var _ machinery.Template = &NetworkPolicy{}
    +
    +// NetworkPolicy scaffolds default NetworkPolicy manifests for the Helm chart.
    +type NetworkPolicy struct {
    +	machinery.TemplateMixin
    +	machinery.ProjectNameMixin
    +
    +	// Webhook generates the webhook ingress policy instead of the metrics ingress policy.
    +	Webhook bool
    +	// OutputDir specifies the output directory for the chart.
    +	OutputDir string
    +	// Force if true allows overwriting the scaffolded file.
    +	Force bool
    +}
    +
    +// SetTemplateDefaults implements machinery.Template.
    +func (f *NetworkPolicy) SetTemplateDefaults() error {
    +	if f.Path == "" {
    +		outputDir := f.OutputDir
    +		if outputDir == "" {
    +			outputDir = common.DefaultOutputDir
    +		}
    +		filename := "allow-metrics-traffic.yaml"
    +		if f.Webhook {
    +			filename = "allow-webhook-traffic.yaml"
    +		}
    +		f.Path = filepath.Join(outputDir, "chart", "templates", "network-policy", filename)
    +	}
    +
    +	chartName := f.ProjectName
    +	if f.Webhook {
    +		f.TemplateBody = fmt.Sprintf(webhookNetworkPolicyTemplate, chartName, chartName)
    +	} else {
    +		f.TemplateBody = fmt.Sprintf(networkPolicyTemplate, chartName, chartName)
    +	}
    +
    +	f.IfExistsAction = machinery.OverwriteFile
    +
    +	return nil
    +}
    +
    +const networkPolicyTemplate = `{{` + "`" + `{{- if .Values.networkPolicy.enable }}` + "`" + `}}
    +apiVersion: networking.k8s.io/v1
    +kind: NetworkPolicy
    +metadata:
    +  labels:
    +    app.kubernetes.io/managed-by: {{ "{{ .Release.Service }}" }}
    +    app.kubernetes.io/name: {{ "{{ include \"%s.name\" . }}" }}
    +  name: allow-metrics-traffic
    +  namespace: {{ "{{ .Release.Namespace }}" }}

    It seems solved right?

    camilamacedo86 camilamacedo86 commented on code on May 26, 2026 05:00 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/edit.go:1
    @@ -58,7 +58,8 @@ func (p *editSubcommand) UpdateMetadata(cliMeta plugin.CLIMetadata, subcmdMeta *
     	subcmdMeta.Description = `Generate a Helm chart from your project's kustomize output.
     
     Parses 'make build-installer' output (dist/install.yaml) and generates chart to allow easy
    -distribution of your project. When enabled, adds Helm helpers targets to Makefile`
    +distribution of your project. It also scaffolds default ServiceMonitor and NetworkPolicy templates

    👍 Great

    camilamacedo86 camilamacedo86 commented on May 26, 2026 05:01 UTC
    Reviewer

    Hi @mattsu2020

    Really good work 🎉
    I just add small few comments as my last round of reviews.
    Amazing work really !!!

    Copilot Copilot commented on code on May 26, 2026 05:07 UTC
    Code Review
    pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go:1
    @@ -146,6 +147,21 @@ func (s *ChartScaffolder) PrepareTemplates(_ machinery.Filesystem) ([]machinery.
     		})
     	}
     
    +	// Add fallback policies only for traffic paths missing from the kustomize output.
    +	if !extraction.Features.HasMetricsNetworkPolicy {
    +		builders = append(builders, &charttemplates.NetworkPolicy{
    +			OutputDir: s.config.OutputDir,
    +			Force:     s.config.Force,
    +		})
    +	}
    +	if extraction.Features.HasWebhooks && !extraction.Features.HasWebhookNetworkPolicy {

    The fallback NetworkPolicy templates are added based on HasMetricsNetworkPolicy/name-suffix detection rather than on the presence of any NetworkPolicy resources. If a project provides custom NetworkPolicies (or uses different names), HasNetworkPolicy will still default networkPolicy.enable to true, and this block may silently add the default restrictive policy on top—changing default behavior and potentially breaking ingress expectations. Consider only scaffolding fallback policies when no NetworkPolicy resources are present at all (e.g., !extraction.Features.HasNetworkPolicy), or make the fallback decision based on stronger detection than filename suffixes.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on May 26, 2026 05:07 UTC
    Reviewer

    Pull request overview

    Copilot reviewed 18 out of 29 changed files in this pull request and generated 4 comments.

    camilamacedo86 camilamacedo86 commented on May 26, 2026 13:31 UTC
    Contributor

    /override pull-kubebuilder-e2e-k8s-1-36-0

    k8s-ci-robot k8s-ci-robot commented on May 26, 2026 13:31 UTC
    Contributor

    @camilamacedo86: Overrode contexts on behalf of camilamacedo86: pull-kubebuilder-e2e-k8s-1-36-0

    <details>

    In response to this:

    >/override pull-kubebuilder-e2e-k8s-1-36-0

    Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
    </details>

    camilamacedo86 camilamacedo86 commented on May 26, 2026 13:32 UTC
    Contributor

    /override pull-kubebuilder-e2e-k8s-1-36-0

    k8s-ci-robot k8s-ci-robot commented on May 26, 2026 13:32 UTC
    Contributor

    @camilamacedo86: Overrode contexts on behalf of camilamacedo86: pull-kubebuilder-e2e-k8s-1-36-0

    <details>

    In response to this:

    >/override pull-kubebuilder-e2e-k8s-1-36-0

    >

    Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
    </details>

    k8s-ci-robot k8s-ci-robot commented on May 26, 2026 13:34 UTC
    Contributor

    [APPROVALNOTIFIER] This PR is APPROVED

    This pull-request has been approved by: <a href="https://github.com/kubernetes-sigs/kubebuilder/pull/5708#pullrequestreview-4364040602" title="Approved">camilamacedo86</a>, <a href="https://github.com/kubernetes-sigs/kubebuilder/pull/5708#" title="Author self-approved">mattsu2020</a>

    The full list of commands accepted by this bot can be found here.

    The pull request process is described here

    <details >
    Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [camilamacedo86]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    mattsu2020 mattsu2020 commented on May 26, 2026 22:52 UTC
    Author

    It seems great 🎉 Well done

    Thank you.
    It was a great learning experience for me regarding Kubebuilder.

    camilamacedo86 camilamacedo86 commented on May 27, 2026 05:41 UTC
    Contributor

    /override pull-kubebuilder-e2e-k8s-1-36-0

    k8s-ci-robot k8s-ci-robot commented on May 27, 2026 05:41 UTC
    Contributor

    @camilamacedo86: Overrode contexts on behalf of camilamacedo86: pull-kubebuilder-e2e-k8s-1-36-0

    <details>

    In response to this:

    >/override pull-kubebuilder-e2e-k8s-1-36-0

    Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
    </details>

    mattsu2020 mattsu2020 commented on May 27, 2026 09:43 UTC
    Author

    Thank you again for the review and approval.

    could you please add /lgtm

    camilamacedo86 camilamacedo86 commented on May 29, 2026 05:26 UTC
    Contributor

    /lgtm

    Reviewers
    Assignees
    mattsu2020 mattsu2020
    Labels
    risk: low confidence: 79.9% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 96% (HIGH) · Higher = larger blast radius
    96%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 79.9% · Lower = rushed or shallow review
    79.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 19.3% · Safe to merge
    19.3%