Markdown Editor

AI Coding Assistant System Design Template

AI coding assistant design: IDE and CLI clients, repo indexing, context assembly, agent loop, microVM sandbox, MCP and Agent Skills, approvals, security

Desain SistemLengkapMCP 2026-07-28; Agent Skills spec; OWASP LLM Top 10 2026designcodingassistant

Cara menggunakan: Use it when you design or review an AI coding assistant with inline completion and an agent that edits code and runs tests. Fill the capacity estimates (3) and the tool risk classes (7.4) first, because token cost and permissions shape everything else. The main pitfall is letting the agent run with the developer's credentials and network, so a poisoned README becomes a breach.

Pratinjau

System Design: [AI coding assistant name]

Reference design for an AI coding assistant used by an engineering organisation from the IDE and the command line. It covers repository indexing and code search, context assembly, the split between inline completion and agentic edit loops, sandboxed tool execution and tests, the review and approval loop, tool integration through the Model Context Protocol (MCP, revision 2026-07-28) and Agent Skills (agentskills.io specification), latency and cost, and the security problems specific to code: secrets, prompt injection from repository content, and licence and provenance of generated code. Threats are mapped to the OWASP Top 10 for LLM Applications 2026. It follows the 12-section skeleton of the System Design Document template and is pre-filled with a worked design to adapt. Replace every [bracketed] value and every row marked Example; all numbers are illustrative examples, not benchmarks.

Document control

FieldValue
Document ID[SDD-CODE-001]
System / feature[AI coding assistant: IDE extension, CLI agent, backend]
Version[0.1]
Status[Draft / In review / Approved / Implemented / Superseded]
Author(s)[@author]
Reviewers[@reviewer-1], [@reviewer-2]
Last updatedYYYY-MM-DD
Classification[Internal]
Models in scope[Completion model, agent model, embedding model, with versions and licences]
Repositories in scope[All internal repositories / listed organisations / excluded repositories]
Protocols[MCP revision 2026-07-28], [Agent Skills specification]
Related[AI agent specification], [Agent tool permission design], [Threat model], [LLM observability spec]

Approvals

