<metadata>
purpose: Advanced context engineering and Agentic Horizon framework
type: advanced-optimization
domain: agentic-coding
phase: elite-mastery
audience: LLM-optimized
last-updated: 2025-09-30
</metadata>

<overview>
Elite Context Management represents the apex of agentic coding optimization. At this level, context is recognized as the most precious and constrained resource in agent systems. The Agentic Horizon framework provides systematic approaches for context engineering, focusing agents on high-value work while minimizing cognitive load.
</overview>

<fundamental-truth>
<principle>Context is the Most Precious Resource</principle>

<scarcity>
  <constraint type="token-limits">
    Claude: 200K tokens
    GPT-4: 128K tokens
    Gemini: 2M tokens (but processing cost scales)
  </constraint>

  <constraint type="attention-degradation">
    <description>Agent performance degrades with context size</description>
    <phenomenon>Lost in the middle: Information in middle of large context often ignored</phenomenon>
    <implication>More context ≠ better performance</implication>
  </constraint>

  <constraint type="processing-cost">
    <description>Cost scales with input tokens</description>
    <calculation>Wasted context = wasted money + wasted time</calculation>
  </constraint>
</scarcity>

<optimization-goal>
  Maximize signal-to-noise ratio in context provision.
  Provide exactly what agent needs, nothing more, nothing less.
</optimization-goal>
</fundamental-truth>

<agentic-horizon>
<name>R&D Framework for Focused Agents</name>

<definition>
The Agentic Horizon is the boundary of what an agent can effectively handle in a single session. Tasks within the horizon: high success rate. Tasks beyond: failure, hallucination, context overflow. Elite developers engineer contexts to keep work within horizon.
</definition>

<horizon-dimensions>
  <dimension name="Complexity">
    <description>Cognitive load of task</description>
    <examples>
      <within-horizon>Fix specific bug with known root cause</within-horizon>
      <beyond-horizon>Redesign entire authentication system</beyond-horizon>
    </examples>
  </dimension>

  <dimension name="Scope">
    <description>Number of files/components affected</description>
    <examples>
      <within-horizon>Modify 3-5 related files</within-horizon>
      <beyond-horizon>Refactor 50+ files across multiple modules</beyond-horizon>
    </examples>
  </dimension>

  <dimension name="Context Size">
    <description>Information required for task understanding</description>
    <examples>
      <within-horizon>Single module with clear boundaries</within-horizon>
      <beyond-horizon>Entire codebase with complex dependencies</beyond-horizon>
    </examples>
  </dimension>

  <dimension name="Uncertainty">
    <description>Ambiguity in requirements or approach</description>
    <examples>
      <within-horizon>Well-defined task with established patterns</within-horizon>
      <beyond-horizon>Open-ended exploration with unclear requirements</beyond-horizon>
    </examples>
  </dimension>
</horizon-dimensions>

<horizon-expansion-strategies>
  <strategy name="Task Decomposition">
    <description>Break beyond-horizon tasks into within-horizon subtasks</description>
    <example>
      Beyond-horizon: "Migrate entire API to GraphQL"
      Decomposed:
      1. Research GraphQL schema design for User model
      2. Implement User queries (read operations)
      3. Implement User mutations (write operations)
      4. Add tests for User resolvers
      5. Repeat for each model
      Each subtask is within horizon
    </example>
    <benefit>Maintain high success rate for complex initiatives</benefit>
  </strategy>

  <strategy name="Progressive Context Hydration">
    <description>Load context incrementally as needed</description>
    <workflow>
      <phase1>High-level context: Project overview, architecture</phase1>
      <phase2>Module context: Specific subsystem details</phase2>
      <phase3>Implementation context: Exact files and functions</phase3>
    </workflow>
    <benefit>Avoid overwhelming agent with irrelevant information</benefit>
  </strategy>

  <strategy name="Context Anchors">
    <description>Provide minimal core context, point to additional resources</description>
    <example>
      Core context: "We use JWT authentication (see auth/README.md for details)"
      Agent can read auth/README.md if needed, but not loaded by default
    </example>
    <benefit>Keep working context lean while maintaining access to details</benefit>
  </strategy>

  <strategy name="Focused Agent Specialization">
    <description>Use different agents for different subtasks</description>
    <example>
      Agent 1: Research best GraphQL patterns (sherlock)
      Agent 2: Implement User resolvers (jsmaster)
      Agent 3: Write tests (bugsy)
      Each agent sees only relevant context for their task
    </example>
    <benefit>No single agent overwhelmed by full project scope</benefit>
  </strategy>
