Building the Digital Employee: Architecture, Worktrees, and Self-Healing Loops

Building the Digital Employee: Architecture, Worktrees, and Self-Healing Loops
A practical engineering guide to taking AI out of the IDE chat sidebar and into an autonomous, governed delivery runtime.
In [Part 1], we covered why buying AI seats is stalling enterprise budgets and how the "Digital Employee" paradigm shifts AI from an interactive typing assistant to an autonomous, budgeted teammate.
This article is the implementation blueprint.
I'll break down the complete architecture: how to bridge enterprise webhooks to model gateways, isolate execution runtimes using disposable git worktrees, build self-healing test loops, and enforce strict security and cost guardrails.
I'll also show how we implemented this in production with our two digital teammates: DeepSeat (implementation specialist) and GeminiStick (review and QA specialist).
System Architecture Overview
To run autonomous code generation safely in production, the infrastructure must decouple protocol connectors from the orchestration engine, wrapped inside a dual-mode execution runtime:
+--------------------------------------------------------------------------+
| ENTERPRISE SURFACES |
| Jira - GitHub - Bitbucket - Slack - Teams - Email/SharePoint (polled) |
| | webhooks | developer CLI |
+---------------+--------------------------------+-------------------------+
| | (/ba, /dev, /qa, /review)
v v
+--------------------------------------------------------------------------+
| ORCHESTRATION & PRESET ROUTER |
| Agents (dev/review/qa/ba) + Router MCP + Preset Matrix |
+---------------+--------------------------------+-------------------------+
| |
v v
+------------------------------+ +-----------------------------------------+
| CONNECTOR MCPs | | LITELLM GATEWAY |
| Jira - GitHub - Confluence | | Haiku / Fable / Opus / DeepSeek / Gemini|
+------------------------------+ +-----------------------------------------+
The system operates across two complementary execution modes sharing a single cognitive core:
- Interactive CLI Mode: Developers invoke specialized slash commands (
/ba,/dev,/review,/qa) locally inside Claude Code during day-to-day engineering. - Autonomous Bridge Mode: A centralized worker processes webhooks (and polls pull-only channels like email or SharePoint), spawns headless runs in clean
git worktreesinside per-squad containers, executes the identical commands via a non-interactive execution wrapper, and reports back under dedicated bot identities.
Step 1: Ingress & Webhook Normalization
Digital teammates cannot require a human to copy-paste prompts. They must react natively to where work already lives.
The entry point listens for events across our squad tooling:
- Jira: Issue transitions (e.g., ticket moved to
Ready for Devwith assignee@deepseat). - GitHub: PR review requests, issue assignments,
@mentions, and check-run failures. - Chat: Slash commands or mentions in dedicated Slack or Teams squad channels.
- Polled Surfaces: For systems without clean inbound webhooks (e.g., corporate SharePoint document libraries or shared email boxes), the bridge runs a polling listener via IMAP/Graph API without exposing inbound firewall ports.
Webhook Verification & Job Normalization
The ingress service runs three critical pre-processing steps:
- Signature Verification & Deduplication: Validates HMAC webhook signatures and rejects replays via a Redis-backed event cache.
- Untrusted Data Isolation: Ticket titles and user descriptions are untrusted external inputs. The ingress wraps all text inside
<untrusted_data>boundaries before passing to any agent prompt to prevent prompt injection attacks. - Job Schema Transformation: Emits a normalized, typed job contract containing:
- Acceptance criteria & ticket keys
- Repository remote URL & base commit SHA
- Assigned squad profile & active preset matrix
A lightweight triage model (e.g., Gemini Flash or DeepSeek-Flash) inspects the normalized metadata to drop social chatter or reprioritize urgent tickets before spinning up full workers.
Step 2: The Preset Router & LiteLLM Gateway
Running every task through a top-tier frontier model like Claude Opus is financial suicide at enterprise scale.
We place a LiteLLM Gateway between the agent orchestration layer and model providers. The gateway exposes standard OpenAI-compatible endpoints while enforcing routing matrices and budget ceilings.
The Four Cognition Tiers
Every subtask inside an agent run is dispatched to a specific tier:
- Cheap Discovery Tier (DeepSeek-Flash / Gemini Flash / Haiku):
- Tasks: AST code navigation, grep sweeps, ticket triage, file-tree indexing.
- Cost: Fractions of a cent per thousand tokens.
- Primary Reasoning Tier (Claude Fable / DeepSeek):
- Tasks: Core feature planning, architectural synthesis, test writing, bug fixes.
- Cost: The primary operational workhorse—reliable logic without frontier premiums.
- High-Context Judging Tier (Gemini Pro / DeepSeek-V4):
- Tasks: Reviewing massive diffs (>1,000 lines), scanning cross-repo dependencies.
- Cost: Optimized for 1M+ token context windows where ingestion volume trumps raw reasoning speed.
- Critical Escalation Tier (Claude Opus):
- Tasks: Security boundary approvals, core cryptography reviews, architectural sign-offs.
- Cost: Premium pricing reserved for high-stakes, low-frequency tasks.
Enforcing the Budget Cap at the Gateway
Each digital employee configuration includes a hard financial limit:
{
"employee_id": "deepseat",
"monthly_budget_usd": 50.00,
"warning_threshold": 0.80,
"allowed_models": [
"deepseek/*",
"gemini/gemini-2.5-flash"
]
}
The gateway tracks cumulative token spend in real time. At 80% of budget, it fires an alert to the squad Slack channel. At 100%, the gateway actively refuses model calls with a BudgetExceededException.
Cost control is physically enforced by the network proxy, not dependent on prompt compliance.
Step 3: Worktree Isolation & The Execution Runtime
Running autonomous code generation directly on a developer's local laptop or in a shared repository clone causes file locking, branch collisions, and dirty working trees.
We solve this using git worktree inside ephemeral Docker containers.
+--------------------------------------------------------------------------+
| EPHEMERAL WORKER CONTAINER |
| |
| 1. Sync Bare Mirror: git fetch origin main |
| 2. Create Worktree: git worktree add -b kai/AUTH-412 /workspaces/AUTH |
| 3. Inject Context: .mcp.json + repo conventions + test runner configs |
| 4. Execute Agent: Headless runner / execution harness |
| 5. Verification: pytest / npm test (Self-Healing Loop) |
| 6. Teardown: git worktree remove --force /workspaces/AUTH |
+--------------------------------------------------------------------------+
Why git worktree?
- Instant Provisioning: Worktrees branch off a local bare mirror, meaning setup takes sub-second disk link operations instead of multi-gigabyte
git clonetransfers. - Complete State Isolation: If an agent breaks dependencies or introduces corrupt files, it is quarantined inside its dedicated directory.
- Guaranteed Teardown: Once the run completes (or aborts), the container destroys the worktree directory unconditionally.
The worker mounts an isolated .mcp.json restricting filesystem access strictly to the active worktree path:
{
"mcpServers": {
"filesystem": {
"command": "mcp-server-filesystem",
"args": ["/workspaces/AUTH-412"]
},
"git": {
"command": "mcp-server-git",
"args": ["--repo", "/workspaces/AUTH-412"]
}
}
}
Step 4: The Headless Self-Healing Loop
A digital employee cannot be an "open loop" that writes code and blindly opens a PR. It must prove its code works before asking a human engineer for review.
The runtime wraps agent code generation in an autonomous verification loop:
[Write Code] ---> [Run Test Suite] ---> [Pass?] ---> Yes ---> [Open PR]
|
+---> No (Stderr captured)
|
v
[Inspect Stack Trace]
|
v
[Self-Correct Code] (Max: 2 attempts)
The Execution Cycle:
- Implementation: The agent reads existing middleware, schemas, and controllers using Model Context Protocol (MCP) file-system tools, then writes the requested feature code and accompanying unit tests.
- Test Execution: The runtime invokes the repository's native test runner (e.g.,
pytest tests/,npm test,cargo test). - Trace Feedback: If tests fail, the exit code,
stdout, andstderrare captured and appended back into the model's context window. - Self-Correction: The agent analyzes the assertion failure or stack trace, updates boundary conditions or typing definitions, and triggers the test suite again.
- The Circuit Breaker:
- The loop has a hard limit of 2 self-correction attempts.
- If tests still fail after attempt 2—or if the task touches sensitive auth files and fails once—the agent trips the circuit breaker.
- It aborts execution, commits the work-in-progress to an isolated draft branch, marks the Jira ticket
Blocked - Human Assistance Needed, and tags the lead engineer with the terminal test output.
Step 5: Governed Reporting & Hand-Off
Once tests pass cleanly, the digital employee executes native delivery actions under its assigned identity:
- Commit Hygiene: Commits changes using Conventional Commit standards signed via the squad's service GPG key:
feat(auth): implement refresh token rotation [AUTH-412] - Pull Request Publication: Pushes the branch and opens a GitHub PR populated with:
- Summary of architectural choices and files modified
- Reproducible CLI test commands
- Terminal output proving passing assertions
- Direct link to the Jira story
- Ticket & Chat Sync: Transitions the Jira ticket to
In Review, assigns the designated human peer reviewer, and drops a completion notice in#backend-squad:
"PR #84 opened for AUTH-412. Execution completed in 2m 45s. Total cost: $0.14."
The golden rule of governance: Digital employees are structurally forbidden from approving or merging pull requests. The human engineer always conducts the final review and triggers deployment.
The Stack in Action: DeepSeat & GeminiStick
To see how role specialization works in production, consider how we onboarded our two digital teammates:
- DeepSeat: Our dedicated backend implementation engineer. Its allowlist is restricted entirely to DeepSeek models. It has write permissions inside its worktree, but zero permissions to approve pull requests.
- GeminiStick: Our code review and QA specialist. Its allowlist is restricted to Gemini models (utilizing large context windows). It never writes feature code; its sole job is to ingest full-repo diffs, run lint/security reviews, and patch broken CI checks.
[Jira Event] ---> Ticket AUTH-412 moved to "Ready for Dev" (@deepseat)
|
+--- [Ingress] Ack comment: "Spawned worktree kai/AUTH-412-token-rotation"
+--- [Router] Role: Developer ---> Dispatched to DeepSeat (DeepSeek tier)
+--- [Runtime] Inspects auth middleware, implements refresh token rotation
+--- [Verify] Runs pytest: 1 assertion fails on token expiry handling
+--- [Heal] Agent inspects trace, fixes boundary check, reruns: 14/14 passed
+--- [Handoff] PR #84 opened on GitHub ---> @geministick picks up the review
When ticket AUTH-412 was assigned to @deepseat, it picked up the ticket, provisioned an isolated worktree, implemented refresh token rotation, hit a timezone boundary assertion failure, healed itself, and opened PR #84 in under 3 minutes for $0.14.
The PR webhook then notified @geministick, which reviewed the diff and confirmed adherence to squad standards.
Production Security & Observability
Treating digital employees as untrusted contributors requires defensive infrastructure.
Non-Negotiable Security Boundaries
- Git Pre-Push Hooks: A server-side hook on the bare mirror rejects any push targeting protected branches (
main,master,release/*). Digital employees only hold branch-creation rights. - Default-Deny Egress: Containers execute behind
nftables/iptablesfirewall rules blocking all outbound network traffic except to declared model API endpoints and the internal package registry. Sandbox test runs execute with--network none. - DLP Redaction: All outbound payloads pass through automated Data Loss Prevention (DLP) filters to ensure database secrets, API keys, and internal PII are scrubbed before reaching model providers.
Observability Telemetry
Every run streams metrics to Prometheus and Grafana:
- Queue Latency: Time from ticket status change to worktree initialization.
- Self-Healing Success Rate: Percentage of test failures resolved without human intervention.
- Token Spend by Role: Live spend tracking against monthly budget caps.
- Audit Trail: Append-only, hash-chained logs tracking every tool execution and file modification for SIEM compliance.
Getting Started: How to Implement in Your Squad
You don't need a massive platform engineering team to begin. Follow this rollout sequence:
- Start with CLI Mode: Deploy Model Context Protocol (MCP) servers and standardize persona slash commands (
/dev,/review) across your engineers' local Claude Code environments. - Stand Up the Gateway: Put LiteLLM in front of your providers to establish model tiers, assign token budgets per squad, and monitor spend.
- Build the Ingress Bridge: Pick one single, well-defined task—such as scaffolding regression tests for closed bugs or reviewing PR diffs—and wire a webhook listener to spawn containerized
git worktrees. - Enforce the Self-Healing Verification Loop: Never allow an agent to submit work without running the test suite and capturing exit codes.
- Evaluate on Output: Track your digital hires on DORA metrics and PR cycle time alongside human engineers.
Stop treating AI as an interactive typing assistant that drains your budget. Build the governance, spin up the worktrees, and onboard your first autonomous teammate.
In Part 3, we look at the operational reality: reading the live observability dashboard, managing safety guardrails under enterprise audits, analyzing failure modes, and exploring the roadmap ahead.
Comments
Leave a comment