RoleNameDecisionDate
Tech lead, developer platform[@name][Approved / Changes requested]YYYY-MM-DD
Staff / principal engineer[@name][Decision]YYYY-MM-DD
Application security[@name][Decision]YYYY-MM-DD
Legal / open source programme office[@name][Decision]YYYY-MM-DD
FinOps / budget owner[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft for design review
0.2YYYY-MM-DD[@name]Example: Moved test execution from developer laptops to remote microVM sandboxes
0.3YYYY-MM-DD[@name]Example: Added MCP server allowlist and per-tool approval policy
1.0YYYY-MM-DD[@name]Example: Approved

Contents

1. Overview

1.1 Problem statement

[Example: Developers use three unmanaged AI tools with personal accounts. Source code leaves the company without a data processing agreement, nobody can tell which commits were AI-assisted, and one tool executed a shell command suggested by a README in a cloned third-party repository. Teams want completions inside the IDE and an agent that can fix a failing test, run the suite and open a pull request, under company controls.]

1.2 Proposed solution

[Example: One managed assistant with two clients (IDE extension and CLI) and one backend. Inline completion goes through a low-latency path to a small self-hosted model with a context window built from the open file, neighbouring files and the repository index. Agent tasks run a plan, act, observe loop with a larger model; every file edit and command runs in an isolated remote sandbox with a copy of the repository, no production credentials and an egress allowlist. The agent proposes a diff; a human approves it in the IDE or as a pull request. External tools are attached only through allowlisted MCP servers, and team procedures are packaged as Agent Skills. All requests pass a gateway that enforces identity, repository permissions, secret scanning and cost budgets.]

1.3 Decisions requested from reviewers

IDQuestionRecommended optionSection
Q-01Example: Run agent commands on the laptop or in a remote sandbox?Remote microVM sandbox by default; local mode only for approved repositories7.3
Q-02Example: Index with embeddings, lexical search or both?Both, plus a symbol graph; fuse results7.2
Q-03Example: Which actions need human approval?Anything outside the sandbox, any network call off the allowlist, any push7.4, 7.5
Q-04Example: Who may add MCP servers?Platform team allowlist; users choose from it7.4
Q-05Example: Block completions that match public code?Filter on by default, with a reference shown when a match is allowed9.2
[Q-nn][Question][Option][Section]

1.4 45-minute interview path

MinutesCoverOutput on the whiteboard
0 to 5Clarify users, clients (IDE, CLI), completion versus agent, repository countCore requirements list (2.1) and below the line (2.3)
5 to 10Estimate completion QPS, agent tokens per day, sandbox concurrencyThree numbers and their consequences (3.6)
10 to 15API for completion, agent task and events; data model with access patterns4.1 and 5.2
15 to 25High-level diagram: gateway, context engine, index, model pools, agent orchestrator, sandboxSection 6
25 to 40One deep dive. Pick context assembly (7.2) for a retrieval-minded panel, the agent loop and sandbox (7.3) for a platform panel, or tool permissions and prompt injection (7.4, 9.2) for a security panelOptions, choice and reason
40 to 45Failure modes, 10x row of the trade-off table, what you would build next9.1 and 10

2. Requirements

2.1 Core functional requirements

IDRequirementPriority
FR-01Example: Inline completion (single and multi-line) in supported IDEs, streamed, cancellable on the next keystrokeMust
FR-02Example: Chat about the codebase with answers that cite files and line rangesMust
FR-03Example: Agent tasks from IDE or CLI: read code, edit files, run commands and tests in a sandbox, iterate until tests pass or budget endsMust
FR-04Example: Every agent change is presented as a reviewable diff; nothing is pushed without human approvalMust
FR-05Example: Repository index (lexical, symbol and semantic) that respects the user's repository permissionsMust
FR-06Example: Tool integration through MCP servers from an allowlist, with per-tool approval policiesMust
FR-07Example: Organisation and repository instructions and Agent Skills loaded on demandShould
FR-08Example: Pull request creation with an AI-assistance trailer and a task transcript linkShould
FR-09Example: Usage and cost reporting per teamShould
[FR-nn][Requirement][Must / Should / Could]

2.2 Non-functional requirements

IDQualityTargetMeasured as
NFR-01Completion latencyExample: p50 at or below 250 ms, p95 at or below 500 ms from request to first suggestion token in the clientClient telemetry
NFR-02Agent step latencyExample: p95 model turn at or below 20 s; sandbox command start at or below 2 sOrchestrator timing
NFR-03AvailabilityExample: 99.9% monthly for completion; 99.5% for agent tasksSLO on successful responses
NFR-04IsolationExample: Sandbox has no route to production networks; zero secrets from the vault presentQuarterly penetration test, configuration audit
NFR-05Data handlingExample: No source code retained by the model provider; completion prompts logged only as hashes unless the team opts in; agent transcripts kept only for the audit retention in 5.3Contract and configuration audit
NFR-06QualityExample: Completion acceptance rate tracked per language; agent task success on an internal benchmark at or above the baseline before any model changeOffline evaluation, telemetry
NFR-07CostExample: Within the per-developer budget in 3.4Monthly chargeback
[NFR-nn][Quality][Target][Measurement]

2.3 Below the line (out of scope)

  • [Example: model training or fine-tuning on internal code (separate project with its own data review)]
  • [Example: autonomous merging to protected branches; the agent never merges]
  • [Example: agents that run on a schedule without a user who started them]
  • [Example: code review bots on every pull request (consumer of this platform, designed separately)]
  • [Item deferred, with the release that will take it]

3. Capacity estimation

3.1 Assumptions

All values are Example planning inputs.

InputValueSource
Licensed developers20 000Licence plan
Daily active developers12 000Pilot telemetry
Completion requests per active developer per day (after client debounce)400Pilot telemetry
Working window8 hMain time zone
Peak to average ratio3Pilot telemetry
Completion prompt tokens / output tokens2 000 / 40Context budget
Agent tasks per active developer per day3Pilot telemetry
Model turns per agent task25Pilot telemetry
Mean input tokens per agent turn30 000Context grows during a task
Mean output tokens per agent turn800Pilot telemetry
Sandbox time per task10 minPilot telemetry
Lines of code across repositories400 millionSource host statistics

3.2 Completion traffic

Requests per day: 12 000 x 400 = 4.8 million. Spread over the 8-hour window (28 800 s) that is about 167 requests/s on average and about 500 requests/s at peak (ratio 3). Prompt tokens per day: 4.8 million x 2 000 = 9.6 billion.

Consequence: completion needs a dedicated small-model pool with prefix caching and request cancellation; about half of the requests are cancelled by the next keystroke, so the server must abort generation on client disconnect or it pays for tokens nobody sees.

3.3 Agent traffic

Tasks per day: 12 000 x 3 = 36 000. Per task: 25 turns x 30 000 = 750 000 input tokens and 25 x 800 = 20 000 output tokens. Per day: 36 000 x 750 000 = 27 billion input tokens and 36 000 x 20 000 = 720 million output tokens.

Consequence: agent mode is under 1% of requests (36 000 against 4.8 million) yet produces almost three times the input tokens of completion. Cost control is a context design problem: keep the prompt prefix stable so it is cached, and compact the history before it grows past a set size.

3.4 Cost of agent tokens

With Example list prices of USD 3 per million input tokens, USD 0.30 per million cached input tokens and USD 15 per million output tokens:

ScenarioInput cost per dayOutput cost per dayTotal per day
No caching27 000 x 3 = USD 81 000720 x 15 = USD 10 800USD 91 800
80% of input served from cache27 000 x (0.2 x 3 + 0.8 x 0.30) = USD 22 680USD 10 800USD 33 480

Per active developer that is about USD 7.65 per day without caching and about USD 2.79 with it. Consequence: the context engine (7.2) must append to the conversation rather than rewrite earlier turns, because any change to the prefix invalidates the cache. Budgets per task and per day are enforced at the gateway.

3.5 Index and sandboxes

ItemCalculationResultConsequence
Code chunks400 million lines / 40 lines per chunk10 million chunksFits one sharded vector store
Embeddings, 1 024 dimensions, float3210 million x 1 024 x 4 Babout 41 GBQuantize to int8 (about 10 GB); shard by repository
Lexical and trigram indexAbout the size of the source, 400 million x 40 Babout 16 GBMemory-resident lexical index per shard
Re-index loadExample: 50 000 commits/day x 20 changed files1 million files/day, about 12/sIncremental indexing by file hash, never full rebuilds
Sandbox minutes36 000 tasks x 10 min360 000 min/dayBill and budget sandboxes per task, not per developer
Concurrent sandboxes360 000 / 480 min, then x 2 for peaksabout 750 average, about 1 500 at peakWarm pool of snapshot-restored microVMs
Sandbox resources at peak1 500 x 2 vCPU and 4 GB3 000 vCPU, 6 TB memoryDedicated autoscaled node group

3.6 Summary

QuantityEstimateDesign consequence
Completion peakAbout 500 requests/s, 2 000-token promptsSmall model, prefix cache, cancellation, regional pools
Agent input tokensAbout 27 billion per dayPrompt caching and history compaction are the main cost levers
Agent costAbout USD 33 000 per day with caching (Example)Per-task and per-developer budgets at the gateway
IndexAbout 10 million chunks, tens of GBShard by repository; incremental updates
SandboxesAbout 1 500 concurrent at peakSnapshot-based microVM pool, start under 2 s

4. API design

4.1 Endpoints

Method and pathPurpose
POST /v1/completionsInline completion; streamed; cancelled when the client closes the stream
POST /v1/chatCodebase question with citations to files and lines
POST /v1/tasksStart an agent task (repository, branch, instruction, budget)
GET /v1/tasks/{id}/eventsServer-sent events: plan, tool call, approval request, diff, result
POST /v1/tasks/{id}/approvals/{approval_id}Approve or reject a pending action
POST /v1/tasks/{id}/cancelStop the task and tear down the sandbox
GET /v1/tasks/{id}/diffCurrent proposed diff
POST /v1/searchCode search (lexical, symbol, semantic) within permitted repositories
GET /v1/usageTokens, sandbox minutes and cost per user or team

4.2 Request example

An agent task start is shown below. The idempotency key makes a retried start return the existing task instead of creating a second sandbox. Completion requests differ: the client sends what it knows cheaply (cursor, prefix, suffix, open file, recent edits) with a request ID, the server adds repository context, and the request ID lets the server cancel generation when a newer request arrives from the same editor.

POST /v1/tasks
Authorization: Bearer [user token]
Idempotency-Key: [uuid]
Content-Type: application/json

{"repository": "[org/repo]", "base_ref": "main", "instruction": "Fix the failing test in billing/invoice_test.py", "budget": {"max_turns": 40, "max_cost_usd": 5}, "approval_policy": "default"}

4.3 Errors

StatusProblem typeMeaning
403repository-forbiddenUser lacks read access to the repository in the source host
409approval-pendingTask is waiting for a human decision
422secret-detectedContext contained a secret that policy forbids sending
429budget-exceededTask, user or team budget reached; Retry-After for rate limits
503sandbox-capacityNo sandbox available within the start deadline

Errors use RFC 9457 problem details.

5. Data model

5.1 Entities

Index entities are derived from the source host and can be rebuilt; task, tool call and approval records are the audit trail and must be retained.

5.2 Access patterns

QueryServed byPartition key and rationale
Lexical or regex search in repositories the user can readTrigram index per shard, filtered by repository ID listrepo_id: permissions are per repository, so a filter on the key prunes shards
Semantic search for a natural-language questionVector index with repository filter, then rerankrepo_id: same pruning; avoids cross-repository leakage by construction
Go to definition and find references across filesSymbol graph table keyed by fully qualified namerepo_id plus symbol name: graph walks stay inside one repository
Has this file changed since indexing?FILE_VERSION keyed by repository and path, compared by hashrepo_id: the indexer works one repository at a time
Stream events of a running taskEvent log keyed by task ID, ordered by sequencetask_id: one writer, one reader, strict order
Pending approvals for a userSecondary index on approver and statususer_id: the IDE polls only its own queue
Usage per team per dayAggregated usage table in the warehouseteam_id plus date: reporting only, never on the request path

5.3 Storage choices

DataStoreNotes
Repository metadata, ACL cacheRelational databaseACL cache refreshed from the source host on webhook and every 15 min
Lexical and symbol indexSearch engine shards in memoryRebuilt per file on change
EmbeddingsVector store, int8 quantizedOne embedding model version per index; re-embed on model change
Task events and transcriptsAppend-only log, 90-day retention (Example)Needed for audit and for review of the diff
Sandbox images and snapshotsObject storage plus node-local cacheSnapshot per base image and repository warm-up
Usage recordsEvent stream to the warehouseNever on the request path

6. High-level design

ComponentResponsibilityScales by
Assistant gatewayAuthentication, routing, streaming, cancellation, meteringHorizontally
Policy layerRepository permissions, budgets, secret scanning on outbound contextHorizontally, cached ACLs
Context engineRetrieve and rank snippets, assemble prompt within a token budgetHorizontally
Index and indexerLexical, symbol and vector search; incremental updates from webhooksShards per repository group
Completion poolSmall model, low latency, prefix cacheGPUs, per region
Agent orchestratorPlan, act, observe loop; budgets; event logHorizontally, tasks are independent
Sandbox managerCreate, snapshot, destroy microVMs; egress policyNode group size
MCP client hubConnections to allowlisted MCP servers, tool policy enforcementHorizontally
Approval servicePending decisions, notification, auditHorizontally

7. Detailed design

7.1 Completion request flow

The client debounces keystrokes, sends prefix and suffix around the cursor and a list of recently edited and open files. The server uses a fill-in-the-middle prompt format so the model sees code after the cursor. Suggestions stop at a syntactic boundary (end of block or line) decided by the client's parser, which keeps them short and cheap.

7.2 Deep dive 1: repository indexing and context assembly

The quality of both completion and agent work depends more on what enters the context window than on the model. The context engine has a fixed token budget and must fill it with the most useful snippets.

OptionHow it worksStrengthsWeaknesses
A. Open files onlyUse the current file and open tabsNo index, no latencyMisses definitions in closed files; poor for agents
B. Embedding searchChunk code, embed, nearest neighbours to the cursor or questionFinds conceptually related codeWeak on exact identifiers; chunk boundaries cut functions
C. Lexical and symbol graphTrigram search plus a graph of definitions and referencesExact, explainable, cheapMisses natural-language intent
D. Hybrid with rerankingRun B and C, fuse ranks, rerank with a small model, pack by budgetBest recall on both identifiers and intentMore components to run and tune

Choice: D for chat and agent context; for completion, C plus open files and recently edited files, with B only when the prefix is a comment or a docstring. Reason: completion has a 500 ms budget and benefits most from exact definitions of the symbols near the cursor; agents and chat ask intent questions where semantic search helps.

Context assembly rules:

RuleDetail
CTX-01 (Example)Chunk on syntax boundaries (function, class) using a parser, not fixed line counts
CTX-02 (Example)Always include definitions of symbols referenced within 30 lines of the cursor
CTX-03 (Example)Pack by priority until the token budget is spent; truncate the lowest-ranked snippet, never the cursor region
CTX-04 (Example)Exclude files matched by the deny-list (.env, key files, secrets/) and generated or vendored code
CTX-05 (Example)Agent prompts: stable system prompt, tools and skills index first; task history appended; compaction replaces old tool output with summaries only at checkpoints, so the cached prefix survives

7.3 Deep dive 2: agentic edit loop and sandboxed execution

The agent alternates model turns with tool calls (read file, search, edit, run command) until the tests pass, the budget ends or a human stops it.

Option for where commands runStrengthsWeaknesses
A. Developer laptop, with prompts for each commandReal environment, no infrastructureAgent shares the developer's credentials, network and files; prompt fatigue leads to blanket approval
B. Containers on shared hostsCheap, fast startShared kernel; a container escape reaches other tenants
C. MicroVMs per task, restored from snapshotsStrong isolation, fast start from snapshot, disposableImage and snapshot pipeline to maintain

Choice: C by default, A only for repositories on an approved list with read-only credentials. Reason: the agent runs code that it or the repository wrote, including test fixtures and build scripts that could be hostile; a disposable VM with no secrets and an egress allowlist makes a successful injection mostly harmless.

Sandbox rules:

RuleDetail
SBX-01 (Example)Fresh microVM per task from a snapshot of the base image plus a warmed dependency cache
SBX-02 (Example)Repository mounted as a clone at the base commit; no source host credentials inside
SBX-03 (Example)Egress allowlist: package mirrors and the internal artefact proxy only; everything else blocked and logged
SBX-04 (Example)CPU, memory, disk and wall-clock limits per command and per task
SBX-05 (Example)Destroyed on task end; logs and the diff exported, nothing else

Budgets end runaway loops: maximum turns, maximum cost, maximum identical failing command repeats (for example, three) and a wall-clock limit.

7.4 Deep dive 3: tool integration with MCP and Agent Skills

The Model Context Protocol (revision 2026-07-28) connects hosts (here, the orchestrator and IDE), clients (one per server connection) and servers that expose tools, resources and prompts over JSON-RPC 2.0. The specification asks hosts to obtain explicit user consent before invoking tools and to treat tool descriptions and annotations as untrusted unless they come from a trusted server. Long-running operations can use the optional Tasks extension where both sides support it.

Option for tool governanceStrengthsWeaknesses
A. Users add any MCP serverFlexibleUnknown code with the user's tokens; tool descriptions can carry injected instructions
B. Platform allowlist with per-tool risk classesReviewed servers, consistent policySlower to add tools
C. No external toolsSmallest attack surfaceAgents cannot reach issue trackers or documentation

Choice: B. Reason: it keeps the benefit of tools while letting the policy layer, not the model, decide what needs approval.

Risk classExamplesPolicy
Read-only inside sandboxRead file, search, list testsAuto-approved
Write inside sandboxEdit file, run tests, install from mirrorAuto-approved within budget
Read outside sandboxIssue tracker read, documentation search over MCPAuto-approved for allowlisted servers; logged
Write outside sandboxComment on an issue, create a branch, open a pull requestHuman approval each time
Irreversible or privilegedPush to protected branch, change CI secrets, deployNot available to the agent

Agent Skills package team procedures (for example, "how to add a database migration here") as a folder with a SKILL.md file whose YAML front matter holds a required name and description. Only names and descriptions are loaded at start; the body and any scripts/, references/ or assets/ files load when the skill is relevant, which keeps the stable prompt prefix small. Skills come from reviewed repositories only, because a skill's scripts run in the sandbox and its text enters the prompt. The optional allowed-tools field is experimental in the specification, so the policy layer, not the skill, remains the source of truth for permissions. Detailed permission design belongs in Agent Tool Permission Design Template (ai-data/agent-tool-permission-design); server contracts in MCP Server Specification Template (ai-data/mcp-server-spec).

7.5 Review and approval loop

  • The agent ends with a proposed diff, a summary of what it changed and why, and the test results from the sandbox.
  • The developer reviews the diff in the IDE, can ask for changes (which continue the same task) and approves. Only then does the orchestrator push a branch and open a pull request through the source host API with the developer's identity.
  • Pull requests carry a trailer such as Assisted-by: [assistant name] and a link to the task transcript, so reviewers know what to look at and audits can find AI-assisted changes.
  • Normal branch protection, code owners and CI apply unchanged; the agent gets no bypass. Oversight patterns follow Human Oversight Design Template (ai-data/human-oversight-design).

7.6 How real systems do it

How real systems do it (paraphrased from Yang et al., "SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering", arXiv:2405.15793, 2024). The SWE-agent authors found that the interface between the model and the computer matters as much as the model. Instead of a raw shell, they gave the agent a small set of purpose-built commands for viewing a window of a file, searching, and editing a line range, with concise feedback after each action and a syntax check that rejects broken edits before they land. These interface choices raised the share of resolved issues on the SWE-bench benchmark compared with a plain shell. Design lesson for this document: invest in the tool surface (7.4) and in compact, structured tool output, not only in a larger model.

8. Scalability and performance

ConcernApproachLimit before redesign
Completion latency at peakRegional completion pools, prefix cache, cancellationGPU capacity per region
Agent token growth within a taskAppend-only history, compaction at checkpoints, tool output truncationModel context window
Index freshnessWebhook-driven incremental indexing by file hashIndexer throughput on monorepo mass changes
Sandbox start timeSnapshot restore, warm pool sized from the hourly patternNode group quota
Large monoreposSparse index by directory ownership, path filters in queriesSingle shard memory

Completion latency budget (target p95 500 ms, Example):

StepBudget
Client to gateway (regional)40 ms
Auth, ACL cache, secret scan15 ms
Context assembly (index lookups in parallel)60 ms
Model time to first token200 ms
Stream first line to client40 ms
Headroom145 ms

9. Reliability, security and operations

9.1 Failure-mode table

ComponentFailureDetectionBlast radiusMitigationRTO
Completion poolRegion overloadedp95 latency, queue depthCompletions slow in one regionShed to neighbour region; client hides late suggestions5 min
Agent model providerOutage or rate limitError rate, 429sAgent tasks pauseFallback model for opted-in teams; tasks resume from event log30 min
IndexStale after missed webhooksIndex lag metric per repositoryWrong or missing contextPeriodic reconciliation by commit hash1 h
ACL cacheStale permission grantsDrift check against source hostUser sees snippets from a repository they lost access toShort TTL, revoke webhook, fail closed on cache miss15 min
Sandbox managerNode group exhaustedPending sandbox countNew tasks waitQueue with deadline, scale-out, priority for interactive tasks15 min
MCP serverUnavailable or misbehavingTool error rateTool missing in tasksCircuit breaker; task continues without the tool and says soPer server SLO
OrchestratorCrash mid-taskHeartbeatRunning tasks on that instanceResume from event log; sandboxes are idempotently reattached or rebuilt; actions outside the sandbox (branch, comment, pull request) carry an idempotency key of task ID and step, so a resumed step never repeats them10 min

9.2 Security

Threat modelling follows Threat Model Template (security/threat-model) and Agentic AI Threat Model Template (ai-data/agentic-threat-model). The mapping below uses OWASP Top 10 for LLM Applications 2026 IDs.

IDThreatOWASP 2026Control
SEC-01Secrets in source sent to the modelLLM02:2026 Sensitive Information DisclosureSecret scanner on outbound context; deny-list paths; block and report (secret-detected)
SEC-02Instructions hidden in a README, issue, test fixture, dependency, command output or MCP tool result tell the agent to exfiltrate or run commandsLLM01:2026 Prompt InjectionRepository content and every tool result marked as untrusted data, never as instructions; egress allowlist; no secrets in sandbox; approval for any action outside the sandbox
SEC-03Agent takes actions beyond the taskLLM03:2026 Excessive AgencyRisk classes in 7.4; no privileged tools; budgets
SEC-04Agent adds a dependency that does not exist or is typo-squattedLLM04:2026 Supply ChainPackage installs only through the internal proxy; new dependencies flagged in the diff; software composition analysis in CI
SEC-05System prompt, tool schemas or skill text reveal internal endpointsLLM08:2026 Hidden Context ExposureTreat hidden context as discoverable; keep credentials and internal hostnames out of it
SEC-06Generated code renders untrusted output (for example, model output rendered as HTML in the IDE panel)LLM10:2026 Improper Output HandlingIDE panels render Markdown with sanitisation; no automatic link fetching
SEC-07Cross-repository leakage through the indexLLM02:2026Repository filter in every query (5.2); fail closed on ACL cache miss
[SEC-nn][Threat][OWASP ID][Control]

Licence and provenance:

  • Enable a filter that suppresses completions matching public code above a length threshold, or show the matching source and its licence when the organisation allows matches.
  • Record AI assistance in commit trailers and keep task transcripts for the retention period, so provenance questions can be answered later.
  • New third-party code and dependencies go through the normal open source review; see Supply Chain Security Plan Template (security/supply-chain-security).

9.3 Observability

Instrument with LLM and Agent Observability Specification Template (ai-data/llm-observability-spec): one trace per task, spans per model turn, tool call and sandbox command.

SignalMetricAlert threshold
Completion latencyp95 by region and languageAbove 500 ms for 10 min
Completion acceptanceAccepted suggestions over shownDrop of 20% week over week
Agent successTasks ending in an approved diff over tasks startedDrop of 15% after a model change
Agent costUSD per task, p95Above budget for a team
Approval waitTime from request to decisionInformational; tune risk classes
Sandbox egress blocksBlocked connections per taskSpike may indicate injection attempts
Secret detectionsCount per repositoryAny new repository with detections

9.4 Cost estimate

ItemUnit costQuantityMonthly cost
Agent model tokensUSD per million tokens (3.4)[Tokens][USD]
Completion GPUs[USD per GPU-hour][GPU-hours][USD]
Sandboxes[USD per vCPU-hour][vCPU-hours][USD]
Index and storage[USD per node-month][Nodes][USD]
Total[USD]

10. Trade-offs and alternatives

DecisionOptionsChosenWhyWhat we give up
Completion modelLarge hosted model; small self-hostedSmall self-hostedLatency and token volumeSome quality on long completions
Context retrievalEmbeddings only; lexical only; hybridHybrid with rerankingIdentifiers and intent both matterTwo index types to operate
ExecutionLaptop; containers; microVMsMicroVMs by defaultIsolation against hostile repository contentImage pipeline and cost
Tool accessOpen; allowlist; noneAllowlist with risk classesUsefulness with controlSlower tool onboarding
Merge authorityAgent merges; human approvesHuman approves every diffAccountability and reviewThroughput of trivial fixes
What changes at 10x (200 000 developers)Regional cells with own index shards, sandbox pools and completion pools; per-tenant budgets enforced in each cellSingle global orchestrator and index would become the bottleneckMore operational surface
What changes at 0.1x (2 000 developers)Hosted completion API instead of self-hosted GPUs; containers with gVisor-style isolation instead of a microVM fleetGPU and microVM fixed costs dominate at small scaleLess control over latency and data path
[Decision][Options][Chosen][Why][Cost]

11. Delivery plan and risks

11.1 Milestones

MilestoneScopeExit criterionTarget date
M1Gateway, policy layer, completion path, lexical indexPilot of 200 developers meets NFR-01YYYY-MM-DD
M2Chat with citations, hybrid indexAnswer citation accuracy checked on a labelled setYYYY-MM-DD
M3Agent tasks in microVM sandboxes, approval loopPenetration test of sandbox passes NFR-04YYYY-MM-DD
M4MCP allowlist and Agent SkillsThree reviewed servers and five skills liveYYYY-MM-DD
M5Organisation-wide rolloutBudgets, chargeback and audit reports liveYYYY-MM-DD

11.2 Rollout and rollback

[Example: Roll out by team with a feature flag in the IDE extension. Model changes go to 5% of users, compared on acceptance rate and agent success; automatic rollback when either drops past its threshold. The previous extension version stays installable for 30 days.]

11.3 Risks

IDRiskLikelihoodImpactMitigationOwner
R-01Example: Prompt injection leads to data exfiltrationMediumHighSandbox without secrets, egress allowlist, approvals[@name]
R-02Example: Token cost exceeds budgetMediumMediumCaching, compaction, budgets, model routing[@name]
R-03Example: Developers approve diffs without readingHighMediumSmall diffs, test evidence in the summary, code owner review unchanged[@name]
R-04Example: Licence claim over generated codeLowHighPublic code filter, provenance records, legal review[@name]
[R-nn][Risk][L / M / H][L / M / H][Mitigation][@name]

12. Appendices

12.1 Traceability

RequirementDesign elementVerification
FR-037.3 agent loop and sandboxInternal task benchmark
FR-047.5 approval loopAudit of pull requests with assistance trailer
FR-055.2 repository filter, 9.2 SEC-07Cross-repository leakage test
FR-067.4 MCP allowlist and risk classesTool policy unit tests
NFR-017.1, 8 latency budgetClient telemetry at peak
NFR-047.3 SBX rulesPenetration test
[ID][Element][Test]

12.2 Open questions

IDQuestionOwnerDue
OQ-01Example: Allow local mode for repositories that need hardware access?[@name]YYYY-MM-DD
OQ-02Example: Retain transcripts longer for regulated codebases?[@name]YYYY-MM-DD
[OQ-nn][Question][@name]YYYY-MM-DD

12.3 Glossary

TermMeaning
Fill-in-the-middlePrompt format giving the model code before and after the cursor
Agent loopRepeated cycle of model turn, tool call and observation
MCPModel Context Protocol: hosts, clients and servers exchanging tools, resources and prompts over JSON-RPC 2.0
Agent SkillFolder with a SKILL.md file (name, description, instructions) and optional scripts and references, loaded on demand
MicroVMLightweight virtual machine with its own kernel, used for strong isolation with fast start
Prefix cacheReuse of computed attention state or billed tokens for an unchanged prompt prefix
Acceptance rateShare of shown completions the developer keeps

12.4 References

ReferenceUse
Model Context Protocol specification, revision 2026-07-28, https://modelcontextprotocol.io/specification/2026-07-28Roles, features, consent and tool safety principles in 7.4
Agent Skills specification, https://agentskills.io/specificationSKILL.md format and progressive disclosure in 7.4
OWASP Top 10 for LLM Applications 2026, OWASP GenAI Security Project, https://genai.owasp.org/Threat mapping in 9.2
Yang et al., "SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering", arXiv:2405.15793 (2024)Box in 7.6
Jimenez et al., "SWE-bench: Can Language Models Resolve Real-World GitHub Issues?", ICLR 2024 (arXiv:2310.06770)Benchmark style for the internal task suite
RFC 9457, Problem Details for HTTP APIsError format in 4.3
LLM Inference Serving System Design (system-design/design-llm-inference-serving)Model pools behind this design
AI Agent Specification Template (ai-data/ai-agent-spec)Agent behaviour specification
Guardrails Specification Template (ai-data/guardrails-spec)Input and output guardrails
RAG System Design Template (ai-data/rag-system-design)Retrieval patterns for chat

Standard and licence note

Based on the Model Context Protocol specification (revision 2026-07-28), the Agent Skills specification and the OWASP Top 10 for LLM Applications 2026 by the OWASP GenAI Security Project (https://genai.owasp.org/), licensed under Creative Commons Attribution-ShareAlike 4.0 (https://creativecommons.org/licenses/by-sa/4.0/). The OWASP IDs and short names are used for the mapping in 9.2; all descriptions and controls are original text. Because that mapping adapts the OWASP structure, the adapted structure is shared under CC BY-SA 4.0 and any further adaptation must carry the same licence. The research paper in 7.6 is paraphrased, not copied. All numbers are illustrative examples, not benchmarks. Check the current official versions of each specification and list before use. Apart from the adapted OWASP structure, the original text is under the template licence. Template licence: MIT.

Templat terkait