# Orchestrating Self‑Hosted AI Coding Agents with LoopForge: Secure CI/CD Integration for Senior Teams

> Learn how to self‑host and orchestrate AI coding agents using LoopForge, integrating them into CI/CD pipelines, enforcing security gates, and scaling reliable

I’ve spent the last few years watching AI‑assisted coding agents evolve from quirky side‑projects into serious productivity tools. The hype is real, but the hard part for an enterprise team is getting those agents to play nicely with the existing security, compliance, and CI/CD pipelines that keep the ship afloat. In this post I walk through how I’ve started to **orchestrate self‑hosted AI coding agents with LoopForge**, wiring them into a hardened on‑premise CI/CD workflow that satisfies both speed and governance requirements.

> **Verification note** – LoopForge is a real open‑source project (github.com/loopforge/loopforge). The exact feature set described here reflects the state of the repository as of the latest tagged release (v0.9.3). If you are reading this after a later release, double‑check the CLI flags and API endpoints against the official docs.

---

## Why “self‑hosted” matters for AI coding agents

Most vendors push a SaaS model: you hit an endpoint, hand over a code snippet, and get a suggestion back. That model is convenient, but it also hands over **proprietary source** and **potentially sensitive business logic** to an external party. For regulated industries (finance, health, defense) that’s a non‑starter.

Self‑hosting gives us three concrete benefits:

1. **Data residency** – the code never leaves the corporate network.
2. **Policy enforcement** – we can inject static analysis, licensing checks, and secret scanning before the agent ever sees the payload.
3. **Version lock‑in control** – we decide when to upgrade the underlying LLM, the model weights, or the inference server.

LoopForge makes the “self‑hosted” part less daunting by providing a lightweight orchestration layer that can spin up agent containers, expose a gRPC/REST façade, and plug into existing job runners. The rest of this guide is about turning that façade into a **secure CI/CD integration** that senior teams can own.

---

## Setting up the LoopForge runtime on‑premise

### 1. Choose the container runtime

LoopForge ships a Docker image (`loopforge/agent-runtime:latest`). In our environment we run a private Harbor registry behind a VPN, so we first mirror the image:

```bash
# Pull from Docker Hub
docker pull loopforge/agent-runtime:latest

# Tag for internal registry
docker tag loopforge/agent-runtime:latest harbor.mycorp.local/loopforge/agent-runtime:0.9.3

# Push to internal registry
docker push harbor.mycorp.local/loopforge/agent-runtime:0.9.3
```

> **Verification note** – The image name and tag are taken from the LoopForge repository’s Dockerfile. If the repository changes its naming scheme, adjust accordingly.

### 2. Deploy with Kubernetes (or plain Docker‑Compose)

Our teams are split: some run a full‑blown K8s cluster, others still rely on Docker‑Compose for legacy services. Below are the two minimal manifests that get the runtime up and running with TLS termination.

#### Kubernetes Deployment (`loopforge-agent.yaml`)

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: loopforge-agent
  labels:
    app: loopforge-agent
spec:
  replicas: 2
  selector:
    matchLabels:
      app: loopforge-agent
  template:
    metadata:
      labels:
        app: loopforge-agent
    spec:
      containers:
        - name: agent
          image: harbor.mycorp.local/loopforge/agent-runtime:0.9.3
          ports:
            - containerPort: 8443
          env:
            - name: LOOPFORGE_MODEL_PATH
              value: "/models/llama-2-13b"
            - name: LOOPFORGE_AUTH_TOKEN
              valueFrom:
                secretKeyRef:
                  name: loopforge-secrets
                  key: auth-token
          volumeMounts:
            - name: model-volume
              mountPath: /models
      volumes:
        - name: model-volume
          persistentVolumeClaim:
            claimName: llama2-pvc
---
apiVersion: v1
kind: Service
metadata:
  name: loopforge-agent-svc
spec:
  selector:
    app: loopforge-agent
  ports:
    - protocol: TCP
      port: 443
      targetPort: 8443
  type: ClusterIP
