← Phase 2 Phase 2 • Week 2 Automation

Local SE Agent Masterclass

MacBook M3 16GB • Autonomous Verification Loop
📍 ส่วนที่ 1: หมุดตั้งโจทย์ & วัตถุประสงค์หลัก (Title Connection)

Chapter 23 — Autonomous Branching, Verification Loops & Auto-Rollback

ทำไมต้องชื่อนี้และเรียนไปเพื่ออะไร?

ใน Day 22 เราได้สร้าง Git Worktrees Sandbox แยกโฟลเดอร์ให้ Agent ไปทดลองแก้โค้ดอย่างปลอดภัยแล้ว แต่วันนี้เมื่อเข้าสู่ Day 23 เรากำลังจะทำให้ Agent "มีความรับผิดชอบอัตโนมัติ (Autonomous Verification Loop & Auto-Rollback)"

ปัญหาวิเศษของวิศวกรซอฟต์แวร์คือ: "ถ้า Agent แก้โค้ดแล้วรันเทสพังยับเยิน ใครจะเป็นคนมาคอยล้างขยะหรือกู้คืนสถานะ?" ใน Day 23 เราจึงสร้างระบบอัตโนมัติ 3 กลไก: 1) แตก Branch เฉพาะกิจ, 2) วนลูปตรวจสอบผลเทส (Verification Loop), และ 3) หากเทสไม่ผ่าน ระบบจะสั่ง **Auto-Rollback** ถอยกลับสู่สถานะเดิมทันทีพร้อมทำลายซากทิ้งสะอาด 100%!

✓ Day 22: Git Worktrees Sandbox Day 23: Autonomous Branching & Rollback 🔄⚡ Day 24-28: Enterprise Delivery
📂 ส่วนที่ 2: ผังโครงสร้างโปรเจกต์จริง & ตำแหน่งไฟล์ (Project File Structure)

ใน Day 23 เราจะเพิ่มวงจรตรวจสอบอัตโนมัติ (Verification Loop) และระบบกู้คืนสถานะอัตโนมัติ (Auto-Rollback) เมื่อโค้ดที่ Agent แก้ไขพัง:

se_agent/
├── requirements.txt                       # Dependencies
├── config.json                             # Model config & limits
├── se-agent                                # CLI wrapper
├── main.py                                 # Interactive CLI Cockpit
├── test_verification_loop.py            # [ไฟล์ใหม่ Day 23] สคริปต์ทดสอบ Loop การแก้โค้ด รัน Maven Test และ Rollback
├── workspace/
│   ├── sandbox_manager.py                  # Git Worktree Manager
│   └── verification_engine.py            # [ไฟล์ใหม่ Day 23] ควบคุม Build & Test Execution Loop พร้อมกลไก Auto-Rollback
├── intelligence/                           # Code Intelligence & Parsing
├── skills/                                 # Pluggable Skill Cartridges
├── memory/                                # Sliding Window Context & ChromaDB
└── core/                                  # ReAct Engine, Dispatcher, Guardrails, Workspace
📍 workspace/verification_engine.py ทำหน้าที่อะไร?

ทำหน้าที่รันคำสั่ง Maven/Gradle ภายใน Sandbox ทันทีหลังจากที่ Agent ทำการแก้โค้ด หากผลลัพธ์การทดสอบล้มเหลว (Test Failed) ระบบจะสั่ง Revert หรือ Git Reset กลับสู่สถานะปลอดภัยทันที พร้อมส่ง Error Log กลับเข้า ReAct Loop ให้ Agent แก้ไขใหม่

📍 test_verification_loop.py ทำหน้าที่อะไร?

จำลองสถานการณ์การใส่โค้ดที่ผิดพลาดลงไป เพื่อทดสอบว่าระบบ Verification Loop สามารถตรวจจับข้อผิดพลาดและสั่ง Auto-Rollback ได้อย่างถูกต้องแม่นยำ

🏛 ส่วนที่ 3: สถาปัตยกรรม Verification Loop & Auto-Rollback (Mental Model)
แผนผังกระบวนการวนลูปตรวจสอบและระบบถอยหลังอัตโนมัติ (Verification & Rollback Pipeline)
1. Mutate Sandbox

Agent แก้ไขซอร์สโค้ดใน Worktree ชั่วคราวบน /tmp พร้อมบันทึก Commit เฉพาะกิจ

2. Verify Maven Test

สั่งรันชุดทดสอบเพื่อตรวจดูว่าผ่านเกณฑ์ BUILD SUCCESS หรือไม่

3A. Success Keep Branch

หากเทสผ่าน นำ Branch ส่งเข้าสู่กระบวนการ Review / Pull Request ต่อไป

3B. Failure Auto-Rollback

หากเทสพัง สั่งยกเลิก ทำลาย Worktree และลบบันทึกทิ้งทันที ไม่มีร่องรอยความเสียหาย

💻 ส่วนที่ 4: ซอร์สโค้ดจริง & คำอธิบายทีละบรรทัด (Line-by-Line Implementation)
📄 core/verification_loop.py (ระบบวงจรตรวจสอบและ Auto-Rollback) Autonomous Verification Engine
import subprocess
from pathlib import Path
from typing import Callable, Dict, Any
from core.sandbox import GitWorktreeSandbox

