Skip to content
KoishiAI
ไทย
← Back to contents
Chapter 6 / 6 · April 24, 2026

CLI และ Automation ขั้นสูง

Agent SDK, headless mode, scripting และการ automate flow

This guide is All Rights Reserved — free to read, copying/republication requires permission.

บทที่ 6 | เทคนิค CLI และ AI Wiki / RAG สำหรับ Claude Code กลุ่มเป้าหมาย: Developer ทุกระดับที่ต้องการใช้ Claude Code อย่างมืออาชีพผ่าน CLI

CLI คืออะไร และทำไมถึงทรงพลัง

CLI (Command Line Interface) คือการสั่งงานคอมพิวเตอร์ผ่านการพิมพ์คำสั่งข้อความ แทนที่จะคลิก GUI ฟังดูเก่า แต่ใน workflow ของ Developer ปัจจุบัน CLI ทรงพลังกว่า GUI มากในหลายด้าน โดยเฉพาะเมื่อใช้ร่วมกับ Claude Code

ทำไม CLI ถึงสำคัญใน Vibe Coding?

สิ่งที่ทำใน GUIทำด้วย CLI ได้เร็วกว่า
เปิดไฟล์ → คัดลอก → วางใน Claudecat file.py | claude -p “อธิบาย”
รัน test → copy error → วางใน Claudenpm test 2>&1 | claude -p “แก้ error”
ดู git diff → copy → วางใน Claudegit diff | claude -p “review”
ทำซ้ำๆ manual ทีละโปรเจคเขียน shell script ทำอัตโนมัติ
ดู log จาก web UItail -f app.log | claude -p “monitor”
ต้องสลับหน้าต่างตลอดทุกอย่างอยู่ใน terminal เดียว

Terminal ที่ใช้งานได้เลย

ระบบTerminal ที่แนะนำเหตุผล
macOSiTerm2 + zsh + Oh My ZshSplit pane, plugin ecosystem, syntax highlight
macOSWarp TerminalAI-native terminal, command history อัจฉริยะ
LinuxKitty หรือ Alacrittyเร็ว, GPU-accelerated, config ด้วย text
WindowsWindows Terminal + WSL2รัน Linux commands ได้เต็มรูปแบบ
ทุกระบบtmuxSession management, split pane, ไม่หายเมื่อ disconnect

Claude Code CLI — ทุก Flag และ Option ที่ต้องรู้

Claude Code มี CLI interface ที่ครบครันมาก การรู้ทุก flag ช่วยให้ใช้งานได้อย่างมีประสิทธิภาพสูงสุด

Flags พื้นฐาน

claudeเปิด Interactive mode — โต้ตอบกับ Claude แบบ chat
claude -p “prompt”One-shot mode — ส่ง prompt แล้วรับคำตอบ ปิดทันที
claude —versionแสดง version ปัจจุบันของ Claude Code
claude —helpแสดง help ทุก flag และ option
claude —model [model]เลือก model: claude-opus-4, claude-sonnet-4, claude-haiku-4-5
claude —max-tokens [n]จำกัดความยาวของ response (1-8192 tokens)
claude —temperature [0-1]ความ creative ของ response (0=ตรงๆ, 1=สร้างสรรค์)

Flags สำหรับ Input

claude -p ”…” —file [path]แนบไฟล์ไปกับ prompt
cat file | claude -p ”…”ส่งเนื้อหาผ่าน stdin (pipe)
claude -p ”…” < input.txtอ่าน input จากไฟล์
claude —add-dir [path]เพิ่มโฟลเดอร์ให้ Claude เข้าถึงได้
claude —system-prompt ”…”กำหนด system prompt แทน CLAUDE.md
claude —continueต่อ Session ล่าสุดที่ค้างอยู่
claude —resume [session-id]เปิด Session เฉพาะด้วย ID

Flags สำหรับ Output

claude -p ”…” —output-format jsonOutput เป็น JSON (เหมาะสำหรับ scripting)
claude -p ”…” —output-format textOutput เป็น plain text (default)
claude -p ”…” —output-format stream-jsonStream JSON ทีละ chunk
claude -p ”…” > output.txtบันทึก output ลงไฟล์
claude -p ”…” | tee output.txtแสดงบนจอและบันทึกไฟล์พร้อมกัน
claude —no-colorปิด color output (เหมาะสำหรับ pipe ไปที่อื่น)

Flags สำหรับ Automation

claude -p ”…” —dangerously-skip-permissionsข้าม permission prompt ทั้งหมด (ใช้ใน CI/CD)
claude -p ”…” —allowedTools “Bash,Read”อนุญาตเฉพาะ tools ที่ระบุ
claude -p ”…” —disallowedTools “Write”ห้ามใช้ tools ที่ระบุ
claude —print-statsแสดงสถิติ tokens ที่ใช้
claude —verboseแสดงข้อมูล debug เพิ่มเติม

ตัวอย่างการใช้ Flag จริง

# 1. วิเคราะห์ไฟล์เดียวแบบ one-shot
claude -p "สรุปฟังก์ชันสำคัญ" --file src/auth.ts
 
# 2. เลือก model ที่ถูกกว่าสำหรับงานง่าย
claude --model claude-haiku-4-5 -p "แก้ typo ในไฟล์นี้" --file README.md
 
# 3. Output เป็น JSON สำหรับนำไปใช้ต่อ
claude -p "list ทุก function ในไฟล์นี้เป็น JSON array" \
  --file src/utils.ts --output-format json
 
# 4. รัน batch analysis หลายไฟล์
for f in src/**/*.ts; do
  echo "=== $f ==="
  claude -p "มี security issue ไหม? ตอบ YES/NO และเหตุผล" --file "$f"
done
 
# 5. ใช้ใน CI/CD โดยไม่ถาม permission
claude -p "รัน tests และรายงานผล" \
  --dangerously-skip-permissions \
  --output-format json > test-report.json

Pipe และ Stdin — หัวใจของ CLI Power

Pipe (|) คือเครื่องมือที่ทำให้ CLI ทรงพลังมาก มันส่ง output ของคำสั่งหนึ่งไปเป็น input ของอีกคำสั่ง ทำให้สร้าง workflow ซับซ้อนได้โดยไม่ต้องเขียน intermediate files

Pipe Patterns ที่ใช้บ่อย

Pattern 1: File Analysis
# วิเคราะห์ไฟล์ต่างๆ
cat src/api/users.ts | claude -p "หา N+1 query"
 
# ส่งหลายไฟล์รวมกัน
cat src/lib/auth.ts src/middleware/auth.ts | \
  claude -p "วิเคราะห์ authentication flow ทั้งหมด"
 
# ส่งเฉพาะบางบรรทัด
sed -n "45,80p" src/payments.ts | \
  claude -p "อธิบาย logic ในบรรทัดนี้"
 