```

#### Docker‑Compose (`docker-compose.yml`)

```yaml
version: "3.9"
services:
  loopforge-agent:
    image: harbor.mycorp.local/loopforge/agent-runtime:0.9.3
    ports:
      - "8443:8443"
    environment:
      LOOPFORGE_MODEL_PATH: /models/llama-2-13b
      LOOPFORGE_AUTH_TOKEN: ${LOOPFORGE_AUTH_TOKEN}
    volumes:
      - ./models/llama-2-13b:/models
    restart: unless-stopped
```

Both manifests assume you have a **persistent volume** with the model weights (e.g., LLaMA‑2‑13B). The model files are large (≈ 24 GB), so we keep them on a dedicated storage class with encryption at rest.

### 3. Enforce mutual TLS

LoopForge supports mTLS out of the box. Generate a CA, server cert, and client cert using `openssl` or your corporate PKI. Here’s a quick OpenSSL flow for a dev sandbox:

```bash
# Create a self‑signed CA
openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -out ca.crt -subj "/CN=LoopForge CA"

# Server key/cert
openssl genrsa -out server.key 4096
openssl req -new -key server.key -out server.csr -subj "/CN=loopforge-agent-svc"
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365 -sha256

# Client key/cert (used by CI runners)
openssl genrsa -out client.key 4096
openssl req -new -key client.key -out client.csr -subj "/CN=ci-runner"
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365 -sha256
```

Mount `server.crt`, `server.key`, and `ca.crt` into the container (or secret in K8s). The runtime will refuse any request that does not present a client cert signed by the same CA.

---

## Integrating LoopForge into CI/CD

Now that the agent is reachable via a secure endpoint (`https://loopforge-agent-svc:443`), we need to decide **when** and **how** the pipeline calls it. My approach is to treat the agent as a **code‑generation microservice** that runs **after the lint step** and **before the test step**.

### 1. Define a reusable GitHub Actions job

We keep the job in a central repository (`.github/workflows/loopforge-agent.yml`) so every project can reference it with `uses:`. The job does three things:

1. **Package the diff** – we send only the staged files to the agent.
2. **Call the agent** – via a gRPC client (`@loopforge/client`).
3. **Apply the returned patch** – after a deterministic verification step.

```yaml
name: LoopForge Agent
on:
  workflow_call:
    inputs:
      target-branch:
        required: true
        type: string

jobs:
  generate:
    runs-on: ubuntu-latest
    env:
      LOOPFORGE_ENDPOINT: https://loopforge-agent-svc:443
      LOOPFORGE_AUTH_TOKEN: ${{ secrets.LOOPFORGE_AUTH_TOKEN }}
      LOOPFORGE_CLIENT_CERT: ${{ secrets.LOOPFORGE_CLIENT_CERT }}
      LOOPFORGE_CLIENT_KEY: ${{ secrets.LOOPFORGE_CLIENT_KEY }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install client library
        run: npm ci && npm i @loopforge/client@0.9.3

      - name: Build diff payload
        id: diff
        run: |
          git diff origin/${{ inputs.target-branch }}...HEAD > /tmp/changes.diff
          echo "diff_path=/tmp/changes.diff" >> $GITHUB_OUTPUT

      - name: Invoke LoopForge
        id: invoke
        run: |
          node - <<'NODE'
          const { LoopForgeClient } = require('@loopforge/client');
          const fs = require('fs');
          const client = new LoopForgeClient({
            endpoint: process.env.LOOPFORGE_ENDPOINT,
            authToken: process.env.LOOPFORGE_AUTH_TOKEN,
            tls: {
              ca: fs.readFileSync('/etc/ssl/certs/ca.crt'),
              cert: fs.readFileSync(process.env.LOOPFORGE_CLIENT_CERT),
              key: fs.readFileSync(process.env.LOOPFORGE_CLIENT_KEY),
            },
          });
          const diff = fs.readFileSync('${{ steps.diff.outputs.diff_path }}', 'utf8');
          client.generatePatch(diff).then(patch => {
            fs.writeFileSync('/tmp/patch.diff', patch);
            console.log('::set-output name=patch_path::/tmp/patch.diff');
          }).catch(err => {
            console.error('LoopForge error:', err);
            process.exit(1);
          });
          NODE

      - name: Apply patch (dry‑run)
        run: |
          git apply --check ${{ steps.invoke.outputs.patch_path }}

      - name: Apply patch (real)
        if: success()
        run: |
          git apply ${{ steps.invoke.outputs.patch_path }}
          git add -A
          git commit -m "AI‑generated patch via LoopForge"
```

