# Running a Fleet of AI Coding Agents? Stop Context Reset—and Wire in a Knowledge Graph

> Source: <https://dev.to/tamizuddin/running-a-fleet-of-ai-coding-agents-stop-context-reset-and-wire-in-a-knowledge-graph-1bh>
> Published: 2026-11-22 00:07:35+00:00

**Recommendation:** Before scaling to parallel coding agents, model architectural decisions and boundaries as a versioned, auditable graph and have each agent query only the slice relevant to its ticket.
More in the playbook "Working with AI coding agents": <https://wpnews.pro/playbooks/coding-agents>

*Originally published on [tamiz.pro](https://tamiz.pro/insights/ai-coding-agent-fleet-knowledge-graph-architecture-memory).*

Most teams adopting AI coding agents expect a productivity gain. They get something more complicated: a fleet of brilliant, amnesiac contractors. Each agent starts with a clean context window, reads a few files, and produces a plausible implementation that ignores the service boundaries, naming conventions, and architectural decisions your team spent months documenting.

The problem is not usually model capability. It is context architecture. A coding agent is a stateless reasoning engine attached to a temporary workspace, while your codebase is a long-lived, interconnected system of constraints. Asking an agent to “read the docs” is not a memory strategy; it is a suggestion.

The durable fix is to treat architectural knowledge as a **queryable graph** rather than a pile of Markdown files. Agents should retrieve the smallest relevant slice of your system—decisions, dependencies, ownership boundaries, and constraints—before they plan or write code. This guide explains why multi-agent fleets amplify context drift, how to model architecture as a knowledge graph, and how to wire a graph-backed context layer into an agent workflow that remains auditable and cheap enough to run at scale.

Consider a common scenario. You run five coding agents in parallel:

Every agent receives a ticket, some file paths, and a prompt such as:

Implement this feature following our architecture guidelines.

The agents work independently. Two weeks later, you discover:

None of these agents made an obviously absurd choice. Each inferred a reasonable architecture from the limited context it had. But “reasonable” is not “consistent,” and consistency is what turns a collection of changes into a coherent system.

This is the difference between **local correctness** and **architectural coherence**. An agent can write a clean function that violates a company-wide boundary. It can pass a unit test while creating a dependency cycle. It can follow a file-level style guide while ignoring a decision record explaining why a particular pattern was rejected.

The failure mode is not “the agent forgot the rules.” It is “the agent never received the rules in a form it could reliably use.”

Modern coding agents have long context windows, but length is not the same thing as memory. There are three distinct mechanisms teams often conflate.

A context window holds the tokens for the current run: the prompt, selected files, tool output, and intermediate reasoning. It is useful for reasoning about the task at hand. It is not a durable knowledge store, because:

Your codebase contains a great deal of architectural knowledge, but it encodes it implicitly. A dependency rule might live in an ESLint configuration. A boundary might be visible only in import statements. A rejected design might be documented in a proposal that no longer resembles the code.

Retrieving raw files is therefore noisy. An agent that reads twenty files may still miss the rule that matters most.

Conversation history helps an agent remember what happened within a session. It does not help a different agent, a different branch, or a run three weeks later. In a fleet, conversation history is particularly weak as shared state because each agent owns a separate thread.

A useful architecture-memory layer needs to be:

| Requirement | Why it matters | 
|---|---|
| Durable | Knowledge survives sessions, branches, and agent restarts | 
| Structured | Relationships and constraints can be queried, not just semantically matched | 
| Scoped | An agent receives only the context relevant to its task | 
| Versioned | Agents can distinguish current rules from superseded ones | 
| Auditable | A human can inspect why an agent received a given fact | 
| Mutable | New decisions update future behavior without rewriting every prompt | 

A knowledge graph satisfies all six when it is modeled around engineering semantics rather than generic document chunks.

A single agent can sometimes reconstruct enough architecture by reading the repository. A fleet multiplies the cost of inconsistency because agents do not merely share a codebase—they share a codebase with **concurrent, mutually unaware mutations**.

Two agents can independently infer that a module is owned by the platform team. One may add a public method; the other may bypass it to meet a deadline. No single prompt was wrong. The assumptions were simply incompatible.

A branch is an excellent unit of code change but a poor unit of architectural reasoning. If one agent changes an event schema, every downstream consumer should know. If another changes an API contract, every client and test should know. Without a shared semantic layer, those dependencies are discovered through compilation failures—or, worse, at runtime.

Prompt engineering treats architectural guidance as prose embedded in a template. That works until the template grows too large, guidance becomes ambiguous, or different agents interpret it differently. As the fleet scales, prompt quality becomes a hidden central bottleneck.

Documentation retrieval is useful, but plain text lacks the relationships needed for impact analysis. If a decision says “the billing service owns subscription state,” an agent changing a checkout flow needs to know which services, tables, events, and teams are affected. That is a graph traversal, not a keyword search.

The core shift is from **prompt-centric context** to **architecture-centric context**:

```
Prompt-centric:  task → retrieve text → ask model → write code

Architecture-centric: task → resolve scope → traverse graph →
                    retrieve justified facts → plan → write code → validate
```

A knowledge graph represents entities and the relationships between them. For software architecture, the entities are not abstract concepts; they are the things engineers actually reason about:

The relationships capture why those entities matter to one another.

A graph does not need to duplicate every function or line of code. Instead, it provides a **semantic index over the codebase**. The graph says:

The agent then retrieves the concrete source files and snippets needed to act on those facts.

This division of labor is important:

The graph supplies relevance and authority. The repository supplies implementation detail.

Without a graph, the unit of work is “a ticket plus a prompt.” With a graph, the unit of work becomes “a ticket plus a resolved architectural scope.”

For example:

```
{
  "task": "Add a refund webhook to the checkout service",
  "scope": {
    "owned_components": ["checkout-api", "refund-events"],
    "forbidden_dependencies": ["payment-ledger"],
    "required_patterns": ["outbox", "idempotency-key"],
    "affected_consumers": ["orders-web", "notification-worker"]
  }
}
```

The agent no longer has to rediscover that it must use a transactional outbox, cannot call the ledger directly, and must update two downstream consumers. It receives that scope as structured context, with links back to the source of each fact.

Because the graph is external to any individual agent session, it can serve as a coordination substrate. When an agent changes an event contract, it updates the graph. Subsequent agents see the new relationship and affected components.

This does not eliminate the need for branch review, tests, or deployment coordination. It makes those mechanisms less likely to be the first place architectural inconsistency becomes visible.

You do not need a massive ontology. Start with a small schema that captures the relationships your agents most often violate.

| Entity | Purpose | Example | 
|---|---|---|
| `Component` | A deployable or logically bounded unit | `checkout-api` | 
| `Module` | A code-level unit within a component | `refunds` | 
| `Interface` | A contract between components | `RefundRequested` | 
| `DataStore` | A persistent data boundary | `billing_db.orders` | 
| `Decision` | A ratified architectural choice | `ADR-014: use outbox` | 
| `Policy` | A machine-checkable or human-enforced rule | `No direct ledger access` | 
| `Team` | An ownership domain | `Payments` | 

| Relationship | Direction | Example | 
|---|---|---|
| `OWNS` | Team → Component | Payments owns checkout-api | 
| `CONTAINS` | Component → Module | checkout-api contains refunds | 
| `DEPENDS_ON` | Component → Component | checkout-api depends on inventory-api | 
| `IMPLEMENTS` | Component → Interface | orders-worker implements RefundRequested | 
| `PRODUCES` /`CONSUMES` | Component → Interface | checkout-api produces RefundRequested | 
| `READS` /`WRITES` | Component → DataStore | checkout-api writes orders | 
| `GOVERNED_BY` | Any entity → Policy | checkout-api governed by outbox policy | 
| `DECIDED_BY` | Any entity → Decision | outbox governed by ADR-014 | 
| `APPLIES_TO` | Policy → Scope | policy applies to checkout-api | 

A graph edge should carry enough metadata to answer “Can I rely on this?”

```
{
  "from": "checkout-api",
  "type": "GOVERNED_BY",
  "to": "pol:outbox-for-external-events",
  "properties": {
    "source": "docs/architecture/adr-014.md#decision",
    "status": "accepted",
    "effective_from": "2025-02-10",
    "confidence": "verified",
    "observed_at": "2025-03-01T12:00:00Z"
  }
}
```

Useful edge properties include:

`status`: proposed, accepted, deprecated, superseded` scope`: where the rule applies` source`: the file, ADR, pull request, or schema that establishes it` effective_from`: when the rule became authoritative` confidence`: verified, inferred, or unknown` observed_at`: when the extractor last saw the evidence
The `confidence` field is especially important. A graph that silently mixes verified policy with machine-generated guesses is worse than no graph, because agents cannot calibrate their behavior against uncertainty.

The graph does not retrieve itself. You still need a retrieval strategy that combines graph traversal with semantic search.

Start with the ticket, changed files, repository name, and explicit service names. Extract candidate identifiers and search the graph for matching components, modules, interfaces, and teams.

Do not assume the ticket title contains the canonical component name. “Add refund support” might map to `checkout-api` and `refund-events`, not to a directory literally named `refund`.

Traverse a small number of relationship hops:

```
task component
  ├─ governed_by → policies and decisions
  ├─ depends_on → upstream components
  ├─ produces/consumes → interfaces
  ├─ reads/writes → data stores
  └─ owned_by → team and runbooks
```

A depth of two or three is often sufficient. Unlimited traversal recreates the “dump the whole repository” problem in graph form.

Rank candidate facts using:

A policy such as “all external events use Kafka” may be globally accepted but explicitly scoped to a particular region or team. Scope-aware filtering prevents false universalization.

Use the graph to identify the files that matter, then search or read those files. For example, if the graph says `checkout-api` implements `RefundRequested`, retrieve:

Do not paste entire files into the prompt. Retrieve the smallest useful code region, ideally with symbol boundaries and a stable reference.

The model should receive a compact, structured packet rather than a raw graph dump:

```
{
  "task": "Add a refund webhook",
  "architecture": [
    {
      "fact": "External events must be published through the transactional outbox",
      "applies_to": ["checkout-api"],
      "source": "docs/architecture/adr-014.md",
      "status": "accepted"
    },
    {
      "fact": "checkout-api must not call payment-ledger directly",
      "applies_to": ["checkout-api"],
      "source": "architecture/policies/boundaries.yaml",
      "status": "active"
    }
  ],
  "relevant_code": [
    {
      "path": "services/checkout/src/events/refund_publisher.ts",
      "reason": "Canonical publisher for refund events"
    },
    {
      "path": "packages/events/src/refund_requested.ts",
      "reason": "Event contract to extend"
    }
  ],
  "affected_consumers": ["orders-web", "notification-worker"]
}
```

This packet is auditable. Every fact has a source, and every file has a reason.

The runtime should make graph retrieval a **mandatory phase**, not an optional tool the model may forget to call.

```
1. Scope
   Identify the component, interface, and files involved.

2. Retrieve
   Resolve architecture facts and implementation evidence.

3. Plan and implement
   Use the retrieved constraints while editing code.

4. Validate and record
   Check the diff against graph-derived constraints and update the graph.
```

The validation phase is what turns the graph from passive documentation into an active control plane.

Do not rely on the model to “remember” a rule while generating code. Validate the resulting diff against the same graph facts:

After a successful change, emit an event such as:

```
{
  "type": "ArchitectureChangeRecorded",
  "component": "checkout-api",
  "change": {
    "operation": "add_interface",
    "interface": "RefundRequested.v2",
    "source_pr": 1842
  },
  "evidence": ["services/checkout/src/events/refund_publisher.ts"],
  "recorded_at": "2025-03-01T12:00:00Z"
}
```

The graph updater should validate the event before applying it. A pull request number alone is not proof that a decision was accepted; a schema change may still be under review.

When the graph lacks a fact, the agent should be told to do one of three things:

It should not silently invent an architectural pattern and then treat that invention as project knowledge.

The following example uses Python, SQLite, and a simple graph store implemented as an adjacency table. It demonstrates the important mechanics without requiring a dedicated graph database.

`services/` directory
The example is intentionally compact. In production, you would likely use a graph database or an embedded vector-plus-graph store, but the retrieval contract remains the same.

```
python -m venv .venv
source .venv/bin/activate
pip install networkx
```

`architecture_graph.py`

``` python
from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import networkx as nx

@dataclass(frozen=True)
class ContextRequest:
    task: str
    components: list[str]
    changed_paths: list[str]
    max_hops: int = 2

class ArchitectureGraph:
    def __init__(self) -> None:
        self.graph = nx.MultiDiGraph()

    def add_entity(self, entity_id: str, entity_type: str, **properties: Any) -> None:
        self.graph.add_node(entity_id, type=entity_type, **properties)

    def add_relation(
        self,
        source: str,
        relation: str,
        target: str,
        **properties: Any,
    ) -> None:
        self.graph.add_edge(source, target, type=relation, **properties)

    def load_repository(self, root: Path) -> None:
        """Infer a minimal component graph from the repository layout."""
        services_dir = root / "services"
        if not services_dir.exists():
            return

        for service_dir in sorted(services_dir.iterdir()):
            if not service_dir.is_dir():
                continue

            component_id = f"component:{service_dir.name}"
            self.add_entity(component_id, "component", path=str(service_dir))

            for source_file in service_dir.rglob("*.ts"):
                module_id = f"module:{service_dir.name}/{source_file.stem}"
                self.add_entity(
                    module_id,
                    "module",
                    path=str(source_file.relative_to(root)),
                )
                self.add_relation(component_id, "CONTAINS", module_id)

    def load_policies(self, path: Path) -> None:
        """Load simple YAML-like policy records without external dependencies."""
        # This example uses JSON to keep the file runnable without PyYAML.
        records = json.loads(path.read_text(encoding="utf-8"))

        for record in records:
            policy_id = f"policy:{record['id']}"
            self.add_entity(
                policy_id,
                "policy",
                text=record["text"],
                status=record.get("status", "active"),
                source=record.get("source", str(path)),
            )

            for component in record.get("applies_to", []):
                component_id = f"component:{component}"
                self.add_entity(component_id, "component")
                self.add_relation(
                    component_id,
                    "GOVERNED_BY",
                    policy_id,
                    status=record.get("status", "active"),
                    source=record.get("source", str(path)),
                )

    def resolve_component(self, name: str) -> str | None:
        candidates = [
            node
            for node, data in self.graph.nodes(data=True)
            if data.get("type") == "component"
            and (
                node == f"component:{name}"
                or node.endswith(f":{name}")
                or name in node
            )
        ]
        return candidates[0] if candidates else None

    def collect_neighborhood(self, component_id: str, max_hops: int) -> set[str]:
        nodes = {component_id}
        frontier = {component_id}

        for _ in range(max_hops):
            next_frontier: set[str] = set()
            for node in frontier:
                for neighbor in self.graph.successors(node):
                    if neighbor not in nodes:
                        nodes.add(neighbor)
                        next_frontier.add(neighbor)

                for neighbor in self.graph.predecessors(node):
                    if neighbor not in nodes:
                        nodes.add(neighbor)
                        next_frontier.add(neighbor)

            frontier = next_frontier

        return nodes

    def build_context(self, request: ContextRequest) -> dict[str, Any]:
        component_ids = [
            component_id
            for name in request.components
            if (component_id := self.resolve_component(name)) is not None
        ]

        if not component_ids:
            return {
                "task": request.task,
                "architecture": [],
                "relevant_code": [],
                "warnings": [
                    "No component matched the task. "
                    "Ask for clarification before implementing."
                ],
            }

        relevant_nodes: set[str] = set()
        for component_id in component_ids:
            relevant_nodes.update(
                self.collect_neighborhood(component_id, request.max_hops)
            )

        architecture: list[dict[str, Any]] = []
        relevant_code: list[dict[str, Any]] = []

        for node_id in relevant_nodes:
            node = self.graph.nodes[node_id]

            if node.get("type") == "policy" and node.get("status") == "active":
                architecture.append(
                    {
                        "fact": node.get("text", node_id),
                        "source": node.get("source", node_id),
                        "status": node.get("status", "active"),
                    }
                )

            if node.get("type") == "module":
                relevant_code.append(
                    {
                        "path": node.get("path"),
                        "reason": f"Module within {node_id.split(':')[1]}",
                    }
                )

        # Include changed paths explicitly, even if the graph is incomplete.
        known_code_paths = {item["path"] for item in relevant_code}
        for changed_path in request.changed_paths:
            if changed_path not in known_code_paths:
                relevant_code.append(
                    {
                        "path": changed_path,
                        "reason": "Explicitly included by the task",
                    }
                )

        return {
            "task": request.task,
            "architecture": architecture,
            "relevant_code": relevant_code,
            "warnings": [],
        }

def main() -> None:
    root = Path.cwd()
    graph = ArchitectureGraph()
    graph.load_repository(root)
    graph.load_policies(root / "architecture_policies.json")

    request = ContextRequest(
        task="Add a refund webhook",
        components=["checkout-api"],
        changed_paths=["services/checkout/src/refunds.ts"],
    )

    context = graph.build_context(request)
    print(json.dumps(context, indent=2))

if __name__ == "__main__":
    main()
```

`architecture_policies.json`

```
[
  {
    "id": "outbox-for-external-events",
    "text": "External events must be published through the transactional outbox.",
    "applies_to": ["checkout-api"],
    "status": "active",
    "source": "docs/architecture/adr-014.md"
  },
  {
    "id": "no-direct-ledger-access",
    "text": "checkout-api must not call payment-ledger directly.",
    "applies_to": ["checkout-api"],
    "status": "active",
    "source": "architecture/policies/boundaries.json"
  }
]
```

Create the expected directory structure:

```
mkdir -p services/checkout/src
cat > services/checkout/src/refunds.ts <<'EOF'
export function createRefund() {
  return { status: "pending" };
}
EOF
```

Then execute:

```
python architecture_graph.py
```

Expected output will include the two active policies and the relevant checkout module:

```
{
  "task": "Add a refund webhook",
  "architecture": [
    {
      "fact": "checkout-api must not call payment-ledger directly.",
      "source": "architecture/policies/boundaries.json",
      "status": "active"
    },
    {
      "fact": "External events must be published through the transactional outbox.",
      "source": "docs/architecture/adr-014.md",
      "status": "active"
    }
  ],
  "relevant_code": [
    {
      "path": "services/checkout/src/refunds.ts",
      "reason": "Explicitly included by the task"
    }
  ],
  "warnings": []
}
```

The example demonstrates the essential pattern: **resolve scope, traverse a bounded neighborhood, filter by status, and return a small auditable context packet**.

A framework-neutral integration looks like this:

``` python
from pathlib import Path
from architecture_graph import ArchitectureGraph, ContextRequest

def build_agent_prompt(task: str, components: list[str]) -> str:
    graph = ArchitectureGraph()
    graph.load_repository(Path.cwd())
    graph.load_policies(Path.cwd() / "architecture_policies.json")

    context = graph.build_context(
        ContextRequest(task=task, components=components, changed_paths=[])
    )

    return f"""
Implement the task while obeying the architecture constraints below.

TASK:
{task}

ARCHITECTURE CONTEXT:
{json.dumps(context, indent=2)}

If a required fact is missing, inspect the referenced implementation or ask for
clarification. Do not invent a new architectural pattern.
""
```

In a real agent runtime, the same packet should be produced before the model is allowed to call edit tools.

A stale knowledge graph is dangerous. If a policy was retired but remains in the graph, agents will preserve obsolete architecture. If a dependency is missing, agents will invent one.

Store provenance and confidence on every edge. An inferred dependency from an import statement is useful, but it should not outrank an explicit ownership boundary.

Use static analysis for imports, exposed interfaces, database access, and dependency declarations. These are mechanically verifiable and should not depend on an LLM guess.

Use language models for softer extraction—intent, rationale, ownership ambiguity—but require validation before treating the result as authoritative.

Never delete the history of a decision. Mark the old decision as superseded and link it to the new one:

```
{
  "from": "decision:adr-014",
  "type": "SUPERSEDES",
  "to": "decision:adr-031",
  "properties": {
    "effective_from": "2025-06-01",
    "source": "docs/architecture/adr-031.md"
  }
}
```

Run periodic checks that compare graph facts with code:

Surface drift as an explicit queue rather than silently rewriting the graph. Human review is valuable for architectural meaning, even if it is not valuable for every file-level fact.

A common mistake is to make the graph authoritative for everything. That creates a second codebase with a second set of bugs.

Use this authority model:

| Information | Source of truth | 
|---|---|
| Business behavior | Source code and tests | 
| API schemas | Versioned schema files | 
| Architecture decisions | ADRs and accepted proposals | 
| Ownership | Ownership registry or service catalog | 
| Dependency relationships | Static analysis and deployment metadata | 
| Graph | Derived index linking the above | 

The graph should point to authoritative sources, not compete with them.

A graph-backed agent fleet can become another expensive platform. The key is to retrieve narrowly and cache aggressively.

Cache context packets using a key derived from:

```
component scope + graph revision + task archetype + policy revision
```

If the graph has not changed and the task maps to a known archetype, reuse the packet. Do not cache model reasoning itself unless your framework supports safe, versioned reuse.

Retrieval should be fast and cheap. Graph traversal, metadata filtering, and code lookup should not require a large model call. Use the model for semantic interpretation only where deterministic matching is insufficient.

A practical stack often combines:

Each source has a different strength. The graph is particularly valuable for **joining** results that other retrieval methods return independently.

Set hard limits for:

A useful default is a small architecture packet, a handful of focused code regions, and explicit uncertainty instead of exhaustive context.

Typical agent metrics—tests passed, tickets closed, lines changed—do not reveal whether the fleet is becoming less coherent. Add metrics such as:

These metrics tell you whether the memory layer is actually working.

A practical sequence is:

Do not begin by trying to model every architectural concept in your company. Begin with the rules agents most often violate.

A vector database is useful for finding semantically similar code and documents, but it does not directly answer relationship questions such as “Which consumers are affected if this event changes?” or “Which components are allowed to depend on this package?” That is where a graph adds value. A hybrid system is usually best: vectors for semantic discovery, a graph for relationships and provenance, and deterministic analysis for hard dependencies.

They should share a consistent view, but not necessarily mutate it freely. Read access can come from a shared graph revision, while updates should pass through validation and merge workflows. Otherwise, one agent can record an unapproved architectural decision and immediately contaminate the context of every other agent.

Treat graph entries as derived, versioned facts with explicit sources and confidence. Generate hard facts from code and schemas, record decisions from approved ADRs, and run reconciliation jobs that detect divergence. Most importantly, make agents cite the graph facts they used so reviewers can immediately verify whether the context was correct.

No. A knowledge graph reduces avoidable violations and makes architectural knowledge machine-accessible; it does not replace human judgment. The strongest setup uses the graph to narrow context, deterministic checks to catch violations, and humans to approve genuinely new architectural choices.
