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 23 เราจะเพิ่มวงจรตรวจสอบอัตโนมัติ (Verification Loop) และระบบกู้คืนสถานะอัตโนมัติ (Auto-Rollback) เมื่อโค้ดที่ Agent แก้ไขพัง:
ทำหน้าที่รันคำสั่ง Maven/Gradle ภายใน Sandbox ทันทีหลังจากที่ Agent ทำการแก้โค้ด หากผลลัพธ์การทดสอบล้มเหลว (Test Failed) ระบบจะสั่ง Revert หรือ Git Reset กลับสู่สถานะปลอดภัยทันที พร้อมส่ง Error Log กลับเข้า ReAct Loop ให้ Agent แก้ไขใหม่
จำลองสถานการณ์การใส่โค้ดที่ผิดพลาดลงไป เพื่อทดสอบว่าระบบ Verification Loop สามารถตรวจจับข้อผิดพลาดและสั่ง Auto-Rollback ได้อย่างถูกต้องแม่นยำ
Agent แก้ไขซอร์สโค้ดใน Worktree ชั่วคราวบน /tmp พร้อมบันทึก Commit เฉพาะกิจ
สั่งรันชุดทดสอบเพื่อตรวจดูว่าผ่านเกณฑ์ BUILD SUCCESS หรือไม่
หากเทสผ่าน นำ Branch ส่งเข้าสู่กระบวนการ Review / Pull Request ต่อไป
หากเทสพัง สั่งยกเลิก ทำลาย Worktree และลบบันทึกทิ้งทันที ไม่มีร่องรอยความเสียหาย
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)}"
}
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()
เปิด Terminal บน MacBook M3 แล้วทำตามขั้นตอนเพื่อทดสอบระบบ Autonomous Verification Loop:
cd ~/se_agent
source .venv/bin/activate
touch core/verification_loop.py test_verification_loop.py
python test_verification_loop.py
ข้อที่ 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 ของคุณสามารถทดลองแก้โค้ด รันเทส และถอยกลับอัตโนมัติได้อย่างมืออาชีพแล้วครับ!