</horizon-expansion-strategies>
</agentic-horizon>

<context-engineering-tactics>
<tactic name="Context Layering">
  <description>Hierarchical organization of information by relevance</description>

  <layers>
    <layer priority="1" name="Essential Context">
      <contents>
        <item>Task requirements (what to do)</item>
        <item>Constraints (what NOT to do)</item>
        <item>Success criteria (when done)</item>
        <item>Immediately relevant files (2-3 max)</item>
      </contents>
      <placement>Beginning of prompt</placement>
      <token-budget>20-30% of total context</token-budget>
    </layer>

    <layer priority="2" name="Supporting Context">
      <contents>
        <item>Related patterns/examples</item>
        <item>Adjacent code for consistency</item>
        <item>API documentation for dependencies</item>
      </contents>
      <placement>Middle of prompt</placement>
      <token-budget>40-50% of total context</token-budget>
    </layer>

    <layer priority="3" name="Reference Context">
      <contents>
        <item>Broader architecture</item>
        <item>Historical decisions (ADRs)</item>
        <item>Edge cases and error handling</item>
      </contents>
      <placement>End of prompt or linked documents</placement>
      <token-budget>20-30% of total context</token-budget>
    </layer>
  </layers>

  <principle>Most important information first (attention is front-loaded)</principle>
</tactic>

<tactic name="Context Compression">
  <description>Maximize information density per token</description>

  <techniques>
    <technique name="XML Tagging">
      <rationale>LLMs parse XML efficiently, provides structure</rationale>
      <example>
        Verbose: "This is the authentication module. It handles login and logout."
        Compressed: &lt;module name="auth" purpose="login/logout"/&gt;
      </example>
    </technique>

    <technique name="Code Over Prose">
      <rationale>Code is denser than natural language descriptions</rationale>
      <example>
        Verbose: "The function takes a user ID and returns the user object from the database"
        Compressed:
        function getUser(userId: string): Promise&lt;User&gt; {
          return db.users.findById(userId);
        }
      </example>
    </technique>

    <technique name="Bullet Points Over Paragraphs">
      <rationale>Scannable structure, no filler words</rationale>
      <example>
        Verbose: "The authentication system is designed to handle user sessions. It uses JWT tokens for security and Redis for session storage."
        Compressed:
        - Auth: JWT tokens
        - Storage: Redis sessions
      </example>
    </technique>

    <technique name="Symbolic Encoding">
      <rationale>Symbols convey meaning efficiently</rationale>
      <example>
        User → Profile → Orders → Items (relationship chain)
        ✓ Required field
        ✗ Forbidden operation
      </example>
    </technique>

    <technique name="Diff Format">
      <rationale>Show only changes, not full files</rationale>
      <example>
        Instead of: Full 200-line file
        Provide:
        ```diff
        - const timeout = 5000;
        + const timeout = 10000;
        ```
      </example>
    </technique>
  </techniques>
</tactic>

<tactic name="Context Scoping">
  <description>Explicit boundaries on what agent should consider</description>

  <scoping-methods>
    <method name="File Whitelisting">
      <description>List exactly which files are relevant</description>
      <example>
        "For this task, ONLY consider:
         - auth/login.ts
         - auth/middleware.ts
         - models/user.ts
         All other files are out of scope."
      </example>
    </method>

    <method name="Temporal Scoping">
      <description>Focus on specific time period or version</description>
      <example>
        "Use patterns from code written in last 6 months (post-refactor), ignore legacy patterns"
      </example>
    </method>

    <method name="Conceptual Scoping">
      <description>Limit to specific domain concepts</description>
      <example>
        "This task is authentication ONLY. Do not consider authorization, user profiles, or billing."
      </example>
    </method>

    <method name="Dependency Scoping">
      <description>Specify allowed dependencies</description>
      <example>
        "Use existing libraries only: express, bcrypt, jsonwebtoken. No new dependencies."
      </example>
    </method>
  </scoping-methods>

  <benefit>Prevents context wandering and scope creep</benefit>
