Part II: Discovery Through Software Engineering and Vibe Coding
Chapter 11: Context Engineering at Repository Scale

Context Engineering at Repository Scale

"I have 200,000 tokens of context window and 2,000,000 lines of code. Something has to give, and it will not be my confidence."

A Coding Agent With a Context Budget

Overview

A coding agent is only as effective as the context it carries into the conversation. Feed it the wrong files and it hallucinates APIs that do not exist. Feed it too many files and critical details drown in noise. Feed it too few and it reinvents logic that already lives three directories away. This chapter treats context engineering as a first-class engineering discipline: the systematic construction, compression, and retrieval of the information a language model needs to act correctly on a large codebase.

We begin by quantifying why context is the bottleneck for coding agents (Section 11.1), then build the chunking and summarization machinery that compresses code into context-friendly units (Section 11.2). Section 11.3 introduces retrieval-augmented code generation, combining embedding search, BM25, and hybrid ranking to surface the right code at the right time. Finally, Section 11.4 assembles these pieces into a working repository intelligence layer that scales to codebases of 50,000 lines and beyond.

The ideas here connect backward to the prompt construction techniques of Chapter 10 and forward to the MCP server architecture of Chapter 12, where the intelligence layer becomes a tool that agents call through the Model Context Protocol. The Discovery Workbench, introduced in Chapter 6, gains a repository intelligence module in Section 11.4 that every subsequent chapter builds upon.

Prerequisites

This chapter assumes you have read Chapter 8: Foundations of AI-Assisted Software Engineering (for the mental model of how LLMs process code) and Chapter 10: Prompting to Programming (for prompt construction patterns). Familiarity with Python, basic linear algebra (dot products, cosine similarity), and introductory information retrieval concepts (TF-IDF, inverted indexes) will be helpful. If you need a refresher on embeddings and vector spaces, see Chapter 26.

Learning Outcomes

Sections

11.1 Why Context Is the Bottleneck

Token limits versus codebase size. Attention decay and the lost-in-the-middle problem. Information density of code versus prose. Repo structure signals: file trees, import graphs, symbol tables. The context budget as a scarce resource.

11.2 Chunking and Summarization

Syntactic chunking with tree-sitter. Semantic chunking by logical units. Hierarchical chunking for nested structures. Summarization via docstring extraction, signature condensation, and LLM-generated overviews. Building a chunk store.

11.3 Retrieval-Augmented Code Generation

Dense retrieval with code embeddings. Sparse retrieval with BM25. Hybrid search and reciprocal rank fusion. Structural re-ranking with import graphs. Context budget as a knapsack problem. Evaluation metrics for code retrieval.

11.4 Building a Repository Intelligence Layer

Recipe: assembling tree-sitter, ripgrep, sentence-transformers, and pgvector into a repository intelligence service. Indexing pipeline, query interface, and integration with the Discovery Workbench. Performance benchmarks on a 50k-LOC codebase.

What's Next

The repository intelligence layer you build in this chapter provides the context backbone that coding agents need. In Chapter 12: Building MCP Servers for Scientific Workflows, we wrap this intelligence layer (and many other tools) in the Model Context Protocol, giving agents a standardized way to query repository structure, retrieve relevant code, and invoke development tools. The context engineering techniques from this chapter become the foundation for every agent interaction in the rest of Part II.

Bibliography

Foundational Papers

Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F., & Liang, P. (2024). Lost in the middle: How language models use long contexts. Transactions of the ACL, 12, 157-173.

The landmark study showing that LLMs attend most strongly to the beginning and end of their context window, with significant degradation for information placed in the middle.

Jimenez, C. E., Yang, J., Wettig, A., Yao, S., Pei, K., Press, O., & Narasimhan, K. (2024). SWE-bench: Can language models resolve real-world GitHub issues? ICLR 2024.

The benchmark that revealed how critically context retrieval quality affects coding agent success rates on real repository issues.

Books

Manning, C. D., Raghavan, P., & Schutze, H. (2008). Introduction to Information Retrieval. Cambridge University Press.

The classic information retrieval textbook covering TF-IDF, BM25, and inverted indexes; essential background for code search systems.

Tools & Libraries

Tree-sitter

An incremental parsing library that builds concrete syntax trees for source code in dozens of languages, used throughout this chapter for syntactic chunking.

ripgrep (rg)

A blazing-fast line-oriented search tool that respects .gitignore rules, used as the text search backbone in the repository intelligence layer.

sentence-transformers

The Python library for computing dense vector embeddings with pre-trained transformer models, used for semantic code search in Section 11.3.

pgvector

A PostgreSQL extension for vector similarity search, providing the persistent embedding store in the repository intelligence layer.

rank_bm25

A Python implementation of the BM25 ranking algorithm, used for sparse keyword-based code retrieval.

Tutorials & Surveys

Shrivastava, D., Larochelle, H., & Tarlow, D. (2023). Repository-level prompt generation for large language models of code. ICML 2023.

Proposes Repo-Level Prompt Generator (RLPG), which learns to compose prompts from repository context for code completion.

Ding, Y., et al. (2024). CrossCodeEval: A diverse and multilingual benchmark for cross-file code completion. NeurIPS 2023.

A benchmark specifically designed to evaluate cross-file code understanding, directly testing the retrieval quality that context engineering aims to optimize.