AI Workflows Quy Trình AI · · 8 min read

Context Engineering and the Subagent Triad Architecture Kỹ Thuật Ngữ Cảnh và Kiến Trúc Bộ Ba Subagent Tự Trị

How disciplined context engineering and structured multi-agent triads transform AI code generation from stochastic guessing into high-velocity production engineering. Cách kỹ thuật ngữ cảnh kỷ luật và mô hình phân rã nhiệm vụ đa agent chuyển hóa việc tạo mã AI từ phỏng đoán ngẫu nhiên thành quy trình kỹ thuật sản xuất tốc độ cao.

Written by Nguyen Cong Ben Nguyễn Công Ben
Context Engineering and Subagent Triad Architecture

1. 🧠 The Context Window Illusion

As modern Large Language Models (LLMs) expanded from 8K to 1M+ token context windows, a common misconception took hold: simply stuffing entire codebases into the prompt will solve complex software engineering tasks.

In practice, production benchmarks reveal the Context Degradation Curve: as context size swells, attention mechanisms experience “needle in a haystack” dilution, resulting in:

  • Hallucinated Interfaces: Invoking non-existent methods or outdated dependency versions.
  • Architectural Drift: Creating duplicate helper functions across different directories instead of reusing existing core modules.
  • Silent Regressions: Modifying unrelated edge cases and breaking unit tests.

Context Engineering is the discipline of curating, structuring, and scoping the exact minimum viable knowledge required for an AI agent to execute a task with deterministic precision.


2. 🏛️ The Subagent Triad Architecture

Rather than assigning a monolithic prompt to handle research, architecture, implementation, and quality assurance simultaneously, we decompose workflows into a Subagent Triad:

flowchart TD
    User["Lead Engineer / Developer Prompt"] --> Governor["🛡️ 1. Ecosystem Governor\n- Validates workspace prerequisites\n- Locks package versions & lint rules\n- Guards directory & boundary constraints"]
    
    Governor --> Architect["📐 2. Domain Architect\n- Researches existing codebase patterns\n- Drafts explicit interface contracts & schemas\n- Establishes formal verification criteria"]
    
    Architect --> Director["⚡ 3. Implementation Director\n- Executes code modifications in narrow slices\n- Runs automated unit & integration tests\n- Delivers verified, self-documenting diffs"]
    
    Director -->|Feedback Loop on Test Failure| Architect

3. 🎯 The Four Pillars of Context Engineering

  1. Just-In-Time (JIT) Context Ingestion: Never dump full repository dumps into the model prompt. Use AST-aware search tools (ripgrep, semantic symbol lookups) to pull in only the targeted file chunks relevant to the current call stack.
  2. Explicit Negative Constraints: Define what the model must NOT do (e.g., “Do not install new npm dependencies; do not modify existing public API signatures”).
  3. Structured Machine-Readable Interfaces: Prefer JSON Schema tool definitions and strict type contracts over ambiguous prose instructions.
  4. Adversarial Verification Loops: Require a fresh-context subagent to inspect the final code diff against the original task specification before marking a task complete.

4. 💻 Practical Implementation: Subagent Task Spec

{
  "role": "ImplementationDirector",
  "task": "Refactor token bucket algorithm in auth_middleware.py",
  "context_scope": {
    "target_file": "src/core/auth_middleware.py",
    "interface_definition": "src/types/auth.ts",
    "permitted_modifications": ["TokenBucket", "acquire_slot"]
  },
  "invariants": [
    "Must maintain backward compatibility with v1 clients",
    "Zero external dependencies outside standard asyncio library",
    "Must achieve 100% test coverage in tests/test_auth.py"
  ],
  "verification_command": "pytest tests/test_auth.py -v"
}

5. 📊 Results & Velocity Gains

Applying the Subagent Triad and Context Engineering principles across real-world projects yields:

  • 85% Reduction in Hallucinations: Strict JIT scoping eliminates phantom API imports.
  • 3.2x Faster Completion Cycles: Narrow subagent tasks avoid endless backtracking loops.
  • Production-Grade Code Quality: Changes pass linters and test suites on the first execution pass.

1. 🧠 Ảo Tưởng Về Dung Lượng Cửa Sổ Ngữ Cảnh (Context Window)

Khi các mô hình ngôn ngữ lớn (LLM) mở rộng cửa sổ ngữ cảnh từ 8K lên hơn 1 triệu token, nhiều người lầm tưởng rằng: chỉ cần ném toàn bộ mã nguồn của dự án vào prompt là AI có thể tự động viết phần mềm hoàn hảo.