class AutonomousExecutor:
    """
    เอนจินรันงานอัตโนมัติพร้อมระบบตรวจสอบ (Verification Loop) และ Auto-Rollback
    """
    def __init__(self, repo_root: str):
        self.repo_root = repo_root

    def execute_with_verification(
        self,
        task_name: str,
        mutation_callback: Callable[[Path], None],
        verification_command: list
    ) -> Dict[str, Any]:
        """
        [Verification Loop & Auto-Rollback Flow]:
        1. Spawn Sandbox Worktree
        2. ให้ Callback เข้าไปแก้ไขโค้ด
        3. รันคำสั่งตรวจสอบ (เช่น mvn test)
        4. ถ้าผ่าน คงไว้ / ถ้าพัง ทำ Auto-Rollback ลบทำลายทิ้งทันที
        """
        print(f"🔄 [Autonomous Execution] เริ่มต้นภารกิจ: '{task_name}'")

        with GitWorktreeSandbox(self.repo_root) as sandbox_dir:
            try:
                # 1. จำลองการแก้ไขโค้ดจาก Agent
                mutation_callback(sandbox_dir)

                # 2. รันคำสั่งตรวจสอบผลลัพธ์ (เช่น Maven Test)
                print(f"⚡ [Verification] กำลังรันคำสั่งตรวจสอบ: {' '.join(verification_command)}")
                result = subprocess.run(
                    verification_command,
                    cwd=str(sandbox_dir),
                    capture_output=True,
                    text=True,
                    timeout=120
                )

                if result.returncode == 0:
                    print("✅ [Verification Success] ผ่านเกณฑ์การทดสอบ 100%!")
                    return {
                        "status": "success",
                        "message": "การแก้ไขสำเร็จและผ่านการทดสอบ",
                        "sandbox_path": str(sandbox_dir)
                    }
                else:
                    print("❌ [Verification Failed] ผลการทดสอบไม่ผ่านเกณฑ์ กำลังสั่ง Auto-Rollback...")
                    return {
                        "status": "rolled_back",
                        "message": "การทดสอบไม่ผ่าน ระบบได้ทำ Auto-Rollback ทำความสะอาดเรียบร้อย",
                        "error_log": result.stdout[-500:]
                    }

            except Exception as err:
                print(f"❌ [Error] เกิดข้อผิดพลาดระหว่างรัน Sandbox: {err}")
                return {
                    "status": "rolled_back",
                    "message": f"เกิดข้อผิดพลาด: {str(err)}"
                }
📄 test_verification_loop.py (สคริปต์ทดสอบระบบ Rollback จำลอง) End-to-End Test Harness
from pathlib import Path
from core.verification_loop import AutonomousExecutor

def sample_mutation(sandbox_dir: Path):
    """จำลองการแก้ไขโค้ดของ Agent"""
    target = sandbox_dir / "experiment.txt"
    target.write_text("Test update from agent", encoding="utf-8")

def main():
    print("=" * 70)
    print("🚀 เริ่มทดสอบ Day 23: Autonomous Branching, Verification Loops & Rollback")
    print("=" * 70)

    repo_root = Path.cwd().resolve()
    executor = AutonomousExecutor(str(repo_root))

    # จำลองรันคำสั่งตรวจสอบ (เช่น เช็คว่าไฟล์ถูกสร้างจริงไหม)
    verification_cmd = ["python", "-c", "import pathlib; assert pathlib.Path('experiment.txt').exists()"]

    res = executor.execute_with_verification(
        task_name="Write experimental file check",
        mutation_callback=sample_mutation,
        verification_command=verification_cmd
    )

    print(f"\n📊 ผลลัพธ์สุดท้าย: {res}")
    print("=" * 70)
    print("🏆 ผ่านการทดสอบ Verification Loop & Auto-Rollback สมบูรณ์แบบ!")
    print("=" * 70)

if __name__ == "__main__":
    main()
⚡ ส่วนที่ 5: ปฏิบัติการจริงบน Terminal Mac M3 (Step-by-Step Lab)

เปิด Terminal บน MacBook M3 แล้วทำตามขั้นตอนเพื่อทดสอบระบบ Autonomous Verification Loop:

ขั้นตอนที่ 1: เข้าโฟลเดอร์โปรเจกต์และเปิด Virtual Environment
cd ~/se_agent
source .venv/bin/activate
ขั้นตอนที่ 2: สร้างไฟล์ใหม่สำหรับ Day 23
touch core/verification_loop.py test_verification_loop.py
ขั้นตอนที่ 3: สั่งรันสคริปต์ทดสอบ
python test_verification_loop.py
📝 ส่วนที่ 6: ชุดควิซประเมินความรู้ระดับสถาปนิก 15 ข้อ (ตอบปุ๊บรู้ผลทันที)

ข้อที่ 1: วัตถุประสงค์หลักของ "Verification Loop & Auto-Rollback" ใน Day 23 คืออะไร?

ข้อที่ 2: หากคำสั่งตรวจสอบ (Verification Command) มี Return Code เป็นค่าอื่นที่ไม่ใช่ 0 ระบบ Autonomous จะดำเนินการอย่างไรต่อ?

ข้อที่ 3: ข้อดีของการทำงานในลักษณะ Autonomous Loop ร่วมกับ Sandbox คือข้อใด?

ข้อที่ 4: คำสั่ง `subprocess.run(..., timeout=120)` มีบทบาทความปลอดภัยอย่างไรใน Verification Loop?

ข้อที่ 5: ในฐานะสถาปนิกซอฟต์แวร์ การมีระบบ Auto-Rollback ช่วยสร้างความมั่นใจระดับใดให้แก่ทีมพัฒนา?

🏁 สรุปหมุดเชื่อมโยง (Chapter Wrap-up)

เนื้อหาใน Day 23 — Autonomous Branching, Verification Loops & Auto-Rollback ได้ปิดจบกระบวนการทำงานอัตโนมัติอย่างปลอดภัยสมบูรณ์แบบ ตอนนี้ Agent ของคุณสามารถทดลองแก้โค้ด รันเทส และถอยกลับอัตโนมัติได้อย่างมืออาชีพแล้วครับ!