</tactic>

<tactic name="Context Caching">
  <description>Reuse common context across multiple tasks</description>

  <approaches>
    <approach name="Documentation-Based Caching">
      <description>CLAUDE.md provides persistent context</description>
      <contents>
        - Project conventions
        - Architecture patterns
        - Common workflows
        - Tool preferences
      </contents>
      <benefit>Avoid repeating project basics every session</benefit>
    </approach>

    <approach name="Memory-Based Caching">
      <description>ken-you-remember stores reusable context</description>
      <usage>
        store_fr3k: "Database: PostgreSQL 14, connection pooling via pg-pool"
        Later: recall_fr3k("database") retrieves this context
      </usage>
      <benefit>Context persists across sessions automatically</benefit>
    </approach>

    <approach name="Template-Based Caching">
      <description>Reusable context templates for common scenarios</description>
      <example>
        Bug Fix Template:
        - Error logs: [paste here]
        - Relevant files: [list here]
        - Expected behavior: [describe here]
        - Constraints: No refactoring, minimal changes
      </example>
      <benefit>Standardized context provision</benefit>
    </approach>
  </approaches>
</tactic>

<tactic name="Context Validation">
  <description>Verify context quality before task execution</description>

  <validation-checks>
    <check name="Completeness">
      <question>Does agent have everything needed to complete task?</question>
      <test>Can task be done without asking clarifying questions?</test>
    </check>

    <check name="Relevance">
      <question>Is every piece of context necessary?</question>
      <test>Remove one piece - would agent still succeed?</test>
    </check>

    <check name="Clarity">
      <question>Is context unambiguous?</question>
      <test>Would different agents interpret this identically?</test>
    </check>

    <check name="Structure">
      <question>Is context organized for easy parsing?</question>
      <test>Most important information first, logical grouping?</test>
    </check>
  </validation-checks>

  <feedback-loop>
    1. Provide context
    2. Observe agent performance
    3. Identify context gaps or bloat
    4. Refine context provision
    5. Repeat
  </feedback-loop>
</tactic>

<tactic name="Context Substitution">
  <description>Replace large context with compact representations</description>

  <substitutions>
    <substitution>
      <instead-of>Full API documentation (1000+ lines)</instead-of>
      <use>OpenAPI schema (structured, parseable)</use>
    </substitution>

    <substitution>
      <instead-of>Detailed architecture explanation</instead-of>
      <use>Diagram (ASCII or image) + brief legend</use>
    </substitution>

    <substitution>
      <instead-of>Multiple similar examples</instead-of>
      <use>One canonical example + "follow this pattern"</use>
    </substitution>

    <substitution>
      <instead-of>Natural language requirements doc</instead-of>
      <use>Structured checklist or acceptance criteria</use>
    </substitution>
  </substitutions>

  <principle>Leverage LLM's ability to parse structured formats efficiently</principle>
</tactic>
</context-engineering-tactics>

<memory-optimization>
<principle>Agent's working memory is context window. Optimize like RAM.</principle>

<optimization-strategies>
  <strategy name="Just-In-Time Context Loading">
    <description>Load context only when needed, not preemptively</description>
    <example>
      Task: Fix bug in checkout flow
      Initial context: Error logs + checkout.ts
      If agent needs payment integration: Then load payment.ts
      Don't load payment.ts upfront "just in case"
    </example>
    <benefit>Keeps working memory lean</benefit>
  </strategy>

  <strategy name="Context Eviction">
    <description>Remove irrelevant context as task progresses</description>
    <example>
      Phase 1: Research (load docs, examples)
      Phase 2: Implementation (keep docs link, focus on code)
      Phase 3: Testing (evict docs, focus on test output)
    </example>
    <implementation>Start new conversation for phase shifts</implementation>
  </strategy>

  <strategy name="Context Summarization">
    <description>Compress previous work into summaries</description>
    <pattern>
      Long conversation → store_fr3k("Implemented JWT refresh. Used 7-day expiry. Token in DB.")
      Next session → recall_fr3k retrieves summary, not full history
    </pattern>
    <benefit>Preserve decisions without full transcript</benefit>
  </strategy>

  <strategy name="External Memory">
    <description>Store context externally, reference as needed</description>
    <locations>
      <location>CLAUDE.md: Project conventions</location>
      <location>ken-you-remember: Decisions and patterns</location>
      <location>ADRs: Architectural rationale</location>
      <location>Code comments: Implementation details</location>
    </locations>
    <access>Agent reads when needed via Read tool</access>
  </strategy>
