Context Engineering in Practice: Building an Editable Nonlinear Graph of Thought

    This article explores context pollution in long AI agent sessions and introduces a practical alternative to linear chat history: an editable directed graph where "an edge is context." It explains the core node and edge model, shows how to isolate unproductive debugging branches without losing audit records, and outlines layered context budgeting that reduced a 200-plus-turn session from over 200,000 tokens to roughly 15,000. The article also covers engineering essentials such as persistence, idempotent execution, observability, and team review, making it a useful reference for designing a context layer for AI coding tools or custom agent platforms.

    1. The Problem: Context Pollution in Long Sessions

    When you use an AI coding assistant or a general-purpose agent for a complex task, one pattern shows up repeatedly: the session grows rapidly as the work progresses. After a few dozen turns, the context usually contains four kinds of content mixed together—assumptions that have already been disproven, large volumes of tool output generated during debugging, branch explorations unrelated to the current goal, and the decisions and constraints that genuinely need to be retained long term.

    In a linear session, all of this content carries equal weight. The model can read the full history or rely on automatic compaction to shorten the context, but it is hard for the user to tell which content actually influenced the next round of reasoning. That is the essence of context pollution: the problem is not a lack of information, but invalid information crowding out the attention budget available to valid information.

    It is worth emphasizing that the session logs and trajectory replay features of mainstream AI coding tools mainly answer the question “what did the agent just do?”—an after-the-fact audit perspective. Context engineering answers a different question: before the next round begins, can a human decide which context the agent should carry forward?

    2. Core Design: An Edge Is Context

    One workable approach is to organize the session as a continuously updated directed graph with a single minimal rule: an edge is context.

    • Node types: conversation turns, external material (documents, web excerpts), and human notes;
    • Content connected into a question node forms the context actually carried by the next request;
    • Disconnecting an edge only affects context propagation; it does not delete content from the canvas;
    • A long chain can be condensed into a shorter new path without overwriting the original records.

    The value of this rule is that it turns “context selection” from an implicit behavior into an explicit operation. The traditional approaches—deleting messages or relying on compaction—both cause irreversible information loss. A graph structure decouples “retention” from “participation”: content can be kept permanently for auditing while staying out of the inference request.

    A schematic data structure can be abstracted as follows:

    1. class Node:
    2. id: str
    3. kind: str # message | material | note | question
    4. payload: dict
    5. summary: str = "" # condensed short description
    6. class Edge:
    7. src: str
    8. dst: str
    9. active: bool = True # set to False when disconnected; never deleted
    10. def build_context(question_id: str, edges: list[Edge]) -> list[Node]:
    11. """Collect upstream nodes along active edges only, as the context for this turn."""
    12. return [e.src for e in edges if e.dst == question_id and e.active]

    3. Typical Scenario: Managing Branches During Debugging

    Consider a code defect investigation. For the first twenty turns, the working assumption is a caching problem, with extensive searching, changes, and failed verification. The real root cause turns out to be a data structure change.

    In a linear session, those twenty turns in the wrong direction remain in the history, continuously consuming context budget and potentially misleading later reasoning. With the graph-of-thought approach, the operational path is clear:

    1. Keep the “cache hypothesis” branch and all its tool output as an auditable record;
    2. Set the edges between that branch and subsequent question nodes to disconnected;
    3. Connect the real root cause, the final fix, and relevant documentation into a new question node;
    4. Have the agent continue verification on that node, with the answer written back into the graph and synchronized to the session log.

    The key is the combination of steps 2 and 3: audit integrity is not sacrificed, while the reasoning context is actively trimmed.

    4. Context Budget and Compression Strategy

    A graph structure naturally supports layered budget management. One possible allocation strategy:

    • System constraints and long-term decisions: always resident; small in size but highest priority;
    • Direct upstream of the current question: retain the original tool output in full;
    • Historical branches: not connected by default; temporarily connected only when backtracking is needed;
    • Overly long nodes: summarize and condense first, with the original text kept inside the node and expanded on demand.

    In one real long-session test, the original chain exceeded two hundred turns and roughly two hundred thousand tokens. Without overwriting the original records, the content that genuinely needed to carry forward was organized into a new path of about fifteen thousand tokens, reducing the context size by roughly an order of magnitude. This shows that the main benefit of context governance comes from “selective carrying,” not simply from raising the model’s context window limit.

    5. Engineering Implementation Notes

    • Persistence: store graph data separately from the original session logs; the former can be versioned, the latter is append-only;
    • Idempotent execution: when the same question node is triggered repeatedly, reuse the already generated answer to avoid wasting compute;
    • Observability: record the set of nodes actually carried by each request and the token estimate, making it easier to trace the source of pollution;
    • Integration with general cloud capabilities: use object storage for graph snapshots, a message queue to decouple node updates, and logging and monitoring with alerting to track context size trends;
    • Team collaboration: graph nodes can serve as review units, making “why we decided this way” explicit and reducing information decay from verbal handoffs.

    6. Conclusion

    Context pollution is a hurdle every agent must clear on the way from short tasks to long ones. Restructuring the session from a linear sequence into an editable nonlinear graph, with “an edge is context” as the only rule, lets humans regain control over context selection without losing audit information. This approach does not depend on any specific product capability and can serve as a general context layer design reference for AI coding tools and custom agent platforms.