# ส่งผ่าน head/tail
tail -100 src/server.ts | \
  claude -p "100 บรรทัดสุดท้ายมีปัญหาอะไรไหม"
Pattern 2: Error Analysis
# วิเคราะห์ error จาก tests
npm test 2>&1 | claude -p "แก้ tests ที่ fail"
 
# ดักจับ error เฉพาะ
npm run build 2>&1 | grep -E "ERROR|error" | \
  claude -p "อธิบาย errors เหล่านี้และวิธีแก้"
 
# TypeScript errors
npx tsc --noEmit 2>&1 | \
  claude -p "แก้ TypeScript errors ทั้งหมด เรียงตาม priority"
 
# ESLint
npx eslint src/ --format json 2>&1 | \
  claude -p "สรุป linting issues และวิธีแก้จากสำคัญมากไปน้อย"
 
# Runtime error จาก server log
tail -50 logs/error.log | \
  claude -p "วิเคราะห์ pattern ของ errors และหา root cause"
Pattern 3: Git Integration
# เขียน commit message
git diff --staged | \
  claude -p "เขียน commit message ตาม Conventional Commits"
 
# Review ก่อน PR
git diff main...HEAD | \
  claude -p "รีวิว code changes เหล่านี้แบบ senior developer"
 
# PR Description
git log main..HEAD --oneline | \
  claude -p "สร้าง PR description จาก commits เหล่านี้"
 
# หาว่า commit ไหนแก้อะไร
git log --oneline -20 | \
  claude -p "สรุปว่า 20 commits นี้เปลี่ยนแปลงระบบอย่างไร"
 
# วิเคราะห์ merge conflict
git diff --diff-filter=U | \
  claude -p "แก้ merge conflicts ทั้งหมดนี้อย่างเหมาะสม"
Pattern 4: System & Process
# วิเคราะห์ process ที่กิน CPU สูง
ps aux | sort -k3 -rn | head -20 | \
  claude -p "process ไหนน่าเป็นห่วง อธิบายและแนะนำ"
 
# วิเคราะห์ disk usage
du -sh * | sort -rh | head -20 | \
  claude -p "อะไรกินพื้นที่มากที่สุด ควรทำอะไร"
 
# ดู network connections
netstat -an | grep ESTABLISHED | \
  claude -p "มี connection ที่น่าสงสัยไหม"
 
# วิเคราะห์ docker
docker ps --format json | \
  claude -p "containers ไหนใช้ resource มากผิดปกติ"
 
# Package vulnerabilities
npm audit --json | \
  claude -p "สรุป vulnerabilities เรียงตาม severity และวิธีแก้"
Pattern 5: Data Processing
# วิเคราะห์ CSV
cat sales-data.csv | \
  claude -p "สรุป top 10 products และ revenue trends"
 
# ดึงข้อมูลจาก JSON API แล้ววิเคราะห์
curl -s https://api.myapp.com/stats | \
  claude -p "อธิบาย metrics เหล่านี้และ identify anomalies"
 
# แปลง format
cat data.json | \
  claude -p "แปลง JSON นี้เป็น CSV format พร้อม headers"
 
# วิเคราะห์ log patterns
grep "ERROR" logs/app.log | \
  sort | uniq -c | sort -rn | head -20 | \
  claude -p "errors ไหนเกิดบ่อยที่สุด น่าแก้อันไหนก่อน"

Chaining Commands — ต่อหลาย Pipe

การต่อหลาย pipe ทำให้สร้าง workflow ที่ซับซ้อนได้ในบรรทัดเดียว:

# Chain ซับซ้อน: หา dead code และเสนอวิธีลบ
find src/ -name "*.ts" -exec grep -l "export" {} \; | \
  xargs grep -L "import.*from" | \
  claude -p "ไฟล์เหล่านี้ export แต่ไม่มีใคร import อาจเป็น dead code"
 
# หา TODO comments ที่ค้างนานที่สุด
git log --all --format="%ai %H" | \
  head -100 | \
  while read date hash; do
    git grep -l "TODO" $hash 2>/dev/null | head -5
  done | sort | uniq | \
  claude -p "TODOs ไหนที่น่าจะค้างมานานที่สุด"
 
# วิเคราะห์ performance ของ API endpoints
cat logs/access.log | \
  awk "{print $7, $10}" | \
  sort -k2 -rn | head -20 | \
  claude -p "endpoints ไหนที่ response time สูงที่สุด วิเคราะห์ pattern"

Shell Scripting ร่วมกับ Claude Code

เมื่อรู้ pipe แล้ว ขั้นต่อไปคือเขียน shell script ที่ใช้ Claude เป็นส่วนหนึ่งของ automation workflow

Script พื้นฐาน: Daily Code Review

Script ที่รันทุกเช้า review code ที่ commit เมื่อวาน:

#!/bin/bash
# daily-review.sh
# รัน: chmod +x daily-review.sh && ./daily-review.sh
 
YESTERDAY=$(date -d "yesterday" +%Y-%m-%d 2>/dev/null || date -v-1d +%Y-%m-%d)
REPORT_FILE="reports/review-$(date +%Y-%m-%d).md"
 
mkdir -p reports
 
echo "# Daily Code Review Report: $(date)" > "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
 
# ดู commits เมื่อวาน
COMMITS=$(git log --oneline --after="$YESTERDAY 00:00" --before="$YESTERDAY 23:59")
 
if [ -z "$COMMITS" ]; then
  echo "ไม่มี commits เมื่อวาน" >> "$REPORT_FILE"
  exit 0
fi
 
echo "## Commits" >> "$REPORT_FILE"
echo "$COMMITS" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
 
# วิเคราะห์ code changes
echo "## Code Analysis" >> "$REPORT_FILE"
git diff HEAD~$(echo "$COMMITS" | wc -l)..HEAD | \
  claude -p "รีวิว code changes เมื่อวานทั้งหมด
            ครอบคลุม: quality, security, performance
            ให้ summary และ action items" \
  >> "$REPORT_FILE"
 
# ส่ง report ไป Slack
REPORT_CONTENT=$(cat "$REPORT_FILE")
curl -X POST "$SLACK_WEBHOOK" \
  -H "Content-Type: application/json" \
  -d "{"text": "$REPORT_CONTENT"}"
 
echo "Report saved: $REPORT_FILE"

Script: อัตโนมัติ Commit Message

Hook ที่สร้าง commit message อัตโนมัติจาก staged changes:

#!/bin/bash
# .git/hooks/prepare-commit-msg
# ติดตั้ง: chmod +x .git/hooks/prepare-commit-msg
 
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
 
# รันเฉพาะเมื่อ commit ใหม่ (ไม่ใช่ merge, squash, etc.)
if [ "$COMMIT_SOURCE" != "" ]; then
  exit 0
fi
 
# ดูว่ามีอะไร staged
DIFF=$(git diff --staged)
if [ -z "$DIFF" ]; then
  exit 0