Thực tế kiểm nghiệm cho thấy Đường Cong Suy Thoái Ngữ Cảnh (Context Degradation): khi kích thước ngữ cảnh quá lớn, cơ chế Attention của mô hình bị phân tán, dẫn đến các sai lầm nghiêm trọng:

  • Tạo ra API giả (Hallucination): Gọi các hàm không tồn tại hoặc sử dụng cú pháp của thư viện phiên bản cũ.
  • Phá vỡ kiến trúc: Tự tiện viết lại các hàm tiện ích trùng lặp thay vì tái sử dụng mô-đun cốt lõi có sẵn.
  • Gây lỗi suy thoái ngầm: Vô tình làm hỏng các bài kiểm thử đơn vị (unit tests) của các tính năng lân cận.

Kỹ thuật Ngữ cảnh (Context Engineering) chính là bộ môn khoa học về việc chọn lọc, cấu trúc hóa và giới hạn lượng thông tin tối thiểu cần thiết để AI coding agent thực thi nhiệm vụ với độ chính xác tuyệt đối.


2. 🏛️ Kiến Trúc Bộ Ba Subagent (Subagent Triad)

Thay vì giao toàn bộ quá trình khảo sát, thiết kế, lập trình và kiểm thử cho một prompt nguyên khối duy nhất, quy trình được phân rã thành Bộ Ba Subagent chuyên biệt:

flowchart TD
    User["Yêu Cầu Từ Kỹ Sư Trưởng"] --> Governor["🛡️ 1. Người Quản Trị (Governor)\n- Kiểm tra tính toàn vẹn của môi trường\n- Khóa phiên bản thư viện & quy tắc linter\n- Bảo vệ ranh giới các thư mục cốt lõi"]
    
    Governor --> Architect["📐 2. Kiến Trúc Sư (Architect)\n- Khảo sát cấu trúc mã nguồn hiện hữu\n- Soạn thảo hợp đồng giao tiếp & interface\n- Xác lập tiêu chí nghiệm thu kiểm thử"]
    
    Architect --> Director["⚡ 3. Đạo Diễn Thực Thi (Director)\n- Viết mã theo từng phần nhỏ có kiểm chứng\n- Chạy kiểm thử tự động (Unit / Integration)\n- Bàn giao bản diff sạch sẽ, tự tài liệu hóa"]
    
    Director -->|Phản hồi khi kiểm thử thất bại| Architect

3. 🎯 Bốn Trụ Cột Của Kỹ Thuật Ngữ Cảnh

  1. Nạp Ngữ Cảnh Đúng Lúc (Just-In-Time Context): Không bao giờ nạp toàn bộ dự án vào bộ nhớ. Sử dụng các công cụ tìm kiếm AST (ripgrep, phân tích cây cú pháp) để chỉ trích xuất đúng các đoạn code liên quan đến call stack hiện tại.
  2. Ràng Buộc Tiêu Cực Rõ Ràng (Negative Constraints): Định nghĩa rõ những điều mô hình tuyệt đối KHÔNG được làm (ví dụ: “Không cài thêm thư viện npm mới; không sửa chữ ký hàm công khai hiện hữu”).
  3. Giao Diện Có Cấu Trúc Máy Đọc Được: Sử dụng chuẩn schema JSON và kiểu dữ liệu chặt chẽ thay vì các câu lệnh mô tả văn xuôi mơ hồ.
  4. Vòng Lặp Phản Biện Độc Lập: Yêu cầu một subagent có ngữ cảnh mới hoàn toàn kiểm tra lại bản diff code so với yêu cầu ban đầu trước khi đánh dấu hoàn thành.

4. 💻 Ví Dụ Về Cấu Trúc Nhiệm Vụ Cho Subagent

{
  "role": "ImplementationDirector",
  "task": "Tối ưu hóa thuật toán Token Bucket trong auth_middleware.py",
  "context_scope": {
    "target_file": "src/core/auth_middleware.py",
    "interface_definition": "src/types/auth.ts",
    "permitted_modifications": ["TokenBucket", "acquire_slot"]
  },
  "invariants": [
    "Bắt buộc phải tương thích ngược với client phiên bản v1",
    "Không dùng thư viện bên ngoài ngoài thư viện chuẩn asyncio của Python",
    "Bắt buộc vượt qua 100% test case trong tests/test_auth.py"
  ],
  "verification_command": "pytest tests/test_auth.py -v"
}

5. 📊 Kết Quả Thực Tiễn & Hiệu Suất

Áp dụng phương pháp Kỹ thuật Ngữ cảnh và mô hình Subagent Triad mang lại:

  • Giảm 85% Lỗi Ảo Giác (Hallucinations): Ranh giới ngữ cảnh rõ ràng ngăn chặn việc gọi sai thư viện.
  • Tăng Tốc Độ Hoàn Thành Nhiệm Vụ 3.2 Lần: Không còn các vòng lặp sửa sai vô tận.
  • Chất Lượng Mã Nguồn Sẵn Sàng Cho Production: Mã nguồn được tạo ra vượt qua toàn bộ linter và test runner ngay từ lần chạy đầu tiên.