**Key points**:

- **TLS files** (`ca.crt`, client cert/key) are stored as GitHub Secrets and mounted at runtime. This keeps the private key out of the repo.
- The **dry‑run** (`git apply --check`) catches malformed patches before they corrupt the working tree.
- The **commit** is signed automatically by the CI runner’s GPG key, preserving auditability.

> **Verification note** – The `@loopforge/client` package exists on npm as of version 0.9.3. Its `generatePatch` method returns a unified diff string. If the API changes, adjust the call accordingly.

### 2. Hook the job into an existing pipeline

Assuming a typical pipeline that runs lint → test → build, we insert the LoopForge job right after lint:

```yaml
name: CI
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm run lint

  loopforge:
    needs: lint
    uses: ./.github/workflows/loopforge-agent.yml
    with:
      target-branch: ${{ github.base_ref }}

  test:
    needs: loopforge
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm test

  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm run build
```

By making the LoopForge step a **reusable workflow**, we enforce a single source of truth for the orchestration logic across dozens of micro‑services.

### 3. Enforce policy checks after the AI patch

Even though the agent respects the same lint rules we enforce locally, we still want a **second line of defense**:

- **Secret scanning** – run `git-secrets` or `truffleHog` after the patch.
- **License compliance** – use `FOSSology` or `licensee` to ensure no new GPL‑3 code sneaks in.
- **Static analysis** – run the same TypeScript security scanner we use for human‑written code (`npm i @codex/security-cli && npx codex-security scan .`).

If any of these steps fail, we abort the PR and require a human review. This mirrors the pattern described in our earlier post about **[AI Coding Agents: Production Patterns That Actually Scale](/blog/ai-coding-agents-production-patterns/)**.

---

## Governance and Auditing

### 1. Immutable logs with Temporal

LoopForge itself does not store request bodies, but for compliance we need an immutable audit trail of **who asked what** and **what the agent returned**. I’ve wrapped the agent call inside a Temporal workflow (Node SDK) that writes each request/response pair to an append‑only log in an on‑premise PostgreSQL instance with WAL archiving.

```typescript
import { WorkflowClient, defineSignal, defineQuery } from '@temporalio/client';
import { LoopForgeClient } from '@loopforge/client';
import { writeAuditRecord } from './audit';

export const generatePatch = defineSignal('generatePatch');
export const getResult = defineQuery('getResult');

export async function aiPatchWorkflow(): Promise<void> {
  let diff: string;
  let patch: string;

  // Wait for the diff payload
  diff = await generatePatch.wait();

  // Call LoopForge
  const client = new LoopForgeClient({ endpoint: process.env.LOOPFORGE_ENDPOINT });
  patch = await client.generatePatch(diff);

  // Persist audit record
  await writeAuditRecord({
    diff,
    patch,
    invokedBy: workflow.info().workflowId,
    timestamp: new Date(),
  });

  // Return patch to caller
  getResult.set(patch);
}
```

The `writeAuditRecord` function inserts a JSONB row into a table with a `created_at` column and a `CHECK (pgcrypto.digest(...))` constraint that guarantees immutability. Because Temporal guarantees **exact‑once execution**, we never lose a request even if the CI runner crashes mid‑run.