fi
 
# ให้ Claude เขียน message
echo "🤖 กำลังสร้าง commit message..."
 
GENERATED_MSG=$(echo "$DIFF" | claude -p \
  "เขียน commit message ตาม Conventional Commits format
   format: type(scope): description
   types: feat|fix|refactor|docs|test|chore|perf
   ใช้ภาษาอังกฤษ ไม่เกิน 72 ตัวอักษรในบรรทัดแรก
   ถ้ามีรายละเอียดเพิ่มเติม เว้นบรรทัดแล้วใส่ bullet points
   ตอบเฉพาะ commit message ไม่มีคำอธิบายเพิ่ม" \
  --model claude-haiku-4-5)
 
# ใส่ message ที่สร้างไว้ใน commit file
echo "$GENERATED_MSG" > "$COMMIT_MSG_FILE"
 
echo "✅ Commit message พร้อมแล้ว (แก้ไขได้ใน editor)"

Script: Batch File Processing

วิเคราะห์หรือ transform หลายไฟล์พร้อมกัน:

#!/bin/bash
# batch-analyze.sh — วิเคราะห์ทุก Python file ใน project
 
OUTPUT_DIR="analysis"
mkdir -p "$OUTPUT_DIR"
 
TOTAL=0
ISSUES=0
 
# วิเคราะห์ทุก .py ไฟล์
find src/ -name "*.py" | while read file; do
  BASENAME=$(basename "$file" .py)
  OUTPUT="$OUTPUT_DIR/$BASENAME-analysis.md"
 
  echo "วิเคราะห์: $file"
 
  RESULT=$(cat "$file" | claude -p \
    "วิเคราะห์ไฟล์นี้:
     1. มี bug ที่เห็นชัดไหม?
     2. มี security issue ไหม?
     3. Performance ปรับปรุงได้ไหม?
     ตอบ JSON: {bugs: [], security: [], performance: []}",
    --output-format json)
 
  echo "## $file" > "$OUTPUT"
  echo "$RESULT" >> "$OUTPUT"
 
  # นับ files ที่มีปัญหา
  HAS_ISSUES=$(echo "$RESULT" | python3 -c
    "import json,sys; d=json.load(sys.stdin)
    print(1 if any(d.values()) else 0)")
 
  TOTAL=$((TOTAL + 1))
  if [ "$HAS_ISSUES" = "1" ]; then
    ISSUES=$((ISSUES + 1))
  fi
done
 
echo "สรุป: $ISSUES/$TOTAL ไฟล์มีปัญหา"
echo "ดูรายละเอียดใน $OUTPUT_DIR/"

Script: Environment Setup อัตโนมัติ

Script สำหรับ setup developer environment ใหม่:

#!/bin/bash
# setup-dev.sh — setup environment สำหรับ developer ใหม่
 
echo "🚀 Setup Development Environment"
 
# ตรวจสอบ dependencies
check_dependency() {
  if ! command -v $1 &> /dev/null; then
    echo "❌ $1 ไม่ได้ติดตั้ง"
    return 1
  fi
  echo "✅ $1 พร้อม"
}
 
check_dependency node || exit 1
check_dependency npm || exit 1
check_dependency git || exit 1
 
# ดู README แล้วถาม Claude ว่ามีขั้นตอนพิเศษอะไรบ้าง
if [ -f README.md ]; then
  SETUP_STEPS=$(cat README.md | claude -p \
    "ดึง setup steps ทั้งหมดจาก README นี้
     เป็น numbered list คำสั่งที่ต้องรัน",
    --model claude-haiku-4-5)
  echo "📋 Setup steps จาก README:"
  echo "$SETUP_STEPS"
fi
 
# ติดตั้ง packages
npm install
 
# ตรวจสอบว่า .env มีครบ
if [ -f .env.example ] && [ ! -f .env ]; then
  MISSING_VARS=$(diff <(grep -oP "^[A-Z_]+" .env.example) \
    <(grep -oP "^[A-Z_]+" .env 2>/dev/null) | \
    grep "^<" | sed "s/< //")
 
  if [ -n "$MISSING_VARS" ]; then
    echo "$MISSING_VARS" | claude -p \
      "Environment variables เหล่านี้ขาดใน .env
       อธิบายแต่ละตัวว่าคือค่าอะไร หาได้จากไหน"
  fi
fi
 
echo "✅ Setup เสร็จสมบูรณ์!"

tmux — จัดการ Terminal อย่างมืออาชีพ

tmux (terminal multiplexer) ช่วยให้เปิดหลาย terminal พร้อมกันในหน้าต่างเดียว และที่สำคัญคือ session ไม่หายแม้ปิด terminal ทำให้ Claude Code sessions ยังคงอยู่

ติดตั้ง tmux

# macOS
brew install tmux
 
# Ubuntu/Debian
sudo apt install tmux
 
# ตรวจสอบ
tmux --version

คำสั่ง tmux ที่ใช้บ่อยกับ Claude Code

tmux new -s claudeสร้าง session ใหม่ชื่อ “claude”
tmux attach -t claudeกลับเข้า session ที่มีอยู่
tmux lsแสดง sessions ทั้งหมด
Ctrl+b dDetach จาก session (session ยังรันอยู่)
Ctrl+b %แบ่ง pane แนวตั้ง (side by side)
Ctrl+b “แบ่ง pane แนวนอน (top/bottom)
Ctrl+b [arrow]เลื่อนระหว่าง panes
Ctrl+b zZoom pane ปัจจุบัน (เต็มจอ)
Ctrl+b [Scroll mode (ใช้ arrow keys เลื่อน)
Ctrl+b cสร้าง window ใหม่
Ctrl+b [0-9]สลับ windows

Layout แนะนำสำหรับ Vibe Coding

Layout ที่ optimal สำหรับการทำงานกับ Claude Code:

# สร้าง layout อัตโนมัติด้วย script
#!/bin/bash
# claude-layout.sh
 
SESSION="dev"
PROJECT=$(basename $(pwd))
 
# สร้าง session ถ้ายังไม่มี
tmux new-session -d -s $SESSION -n "main"
 
# Window 1: Claude Code (ซ้าย 60%) + Terminal (ขวา 40%)
tmux split-window -h -p 40
tmux select-pane -t 0
tmux send-keys "claude" Enter
tmux select-pane -t 1
 
# Window 2: Editor
tmux new-window -n "editor"
tmux send-keys "code ." Enter
 
# Window 3: Logs (split top/bottom)
tmux new-window -n "logs"
tmux split-window -v -p 30
tmux select-pane -t 0
tmux send-keys "npm run dev" Enter
tmux select-pane -t 1
tmux send-keys "tail -f logs/error.log" Enter
 
# Window 4: Git
tmux new-window -n "git"
 
# กลับ Window แรก
tmux select-window -t 0
 
# Attach
tmux attach -t $SESSION

ส่ง Command ไปยัง Claude ใน tmux อัตโนมัติ

ทักษะขั้นสูง: ส่ง text ไปยัง tmux pane อื่นโดยอัตโนมัติ ทำให้ script ส่ง prompt ให้ Claude ได้โดยไม่ต้องพิมพ์เอง:

# ส่ง prompt ไปยัง Claude pane
tmux send-keys -t dev:main.0 "อธิบาย error นี้: $(cat error.log | tail -5)" Enter
 
# Script: เมื่อ test fail ให้ถาม Claude อัตโนมัติ
#!/bin/bash
# auto-debug.sh
 
npm test 2>&1 | tee /tmp/test-output.txt
 
if [ ${PIPESTATUS[0]} -ne 0 ]; then
  ERROR=$(tail -20 /tmp/test-output.txt)
  # ส่ง error ไปยัง Claude pane ใน tmux
  tmux send-keys -t dev:claude "$(echo $ERROR | claude -p "แก้ test failures นี้")" Enter
fi

AI Wiki — คู่มือฉบับสมบูรณ์

AI Wiki คือระบบเอกสารที่ออกแบบมาให้ Claude อ่านแล้วเข้าใจ context ได้ทันที บทนี้จะสร้าง Wiki ที่ใช้งานได้จริงตั้งแต่ต้น

ทำไม AI Wiki ต่างจาก Documentation ทั่วไป

Documentation ทั่วไป
เขียนสำหรับคนอ่าน
ใช้ narrative writing
อธิบายแบบเล่าเรื่อง
ไม่มี structure เฉพาะ
Claude อ่านแล้วอาจสับสน context
AI Wiki
เขียนสำหรับ Claude + คน
ใช้ structured format
ข้อมูลชัดเจน actionable
มี headings, tables, examples
Claude อ่านแล้วเข้าใจ context ทันที

สร้าง AI Wiki ตั้งแต่ต้น — Step by Step

1วิเคราะห์โปรเจคและสร้าง Index
ให้ Claude วิเคราะห์โปรเจคและบอกว่าต้องมี doc อะไรบ้าง
> วิเคราะห์โปรเจคนี้ทั้งหมด:
  @package.json @prisma/schema.prisma @src/
 
  สร้าง AI Wiki structure ที่เหมาะสม:
  - บอกว่าต้องมี doc file อะไรบ้าง
  - อธิบายว่า doc แต่ละไฟล์ควรมีเนื้อหาอะไร
  - สร้าง docs/README.md เป็น index
 
  Format index:
  | ไฟล์ | เนื้อหา | อ่านก่อนทำ |
  |------|---------|-----------|
  | architecture.md | ... | ทุกอย่าง |
2สร้าง Architecture Overview
อธิบาย big picture ของระบบ
# docs/architecture/overview.md
# System Architecture Overview
 
## System Purpose
E-commerce platform สำหรับขาย digital products
ผู้ใช้: 10,000 DAU, peak 50,000 concurrent
 
## Technology Stack
| Layer | Technology | Version | Why |
|-------|-----------|---------|-----|
| Frontend | Next.js App Router | 14.x | SSR + RSC |
| Backend | Next.js Server Actions | 14.x | Type-safe |
| Database | PostgreSQL | 16 | ACID, jsonb support |
| ORM | Prisma | 5.x | Type-safe, migration |
| Cache | Redis | 7 | Session, rate limit |
| Auth | NextAuth.js | 5 beta | OAuth + credentials |
| Deploy | Vercel + AWS | - | Frontend + DB |
 
## Data Flow
Browser → CDN → Vercel Edge → Next.js → Prisma → PostgreSQL

                     Redis Cache
 
## Key Design Decisions
- ใช้ Server Actions แทน REST API (ลด boilerplate 40%)
- PostgreSQL jsonb สำหรับ product metadata (flexible schema)
- Redis session ไม่ใช้ JWT (revokable, stateful)
 
## Performance Targets
- API P95: < 200ms
- Page LCP: < 2.5s on 4G
- Database query: < 50ms
3สร้าง Business Rules
กฎ business ที่ Claude ต้องรู้ก่อน implement
# docs/domain/business-rules.md
# Business Rules Reference
 
## Pricing Engine
 
### Priority Order (สำคัญมาก: ต้อง apply ตามลำดับ)
1. Original price
2. Product sale price (ถ้ามี)
3. Coupon discount (ลดจากราคาใน step 2)
4. Member discount (ลดจากราคาใน step 3)
5. Bundle discount (ลดจากราคาใน step 4)
6. Floor price (ราคาต่ำสุดที่ยอมให้ = cost + 10%)
 
### Coupon Rules
| Rule | Detail |
|------|--------|
| 1 coupon ต่อ order | ไม่สามารถใช้หลาย coupon พร้อมกัน |
| ต้องตรงกับ user tier | Silver coupon ใช้ได้กับ Silver+ เท่านั้น |
| ยอดขั้นต่ำ | บาง coupon กำหนด minimum order amount |
| ใช้ได้ครั้งเดียว | ต่อ user ต่อ coupon code |
 
### Member Tiers
| Tier | ยอดซื้อสะสม | ส่วนลด | Benefit เพิ่มเติม |
|------|------------|--------|-----------------|
| Bronze | < 5,000 | 0% | - |
| Silver | 5,000-19,999 | 3% | Free shipping |
| Gold | 20,000-49,999 | 5% | Priority support |
| Platinum | 50,000+ | 8% | Early access |
 
## Order State Machine

pending → confirmed → processing → shipped → delivered ↓ ↓ cancelled cancelled

 
### State Transition Rules
- pending → confirmed: ต้องมี payment confirmation
- confirmed → cancelled: คืนเงินอัตโนมัติภายใน 3 วันทำการ
- shipped → delivered: ต้อง confirm จาก tracking หรือ manual
- ห้าม: delivered → ใดๆ (final state)
 
## Inventory Rules
- Stock < 10 → แจ้ง admin alert
- Stock = 0 → ซ่อน add to cart button
- Reserved stock → lock 15 นาทีเมื่อ add to cart
4สร้าง API Reference
อธิบาย endpoints ทั้งหมด
# docs/api/endpoints.md
# API Endpoints Reference
 
## Authentication
ทุก endpoint ที่ไม่ได้ระบุว่า Public ต้องมี session cookie
หรือ Authorization: Bearer {token}
 
## Products
 
### GET /api/products
**Purpose**: ดึง product list พร้อม pagination และ filter
**Auth**: Public
**Query params**:
| param | type | required | description |
|-------|------|----------|-------------|
| page | number | no | default: 1 |
| limit | number | no | default: 20, max: 100 |
| category | string | no | category slug |
| q | string | no | search term |
| sort | string | no | price_asc, price_desc, newest |
 
**Response 200**:
```json
{
  "products": [{ "id": "...", "name": "...", "price": 0 }],
  "pagination": { "total": 0, "page": 1, "totalPages": 0 }
}

Error cases:

statuscodeเมื่อไหร่
400INVALID_PARAMSlimit > 100
404CATEGORY_NOT_FOUNDcategory ไม่มีในระบบ

POST /api/orders

Purpose: สร้าง order ใหม่ Auth: Required Body:

{
  "items": [{ "productId": "...", "quantity": 1 }],
  "couponCode": "SAVE10",
  "shippingAddressId": "..."
}

Important: ระบบจะ lock inventory ทันทีที่รับ request ถ้า payment ไม่สำเร็จใน 15 นาที จะ release lock อัตโนมัติ


| 5 | สร้าง Runbook <br> คู่มือแก้ปัญหาที่พบบ่อย |
|---|---|

docs/runbooks/common-issues.md

Common Issues Runbook

Redis Connection Failed

Symptoms: Login ล้มเหลว, session หาย Steps:

  1. ตรวจสอบ Redis status: redis-cli ping
  2. ถ้า NOAUTH error: ตรวจสอบ REDIS_PASSWORD ใน .env
  3. ถ้า Connection refused: ตรวจสอบ Redis service
    • AWS: ดู ElastiCache status ใน console
    • Local: docker start redis
  4. Flush session ถ้าจำเป็น: redis-cli FLUSHDB (ผู้ใช้ต้อง login ใหม่ทุกคน)

Stripe Webhook ไม่ทำงาน

Symptoms: Order ค้างที่ “pending” แม้จ่ายเงินแล้ว Steps:

  1. ดู Stripe Dashboard → Webhooks → View attempts
  2. ตรวจสอบ endpoint URL ถูกต้อง
  3. ตรวจสอบ STRIPE_WEBHOOK_SECRET ตรงกัน
  4. ดู server logs: grep "stripe" logs/app.log
  5. Retry webhook ใน Stripe Dashboard

Database Connection Pool Exhausted

Symptoms: “too many connections” error Steps:

  1. ดู connections ปัจจุบัน: SELECT count(*) FROM pg_stat_activity;
  2. ดู long-running queries: SELECT pid, now()-query_start, query FROM pg_stat_activity WHERE state="active" ORDER BY 2 DESC LIMIT 10;
  3. Kill query ที่ stuck: SELECT pg_terminate_backend(pid);
  4. Long-term: เพิ่ม connection pool limit ใน DATABASE_URL

### วิธีใช้ AI Wiki กับ Claude Code CLI

หลัง Wiki พร้อมแล้ว นี่คือวิธีใช้งานจริงกับ Claude Code CLI:

1. ส่ง Wiki file โดยตรง

cat docs/domain/business-rules.md |
claude -p “implement coupon validation ตาม business rules นี้”

2. รวม Wiki + Source code

cat docs/api/endpoints.md src/app/api/orders/route.ts |
claude -p “ตรวจสอบว่า implementation ตรงกับ API spec ไหม”

3. ค้นหา Wiki แล้วส่งให้ Claude

ใช้ grep หาส่วนที่เกี่ยวข้อง

grep -A 20 ”## Coupon Rules” docs/domain/business-rules.md |
claude -p “implement validateCoupon ตาม rules เหล่านี้”

4. ส่งหลาย Wiki files

cat docs/architecture/overview.md
docs/domain/business-rules.md
docs/api/endpoints.md |
claude -p “ออกแบบ Notification system ที่ consistent กับ architecture”

5. Script ค้นหา Wiki อัตโนมัติ

#!/bin/bash

wiki-search.sh [keyword] [question]

KEYWORD=$1 QUESTION=$2

หา relevant sections จาก Wiki

RELEVANT=$(grep -r -l “$KEYWORD” docs/ |
xargs grep -A 30 “$KEYWORD” 2>/dev/null)

if [ -z “$RELEVANT” ]; then echo “ไม่พบข้อมูลเกี่ยวกับ: $KEYWORD” exit 1 fi

ส่งให้ Claude

echo “Context จาก Wiki:” > /tmp/wiki-context.txt echo “$RELEVANT” >> /tmp/wiki-context.txt echo “คำถาม: $QUESTION” >> /tmp/wiki-context.txt

cat /tmp/wiki-context.txt | claude -p “$QUESTION”

ใช้งาน:

./wiki-search.sh “coupon” “implement coupon validation”


### Auto-update Wiki จาก Code

Script ที่สร้าง API docs จาก source code อัตโนมัติ ทำให้ Wiki ไม่ outdated:

#!/bin/bash

update-wiki.sh — อัปเดต Wiki หลัง implement feature

รัน: ./update-wiki.sh “notification system”

FEATURE=$1

echo “อัปเดต Wiki สำหรับ feature: $FEATURE”

1. สร้าง API docs จาก route files ใหม่

ROUTES=$(find src/app/api -name “route.ts” -newer docs/api/endpoints.md)

if [ -n “$ROUTES” ]; then echo “พบ route files ใหม่ อัปเดต API docs…” cat $ROUTES | claude -p
“เพิ่ม documentation สำหรับ routes ใหม่เหล่านี้ ใช้ format เดียวกับ @docs/api/endpoints.md ตอบเฉพาะ markdown สำหรับ endpoints ใหม่เท่านั้น”
>> docs/api/endpoints.md fi

2. อัปเดต architecture overview

git diff —staged —name-only | grep -E “prisma|schema” | while read f; do cat “$f” | claude -p
“database schema เปลี่ยนอะไรบ้าง อัปเดต docs/database/schema.md ส่วนที่เกี่ยวข้อง”
| tee -a docs/database/schema.md > /dev/null done

3. บันทึก decision

DATE=$(date +%Y-%m-%d) CHANGES=$(git diff —staged —stat)

cat >> docs/architecture/decisions.md << EOF

ADR-$(date +%Y%m%d): $FEATURE

วันที่: $DATE สถานะ: Accepted

Changes

$CHANGES EOF

echo ”✅ Wiki อัปเดตเสร็จแล้ว” git add docs/ git commit -m “docs: update wiki for $FEATURE”


### RAG กับ CLI — ค้นหาอัจฉริยะสำหรับ Developer

ส่วนนี้จะสร้าง RAG system ที่ integrate กับ CLI workflow ทำให้ Claude ค้นหาข้อมูลจาก knowledge base และนำมาใช้กับ command line ได้โดยตรง

### RAG Architecture ที่ใช้กับ CLI

ระบบ RAG สำหรับ CLI ต้องตอบสนองเร็ว ใช้ง่าย และ integrate กับ shell commands ได้:

โครงสร้างระบบ

knowledge-base/ ← ข้อมูลทั้งหมด docs/ ← AI Wiki src/ ← Source code external/ ← Third-party docs | ↓ index (build ครั้งเดียว อัปเดตตาม Git Hook) vector-db/ ← Embeddings ที่บันทึกไว้ index.faiss ← FAISS vector index metadata.json ← ข้อมูล source files | ↓ query rag-server/ ← FastAPI server main.py ← API endpoint | ↓ HTTP CLI tools ← Shell scripts ที่ user ใช้ ask.sh ← ถาม knowledge base search.sh ← ค้นหาแบบ semantic update.sh ← อัปเดต index


### ตั้งค่า RAG Server แบบ Minimal

สร้าง RAG server ที่ respond เร็ว เหมาะสำหรับ CLI usage:

requirements.txt

fastapi==0.109.0 uvicorn==0.27.0 llama-index==0.10.0 llama-index-llms-anthropic==0.1.0 faiss-cpu==1.7.4 sentence-transformers==2.3.1

ติดตั้ง

pip install -r requirements.txt

rag_server.py

from fastapi import FastAPI, HTTPException from pydantic import BaseModel from llama_index.core import VectorStoreIndex, StorageContext from llama_index.core import load_index_from_storage from llama_index.llms.anthropic import Anthropic from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core import Settings import os, json

app = FastAPI(title=“Project RAG API”)

ตั้งค่า LLM และ Embeddings

Settings.llm = Anthropic( model=“claude-haiku-4-5”, # ใช้ Haiku เพื่อความเร็ว api_key=os.environ[“ANTHROPIC_API_KEY”] ) Settings.embed_model = HuggingFaceEmbedding( model_name=“BAAI/bge-small-en-v1.5” # โมเดลขนาดเล็ก เร็วกว่า )

โหลด index

try: storage_ctx = StorageContext.from_defaults(persist_dir=”./vector-db”) index = load_index_from_storage(storage_ctx) print(”✅ Index loaded”) except: print(“⚠️ ยังไม่มี index รัน build_index.py ก่อน”) index = None

class Query(BaseModel): question: str top_k: int = 5 include_sources: bool = True

class SearchQuery(BaseModel): query: str top_k: int = 10

@app.post(“/ask”) async def ask(q: Query): """ถามคำถาม Claude จะหาข้อมูลจาก knowledge base ก่อนตอบ""" if not index: raise HTTPException(500, “Index not initialized”)

engine = index.as_query_engine(similarity_top_k=q.top_k)
response = engine.query(q.question)

result = {"answer": str(response)}
if q.include_sources:
    result["sources"] = [
        {
            "file": node.metadata.get("file_path", "unknown"),
            "score": round(node.score, 3),
            "snippet": node.text[:200]
        }
        for node in response.source_nodes
    ]
return result

@app.post(“/search”) async def search(q: SearchQuery): """ค้นหา chunks ที่เกี่ยวข้องโดยไม่ generate คำตอบ""" if not index: raise HTTPException(500, “Index not initialized”)

retriever = index.as_retriever(similarity_top_k=q.top_k)
nodes = retriever.retrieve(q.query)

return {
    "results": [
        {
            "file": n.metadata.get("file_path"),
            "score": round(n.score, 3),
            "text": n.text
        }
        for n in nodes
    ]
}

@app.get(“/health”) async def health(): return {“status”: “ok”, “index_ready”: index is not None}

รัน: uvicorn rag_server:app —port 8765 —reload

build_index.py — สร้าง index จาก knowledge base

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.core.node_parser import SentenceSplitter from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core import Settings import os

Settings.embed_model = HuggingFaceEmbedding( model_name=“BAAI/bge-small-en-v1.5” )

โหลดเอกสาร

print(”📚 Loading documents…”) loader = SimpleDirectoryReader( input_files=[], # หรือ input_dir=”.”, recursive=True, required_exts=[“.md”, “.txt”, “.ts”, “.py”, “.js”], exclude=[“node_modules”, “.git”, “dist”, “.next”, “vector-db”] ) documents = loader.load_data() print(f”Loaded {len(documents)} files”)

แบ่ง text เป็น chunks

splitter = SentenceSplitter(chunk_size=512, chunk_overlap=50)

สร้าง index

print(”🔨 Building index…”) index = VectorStoreIndex.from_documents( documents, transformations=[splitter], show_progress=True )

บันทึก

index.storage_context.persist(persist_dir=”./vector-db”) print(f”✅ Index saved to ./vector-db”)


### CLI Tools สำหรับใช้งาน RAG

สร้าง shell scripts ที่ user ใช้ได้ง่ายในทุก scenario:

### Script 1: ask — ถามคำถามจาก Knowledge Base

#!/bin/bash

ask.sh — ถาม knowledge base

ใช้งาน: ./ask.sh “วิธี implement payment retry”

RAG_URL=“http://localhost:8765” QUESTION=”$*”

if [ -z “$QUESTION” ]; then echo “Usage: ask.sh [คำถาม]” exit 1 fi

เช็คว่า server ทำงานอยู่

if ! curl -s “$RAG_URL/health” | grep -q “ok”; then echo ”❌ RAG server ไม่ทำงาน รัน: uvicorn rag_server:app —port 8765” exit 1 fi

ส่งคำถาม

RESPONSE=$(curl -s -X POST “$RAG_URL/ask”
-H “Content-Type: application/json”
-d ”{“question”: “$QUESTION”, “top_k”: 5}“)

แสดงผล

echo ”=== คำตอบ ===” echo “$RESPONSE” | python3 -c “import json,sys; d=json.load(sys.stdin); print(d[‘answer’])”

echo "" echo ”=== Sources ===” echo “$RESPONSE” | python3 -c ” import json,sys d=json.load(sys.stdin) for s in d.get(“sources”, []): print(f” [{s[“score”]:.2f}] {s[“file”]}”) ”


### Script 2: search — ค้นหา chunks ที่เกี่ยวข้อง

#!/bin/bash

search.sh — ค้นหาแบบ semantic (ไม่ generate คำตอบ)

ใช้งาน: ./search.sh “authentication middleware”

RAG_URL=“http://localhost:8765” QUERY=”$*” TOP_K=${TOP_K:-10}

RESPONSE=$(curl -s -X POST “$RAG_URL/search”
-H “Content-Type: application/json”
-d ”{“query”: “$QUERY”, “top_k”: $TOP_K}”)

echo ”🔍 ผลการค้นหา: $QUERY” echo ""

echo “$RESPONSE” | python3 -c ” import json, sys d = json.load(sys.stdin) for i, r in enumerate(d[“results”], 1): print(f”{i}. [{r[“score”]:.3f}] {r[“file”]}”) print(f” {r[“text”][:150]}…”) print() ”


### Script 3: rag-claude — ค้นหาแล้วส่งให้ Claude Code

#!/bin/bash

rag-claude.sh — ค้นหาข้อมูลแล้วส่งให้ Claude เพื่อ implement

ใช้งาน: ./rag-claude.sh “payment retry” “implement payment retry logic”

SEARCH_TERM=“$1” CLAUDE_PROMPT=“$2” RAG_URL=“http://localhost:8765

if [ -z “$SEARCH_TERM” ] || [ -z “$CLAUDE_PROMPT” ]; then echo “Usage: rag-claude.sh [search_term] [claude_prompt]” echo “Example: rag-claude.sh coupon implement coupon validation” exit 1 fi

ค้นหาข้อมูลที่เกี่ยวข้อง

echo ”🔍 ค้นหาข้อมูลเกี่ยวกับ: $SEARCH_TERM” CONTEXT=$(curl -s -X POST “$RAG_URL/search”
-H “Content-Type: application/json”
-d ”{“query”: “$SEARCH_TERM”, “top_k”: 8}” |
python3 -c ” import json, sys d = json.load(sys.stdin) for r in d[“results”]: print(f”--- {r[“file”]} (score: {r[“score”]:.2f}) ---”) print(r[“text”]) print() “)

ส่งให้ Claude พร้อม context

echo ”🤖 ส่งให้ Claude พร้อม context…” FULL_PROMPT=“Context จาก Knowledge Base:\n$CONTEXT\n\nงาน: $CLAUDE_PROMPT”

echo -e “$FULL_PROMPT” | claude -p “$CLAUDE_PROMPT”


### Integration: RAG + Claude Code + tmux

นี่คือ workflow ที่ใช้ทุกอย่างรวมกัน สมจริงที่สุด:

ตั้งค่า tmux layout สำหรับ RAG workflow

#!/bin/bash

rag-workspace.sh

SESSION=“rag-dev”

Window 1: Claude Code (ซ้าย) + RAG terminal (ขวา)

tmux new-session -d -s $SESSION -n “main” tmux split-window -h -p 35

ซ้าย: Claude Code

tmux select-pane -t 0 tmux send-keys “claude” Enter

ขวา: RAG tools

tmux select-pane -t 1 tmux send-keys “echo Ready for RAG queries” Enter

Window 2: RAG Server

tmux new-window -n “rag-server” tmux send-keys “uvicorn rag_server:app —port 8765 —reload” Enter

Window 3: Build/Watch

tmux new-window -n “watch” tmux send-keys “npm run dev” Enter

tmux select-window -t 0 tmux attach -t $SESSION

─── Workflow จริงในการทำงาน ───

Terminal ขวา: ค้นหาข้อมูลก่อน implement

./ask.sh “วิธี handle order cancellation ตาม business rules”

ผลลัพธ์ที่ได้: context จาก docs/domain/business-rules.md

คำอธิบาย: refund policy, state machine rules, etc.

นำ context ไปใช้ใน Claude Code (terminal ซ้าย)

./rag-claude.sh “order cancellation”
“implement cancelOrder function ใน src/server/actions/order.ts”

Claude จะได้ context ครบและ implement ตาม business rules


### ตัวอย่างจริง: RAG + CLI Workflow ทั้งวัน

นี่คือ workflow จริงของวันทำงานที่ใช้ RAG + CLI ทุกขั้น:

|   | เช้า 9:00 — เริ่ม Session |
|---|---|

เปิด workspace

./rag-workspace.sh

อ่าน Handoff จากเมื่อวาน

./ask.sh “สรุปงานที่ค้างอยู่จาก handoff เมื่อวาน”

ดูว่าวันนี้ต้องทำอะไร

cat .claude/handoffs/latest.md | claude -p “สรุปสิ่งที่ต้องทำวันนี้”


|   | 10:00 — Implement Feature |
|---|---|

หาข้อมูลก่อน implement

./search.sh “notification system architecture”

ถาม specific question

./ask.sh “notification delivery order คืออะไร มี priority ไหม”

Implement พร้อม context จาก RAG

./rag-claude.sh “notification”
“สร้าง createNotification function ใน src/services/notification.ts”

รัน test ทันที

npm test — —testPathPattern=notification 2>&1 |
claude -p “แก้ test ที่ fail”


|   | 14:00 — Code Review |
|---|---|

Review โค้ดที่ทำมาตอนเช้า

git diff main…HEAD |
claude -p “รีวิว code แบบ senior developer focus security + logic”

ตรวจสอบว่า consistent กับ codebase

./search.sh “similar pattern to notification”

อัปเดต Wiki

./update-wiki.sh “notification system”


|   | 17:00 — Wrap Up |
|---|---|

สร้าง Handoff

cat > .claude/handoffs/$(date +%Y-%m-%d).md << EOF $(git diff main…HEAD —stat) EOF

cat .claude/handoffs/$(date +%Y-%m-%d).md |
claude -p “สร้าง handoff document ครบถ้วนสำหรับพรุ่งนี้”

อัปเดต index ถ้ามีไฟล์ใหม่

python3 build_index.py

Commit

git diff —staged | claude -p “เขียน commit message” |
git commit -F -


### Advanced CLI Patterns

### Pattern 1: Parallel Processing

รัน Claude หลาย instances พร้อมกันสำหรับงาน batch:

#!/bin/bash

parallel-analyze.sh — วิเคราะห์ไฟล์แบบ parallel

MAX_JOBS=4 # จำนวน Claude instances พร้อมกัน RESULTS_DIR=“analysis” mkdir -p “$RESULTS_DIR”

analyze_file() { local file=$1 local output=“$RESULTS_DIR/$(basename $file).analysis”

cat “$file” | claude -p
“วิเคราะห์ security issues ใน 3 bullet points”
—model claude-haiku-4-5 > “$output”

echo ”✓ $file” }

export -f analyze_file

รัน parallel ด้วย GNU parallel

find src/ -name “*.ts” |
parallel -j $MAX_JOBS analyze_file

รวม results

echo ”=== Security Analysis Summary ===” cat “$RESULTS_DIR”/*.analysis |
claude -p “สรุป security issues ทั้งหมด เรียงตาม severity”


### Pattern 2: Watch Mode — Monitor แบบ Real-time

รัน Claude ทุกครั้งที่ไฟล์เปลี่ยน เหมาะสำหรับ TDD:

#!/bin/bash

watch-and-fix.sh — TDD helper

ติดตั้ง: npm install -g nodemon

echo ”👀 Watch mode: แก้ test failure อัตโนมัติ”

nodemon
—watch src/
—ext ts,tsx
—exec ’ OUTPUT=$(npm test 2>&1) if echo “$OUTPUT” | grep -q “FAIL”; then echo ”❌ Tests failed, asking Claude…” echo “$OUTPUT” | tail -50 | claude -p
“แก้ test failures นี้ บอก exact changes ที่ต้องทำ” else echo ”✅ All tests pass!” fi ‘


### Pattern 3: Context-Aware Completion

สร้าง shell function ที่รู้ context ของโปรเจคอัตโนมัติ:

เพิ่มใน ~/.zshrc หรือ ~/.bashrc

Function: ask Claude รู้ context ของโปรเจคอัตโนมัติ

function ca() { local QUESTION=”$*” local CONTEXT=""

เพิ่ม context อัตโนมัติถ้าอยู่ใน git repo

if git rev-parse —git-dir > /dev/null 2>&1; then local PROJECT=$(basename $(git rev-parse —show-toplevel)) local BRANCH=$(git branch —show-current) local RECENT_CHANGES=$(git diff —stat HEAD~3..HEAD 2>/dev/null | head -5)

CONTEXT="Project: $PROJECT | Branch: $BRANCH"
if [ -f CLAUDE.md ]; then
  CONTEXT="$CONTEXT\n$(head -20 CLAUDE.md)"
fi

fi

if [ -n “$CONTEXT” ]; then echo -e “$CONTEXT\n\nคำถาม: $QUESTION” | claude -p “$QUESTION” else claude -p “$QUESTION” fi }

Function: วิเคราะห์ไฟล์ที่ open ใน editor

function af() { local PROMPT=”$*“

อ่านไฟล์ที่ open ล่าสุดใน VS Code

local RECENT_FILE=$(code —list-extensions 2>/dev/null | head -1) cat “$1” | claude -p ”${PROMPT:-อธิบายไฟล์นี้}” }

ใช้งาน

ca “วิธี implement payment retry”

af src/utils.ts “หา bug ในฟังก์ชันนี้”


### Pattern 4: Git Automation Suite

ชุด git commands ที่ใช้ Claude อัตโนมัติ:

เพิ่มใน ~/.gitconfig

[alias]

Smart commit: Claude เขียน message

smart-commit = “!git diff —staged | claude -p ‘เขียน git commit message’ | git commit -F -“

PR review: วิเคราะห์ก่อน PR

pr-review = “!git diff main…HEAD | claude -p ‘รีวิวแบบ senior dev‘“

PR description: สร้าง PR body

pr-desc = “!git log main..HEAD —oneline | claude -p ‘สร้าง PR description‘“

Bug blame: หาว่าใคร/commit ไหนทำให้เกิดบัก

smart-blame = “!git log —oneline -20 | claude -p ‘commit ไหนน่าจะทำให้เกิดบัก: $1‘“

ใช้งาน

git smart-commit git pr-review git pr-desc > /tmp/pr-body.txt


### Pattern 5: API Testing Suite

ทดสอบ API ด้วย Claude วิเคราะห์ผลอัตโนมัติ:

#!/bin/bash

api-test.sh — Test API endpoints แล้วให้ Claude วิเคราะห์

BASE_URL=”${1:-http://localhost:3000}” TOKEN=”${API_TOKEN:-}”

run_test() { local name=$1 local method=$2 local endpoint=$3 local body=$4 local expected_status=$5

echo -n “Testing $name… ”

if [ -n “$body” ]; then RESPONSE=$(curl -s -w “\n%{http_code}” -X $method
-H “Authorization: Bearer $TOKEN”
-H “Content-Type: application/json”
-d “$body” “$BASE_URL$endpoint”) else RESPONSE=$(curl -s -w “\n%{http_code}” -X $method
-H “Authorization: Bearer $TOKEN”
“$BASE_URL$endpoint”) fi

STATUS=$(echo “$RESPONSE” | tail -1) BODY=$(echo “$RESPONSE” | head -n -1)

if [ “$STATUS” = “$expected_status” ]; then echo ”✅ $STATUS” else echo ”❌ Expected $expected_status, got $STATUS” echo “$BODY” | claude -p “อธิบาย response นี้และบอกว่าน่าจะมีปัญหาอะไร” fi }

รัน test cases

run_test “Get products” GET “/api/products” "" “200” run_test “Search products” GET “/api/products?q=phone” "" “200” run_test “Create order (no auth)” POST “/api/orders” ”{}” “401” run_test “Apply invalid coupon” POST “/api/coupons/apply” ’{“code”:“INVALID”}’ “404”

วิเคราะห์ response time

echo "" echo “Response time analysis:” for endpoint in /api/products /api/categories /api/users/me; do TIME=$(curl -s -o /dev/null -w ”%{time_total}”
-H “Authorization: Bearer $TOKEN”
“$BASE_URL$endpoint”) echo ” $endpoint: ${TIME}s” done | claude -p “วิเคราะห์ response times เหล่านี้ endpoint ไหนช้าผิดปกติ”


## คำศัพท์ประจำบท

| CLI (Command Line Interface) | การสั่งงานคอมพิวเตอร์ผ่านการพิมพ์คำสั่งข้อความ |
|---|---|
| Terminal | โปรแกรมที่เปิด CLI เช่น iTerm2, Windows Terminal, Warp |
| Shell | โปรแกรมที่รับคำสั่งจาก terminal เช่น bash, zsh, fish |
| Pipe (\|) | ส่ง output คำสั่งหนึ่งไปเป็น input ของอีกคำสั่ง |
| stdin | Standard Input — ช่องรับข้อมูลของโปรแกรม |
| stdout | Standard Output — ช่องส่งข้อมูลออกปกติ |
| stderr | Standard Error — ช่องส่งข้อมูล error (2>&1 รวมกับ stdout) |
| One-shot mode | รัน claude -p "..." ได้คำตอบแล้วปิดทันที ไม่เปิด session |
| Flag | Parameter พิเศษที่ส่งให้ command เช่น --model, --file |
| tmux | Terminal multiplexer เปิดหลาย terminal ในหน้าต่างเดียว |
| Pane | ส่วนแบ่งของ terminal ใน tmux (แนวตั้งหรือแนวนอน) |
| Session (tmux) | กลุ่มของ windows และ panes ใน tmux ที่ยังคงอยู่แม้ detach |
| Shebang (#!/bin/bash) | บรรทัดแรกของ shell script บอกว่าใช้ interpreter อะไร |
| chmod +x | ให้สิทธิ์ execute กับไฟล์ script |
| Semantic Search | ค้นหาด้วยความหมายไม่ใช่แค่ keyword matching |
| FAISS | Facebook AI Similarity Search library สำหรับ vector search |
| Embedding | การแปลงข้อความเป็น vector numbers ที่แสดง semantic meaning |
| RAG Server | Web server ที่ให้บริการ RAG ผ่าน HTTP API |
| Chunking | การแบ่งเอกสารยาวเป็นส่วนเล็กๆ เพื่อ indexing |
| Retriever | ส่วนที่ค้นหา chunks ที่เกี่ยวข้องจาก vector database |
| Parallel Processing | รันหลาย task พร้อมกันแทนที่จะรันทีละอัน |
| Watch Mode | Monitor การเปลี่ยนแปลงและรัน action อัตโนมัติ |
| Git Alias | ชื่อย่อสำหรับคำสั่ง git ที่ยาวหรือซับซ้อน |