</optimization-strategies>

<memory-antipatterns>
  <antipattern name="Context Hoarding">
    <description>Loading every potentially relevant file</description>
    <consequence>Working memory overwhelmed, performance degrades</consequence>
  </antipattern>

  <antipattern name="Context Neglect">
    <description>Assuming agent remembers from previous messages</description>
    <consequence>Agent loses critical context mid-task</consequence>
  </antipattern>

  <antipattern name="Context Duplication">
    <description>Repeating same information in multiple forms</description>
    <consequence>Wasted tokens, no additional value</consequence>
  </antipattern>
</memory-antipatterns>
</memory-optimization>

<elite-context-patterns>
<pattern name="The Surgical Context">
  <description>Minimal, precise context for well-defined tasks</description>
  <structure>
    1. Exact task (one sentence)
    2. Exact file and location
    3. Exact constraint
    4. Exact success criterion
  </structure>
  <example>
    "Add input validation to login endpoint.
     File: auth/login.ts, line 23-45
     Validate: email format, password length (min 8 chars)
     Success: Invalid inputs return 400 with error message"
  </example>
  <use-case>Simple, isolated changes</use-case>
</pattern>

<pattern name="The Scaffolded Context">
  <description>Layered context with progressive detail</description>
  <structure>
    1. High-level goal
    2. Architecture overview
    3. Specific implementation area
    4. Detailed requirements
    5. Examples and patterns
  </structure>
  <example>
    Level 1: "Add real-time notifications to app"
    Level 2: "We use WebSockets (Socket.io), events are pub/sub via Redis"
    Level 3: "Notification service in services/notifications.ts"
    Level 4: "Add notifyUser(userId, message) function"
    Level 5: "Follow pattern in services/email.ts (similar pub/sub)"
  </example>
  <use-case>Complex features requiring context building</use-case>
</pattern>

