1. Sliding Window Eviction with Semantic Anchoring for Multi-File Coding Agents

A naive sliding window that just drops the oldest tokens will silently evict the type definitions and interface contracts your agent needs most — semantic anchoring lets you make eviction decisions based on relevance, not just recency.

  • Recency-only eviction discards structural context like interface signatures and shared type declarations at exactly the moment a multi-file refactor needs them most.
  • Semantic anchoring pins a ranked set of high-salience chunks — type definitions, function signatures, cross-file import graphs — so they survive eviction rounds that clear lower-relevance implementation detail.
  • Window resize events should emit observable signals with a payload describing what was evicted, what was pinned, and why — this is your audit trail when a downstream agent makes a decision that looks wrong.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

The core problem with standard context eviction in long coding sessions is that the model's working memory collapses asymmetrically — narrative task context (what are we trying to build?) and structural dependency context (what does this type look like?) degrade at different rates, but a sliding window treats them identically. A better design partitions the context buffer into tiers: a pinned zone holding AST-derived structural anchors, a recency zone holding recent file edits and tool call results, and a summary zone holding compressed narrative state generated by a cheap summarization step at each resize boundary. The pinned zone should be populated at session initialization by a static analysis pass over the file graph — something a TypeScript compiler API or tree-sitter parser can produce cheaply — and updated incrementally as new files enter scope. Source: [Beyond code generation: A developer's guide to agentic engineering] — GitHub Blog (https://github.blog/ai-and-ml/github-copilot/beyond-code-generation-a-developers-guide-to-agentic-engineering/)

The summarization step at resize boundaries is where most implementations cut corners and pay for it later. A good summary isn't a token-count reduction of recent history; it's a structured extraction of open tasks, pending decisions, and cross-file dependencies the agent has flagged but not yet resolved. Writing this as a typed object rather than free prose makes it inspectable — your observability layer can diff summaries across resize events to detect when the agent's mental model of the task has drifted from the actual file state. [AI Synthesis] This connects directly to the decomposed observability pattern: if you can't read the agent's compressed state at a checkpoint, you can't govern what it does next.

Reference Architecture
// TypeScript: Context buffer manager with tiered zones
type ContextChunk = {
  id: string;
  content: string;
  zone: 'pinned' | 'recency' | 'summary';
  salience: number; // 0–1, computed from AST role + recency decay
  tokenCount: number;
};

type ResizeAuditEvent = {
  timestamp: string;
  evicted: string[];  // chunk ids
  pinned: string[];   // chunk ids retained
  summarySnapshot: StructuredTaskSummary;
  tokensBefore: number;
  tokensAfter: number;
};

type StructuredTaskSummary = {
  openTasks: string[];
  pendingDecisions: string[];
  crossFileDependencies: { source: string; target: string; kind: string }[];
};

function resizeContext(
  buffer: ContextChunk[],
  targetTokenBudget: number,
  emitAuditEvent: (event: ResizeAuditEvent) => void
): ContextChunk[] {
  const pinned = buffer.filter(c => c.zone === 'pinned');
  const recency = buffer
    .filter(c => c.zone === 'recency')
    .sort((a, b) => b.salience - a.salience);

  const summaryChunk = summarizeRecencyZone(recency); // call to LLM summarizer
  const evicted: string[] = [];
  let tokenCount = pinned.reduce((sum, c) => sum + c.tokenCount, 0)
    + summaryChunk.tokenCount;

  const retained: ContextChunk[] = [];
  for (const chunk of recency) {
    if (tokenCount + chunk.tokenCount <= targetTokenBudget) {
      retained.push(chunk);
      tokenCount += chunk.tokenCount;
    } else {
      evicted.push(chunk.id);
    }
  }

  emitAuditEvent({
    timestamp: new Date().toISOString(),
    evicted,
    pinned: pinned.map(c => c.id),
    summarySnapshot: summaryChunk.structuredSummary,
    tokensBefore: buffer.reduce((s, c) => s + c.tokenCount, 0),
    tokensAfter: tokenCount,
  });

  return [...pinned, summaryChunk, ...retained];
}
State Interaction Chart
flowchart TD A[Session Start] --> B[Static Analysis Pass] B --> C[Build File Dependency Graph] C --> D[Populate Pinned Zone] D --> E[Agent Task Loop] E --> F{Context Near Limit?} F -- No --> E F -- Yes --> G[Summarize Recency Zone] G --> H[Emit Resize Audit Event] H --> I[Evict Low-Salience Chunks] I --> J[Refresh Pinned Zone from Graph] J --> E

2. Agentic Coding Pipelines Beyond Raw Generation: The PR Review Bottleneck as a Context Signal

When PR review time balloons 441% while generation speed skyrockets, the bottleneck has moved upstream into the agent's ability to self-review its own output — and that requires holding diff context alongside generation context in the same window budget.

  • Generation volume outpacing review capacity is a system design failure, not a workflow problem — an agentic pipeline that can write but not critically evaluate its own output has incomplete cognitive architecture.
  • Diff-aware context partitioning keeps a compressed representation of what the agent changed alongside what it's currently writing, enabling lightweight self-review passes without a separate review agent.
  • Human-in-the-loop checkpoints placed at context resize boundaries — rather than at arbitrary time intervals — give reviewers a structurally meaningful window into agent state at the moment the agent itself acknowledged a transition.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

GitHub's data is pointing at something structurally important: the 400% surge in commit volume with no corresponding productivity gain tells you that the value bottleneck has shifted entirely to comprehension, review, and integration — not generation. Source: [Beyond code generation: A developer's guide to agentic engineering] — GitHub Blog (https://github.blog/ai-and-ml/github-copilot/beyond-code-generation-a-developers-guide-to-agentic-engineering/) For a coding agent running a multi-file task, this means the agent's context window needs to carry two things simultaneously: the generative working state (what am I building right now?) and the evaluative working state (what have I already changed, and does my current direction contradict any of those earlier decisions?). These compete for tokens, and most current pipelines don't model this competition explicitly — they just write code until the context fills up and then drop history.

A practical solution is to treat the agent's diff log as a first-class context citizen — not the raw diffs, which are token-expensive, but a structured change manifest: which files changed, which interfaces were affected, and which of those changes are now depended on by subsequent edits. This manifest is cheap to maintain incrementally and can be embedded in the pinned zone described in block_1. [AI Synthesis] When a human reviewer picks up this session at a resize boundary, they get both the summarized narrative state and the change manifest — enough to make a genuine governance call rather than reading walls of generated code cold.

Reference Architecture
// TypeScript: Change manifest maintained alongside generation context
type ChangeManifest = {
  affectedFiles: string[];
  interfaceMutations: {
    file: string;
    symbol: string;
    changeKind: 'added' | 'modified' | 'removed';
  }[];
  dependencyLinks: {
    source: string;
    target: string;
    dependsOnSymbol: string;
  }[];
};

function updateManifestOnWrite(
  manifest: ChangeManifest,
  filePath: string,
  changedSymbols: { name: string; kind: 'added' | 'modified' | 'removed' }[],
  newDependencies: { target: string; symbol: string }[]
): ChangeManifest {
  const updatedFiles = Array.from(new Set([...manifest.affectedFiles, filePath]));

  const newMutations = changedSymbols.map(s => ({
    file: filePath,
    symbol: s.name,
    changeKind: s.kind,
  }));

  const newLinks = newDependencies.map(d => ({
    source: filePath,
    target: d.target,
    dependsOnSymbol: d.symbol,
  }));

  return {
    affectedFiles: updatedFiles,
    interfaceMutations: [...manifest.interfaceMutations, ...newMutations],
    dependencyLinks: [...manifest.dependencyLinks, ...newLinks],
  };
}
State Interaction Chart
sequenceDiagram participant Agent participant ContextManager participant ChangeManifest participant HILReviewer Agent->>ContextManager: Write to file A ContextManager->>ChangeManifest: Log affected interfaces Agent->>ContextManager: Write to file B (depends on A) ContextManager->>ChangeManifest: Log dependency link A->B ContextManager->>ContextManager: Context near limit ContextManager->>Agent: Trigger resize + summarize ContextManager->>HILReviewer: Emit checkpoint: summary + change manifest HILReviewer-->>ContextManager: Approve or correct ContextManager->>Agent: Resume with refreshed context

3. Self-Evaluating Context Compression: Borrowing From Recursive Self-Improvement for Window Policy Learning

Lilian Weng's harness framing of recursive self-improvement suggests a near-term design where the agent's context compression policy isn't hand-coded — it's a learned heuristic that the agent evaluates and updates based on whether prior evictions caused downstream failures.

  • Compression policy as a feedback loop means tracking which eviction decisions correlated with subsequent errors — when the agent had to re-fetch something it previously dropped, that's a signal the eviction heuristic was wrong.
  • Harness-based self-evaluation wraps the agent's task execution in an outer evaluation loop that scores output quality against a rubric, then attributes quality degradation to specific context management decisions — giving you data to tune eviction weights.
  • Static hand-coded eviction rules are the baseline, but the ceiling is an agent that learns from its own session history what categories of context are load-bearing and adjusts pin weights accordingly without engineer intervention.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

Weng's treatment of recursive self-improvement distinguishes between models that rewrite their weights and systems that improve their own scaffolding — the latter is immediately applicable to production engineering without the alignment risks of the former. Source: [Harness Engineering for Self-Improvement] — Lilian Weng (https://lilianweng.github.io/posts/2026-07-04-harness/) Applied to context window management, this means treating the eviction policy as a component with its own feedback loop: every time the agent retrieves something it previously evicted, log that as a policy miss; every time a session completes cleanly without re-fetching, log that as a policy hit. Over enough sessions, you accumulate a dataset that maps context chunk attributes — AST role, dependency depth, recency, token cost — to eviction safety scores.

AIThis connects to the decomposed observability trend: the same audit events you emit for human governance (what was evicted, when, why) are also training signal for the policy optimizer. You're not building two separate systems — the observability layer is the data pipeline for self-improvement. The practical starting point is to instrument your existing eviction logic to emit structured miss/hit events, even before you build any learning machinery around it. That data will tell you quickly whether your current salience heuristics are systematically wrong for a particular file type or task class.

Reference Architecture
// TypeScript: Eviction feedback instrumentation
type EvictionFeedbackEvent = {
  sessionId: string;
  chunkId: string;
  chunkAttributes: {
    astRole: 'interface' | 'implementation' | 'test' | 'config';
    dependencyDepth: number;
    tokenCount: number;
    ageInTurns: number;
  };
  outcome: 'hit' | 'miss'; // miss = agent had to re-fetch this chunk
  missedAtTurn?: number;
};

function recordEvictionOutcome(
  emit: (event: EvictionFeedbackEvent) => void,
  sessionId: string,
  chunkId: string,
  attributes: EvictionFeedbackEvent['chunkAttributes'],
  refetchedChunkIds: Set<string>
): void {
  const outcome = refetchedChunkIds.has(chunkId) ? 'miss' : 'hit';
  emit({
    sessionId,
    chunkId,
    chunkAttributes: attributes,
    outcome,
    ...(outcome === 'miss' ? { missedAtTurn: Date.now() } : {}),
  });
}
State Interaction Chart
flowchart TD A[Agent Session Executes] --> B[Context Resize with Eviction] B --> C[Log Eviction Decisions] C --> D{Agent Re-fetches Evicted Chunk?} D -- Yes --> E[Log Policy Miss with Chunk Attributes] D -- No --> F[Log Policy Hit] E --> G[Policy Feedback Store] F --> G G --> H[Periodic Policy Weight Update] H --> I[Updated Salience Scoring Model] I --> B

4. Agentic Security Boundaries When Context Windows Touch the Codebase at Scale

When your coding agent is managing context across dozens of files with write access, the eviction and retrieval layer is also your attack surface — poisoned context that survives eviction can steer agent behavior across an entire session.

  • Context poisoning risk is different from prompt injection in a chat interface — a malicious or corrupted chunk in the pinned zone persists across resize events and influences every subsequent generation step without the agent re-evaluating it.
  • Write-access scope per context zone should be a first-class design decision: the pinned zone (structural anchors) should be read-only after initialization, and only verified tool outputs should be able to modify it — not raw file content.
  • Security event correlation at resize boundaries — logging what entered the pinned zone, from which source, at which turn — gives you the forensic trail you need when an agent produces an unexpected output after a long session.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

The Pragmatic Engineer's framing of AI-accelerated security risk lands differently when you zoom into agentic coding specifically. Source: [The Pulse: Time to rethink software security because of AI?] — Pragmatic Engineer (https://blog.pragmaticengineer.com/the-pulse-time-to-rethink-software-security-because-of-ai/) The concern isn't just that AI generates vulnerable code faster — it's that an agentic pipeline with context persistence creates a new class of vulnerability where the agent's compressed belief about the codebase can be manipulated. If an attacker can get a crafted comment or docstring into a file that ends up in the pinned zone, that content persists and influences generation decisions for the entire session lifetime.

AIThe mitigation pattern mirrors what you'd do for any trust boundary in a distributed system: treat context zone mutations as privileged operations. The pinned zone should be populated only from tool outputs that have been through a validation step — not from raw file reads. Any file-derived content that enters the pinned zone should be stripped of freeform prose and reduced to structured representations: type signatures, import graphs, function stubs. This makes it structurally harder to embed steering instructions in what looks like legitimate source context, and it's a better design anyway because structured representations are more token-efficient.

Reference Architecture
// TypeScript: Pinned zone write gate with provenance
type ProvenanceRecord = {
  chunkId: string;
  sourceFile: string;
  sourceTool: string;
  extractedKind: 'type' | 'interface' | 'function-signature' | 'import-graph';
  insertedAtTurn: number;
  verifiedBy: string; // tool name or validation step id
};

function writeToPinnedZone(
  zone: Map<string, ContextChunk>,
  chunk: ContextChunk,
  provenance: Omit<ProvenanceRecord, 'chunkId'>,
  emitProvenance: (record: ProvenanceRecord) => void,
  emitSecurityAlert: (msg: string) => void
): boolean {
  const allowedKinds = ['type', 'interface', 'function-signature', 'import-graph'];

  if (!allowedKinds.includes(provenance.extractedKind)) {
    emitSecurityAlert(
      `Rejected pinned zone write: unexpected kind '${provenance.extractedKind}' from ${provenance.sourceFile}`
    );
    return false;
  }

  if (!provenance.verifiedBy) {
    emitSecurityAlert(`Rejected unverified pinned zone write from ${provenance.sourceFile}`);
    return false;
  }

  zone.set(chunk.id, chunk);
  emitProvenance({ chunkId: chunk.id, ...provenance });
  return true;
}
State Interaction Chart
flowchart TD A[File Read Tool Output] --> B[Content Sanitizer] B --> C{Structured Extract Only?} C -- Yes --> D[Validated Structural Chunk] C -- No --> E[Reject or Quarantine] D --> F[Pinned Zone Write Gate] F --> G{Source Verified?} G -- Yes --> H[Insert to Pinned Zone] G -- No --> I[Log Security Event and Discard] H --> J[Emit Provenance Record] J --> K[Observability Store]

5. Compliance-Grade Context Audit Trails: What Fintech Automation Gets Right That Coding Agents Don't Yet

The fintech compliance automation pattern — structured extraction, traceable data lineage, auditable outputs — is a direct template for how coding agent context management should be governed, and most current implementations are nowhere near this standard.

  • Compliance pipelines treat every data transformation as a traceable step with inputs, outputs, and a rationale — coding agent context management should work the same way, with every eviction and injection decision logged as a first-class event.
  • Structured extraction over raw retrieval is how fintech agents avoid reconciliation errors; applying this to coding context means transforming file content into typed, schema-validated representations before they enter the context buffer.
  • Audit trail completeness for a coding agent session means you can reconstruct the exact context state the agent held at any turn — not just what files it touched, but what it believed about those files at each decision point.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

The fintech case study's core design decision — replacing manual aggregation with structured agentic extraction that produces traceable, validated intermediate outputs — is exactly the discipline missing from most coding agent context pipelines. Source: [How a Leading Fintech Cuts Weekly Compliance Reporting from 2 Days to 2 Hours] — CrewAI Blog (https://blog.crewai.com/how-a-leading-fintech-cuts-weekly-compliance-reporting-from-2-days-to-2-hours/) In a compliance pipeline, you never let raw source data flow directly into a report — it goes through extraction, normalization, and validation steps, each of which produces a logged artifact. Context management for coding agents should apply the same discipline: raw file content should never land directly in the context buffer; it should pass through a structured extraction step that produces a typed, validated chunk with known semantics.

AIThe payoff is symmetric: just as the fintech team reduced error rates by eliminating untracked manual transformations, a coding agent that processes context through validated extraction steps produces a buffer where every chunk has known provenance and known semantics. This makes the observability story dramatically simpler — when the agent makes a wrong decision, you can trace it to a specific chunk, see where that chunk came from, and identify whether the extraction step introduced the error or the eviction policy retained something it should have dropped. This is the foundation of genuinely governable agentic coding pipelines, not just observable ones.

Reference Architecture
// TypeScript: Validated context chunk factory from file content
import { z } from 'zod';

const FunctionSignatureChunkSchema = z.object({
  file: z.string(),
  symbolName: z.string(),
  parameters: z.array(z.object({ name: z.string(), type: z.string() })),
  returnType: z.string(),
  exportKind: z.enum(['named', 'default', 'none']),
});

type FunctionSignatureChunk = z.infer<typeof FunctionSignatureChunkSchema>;

function extractAndValidateFunctionSignature(
  rawASTNode: unknown,
  filePath: string,
  emitExtractionFailure: (reason: string, file: string) => void
): FunctionSignatureChunk | null {
  const result = FunctionSignatureChunkSchema.safeParse(rawASTNode);

  if (!result.success) {
    emitExtractionFailure(
      result.error.issues.map(i => i.message).join('; '),
      filePath
    );
    return null;
  }

  return result.data;
}
State Interaction Chart
flowchart TD A[Raw File Content] --> B[Structured Extraction Step] B --> C[Schema Validation] C --> D{Valid?} D -- No --> E[Log Extraction Failure] D -- Yes --> F[Typed Context Chunk with Provenance] F --> G[Context Buffer Insert] G --> H[Audit Log Entry] H --> I[Reconstructable Session Store] I --> J[Governance Query: State at Turn N]