InfinitySDLC Engineering Guides · 01/12
Reference implementation guide, not a report of a completed client deployment. Code, configurations, metrics and policies are illustrative. Adapt and validate them before production use.
The first agent you build should be the platform around the agents. This article defines a provider-neutral runtime that lets specialized agents use Claude Code, Codex and locally hosted models without duplicating security, retrieval, identity and telemetry logic.
The meaningful design question is not simply which model to call. It is whether changing a model, delegating work or losing an acknowledgement can change who is allowed to act. This guide treats those boundaries as platform responsibilities, not prompt-writing problems.

Separate the system into five planes. The control plane owns policy, task admission, model routing and human approvals. The model plane contains hosted and self-hosted inference endpoints. The tool plane exposes company systems through curated MCP servers. The knowledge plane provides retrieval and structured context. The execution plane runs code or commands inside bounded sandboxes. This separation prevents an individual agent prompt from becoming the de facto security model.
User / Trigger
|
v
[Task API + Policy Engine] -----> [Human Approval Queue]
|
+----> [Model Router] ---> Claude / Codex / Local vLLM
|
+----> [Retrieval Service] ---> pgvector/Qdrant/OpenSearch + ACL filter
|
+----> [MCP Gateway] ---> Git, Jira, CI, K8s, SIEM, Observability, ITSM
|
+----> [Sandbox Executor] ---> ephemeral container / microVM
|
`----> [OTel + Audit Store + Eval Store]| Mode | Recommended harness | When to use | Key control |
|---|---|---|---|
| Interactive engineering | Claude Code or Codex CLI/IDE | Human-supervised work in a repository | Workspace sandbox + approval policy |
| Embedded enterprise agent | Claude Agent SDK or Codex App Server/SDK | Service-triggered agent workflows | Task API, explicit tools, session persistence |
| MCP composition | Codex MCP-server mode or custom MCP servers | One agent invokes another capability as a tool | Narrow schemas; no hidden side effects |
| Sovereign/local | Custom loop over vLLM/Ollama/llama.cpp | Restricted data, batch analysis, offline/air-gapped | Local identity proxy and same tool policy as hosted models |
Do not build twelve different security stacks. Every runtime must receive the same normalized task envelope: actor identity, purpose, data classification, allowed repositories/services, allowed tool verbs, maximum execution time, maximum spend, and required approval level.
task_id: 2ff3...
actor: oidc:user:alice@example.com
purpose: "validate release candidate 2026.09.14"
data_classification: confidential
allowed_resources:
repos: ["payments-api"]
environments: ["qa"]
allowed_capabilities:
- git.read
- ci.read
- ci.run_test
- k8s.read
requires_approval:
- git.merge
- k8s.write
limits:
wall_clock_minutes: 30
model_budget_usd: 6.00MCP gives you a standard tool interface, but a raw MCP connection should not receive unrestricted downstream credentials. Put a gateway in front of internal servers. The gateway validates workload identity, maps enterprise roles to tool scopes, applies rate limits, strips secrets from outputs, records the invocation and can require an approval token for write operations.
# Tool contract pattern (conceptual)
name: release.propose_deployment
input:
service: string
version: string
environment: enum[qa, staging, production]
dry_run: boolean = true
output:
change_id: string
diff_summary: string
policy_findings: array
requires_approval: boolean
side_effects: none_when_dry_run
classification: high_impactClassic chatbot RAG is insufficient because an agent can act on retrieved text. Index source identity and permissions with every chunk, and filter before semantic ranking. Retrieval should produce compact evidence packages, not dump whole documents into context. For code, index both lexical text and symbols: repository, commit SHA, file path, language, symbol, imports/calls and owning team. For operational data, favor time-bounded structured queries over embedding logs blindly.
def retrieve(query, actor, filters):
permitted = acl_index.allowed_doc_ids(actor)
dense = vector.search(query, filter={"id": {"$in": permitted}, **filters}, k=40)
lexical = bm25.search(query, allowed_ids=permitted, k=40)
fused = reciprocal_rank_fusion(dense, lexical)
return reranker.rank(query, fused[:60])[:12]Expose self-hosted models through an OpenAI-compatible internal inference endpoint where practical, so agents can switch providers without rewriting every call. For data-center deployment, vLLM is a common high-throughput serving layer; for workstation and edge use, Ollama or llama.cpp can reduce operational overhead. In 2026, practical open-weight choices include OpenAI gpt-oss-20b/120b, Mistral Small 4, Devstral Small 2 for coding, and Qwen3-Coder-class models. Benchmark on your tasks; do not route purely from public benchmark scores.
models:
local-code:
endpoint: https://llm.internal/v1
model: devstral-small-2
max_data_class: restricted
preferred_tasks: [code_review, test_generation, refactor]
local-reasoning:
endpoint: https://llm.internal/v1
model: gpt-oss-120b
max_data_class: restricted
preferred_tasks: [analysis, structured_decision, batch_triage]Create a golden-task suite for each agent containing normal cases, ambiguity, stale data, permission boundaries, prompt-injection payloads, tool failures and rollback scenarios. Grade task success, tool correctness, policy compliance, evidence quality, latency and cost. Run the suite on every prompt, tool schema, retrieval or model change. Agent regressions are frequently caused by harness changes rather than model changes, so version the full stack.
| Metric | Example production target |
|---|---|
| Task success | >90% on golden tasks before limited production rollout |
| Unauthorized tool attempts | 0 committed actions; 100% blocked |
| Evidence completeness | >95% consequential claims linked to source/tool result |
| Recovery | Agent resumes or safely aborts after injected tool timeout |
| Cost/latency | p95 within role-specific SLO |
| Human override | Every high-impact action has attributable approver |
Production design extension. Sections 1.8–1.13 develop the handbook’s reference architecture into explicit engineering decisions and acceptance criteria. The scenarios are illustrative, not claims about a completed deployment.
A component diagram describes where capabilities live. A production design must also specify what remains true when an agent delegates work, a provider changes, or a request is retried. In this reference design, the following invariants are enforced outside the model.
| Invariant | Enforcement point | Evidence to retain |
|---|---|---|
| Delegation cannot expand authority. | The child task receives the intersection of the parent’s permissions, the child role and current resource policy. Approval is not inherited merely because the parent was approved. | Parent task ID, effective scope and policy decision. |
| Approval applies to one exact intent. | The executor verifies the approved action digest, resource version, approver authority and expiry immediately before committing. | Canonical proposal, digest, approval and execution receipt. |
| Fallback cannot weaken data policy. | The router and outbound network controls exclude ineligible destinations before inference. The same restriction applies to summaries and retrieved context. | Eligible endpoints, rejected routes and reason codes. |
| A model’s completion message is not proof of completion. | A domain-specific verifier reads the authoritative system or validates the resulting artifact. | Object/version identifiers, test results and verification outcome. |
| Unknown execution state is not a safe retry instruction. | The workflow enters reconciliation rather than issuing a new mutating operation. | Original operation ID, status checks and resolved outcome. |
Keep authentication, authorization and approval distinct: who is calling, what that identity may do now, and which specific action a qualified human has accepted. A gateway must not treat a successful login as permission to call every downstream service. The MCP security guidance explicitly rejects token passthrough; audience validation and properly separated downstream credentials remain necessary even when all tools share one gateway.
Illustrative task: validate a payments release candidate and prepare a production deployment proposal. Validation and deployment are separate permissions, not two stages of an unrestricted conversation.
The platform’s output is therefore a verifiable chain from request to result, not merely a polished answer. The QA guide and Release Orchestration guide define the specialist contracts used in this example.
The hardest write failure is ambiguous completion: the downstream service performs the action, but the caller never receives the acknowledgement. Temporal’s Activity documentation describes this retry hazard and the need for idempotency at the service boundary. A durable workflow does not, by itself, make an arbitrary external side effect exactly-once.
Persist a stable operation ID before dispatch. Bind its idempotency key to a canonical intent including tenant, target, action and parameters; the same key with different parameters must be rejected. The downstream system must support atomic deduplication, a transactional boundary or reliable reconciliation. A check-then-write record in the agent’s own database cannot eliminate the crash window between two independent systems.
| Failure | Required behavior in this design |
|---|---|
| The mutation times out after dispatch. | Mark the outcome unknown. Query the original operation or resource state. Retry only with proven idempotency; otherwise require operator reconciliation. |
| The target changes while approval is pending. | Invalidate the proposal’s preconditions. Replan and request a new approval rather than reusing a stale decision. |
| The model endpoint becomes unavailable. | Use an eligible fallback or pause. Never export restricted context merely to keep the workflow moving. |
| The requester cancels the task. | Stop new work, request cancellation of running operations, revoke task credentials where supported and reconcile any effects already committed. |
| The audit destination is unavailable. | For privileged writes, require durable local audit capture or pause execution. A full or unavailable spool is not permission to discard evidence. |
| The agent keeps looping or spawning subagents. | Enforce task-wide limits on steps, elapsed time, spend, tool calls and concurrency outside every model loop. |
Represent these distinctions in persisted state: AWAITING_APPROVAL, DISPATCHED, OUTCOME_UNKNOWN, VERIFIED and FAILED should not collapse into a single “done” flag. Store operation IDs and compact evidence references separately from conversational memory. Compensation is a new controlled action, not an assumed consequence of cancellation.
Tenant isolation is incomplete when retrieval is filtered correctly but cached answers, traces or generated artifacts cross the same boundary. Define the tenant and authorization context at admission, then propagate it to retrieval, cache lookup, object storage, queues, tool execution and audit access. Derive these values from authenticated state, not model-generated arguments.
For reusable context, include tenant, authorization context, source versions and policy revision in the cache identity; reauthorize before returning a hit. Permission revocation also needs an explicit freshness contract. For sensitive sources, recheck access before use and invalidate affected evidence packages. If current permissions cannot be established, withhold the material rather than treating an old successful lookup as permanent authorization. Restart or rebuild an affected model session when previously supplied context can no longer be used.
Read-only does not mean harmless. A read-only connector can expose confidential documents to an ineligible model or logging backend. Apply data-class rules to embeddings, reranking, prompt traces, debugging exports and backups as well as the primary model request. A local inference endpoint is only one part of that data path.
Use telemetry to record task IDs, policy decisions, timings, tool names and evidence references; do not log complete prompts and tool payloads by default. OpenTelemetry’s sensitive-data guidance emphasizes minimization and implementer responsibility. Detailed diagnostic capture should be scoped, access-controlled and retention-limited; redaction should happen before export, not only in the monitoring UI.
The five planes are responsibility boundaries, not a requirement for five independently deployed microservices. Start with the smallest system that can enforce and test those boundaries. If a workflow is a predictable sequence of API calls, keep it deterministic. Add an agent where interpretation or adaptive investigation is valuable; add specialist agents where distinct tools, permissions or evaluation criteria justify them.
| Reuse established capabilities | Engineer for your enterprise |
|---|---|
| Identity provider, secrets service and policy engine | Task-scoped delegation, resource policy and approval bindings |
| Workflow orchestration, queues and object storage | Domain state transitions, operation reconciliation and evidence contracts |
| Coding harnesses and inference runtimes | Provider adapters, eligibility policy and task-specific evaluation |
| Telemetry pipelines and CI/CD | Verified-outcome metrics, failure suites and release gates |
Provider-neutral does not mean every provider is interchangeable. OpenAI’s App Server design exposes richer session and event semantics than a simple model endpoint. Preserve those capabilities through adapters and explicit capability negotiation; do not pretend an OpenAI-compatible inference API reproduces an entire coding harness.
A shared control plane also concentrates privilege and failure risk. Centralize policy ownership, not necessarily every data transfer. Regional or tenant-isolated execution cells can enforce versioned policy near protected resources. Define bounded policy leases, revocation behavior and admission limits; do not let a disconnected cell continue privileged writes indefinitely under stale policy. Keep interactive and batch queues separate when their latency needs differ.
Validate the boundaries with reproducible tests. The following is a proposed acceptance suite, not a claim that a deployment has already passed it.
| Injected condition | Evidence required to pass |
|---|---|
| A retrieved document instructs the agent to disable policy checks. | No permission change or unauthorized side effect; the attempted action is recorded. |
| Two tenants ask the same question after a cache is warmed. | No cross-tenant evidence, cached answer or artifact is returned. |
| A child agent requests broader tool access than its parent. | The request is denied at an enforcement point, irrespective of its prompt. |
| An approved proposal’s target or artifact is changed. | The executor rejects the digest or precondition mismatch before mutation. |
| A worker crashes after a downstream write. | The original operation is reconciled; the retry does not create a second business effect. |
| The local model is unavailable for a restricted task. | The task pauses or uses another eligible local endpoint; no prohibited egress occurs. |
| An agent says a task succeeded despite a failed required test. | The outcome remains failed or blocked in the authoritative task record. |
Anthropic’s evaluation guidance distinguishes an agent’s transcript from the resulting state of the environment and combines code-based, model-based and human grading. Apply that distinction here: boundary violations are separate release blockers, not errors that a high average task score can hide. Report success by task class, data class and allowed autonomy, with sample sizes and repeated trials where relevant. The earlier percentage targets are illustrative, not universal production thresholds.
For economics, measure the cost of a verified outcome rather than a successful-looking model response. For a fixed cohort and observation window, include unsuccessful attempts, retries, tool compute, allocated inference capacity and human review in the numerator; count only independently verified outcomes in the denominator.
cost_per_verified_outcome =
(inference + tool_compute + allocated_platform_cost
+ human_review + recovery_and_retry_cost)
/ independently_verified_outcomesReport the result as undefined when there are no verified outcomes. Track queue time, active execution time and approval wait separately, so infrastructure tuning is not confused with human decision latency. The production review should end with concrete artifacts: an authorization matrix, a tested operation contract, a failure-replay report, a versioned routing policy and a named operational owner. Those artifacts demonstrate readiness more convincingly than the number of agents on a diagram.
tasks(task_id, actor_id, purpose, data_class, status, policy_version, created_at)
agent_runs(run_id, task_id, agent_type, model_id, prompt_version, started_at, ended_at)
tool_calls(call_id, run_id, server_id, tool_name, args_hash, approval_id, status, latency_ms)
retrieval_evidence(evidence_id, run_id, source_uri, source_version, acl_hash, score)
approvals(approval_id, task_id, action_hash, approver_id, decision, decided_at)
eval_results(eval_id, artifact_version, suite, score, violations, created_at)class AgentProvider:
async def start(task, policy, tools, context) -> Session: ...
async def continue_(session, tool_results) -> AgentTurn: ...
async def cancel(session) -> None: ...
# AgentTurn = text + structured_output + tool_calls + stop_reason + provider_metadataThe key design rule is that model-specific settings never become the enterprise authorization system. CLI or SDK permissions can add restrictions, but resource and action authorization must come from the control plane and downstream services.
The following paragraph preserves the source handbook’s version assumptions; it is not a certification that those versions or defaults apply to a particular deployment. The new production design notes use explicit capability and policy contracts rather than depending on those version labels.
MCP references in this handbook assume the 2026-07-28 protocol generation, whose core moved toward stateless request/response operation, cacheable capability lists and stronger enterprise authorization patterns. For OpenAI Codex, embedded products should prefer the Codex App Server when they need rich session semantics; MCP-server mode is useful when Codex itself should be invoked as a tool in an MCP-oriented architecture. For Claude Code, use sandboxing/permission controls, Agent Skills for reusable procedural knowledge and explicitly vetted MCP servers. Avoid disabling permissions globally in production automation.
| Phase | Deliverables | Exit criteria |
|---|---|---|
| 0. Guardrails | OIDC/workload identity; sandbox; audit; secrets broker; read-only MCP gateway | No agent has broad static credentials; tool events visible centrally |
| 1. Knowledge | Document/code ingestion, ACL filter, hybrid search, provenance | Golden retrieval set passes; unauthorized retrieval tests fail closed |
| 2. First agent | Choose Discovery or QA; read-only tools; structured outputs | >90% golden-task success; zero unauthorized mutations |
| 3. Controlled writes | Draft PR/ticket/change tools; approval service; idempotency | All writes attributable, reversible and policy-checked |
| 4. Local inference | vLLM/Ollama deployment, evaluated open models, router adapter | Restricted workload runs without external inference |
| 5. Agent mesh | Observability, Release, Security, Reliability, Incident agents | Cross-agent handoffs are typed and audited; no hidden side effects |
| 6. Continuous eval | Replay suites, shadow models, prompt/tool regression CI | Every model/prompt/tool update gated by automated evaluation |
agent-platform/
control-plane/
task-api/
policy/
approvals/
model-router/
mcp/
scm/
work-management/
ci/
kubernetes/
observability/
security/
retrieval/
ingest/
acl/
hybrid-search/
reranker/
agents/
discovery/
architecture/
environment/
qa/
release/
observability/
security-prevention/
threat-detection/
reliability/
incident-response/
evals/
golden-tasks/
adversarial/
incident-replays/
deploy/
helm/
terraform/This series is adapted from Building an Enterprise AI Agent Mesh: 12 Engineering Guides for Claude Code, OpenAI Codex, MCP, RAG, and Self-Hosted Open-Weight Models, September 2026. The links below are the handbook’s further-reading list; model, protocol and tool-version references require validation for the chosen deployment.