<pattern name="The Differential Context">
  <description>Provide only differences from known baseline</description>
  <structure>
    1. Reference baseline ("like feature X")
    2. List differences only
    3. Constraints on what stays same
  </structure>
  <example>
    "Add Order endpoints like User endpoints (user/routes.ts).
     Differences:
     - Orders have nested Items array
     - Orders require authentication (Users don't)
     - Orders have payment status enum
     Same:
     - CRUD structure
     - Validation pattern
     - Error handling"
  </example>
  <use-case>Similar to existing functionality</use-case>
</pattern>

<pattern name="The Constraint-Heavy Context">
  <description>Define success by what NOT to do</description>
  <structure>
    1. Task
    2. List of forbidden actions
    3. List of required patterns
    4. Validation method
  </structure>
  <example>
    "Refactor auth/login.ts for readability.
     DO NOT:
     - Change function signatures
     - Modify behavior (tests must pass unchanged)
     - Add dependencies
     DO:
     - Extract helper functions for validation
     - Add descriptive variable names
     - Add JSDoc comments
     Validate: All tests pass, no new dependencies"
  </example>
  <use-case>Refactoring, behavior-preserving changes</use-case>
</pattern>
</elite-context-patterns>

<context-kpis>
<metric name="Context Utilization Rate">
  <definition>% of provided context used in agent's solution</definition>
  <calculation>
    Used Context Tokens / Total Context Tokens × 100
  </calculation>
  <target>70-90% (higher = better targeting)</target>
  <interpretation>
    <low>Context bloat, agent overwhelmed</low>
    <optimal>Precisely targeted context</optimal>
    <too-high>May be missing helpful context</too-high>
  </interpretation>
</metric>

<metric name="Context Sufficiency Rate">
  <definition>% of tasks completed without requesting additional context</definition>
  <target>85%+</target>
  <improvement>Better context anticipation, documentation</improvement>
</metric>

<metric name="Context Efficiency Score">
  <definition>Success rate per 1K tokens of context</definition>
  <calculation>
    (Successful Tasks / Total Tasks) / (Average Context Size / 1000)
  </calculation>
  <interpretation>Higher score = more efficient context usage</interpretation>
</metric>

<metric name="Context Reuse Rate">
  <definition>% of context that comes from cached sources (CLAUDE.md, ken-you-remember)</definition>
  <target>40-60% (balance between reuse and task-specific)</target>
  <benefit>Faster context loading, consistency</benefit>
</metric>
</context-kpis>

<advanced-techniques>
<technique name="Context Precompilation">
  <description>Pre-process codebase into agent-optimized summaries</description>
  <process>
    1. Generate module summaries (purpose, key functions, dependencies)
    2. Create API catalogs (all endpoints with signatures)
    3. Build type indexes (all interfaces/types with purposes)
    4. Store in structured docs
    5. Agent reads relevant summaries, not full code
  </process>
  <benefit>Massive context window savings</benefit>
  <tool-support>Custom scripts, aider, claude-code-helper</tool-support>
</technique>

<technique name="Semantic Context Retrieval">
  <description>Use embeddings to find relevant context automatically</description>
  <implementation>
    1. Embed all docs, code files
    2. Embed task description
    3. Retrieve top-K most similar files/docs
    4. Provide to agent as context
  </implementation>
  <benefit>Automatic context targeting</benefit>
  <tool-support>LlamaIndex, LangChain, custom embedding pipelines</tool-support>
</technique>

<technique name="Context Streaming">
  <description>Provide context in stages as agent requests</description>
  <workflow>
    1. Agent starts with minimal context
    2. Agent requests specific file/doc when needed
    3. Human or tool provides requested context
    4. Agent continues with new context
  </workflow>
  <benefit>Agent pulls exactly what it needs</benefit>
  <implementation>Conversational approach, agent uses Read tool autonomously</implementation>
</technique>

<technique name="Multi-Agent Context Partitioning">
  <description>Divide large context across specialized agents</description>
  <example>
    Task: Migrate monolith to microservices
    - Agent 1: Analyze dependencies (sees full codebase, produces dependency graph)
    - Agent 2: Design service boundaries (sees dependency graph only)
    - Agent 3: Implement User service (sees only User-related code)
    - Agent 4: Implement Order service (sees only Order-related code)
    No single agent overwhelmed
  </example>
  <benefit>Unlimited effective context (distributed)</benefit>
</technique>
</advanced-techniques>

<mastery-indicators>
  <indicator>You can predict exact context needed before starting task</indicator>
  <indicator>Your agents rarely ask clarifying questions</indicator>
  <indicator>You track and optimize context utilization metrics</indicator>
  <indicator>You use context compression techniques automatically</indicator>
  <indicator>You know when to split tasks to fit within horizon</indicator>
  <indicator>First-attempt success rate exceeds 85%</indicator>
  <indicator>You spend more time on context engineering than writing prompts</indicator>
</mastery-indicators>

<elite-mindset>
<principle>Context is not just information. It's the lens through which agents see reality.</principle>
<principle>Bad context → agent is blind. Good context → agent is brilliant.</principle>
<principle>Context engineering is the highest-leverage skill in agentic coding.</principle>
<principle>Every wasted token is a missed opportunity for signal.</principle>
<principle>The best context is invisible - agent doesn't notice, just succeeds.</principle>
</elite-mindset>

<implementation-roadmap>
  <phase1>Measure baseline: Track context utilization and sufficiency</phase1>
  <phase2>Apply compression: XML tags, code over prose, bullets</phase2>
  <phase3>Implement layering: Essential → Supporting → Reference</phase3>
  <phase4>Deploy caching: CLAUDE.md, ken-you-remember for common context</phase4>
  <phase5>Optimize scoping: Explicit boundaries on every task</phase5>
  <phase6>Master horizon: Decompose beyond-horizon tasks systematically</phase6>
  <phase7>Achieve elite: Context engineering becomes subconscious</phase7>
</implementation-roadmap>

<final-insight>
Elite context management is the difference between good and great agentic developers.

Beginners focus on prompts.
Intermediates focus on tools.
Experts focus on context.

Master context engineering, and every other leverage point becomes exponentially more effective.

This is the Agentic Horizon - the frontier where human expertise meets AI capability.
</final-insight>