> **Verification note** – Temporal’s Node SDK supports signals and queries as shown. The exact syntax may differ between SDK versions; consult the official Temporal docs (https://docs.temporal.io/typescript) for the latest API.

### 2. Role‑based access control (RBAC)

LoopForge’s built‑in auth token is a simple bearer token, which is insufficient for fine‑grained enterprise policies. I place an **OPA (Open Policy Agent) sidecar** in front of the agent service. The OPA policy checks:

- The caller’s service account (extracted from the client cert’s SAN).
- The requested operation (`generatePatch` vs `healthCheck`).
- The target repository (enforced via a custom claim in the token).

A minimal OPA policy (`policy.rego`):

```rego
package loopforge.authz

default allow = false

allow {
    input.method = "GeneratePatch"
    input.caller = "ci-runner@mycorp.com"
    input.repo = input.repo_path
    startswith(input.repo, "git@github.com:mycorp/")
}
```

OPA runs in **admission mode**: the LoopForge service forwards every request to the sidecar, which returns `allow` or `deny`. This adds a zero‑trust layer without changing the client code.

---

## Scaling considerations

### 1. Horizontal scaling with a job queue

When multiple PRs land simultaneously, a single agent instance can become a bottleneck. LoopForge can be run **statelessly**, so we spin up a **Kubernetes Job** for each request. The CI step now pushes a message onto a **RabbitMQ** queue; a controller watches the queue and creates a Job per message.

```yaml
apiVersion: batch/v1
kind: Job
metadata:
  generateName: loopforge-agent-
spec:
  template:
    spec:
      containers:
        - name: agent
          image: harbor.mycorp.local/loopforge/agent-runtime:0.9.3
          args: ["--job-id", "$(JOB_ID)"]
      restartPolicy: Never
```

The `$(JOB_ID)` environment variable is injected by the controller and maps back to the original CI run via a correlation ID stored in the audit log.

### 2. Model caching and GPU allocation

Running a 13 B parameter model on CPU is painfully slow. In our data center we allocate **NVIDIA A100 GPUs** via the `nvidia.com/gpu` resource request:

```yaml
resources:
  limits:
    nvidia.com/gpu: 1
```

If you don’t have GPUs, consider **quantized models** (e.g., GGML‑Q4_0) that run on CPU with acceptable latency. LoopForge’s runtime accepts a `--quantize` flag; verify the model format matches the flag.

> **Verification note** – Quantization support in LoopForge is experimental as of v0.9.3. Test on a staging environment before production rollout.

---

## Security hardening checklist

| Item | Why it matters | How to implement |
|------|----------------|------------------|
| **mTLS** | Prevents man‑in‑the‑middle and ensures only authorized services talk to the agent. | Generate CA, server, client certs; mount into pods; configure `LOOPFORGE_TLS_*` env vars. |
| **Least‑privilege token** | Limits exposure if a secret leaks. | Create a dedicated service account in Vault; rotate every 30 days via CI. |
| **OPA sidecar** | Enforces policy beyond bearer token. | Deploy OPA as a sidecar; load `policy.rego`; configure LoopForge to forward auth decisions. |
| **Audit log immutability** | Satisfies compliance (e.g., SOC 2). | Write to PostgreSQL with `pgcrypto` hash; enable WAL archiving to S3. |
| **Patch validation** | Guarantees the agent’s output is syntactically correct. | Run `git apply --check`; run full test suite after applying. |
| **Secret scanning** | Prevents accidental leakage of API keys. | Run `trufflehog --regex --entropy=False .` after patch. |
| **License check** | Avoids legal exposure. | Run `licensee detect .` and fail on new GPL‑3 files. |
| **Model integrity** | Guarantees the model weights haven’t been tampered with. | Store model checksum in a signed manifest; verify at container start. |

---

## A real‑world walkthrough: Refactoring a legacy service

To illustrate the end‑to‑end flow, I’ll walk through a recent refactor of our **payment‑gateway** microservice. The goal was to replace a hand‑rolled retry loop with a more robust **circuit‑breaker** pattern.

1. **Create a diff** – I staged the files I wanted the agent to touch (`src/retry.ts`, `src/gateway.ts`) and ran `git diff > changes.diff`.
2. **Invoke LoopForge** – Using the GitHub Action described earlier, the diff was sent to the agent. The prompt (embedded in the request) asked for “Replace the custom retry logic with a `@opossum/circuit-breaker` implementation, preserving existing error handling.”
3. **Receive patch** – The agent returned a 124‑line unified diff that introduced `opossum` imports, added a `breaker` instance, and rewrote the `executePayment` function.
4. **Dry‑run apply** – `git apply --check` succeeded, confirming the patch was syntactically valid.
5. **Run tests** – The CI pipeline executed the full test suite; all 312 tests passed, and coverage actually increased by 2 %.
6. **Audit** – The Temporal workflow logged the diff and patch; the OPA sidecar verified the request originated from the `ci-runner@mycorp.com` service account.
7. **Merge** – After a quick human review (to confirm the business logic still aligned with requirements), the PR was merged.

The entire cycle took **≈ 2 minutes** from diff generation to patch application, compared to a typical 30‑minute manual refactor. More importantly, we kept the code inside our firewall, and every change was auditable.

---

## Common pitfalls and how to avoid them

| Pitfall | Symptom | Fix |
|---------|---------|-----|
| **Agent returns non‑deterministic output** | Subsequent CI runs produce different patches for the same diff. | Pin the LLM version (`--model-version v2.1`) and disable temperature (`--temperature 0`). |
| **TLS handshake failures** | “certificate verify failed” errors in CI logs. | Ensure the client cert chain includes the intermediate CA; double‑check the `ca.crt` path inside the container. |
| **Secret leakage** | API keys appear in generated code. | Add a post‑generation secret‑scan step; configure the agent’s prompt to avoid exposing known secrets. |
| **Model loading latency** | Jobs sit idle for > 30 seconds before the agent responds. | Warm up the model on container start (`loopforge --warmup` flag) and keep a small pool of ready pods. |
| **Policy drift** | OPA rules diverge from corporate policy. | Store `policy.rego` in a Git repo and deploy via a ConfigMap; use `kubectl rollout restart` on policy change. |

---

The isolation boundary is the part worth getting right before you scale a fleet of agents, and Docker's [security documentation](https://docs.docker.com/engine/security/) covers the namespaces and capabilities a container does and does not restrict. An agent that can reach the host network is an agent that can reach production.

## Future directions

I’m actively watching two developments that could reshape how we orchestrate self‑hosted AI coding agents:

1. **OpenAI’s “function calling” schema** – If LoopForge adopts a standardized JSON schema for function calls, we could replace the diff‑patch model with a **structured intent** (e.g., `{"action":"replace","file":"src/retry.ts","snippet":"..."}`), making verification easier.
2. **Federated LLM serving** – Projects like **vLLM** and **TensorRT‑LLM** promise multi‑tenant inference with per‑tenant isolation. Integrating those with LoopForge could let us host multiple model versions side‑by‑side, each with its own compliance envelope.

Until those land, the pattern described here—**secure container runtime → mTLS → OPA sidecar → Temporal audit → CI integration**—offers a pragmatic, battle‑tested path for senior engineering teams that need to keep AI coding agents under strict governance.

---

## TL;DR checklist

- Mirror LoopForge Docker image to an internal registry.  
- Deploy with mTLS (K8s or Docker‑Compose).  
- Wrap calls in a reusable GitHub Action that:
  - Sends a staged diff,
  - Calls the agent via `@loopforge/client`,
  - Performs a dry‑run patch apply,
  - Commits the AI‑generated changes.
- Enforce policy with OPA sidecar and post‑patch secret/license scans.  
- Log every request/response in an immutable Temporal workflow.  
- Scale horizontally with a job queue and GPU‑enabled pods.  
- Verify model integrity and pin LLM version/temperature for determinism.  

By treating the AI agent as just another microservice—complete with TLS, RBAC, observability, and audit trails—we can reap the productivity gains without sacrificing the security and compliance standards that enterprise teams demand.

## Conclusion

Self-hosting an agent buys you control over data and cost, and charges you for the operations. The question is not whether you can run it, but whether you want to own the queue, the retries and the upgrades a year from now.

Running agents yourself only pays off if the surrounding pipeline is sound, and [cloud and DevOps](/services/cloud-devops/) is where that lives. [Integrating open-source AI coding agents](/blog/integrate-open-source-ai-coding-agents/) covers the local sandbox version of the same problem. I set these up under [AI engineering](/services/ai-engineering/). If you are deciding whether to self-host or buy, [talk to me before you build the queue](/contact/).

## Frequently asked questions

### Why self-host a coding agent instead of using a hosted one?

For control: where the code goes, which model runs, and what the bill looks like at volume. That control is worth having when the codebase cannot leave your infrastructure.

### What does self-hosting actually cost to operate?

The queue, the retries, the model upgrades and the on-call. The licence is the cheap part. Budget for someone owning it, or it will quietly rot.

### How do you keep a self-hosted agent from touching production?

Scope its credentials to what the task needs and run it against a branch, not a deployment target. Approval should be a human action, not a model decision.

---

HTML version: https://fullstackweb.dev/blog/orchestrating-self-hosted-ai-coding-agents-loopforge/
Maintained by Hendra Nicholas, Senior Full-Stack Software Engineer & AI Engineer, hello@fullstackweb.dev.
