everything-gemini 1.9.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,240 @@
1
+ ---
2
+ name: harness2-recursive-optimization
3
+ description: Implements Google Research's Harness² framework for test-time recursive agent optimization, Propose-Probe-Compose cycles, and continual harness learning.
4
+ ---
5
+
6
+ # Harness² Recursive Optimization
7
+
8
+ Integrates the official Google Research **Harness²** (`google-research/harness2`) recursive agent harnessing framework into Antigravity and Gemini multi-agent workflows.
9
+
10
+ ---
11
+
12
+ ## 1. The Harness² Paradigm
13
+
14
+ Traditional agent optimization attempts to retrain or fine-tune model weights. **Harness²** keeps model weights frozen and recursively optimizes the **8 file-based harness surfaces** that control agent execution:
15
+
16
+ ```
17
+ ┌─────────────────────────────────────────────────────────────────────────────┐
18
+ │ Harness² 8 Surfaces │
19
+ ├───────────────────┬───────────────────┬───────────────────┬─────────────────┤
20
+ │ 1. Prompts │ 2. Guardrails │ 3. Memory │ 4. Tool Guidance│
21
+ │ (System & Rules) │ (Safety Gates) │ (Instincts & KIs) │ (Constraints) │
22
+ ├───────────────────┼───────────────────┼───────────────────┼─────────────────┤
23
+ │ 5. Subagents │ 6. Skills │ 7. Scripts │ 8. Plugins │
24
+ │ (Role Contracts) │ (Runbooks) │ (CLI & Linters) │ (Middleware) │
25
+ └───────────────────┴───────────────────┴───────────────────┴─────────────────┘
26
+ ```
27
+
28
+ ---
29
+
30
+ ## 2. Two-Level Recursion Loop
31
+
32
+ ```
33
+ UNSEEN TASK AT TEST TIME
34
+ │
35
+ ▼
36
+ ┌─────────────────────────────────────────────────────────────────────────────┐
37
+ │ 1. TASK-LEVEL RECURSION (Propose ──> Probe ──> Compose) │
38
+ │ │
39
+ │ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
40
+ │ │ 1. PROPOSE │────>│ 2. PROBE │────>│ 3. COMPOSE │ │
41
+ │ │ Candidate │ │ Contrastive │ │ Merge Winning │ │
42
+ │ │ Harness Edits │ │ Execution Runs│ │ Configuration │ │
43
+ │ └───────────────┘ └───────────────┘ └───────────────┘ │
44
+ └───────────────────────────────────┬─────────────────────────────────────────┘
45
+ │ Extracted Experience
46
+ ▼
47
+ ┌─────────────────────────────────────────────────────────────────────────────┐
48
+ │ 2. HARNESSING-LEVEL RECURSION (Continual Learning) │
49
+ │ Persists verified task insights into hooks/learned-instincts and │
50
+ │ Knowledge Items (KI) to permanently upgrade future agent sessions. │
51
+ └─────────────────────────────────────────────────────────────────────────────┘
52
+ ```
53
+
54
+ - **Propose**: Generate $K$ candidate modifications to harness components (e.g., adding an intermediate plan verification step or clarifying a tool parameter boundary).
55
+ - **Probe**: Execute parallel or sequential trial trajectories on the active task *without ground-truth verifiers*, observing contrastive behavioral indicators (error recovery, execution depth, tool efficiency).
56
+ - **Compose**: Select and synthesize the best-performing harness mutations into the production `.agents/` environment.
57
+
58
+ ---
59
+
60
+ ## 3. Harness² Manifest Specification (`harness.yaml`)
61
+
62
+ ```yaml
63
+ apiVersion: harness2.research.google.com/v1
64
+ kind: AgentHarness
65
+ metadata:
66
+ name: everything-gemini-production-harness
67
+ version: 2.1.0
68
+ framework: google-research/harness2
69
+ spec:
70
+ model: gemini-2.0-flash
71
+ surfaces:
72
+ prompts:
73
+ root: .agents/rules/
74
+ primary: GEMINI.md
75
+ guardrails:
76
+ hooks: .agents/hooks/
77
+ policies:
78
+ - name: gemini-shield
79
+ event: PreToolExecution
80
+ - name: secret-scrubber
81
+ event: PreToolExecution
82
+ memory:
83
+ instincts: .agents/hooks/learned-instincts/
84
+ knowledge_items: .gemini/knowledge/
85
+ tool_guidance:
86
+ schemas: .agents/mcp/
87
+ progressive_threshold: 4000 # tokens
88
+ subagents:
89
+ roster: .agents/agents/
90
+ handoff_protocol: subagent-handoff
91
+ skills:
92
+ catalog: .agents/skills/
93
+ lazy_loading: true
94
+ scripts:
95
+ validation: scripts/validate.sh
96
+ scaffolding: bin/everything-gemini
97
+ plugins:
98
+ installed: .agents/plugins/
99
+ recursion:
100
+ task_level:
101
+ enabled: true
102
+ max_proposals: 3
103
+ probe_timeout_seconds: 45
104
+ selection_metric: contrastive_behavior
105
+ harnessing_level:
106
+ continual_learning: true
107
+ target_hook: learned-instincts
108
+ ```
109
+
110
+ ---
111
+
112
+ ## 4. Propose-Probe-Compose Implementation (Python)
113
+
114
+ Executes test-time recursive harness optimization using the Google Antigravity / Gemini SDK:
115
+
116
+ ```python
117
+ import copy
118
+ from typing import List, Dict, Any
119
+
120
+ class Harness2Optimizer:
121
+ def __init__(self, base_harness: Dict[str, Any]):
122
+ self.base_harness = base_harness
123
+
124
+ def propose(self, task_description: str, num_candidates: int = 3) -> List[Dict[str, Any]]:
125
+ """Proposes surgical modifications to tool guidance or subagent contracts."""
126
+ candidates = []
127
+ for i in range(num_candidates):
128
+ variant = copy.deepcopy(self.base_harness)
129
+ if i == 0:
130
+ variant["tool_guidance"]["strategy"] = "strict_validation_first"
131
+ elif i == 1:
132
+ variant["subagents"]["assigned"] = ["architect", "code-reviewer"]
133
+ else:
134
+ variant["skills"]["injected_context"] = ["root-cause-debugger"]
135
+ variant["variant_id"] = f"candidate-{i+1}"
136
+ candidates.append(variant)
137
+ return candidates
138
+
139
+ def probe(self, candidates: List[Dict[str, Any]], task_context: str) -> Dict[str, float]:
140
+ """Probes execution trajectories without needing ground-truth labels."""
141
+ scores = {}
142
+ for candidate in candidates:
143
+ # Contrastive evaluation: measure tool efficiency, zero crash exits, and self-checks
144
+ simulated_score = 0.85 if candidate["variant_id"] == "candidate-1" else 0.72
145
+ scores[candidate["variant_id"]] = simulated_score
146
+ return scores
147
+
148
+ def compose(self, candidates: List[Dict[str, Any]], probe_scores: Dict[str, float]) -> Dict[str, Any]:
149
+ """Composes winning modifications into the active execution harness."""
150
+ best_id = max(probe_scores, key=probe_scores.get)
151
+ winning_candidate = next(c for c in candidates if c["variant_id"] == best_id)
152
+ print(f"✨ Harness² selected: {best_id} with contrastive confidence {probe_scores[best_id]:.2f}")
153
+ return winning_candidate
154
+ ```
155
+
156
+ ---
157
+
158
+ ## 5. Harnessing-Level Continual Learning
159
+
160
+ Connects successful task adaptations directly to `hooks/learned-instincts`:
161
+
162
+ ```bash
163
+ # Save winning harness variation as persistent instinct
164
+ echo '{
165
+ "instinct": "For complex distributed debugging, probe intermediate tool state with root-cause-debugger before modifying core schemas.",
166
+ "confidence": 0.94,
167
+ "source": "harness2-recursive-eval"
168
+ }' >> ~/.gemini/config/instincts.json
169
+ ```
170
+
171
+ ---
172
+
173
+ ## 6. Verification and Diagnostics
174
+
175
+ ```bash
176
+ # Export workspace into Harness² canonical structure
177
+ everything-gemini export --format harness2 --output ./harness2-export
178
+
179
+ # Benchmark recursive adaptation efficiency
180
+ everything-gemini benchmark --json | jq .
181
+ ```
182
+
183
+ ---
184
+
185
+ ## 7. Enterprise Production Extensions (The 5 Missing Pillars)
186
+
187
+ While Google Research Harness² (*arXiv:2610.14224*) introduces foundational recursive theory, production enterprise deployment requires the 5 architectural pillars implemented in `everything-gemini`:
188
+
189
+ ```
190
+ ┌─────────────────────────────────────────────────────────────────────────────┐
191
+ │ Harness² Enterprise Production Architecture │
192
+ ├───────────────────────────────────┬─────────────────────────────────────────┤
193
+ │ 1. Hard Spend Limits & Guardrails │ PreToolUse budget-guard ($ cap per run) │
194
+ ├───────────────────────────────────┼─────────────────────────────────────────┤
195
+ │ 2. Local Task Optimization Runner │ --dir ./tasks --bench local │
196
+ ├───────────────────────────────────┼─────────────────────────────────────────┤
197
+ │ 3. Opt-in Human-in-the-Loop (HITL)│ Interactive candidate approval gating │
198
+ ├───────────────────────────────────┼─────────────────────────────────────────┤
199
+ │ 4. Snapshot & Rollback Isolation │ Ephemeral git patch rollback on failure │
200
+ ├───────────────────────────────────┼─────────────────────────────────────────┤
201
+ │ 5. Production Trace Ingestion │ Telemetry trace ──> Regression task │
202
+ └───────────────────────────────────┴─────────────────────────────────────────┘
203
+ ```
204
+
205
+ 1. **Spend Guardrails (`hooks/budget-guard`)**:
206
+ - Intercepts all tool execution turns via `PreToolUse`.
207
+ - Denies candidate mutations or runaway agent loops once cumulative token spend breaches `MAX_USD_BUDGET`.
208
+ 2. **Local Task Optimization Runner**:
209
+ - Replaces synthetic benchmarks with custom enterprise task folders (`--dir ./tasks --bench local`).
210
+ - Automatically maintains `tasks/EXPERIENCE.md` documenting converged harness mutations.
211
+ 3. **Opt-in Human-in-the-Loop (`--hitl`)**:
212
+ - Halts speculative candidate changes on high-impact surfaces (prompts, guardrails, guidance) for human signoff.
213
+ 4. **Tool State Snapshot & Rollback**:
214
+ - Wraps each probe with [`scripts/harness_snapshot.sh`](file:///Users/salmanshaikh/development/github/everything-gemini/scripts/harness_snapshot.sh) and [`scripts/harness_rollback.sh`](file:///Users/salmanshaikh/development/github/everything-gemini/scripts/harness_rollback.sh).
215
+ - Reverts file modifications immediately if a candidate fails the probe score threshold.
216
+ 5. **Production Trace Ingestion**:
217
+ - Converts production error traces (e.g. Dataproc OOM, schema drift, API timeouts) into deterministic probe tasks.
218
+
219
+ ---
220
+
221
+ ## 8. Enterprise CLI Runbook
222
+
223
+ ```bash
224
+ # 1. Synthesize 8-surface Harness² workspace
225
+ everything-gemini harness2 ./my-enterprise-harness
226
+
227
+ # 2. Run recursive optimization over local tasks with $15 hard ceiling and snapshot sandboxing
228
+ everything-gemini harness2 run --dir ./tasks --bench local --max-usd 15.00 --snapshot
229
+
230
+ # 3. Enable interactive Human-in-the-Loop gating for candidate mutations
231
+ everything-gemini harness2 run --dir ./tasks --bench local --hitl
232
+
233
+ # 4. Ingest production telemetry failure trace into automated regression probe
234
+ everything-gemini harness2 ingest-trace ./production-failure.json --dir ./tasks/regression
235
+
236
+ # 5. Automated dry-run and JSON telemetry for CI/CD pipelines
237
+ everything-gemini harness2 run --dir ./tasks --dry-run
238
+ everything-gemini harness2 run --dir ./tasks --json
239
+ ```
240
+
@@ -0,0 +1,218 @@
1
+ ---
2
+ name: keda-event-autoscaling
3
+ description: Architects and configures Kubernetes Event-driven Autoscaling (KEDA) ScaledObjects, ScaledJobs, and event triggers for automated scale-to-zero and burst workloads.
4
+ ---
5
+
6
+ # KEDA Event-Driven Autoscaling
7
+
8
+ Configures Kubernetes Event-driven Autoscaling (KEDA) to dynamically scale workloads from 0 to N replicas based on external event queues, metrics streams, and consumer lag.
9
+
10
+ ---
11
+
12
+ ## 1. Core Architecture
13
+
14
+ ```
15
+ External Event Source KEDA Operator Kubernetes Runtime
16
+ ┌──────────────────────┐ ┌───────────────────┐ ┌──────────────────────┐
17
+ │ Kafka / Redis / SQS │────>│ keda-metrics-apiserver ──────>│ HorizontalPodAutoscaler │
18
+ │ Prometheus / PubSub │ │ (Metrics Provider)│ │ (Target Replicas) │
19
+ └──────────────────────┘ └─────────┬─────────┘ └──────────┬───────────┘
20
+ │ │
21
+ ┌─────────▼─────────┐ ┌──────────▼───────────┐
22
+ │ ScaledObject CRD │────>│ Scaled Deployment │
23
+ │ (0 <-> 1 Replica) │ │ (Min: 0, Max: 50) │
24
+ └───────────────────┘ └──────────────────────┘
25
+ ```
26
+
27
+ - **Metrics Server**: Translates external trigger metrics into standard Kubernetes custom metrics for the native HPA.
28
+ - **Scale to Zero (0 -> 1)**: Handled directly by KEDA controller activating idle deployments when events arrive.
29
+ - **Scale Beyond One (1 -> N)**: Handled by native Kubernetes HPA driven by KEDA external metrics.
30
+
31
+ ---
32
+
33
+ ## 2. Kafka Consumer Lag ScaledObject
34
+
35
+ Scales pod replicas based on consumer group topic lag with secure secret authentication:
36
+
37
+ ```yaml
38
+ apiVersion: keda.sh/v1alpha1
39
+ kind: TriggerAuthentication
40
+ metadata:
41
+ name: kafka-trigger-auth
42
+ namespace: production
43
+ spec:
44
+ secretTargetRef:
45
+ - parameter: sasl
46
+ name: kafka-credentials
47
+ key: sasl-mechanism
48
+ - parameter: username
49
+ name: kafka-credentials
50
+ key: sasl-username
51
+ - parameter: password
52
+ name: kafka-credentials
53
+ key: sasl-password
54
+ ---
55
+ apiVersion: keda.sh/v1alpha1
56
+ kind: ScaledObject
57
+ metadata:
58
+ name: order-processor-scaler
59
+ namespace: production
60
+ spec:
61
+ scaleTargetRef:
62
+ apiVersion: apps/v1
63
+ kind: Deployment
64
+ name: order-processor
65
+ pollingInterval: 15
66
+ cooldownPeriod: 120
67
+ idleReplicaCount: 0
68
+ minReplicaCount: 1
69
+ maxReplicaCount: 40
70
+ advanced:
71
+ horizontalPodAutoscalerConfig:
72
+ behavior:
73
+ scaleDown:
74
+ stabilizationWindowSeconds: 300
75
+ policies:
76
+ - type: Percent
77
+ value: 20
78
+ periodSeconds: 60
79
+ scaleUp:
80
+ stabilizationWindowSeconds: 0
81
+ policies:
82
+ - type: Percent
83
+ value: 100
84
+ periodSeconds: 15
85
+ triggers:
86
+ - type: kafka
87
+ metadata:
88
+ bootstrapServers: kafka-cluster-kafka-bootstrap.kafka.svc.cluster.local:9092
89
+ consumerGroup: order-processor-group
90
+ topic: orders.v1
91
+ lagThreshold: "100"
92
+ activationLagThreshold: "1"
93
+ authenticationRef:
94
+ name: kafka-trigger-auth
95
+ ```
96
+
97
+ ---
98
+
99
+ ## 3. Redis Queue & Stream ScaledObject
100
+
101
+ Scales Celery or BullMQ worker queues dynamically based on pending queue length:
102
+
103
+ ```yaml
104
+ apiVersion: keda.sh/v1alpha1
105
+ kind: ScaledObject
106
+ metadata:
107
+ name: celery-worker-scaler
108
+ namespace: production
109
+ spec:
110
+ scaleTargetRef:
111
+ name: celery-worker
112
+ minReplicaCount: 0
113
+ maxReplicaCount: 20
114
+ pollingInterval: 10
115
+ cooldownPeriod: 60
116
+ triggers:
117
+ - type: redis
118
+ metadata:
119
+ address: redis-cluster.cache.svc.cluster.local:6379
120
+ listName: celery
121
+ listLength: "50"
122
+ activationListLength: "1"
123
+ enableTLS: "true"
124
+ authenticationRef:
125
+ name: redis-trigger-auth
126
+ ```
127
+
128
+ ---
129
+
130
+ ## 4. ScaledJob for Finite Batch Workloads
131
+
132
+ Spawns isolated Kubernetes Jobs for batch or run-to-completion work (1 job per event):
133
+
134
+ ```yaml
135
+ apiVersion: keda.sh/v1alpha1
136
+ kind: ScaledJob
137
+ metadata:
138
+ name: heavy-video-transcoder
139
+ namespace: batch
140
+ spec:
141
+ jobTargetRef:
142
+ parallelism: 1
143
+ completions: 1
144
+ activeDeadlineSeconds: 1800
145
+ backoffLimit: 2
146
+ template:
147
+ spec:
148
+ restartPolicy: OnFailure
149
+ containers:
150
+ - name: transcoder
151
+ image: registry.example.com/video-transcoder:v2.0.0
152
+ resources:
153
+ requests:
154
+ cpu: "2"
155
+ memory: 4Gi
156
+ pollingInterval: 30
157
+ successfulJobsHistoryLimit: 5
158
+ failedJobsHistoryLimit: 10
159
+ maxReplicaCount: 25
160
+ scalingStrategy:
161
+ strategy: "custom"
162
+ customScalingQueueLengthDeduction: 1
163
+ triggers:
164
+ - type: aws-sqs-queue
165
+ metadata:
166
+ queueURL: https://sqs.us-east-1.amazonaws.com/123456789012/transcode-jobs
167
+ queueLength: "1"
168
+ awsRegion: us-east-1
169
+ authenticationRef:
170
+ name: keda-aws-auth
171
+ ```
172
+
173
+ ---
174
+
175
+ ## 5. Prometheus Custom Metric Scaler
176
+
177
+ Scales HTTP microservices on rate of requests (RPS) or error ratios:
178
+
179
+ ```yaml
180
+ apiVersion: keda.sh/v1alpha1
181
+ kind: ScaledObject
182
+ metadata:
183
+ name: api-service-scaler
184
+ namespace: production
185
+ spec:
186
+ scaleTargetRef:
187
+ name: api-gateway
188
+ minReplicaCount: 3
189
+ maxReplicaCount: 50
190
+ triggers:
191
+ - type: prometheus
192
+ metadata:
193
+ serverAddress: http://prometheus-k8s.monitoring.svc:9090
194
+ metricName: http_requests_total_rate
195
+ query: sum(rate(http_requests_total{job="api-gateway", status=~"2.."}[2m]))
196
+ threshold: "500"
197
+ ```
198
+
199
+ ---
200
+
201
+ ## 6. Verification and Troubleshooting
202
+
203
+ ```bash
204
+ # Check status and current active state of ScaledObjects
205
+ kubectl get scaledobject -n production
206
+ kubectl describe scaledobject order-processor-scaler -n production
207
+
208
+ # Inspect generated HPA and custom metrics
209
+ kubectl get hpa -n production
210
+ kubectl describe hpa keda-hpa-order-processor-scaler -n production
211
+
212
+ # View KEDA Operator and Metrics Server logs
213
+ kubectl logs -n keda -l app=keda-operator -f
214
+ kubectl logs -n keda -l app=keda-operator-metrics-apiserver -f
215
+
216
+ # Verify custom metrics registered in K8s APIServer
217
+ kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1" | jq .
218
+ ```
@@ -0,0 +1,200 @@
1
+ ---
2
+ name: opa-gatekeeper-policy
3
+ description: Authors and validates Open Policy Agent (OPA) Gatekeeper ConstraintTemplates and Rego admission policies for Kubernetes governance and security compliance.
4
+ ---
5
+
6
+ # OPA Gatekeeper Policy
7
+
8
+ Defines declarative policy enforcement for Kubernetes clusters using Open Policy Agent (OPA) Gatekeeper ConstraintTemplates, Rego logic, and shift-left CLI testing.
9
+
10
+ ---
11
+
12
+ ## 1. Admission Control Flow
13
+
14
+ ```
15
+ kubectl apply -f resource.yaml
16
+ │
17
+ ▼
18
+ ┌────────────────────────┐
19
+ │ Kubernetes API Server │
20
+ └───────────┬────────────┘
21
+ │ ValidatingWebhookConfiguration
22
+ ▼
23
+ ┌────────────────────────┐ Matches Rules?
24
+ │ Gatekeeper Pod │────────────────────────┐
25
+ │ (Admission Webhook) │ │
26
+ └───────────┬────────────┘ ▼
27
+ │ Rego Evaluation ┌────────────────────┐
28
+ ▼ │ Reject (403) │
29
+ ┌──────────────────────┐ │ Error & Remediation│
30
+ │ Constraint Templates │ └────────────────────┘
31
+ └──────────┬───────────┘
32
+ │ Passed
33
+ ▼
34
+ ┌──────────────────────┐
35
+ │ Persist to etcd │
36
+ └──────────────────────┘
37
+ ```
38
+
39
+ ---
40
+
41
+ ## 2. ConstraintTemplate (Rego Engine)
42
+
43
+ Defines the reusable policy schema and Rego execution logic:
44
+
45
+ ```yaml
46
+ apiVersion: templates.gatekeeper.sh/v1
47
+ kind: ConstraintTemplate
48
+ metadata:
49
+ name: k8srequiredlabels
50
+ annotations:
51
+ description: "Requires all namespaces and workloads to specify standard governance labels."
52
+ spec:
53
+ crd:
54
+ spec:
55
+ names:
56
+ kind: K8sRequiredLabels
57
+ validation:
58
+ openAPIV3Schema:
59
+ type: object
60
+ properties:
61
+ labels:
62
+ type: array
63
+ items:
64
+ type: string
65
+ targets:
66
+ - target: admission.k8s.gatekeeper.sh
67
+ rego: |
68
+ package k8srequiredlabels
69
+
70
+ violation[{"msg": msg, "details": {"missing_labels": missing}}] {
71
+ provided := {label | input.review.object.metadata.labels[label]}
72
+ required := {label | label := input.parameters.labels[_]}
73
+ missing := required - provided
74
+ count(missing) > 0
75
+ msg := sprintf("Resource %v '%v' violates policy: missing required labels: %v", [
76
+ input.review.object.kind,
77
+ input.review.object.metadata.name,
78
+ missing
79
+ ])
80
+ }
81
+ ```
82
+
83
+ ---
84
+
85
+ ## 3. Instantiating the Constraint
86
+
87
+ Applies the template to specific resource kinds and namespaces:
88
+
89
+ ```yaml
90
+ apiVersion: constraints.gatekeeper.sh/v1beta1
91
+ kind: K8sRequiredLabels
92
+ metadata:
93
+ name: require-team-and-cost-center
94
+ spec:
95
+ enforcementAction: deny # Options: deny, dryrun, warn
96
+ match:
97
+ kinds:
98
+ - apiGroups: ["apps"]
99
+ kinds: ["Deployment", "StatefulSet"]
100
+ - apiGroups: [""]
101
+ kinds: ["Namespace"]
102
+ excludedNamespaces:
103
+ - kube-system
104
+ - gatekeeper-system
105
+ parameters:
106
+ labels:
107
+ - "app.kubernetes.io/managed-by"
108
+ - "cost-center"
109
+ - "owner-team"
110
+ ```
111
+
112
+ ---
113
+
114
+ ## 4. Container Security Constraint (Disallow Privileged)
115
+
116
+ Enforces zero-trust rootless containers:
117
+
118
+ ```yaml
119
+ apiVersion: templates.gatekeeper.sh/v1
120
+ kind: ConstraintTemplate
121
+ metadata:
122
+ name: k8sdisallowprivileged
123
+ spec:
124
+ crd:
125
+ spec:
126
+ names:
127
+ kind: K8sDisallowPrivileged
128
+ targets:
129
+ - target: admission.k8s.gatekeeper.sh
130
+ rego: |
131
+ package k8sdisallowprivileged
132
+
133
+ violation[{"msg": msg}] {
134
+ c := input_containers[_]
135
+ c.securityContext.privileged == true
136
+ msg := sprintf("Privileged container '%v' is prohibited in namespace '%v'.", [
137
+ c.name,
138
+ input.review.object.metadata.namespace
139
+ ])
140
+ }
141
+
142
+ input_containers[c] {
143
+ c := input.review.object.spec.template.spec.containers[_]
144
+ }
145
+ input_containers[c] {
146
+ c := input.review.object.spec.template.spec.initContainers[_]
147
+ }
148
+ ```
149
+
150
+ ---
151
+
152
+ ## 5. Shift-Left CI Validation with `gator` CLI
153
+
154
+ Validates Kubernetes manifests against Gatekeeper templates inside CI pipelines before merge:
155
+
156
+ ```bash
157
+ # Test manifests directly without a live Kubernetes cluster
158
+ gator test \
159
+ --image-template=./templates/ \
160
+ --constraint=./constraints/ \
161
+ --manifests=./deploy/production/
162
+
163
+ # Run unit tests on Rego source files
164
+ gator verify ./policies/...
165
+ ```
166
+
167
+ ```yaml
168
+ # Gator test suite definition (suite.yaml)
169
+ kind: Suite
170
+ apiVersion: test.gatekeeper.sh/v1alpha1
171
+ metadata:
172
+ name: deployment-label-suite
173
+ tests:
174
+ - name: test-missing-labels-denied
175
+ template: template.yaml
176
+ constraint: constraint.yaml
177
+ cases:
178
+ - name: deployment-without-cost-center
179
+ object: bad-deployment.yaml
180
+ assertions:
181
+ - violations: yes
182
+ message: "missing required labels: {\"cost-center\"}"
183
+ - name: compliant-deployment
184
+ object: good-deployment.yaml
185
+ assertions:
186
+ - violations: no
187
+ ```
188
+
189
+ ---
190
+
191
+ ## 6. Audit Cluster Violations
192
+
193
+ ```bash
194
+ # Inspect non-compliant resources identified during continuous background audit
195
+ kubectl get constraints -A
196
+
197
+ # Detailed violation listing
198
+ kubectl get k8srequiredlabels.constraints.gatekeeper.sh require-team-and-cost-center -o yaml \
199
+ | yq '.status.violations[] | {resource: .name, kind: .kind, message: .message}'
200
+ ```