15%

5.4 Codebase Exploration and Context Degradation

Codebase Exploration คืออะไร

Codebase Exploration คือ pattern ที่ agent ใช้เพื่อเข้าใจ codebase ที่ไม่เคยเห็นมาก่อน — ต้องหา relevant files, เข้าใจ architecture, ระบุ dependencies, และหาจุดที่ต้องแก้ไข ทั้งหมดนี้ภายใต้ข้อจำกัดของ context window ที่ไม่สามารถโหลด codebase ทั้งหมดได้

Context Degradation Problem

ยิ่ง context ยาว quality ของ Claude’s attention ยิ่งลดลง:

  • 200K tokens = ได้แค่ ~50 files ขนาดปานกลาง
  • “Lost in the middle” = ข้อมูลกลาง context ถูก attend น้อยกว่าต้น/ท้าย
  • Tool result flooding = tool results ยาวๆ กิน context โดยไม่จำเป็น

Exploration Strategies

1. Top-Down Exploration

# Start broad, then zoom in
exploration_steps = [
    "ls -la",                           # Root structure
    "cat README.md",                    # Project overview
    "find . -name '*.py' | head -20",   # Main files
    "cat src/main.py",                  # Entry point
    # Then: follow imports, find relevant modules
]

2. Search-Based Exploration

# Start with what you're looking for
exploration_steps = [
    "grep -r 'def authenticate' .",     # Find the function
    "grep -r 'import auth' .",          # Find who uses it
    "cat src/auth/middleware.py",       # Read the implementation
]

3. Structural Exploration

# Understand architecture first
exploration_steps = [
    "find . -name '*.py' -path '*/models/*'",   # Data layer
    "find . -name '*.py' -path '*/routes/*'",   # API layer
    "find . -name '*.py' -path '*/services/*'", # Business logic
    "cat pyproject.toml",                        # Dependencies
]

Managing Context During Exploration

Chunked Reading

อ่าน file เป็นส่วนๆ แทนที่จะโหลดทั้งหมด:

# แทนที่จะ cat ทั้งไฟล์ (อาจ 1000+ lines)
# อ่านแค่ส่วนที่เกี่ยวข้อง
tools = [{
    "name": "read_file",
    "input_schema": {
        "properties": {
            "path": {"type": "string"},
            "start_line": {"type": "integer"},
            "end_line": {"type": "integer"}
        }
    }
}]

Summarize-As-You-Go

สรุปข้อมูลที่อ่านแล้วแทนที่จะเก็บ raw content:

# Agent workflow
findings = []

# Read file 1
content = read_file("src/auth.py")
findings.append("auth.py: JWT-based auth, uses Redis for session store")

# Read file 2
content = read_file("src/database.py")  
findings.append("database.py: SQLAlchemy ORM, PostgreSQL, connection pooling")

# When context is getting full, work from summaries not raw files

Progressive Disclosure

เริ่มจาก high-level แล้วเจาะลึกเฉพาะที่จำเป็น:

# Level 1: File list
files = list_directory("src/")  # 50 files

# Level 2: Read only relevant files
relevant = [f for f in files if "auth" in f or "user" in f]

# Level 3: Read specific functions
for f in relevant:
    outline = get_function_signatures(f)  # Just signatures, not body
    if "login" in outline:
        full_content = read_file(f)  # Only read full when needed

Context Degradation Mitigation

1. Prioritize Recent Context

ข้อมูลท้ายสุดใน context ได้ attention มากที่สุด:

# ใส่ข้อมูลสำคัญที่สุดเป็น message สุดท้าย
messages = [
    *old_context,                    # Less attention
    {"role": "user", "content": f"""
    Based on my exploration, the key findings are:
    {important_summary}              # More attention (recent)
    
    Now, please {actual_task}
    """}
]

2. External Memory

เก็บข้อมูลที่ค้นพบไว้นอก context:

# Write findings to a file — can re-read later
def save_exploration_notes(findings):
    with open(".agent-notes.md", "w") as f:
        f.write("# Codebase Exploration Notes\n\n")
        for finding in findings:
            f.write(f"- {finding}\n")

# Later: re-read only what's needed
def load_relevant_notes(topic):
    notes = read_file(".agent-notes.md")
    return filter_by_topic(notes, topic)

3. Focused Agent Delegation

แทนที่จะอ่านเอง ส่ง focused query ให้ sub-agent:

# Main agent doesn't read everything
# Delegates focused questions to sub-agents
answer = await agent(f"""
    In the codebase at {repo_path}:
    Find where user authentication happens.
    Return ONLY: file path, function name, and auth method used.
    Do not return full file contents.
""")

Key Concepts

  • Exploration budget — จำกัด tokens ที่ใช้ explore (ไม่ใช้ 80% ของ context ไปกับ exploration แล้วไม่เหลือให้ทำงาน)
  • Relevant vs Complete — ไม่ต้องเข้าใจทั้ง codebase; เข้าใจส่วนที่เกี่ยวข้องพอ
  • Attention budget — ข้อมูลกลาง context ถูก “ลืม”; ใส่สิ่งสำคัญไว้ต้น/ท้าย
  • Tool result truncation — tool results ที่ยาวเกินไปเป็น anti-pattern; ให้ tool return summary

Exam Tips

  • Context degradation = ยิ่ง context ยาว quality ยิ่งลด (attention กระจาย)
  • “Lost in the middle” = ข้อมูลตรงกลาง conversation ถูก attend น้อยที่สุด
  • ข้อสอบจะถามว่า: agent ต้องเข้าใจ large codebase ทำอย่างไร — ตอบ: progressive disclosure, search-based, summarize
  • Exploration budget สำคัญ — ใช้ tokens กับ exploration มากเกินไป = เหลือน้อยสำหรับ actual work
  • External memory (write to file) เป็น pattern สำคัญสำหรับ long-running agents