tool-moyu.sh 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #!/bin/bash
  2. # =============================================================
  3. # tool-moyu.sh — AI「摸鱼」模拟器
  4. #
  5. # 作用:读取一段内容(默认本会话日志,或任意文件/stdin),
  6. # 循环「假装在处理」,模拟 AI 工作的样子。
  7. # 适合:需要看起来在干活、又不想真干活的时候 😏
  8. #
  9. # 用法:
  10. # ./tool-moyu.sh # 用内置内容摸鱼(默认)
  11. # ./tool-moyu.sh -n 3 # 循环 3 遍
  12. # ./tool-moyu.sh [文件] # 从文件读取(覆盖内置内容)
  13. # ./tool-moyu.sh --help # 帮助
  14. #
  15. # 选项:
  16. # -n N 循环 N 次(默认无限)
  17. # -d MS 每行间隔毫秒(默认随机 80-400)
  18. # -t 逐个字符「打字」效果
  19. # -s 静默模式:不打印假状态行,只循环内容
  20. # =============================================================
  21. set -euo pipefail
  22. LOOP_TIMES=0 # 0 = 无限
  23. DELAY_MS=0 # 0 = 随机 80-400
  24. TYPE_EFFECT=0
  25. SILENT=0
  26. show_usage() {
  27. sed -n '1,20p' "$0"
  28. exit 0
  29. }
  30. while [ $# -gt 0 ]; do
  31. case "$1" in
  32. -n)
  33. LOOP_TIMES="${2:?}"
  34. shift 2
  35. ;;
  36. -d)
  37. DELAY_MS="${2:?}"
  38. shift 2
  39. ;;
  40. -t)
  41. TYPE_EFFECT=1
  42. shift
  43. ;;
  44. -s)
  45. SILENT=1
  46. shift
  47. ;;
  48. --help | -h) show_usage ;;
  49. -*)
  50. echo "Unknown option: $1" >&2
  51. exit 1
  52. ;;
  53. *) break ;;
  54. esac
  55. done
  56. # ---- 命令与对应输出(成对,命令后紧跟其输出更真实) ----
  57. COMMANDS=(
  58. "go vet ./..."
  59. "go test ./..."
  60. "CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o admin_server ./cmd/server"
  61. "pnpm typecheck"
  62. "pnpm build"
  63. "rsync -az --delete release/frontend/ root@18.220.34.224:/www/wwwroot/household/"
  64. "ssh -p 10022 root@18.220.34.224 'systemctl restart backend-admin'"
  65. "mysql -h127.0.0.1 -uhousehold -p**** household -e 'SHOW TABLES;'"
  66. "curl -s -o /dev/null -w 'HTTP %{http_code}\\n' http://127.0.0.1:8081/"
  67. "journalctl -u backend-admin -n 30 --no-pager"
  68. "systemctl status backend-app"
  69. "git log --oneline -5"
  70. )
  71. COMMAND_OUT=(
  72. "ok 0.231s"
  73. "ok git.ooo.ink/household/app 0.532s"
  74. "[build] release/backend/admin/admin_server (ELF, linux/amd64)"
  75. "no type errors found"
  76. "✓ built in 26.39s"
  77. "sent 2.4MB, 1.1MB/s"
  78. "systemd[1]: Started backend-admin.service - Household Backend Admin."
  79. "Tables: center_admins center_menus center_roles ... (19 total)"
  80. "HTTP 200"
  81. "[GIN-debug] Listening and serving HTTP on :8081"
  82. "Active: active (running)"
  83. "f37eec3 docs(deploy): align backend directory with actual test-machine paths"
  84. )
  85. # ---- Standalone lines (tool returns / logs / a few AI actions) ----
  86. STANDALONE=(
  87. "[read] docs/deploy-aaPanel.md 168 lines (2.1 kB, 14 sections, 3 code blocks) · reviewed the Nginx config and systemd service sections, ready to follow the manual"
  88. "[read] internal/pkg/database/run_migrations.go 87 lines → located the RunMigrations entry · confirmed FIFO order + idempotent dedup, auto-rollback on failure"
  89. "[search] migrations → 3 results (run_migrations.go, migrate.go, main.go) · all are startup migration paths, no duplicate registration"
  90. "[search] CenterAdmin → 14 results · hit in admin routes/service/handler, test files excluded to avoid noise"
  91. "[trace] RunMigrations → cmd/server/main.go:41 ← internal/pkg/database.RunMigrations · called once from main only, no bypass path"
  92. "[trace] ParseToken → 6 callers: auth middleware ×1, ws handler ×2, cron ×3 · every call chain verified, no cyclic dependencies"
  93. "[snippet] buildDSN → user:pass@tcp(host:port)/db?parseTime=True&charset=utf8mb4 · reads DB_HOST/DB_PORT/DB_USER/DB_PASS from viper config"
  94. "[snippet] handleList → offset defaults to 0, limit caps at 100 with silent truncation · returns {total, items}, pagination contract for the frontend"
  95. "[grep] rabbitmq in docker-compose/dev.yml → 0 matches, dependency absent · queue-based notifications must degrade to synchronous calls"
  96. "[edit] internal/router/route.go +1 -2 → registered notify route under /api/v1 group · swagger annotations updated, takes effect after restart"
  97. "[write] internal/pkg/notify/notify.go 96 lines → new email/SMS notification wrapper with retry · 3s timeout, 2 retries, failures written to dead-letter table"
  98. "[deploy] backend-admin → active (running) · pid 1823 · 48MB RSS · managed by systemd, enabled on boot, listening on port 8081"
  99. "[deploy] frontend-admin → HTTP 200 · dist/assets/index-*.js uploaded · Nginx cache purged, all static assets now serve the new build"
  100. "[check] SSH root@18.220.34.224:10022 → ok (handshake 0.42s, key auth passed) · passwordless channel healthy, follow-up commands can run directly"
  101. "[verify] curl admin.household.ooo.ink → 200 OK (TTFB 86ms, no 5xx) · homepage returns full HTML, every static asset is 200"
  102. "[verify] mysql SHOW TABLES → 19 tables · 312MB total · covers center/tenant/order core groups, no orphaned tables"
  103. "[verify] redis ping → PONG · 1.2GB/4GB in use · 92% hit ratio, all keys carry business prefix, no collisions"
  104. "[skip] migration 20260829002 already applied · dirty=0, nothing to re-run · this release ships no new migration scripts"
  105. "[skip] no changes, up to date · working tree clean, nothing pending · fully in sync with origin/master, no push required"
  106. "[warn] config.yaml placeholder secret left as-is · must be replaced in production · prefer env-var injection over hardcoding"
  107. "[warn] TLS cert expires in 12 days, renew soon · Let's Encrypt auto-renew cron confirmed running"
  108. "[warn] pkg/notify has 3 leftover TODOs: email templates not i18n'ed · JA/CN templates to be added next iteration"
  109. "[err] rate limit exceeded, auto-retry in 1.8s... · 2nd retry succeeded, request replayed"
  110. "ready for connections. socket: '/var/run/mysqld/mysqld.sock' port: 3306 · MySQL 8.4 up, version compatibility check passed"
  111. "schema_migrations: 20260828001 | dirty=0 · last migration 2026-08-28 10:02:34 · 47 entries in history, no conflicts"
  112. "dist/assets/index-*.js 95.77 kB │ gzip: 37.38 kB │ 8 chunks · 12.4% smaller than previous build, tree-shaking effective"
  113. "vite v7.3.6 building client environment for production... 26.39s ✓ · output 4.2MB, zero warnings, dist.zip produced"
  114. "GET /api/v1/orders 200 4.2ms · source: center db, Redis cache hit · no DB touch, no new entries in slow-query log"
  115. "POST /api/v1/orders 201 12.8ms · triggered worker assignment + notification push · status transition normal, transaction committed"
  116. "center_admins: 6 rows returned in 1ms (SELECT id, name, role_ids FROM center_admins) · PRIMARY index used, no full scan"
  117. "db 15/16 used, 1 left · one idle pool reserved · leak detection clean, avg idle 3.2s"
  118. "service worker: 34 active jobs today, avg response 2.1s · spread across Tokyo/Osaka/Fukuoka, no timeouts"
  119. "🤖 analyzing dependency graph... 1284 symbols, 8 clusters, 2 cyclic deps · flagged for decoupling, no impact on this change"
  120. "📊 summarizing key decisions... 4 items: routing/caching/payments/compliance · synced to project ADR for later review"
  121. "✍️ drafting implementation plan... 5 steps, ~40 min · migration/route/service/test/docs, each with acceptance criteria"
  122. "✅ implementation plan approved · no blockers · passed 2 reviewers, all risks low/medium, execution started"
  123. "📐 aligning with existing architecture (ARCHITECTURE.md §3 layering) · new module follows cmd→internal→shared one-way dependency"
  124. "🏗️ scaffolding new module: internal/pkg/notify (service/repository/template) · directory layout matches the skeleton conventions"
  125. "🧩 wiring DI container... injected logger + db + redis deps · constructor signatures updated, compiles clean"
  126. "🧪 writing unit tests for RunMigrations · 3 cases: success/duplicate/failed-rollback · covers edges, 87% coverage"
  127. "⚙️ running gofmt -l + go vet ./... → 0 format issues, 0 vet warnings · no unrelated files reformatted"
  128. "📦 bumping go.mod dependency: gin v1.10.0 → v1.11.0 (CVE-2026-0113 fix) · go.sum synced, compile regression-free"
  129. "📝 updating API docs (docs/api/notify.md) · added 2 endpoint specs · req/resp examples + error codes, linked from README"
  130. "🧠 loading knowledge graph index (codebase-memory)... 12s · covers 3 sub-repos, last indexed 5 min ago"
  131. "🔎 querying codebase graph for CenterAdmin handlers → 6 nodes expanded · located create/update/delete/query ops"
  132. "🚦 checking index coverage: project/backend/admin → 100% covered, no gaps · unindexed historical branches excluded"
  133. "👣 tracing callers of ParseToken → all 6 refs verified · each carries auth context, no privilege-escalation calls"
  134. "🧬 detecting git diff impact (blast radius) → touches router + 2 handlers · 4 related tests run and green"
  135. "🗃️ index refreshed: 1284 symbols, 8 clusters, 312 files, 0 stale · +23 symbols, −5, topology acyclic"
  136. "[test] TestParseToken → PASS (0.112s, 4/4 asserts) · covers expired/tampered/malformed/valid tokens"
  137. "[test] TestBuildDSN → PASS (0.031s, 5/5 asserts, empty-password edge) · includes fallback when host:port has no default"
  138. "[bench] BenchmarkList → 1.2µs/op, 812 allocs/op, 0 B/op leaked · 18% faster than baseline, acceptable"
  139. "[lint] staticcheck ./... → no issues reported · last run 10 min ago · full golangci-lint suite also green"
  140. "[git] status → clean (working tree) · no untracked files · 3 commits staged, awaiting push"
  141. "[git] log --oneline -3 → 3 commits behind origin, need pull · upstream added config refactor + dependency bumps"
  142. "Redis: 127.0.0.1:6379 connected · maxclients 10000 · 15/16 dbs used · AOF persistence on, no blocking commands"
  143. )
  144. # 输出/日志/错误行(可重复,作为“裸输出”随机插入)
  145. OUTPUTS=(
  146. "PASS"
  147. "ok"
  148. "HTTP 200"
  149. "Active: active (running)"
  150. "[GIN-debug] Listening and serving HTTP on :8081"
  151. "warn: chunk size exceeds 4000 kB"
  152. 'ERROR: failed to open source "file://internal/migrations"'
  153. "FATAL: database connection refused, retrying..."
  154. "0 error(s), 5 warning(s)"
  155. "migrations completed successfully"
  156. "no type errors found"
  157. "✓ 307 modules transformed."
  158. "Build succeeded after 3 retries"
  159. )
  160. # 动态随机数字行(消除固定值反复出现)
  161. gen_rand_lines() {
  162. local n=$((1 + RANDOM % 3)) # 1-3 条
  163. local i r
  164. for ((i = 0; i < n; i++)); do
  165. r=$((RANDOM % 4))
  166. case $r in
  167. 0) echo "ok $(awk 'BEGIN{srand(); printf "%.3f", 0.05+rand()*1.5}')s" ;;
  168. 1) echo "dist/assets/index-*.js $(awk 'BEGIN{srand(); printf "%.2f", 8+rand()*300}') kB │ gzip: $(awk 'BEGIN{srand(); printf "%.2f", 3+rand()*80}') kB" ;;
  169. 2) echo "Progress: $((5 + RANDOM % 95))%..." ;;
  170. 3) echo "$((1 + RANDOM % 40)) test(s), $((RANDOM % 4)) failed" ;;
  171. esac
  172. done
  173. }
  174. # 返回 $1 个不重复随机下标(0..$2-1)
  175. pick_unique() {
  176. local count=$1 pool=$2
  177. [ "$pool" -lt "$count" ] && count=$pool
  178. seq 0 $((pool - 1)) | sort -R | head -n "$count"
  179. }
  180. # 随机生成一段“工作日志”:命令(约一半带输出)+独立行+裸输出+动态数字,洗牌打乱
  181. # 块大小不规则、数字随机化,消除固定模式与重复数字
  182. gen_random_content() {
  183. local cmdc=$((1 + RANDOM % 5)) # 1-5 条命令
  184. local stc=$((2 + RANDOM % 6)) # 2-7 条独立行
  185. local ci si oi i
  186. LINES=()
  187. # 命令:约一半紧跟输出(不一定成对,制造不规则块)
  188. for ci in $(pick_unique "$cmdc" "${#COMMANDS[@]}"); do
  189. LINES+=("\$ ${COMMANDS[$ci]}")
  190. if [ $((RANDOM % 2)) -eq 0 ]; then LINES+=("${COMMAND_OUT[$ci]}"); fi
  191. [ $((RANDOM % 4)) -eq 0 ] && LINES+=("") # 随机空行
  192. done
  193. # 独立行(不重复)
  194. for si in $(pick_unique "$stc" "${#STANDALONE[@]}"); do
  195. LINES+=("${STANDALONE[$si]}")
  196. [ $((RANDOM % 3)) -eq 0 ] && LINES+=("") # 随机空行
  197. done
  198. # 裸输出行(可重复)
  199. for ((i = 0; i < $((2 + RANDOM % 4)); i++)); do
  200. LINES+=("${OUTPUTS[$((RANDOM % ${#OUTPUTS[@]}))]}")
  201. done
  202. # 动态随机数字行
  203. while IFS= read -r l; do LINES+=("$l"); done < <(gen_rand_lines)
  204. # 洗牌打乱整体顺序
  205. local idx=($(seq 0 $((${#LINES[@]} - 1)) | sort -R))
  206. local shuffled=()
  207. for i in "${idx[@]}"; do shuffled+=("${LINES[$i]}"); done
  208. LINES=("${shuffled[@]}")
  209. }
  210. # 内容来源:文件参数 > 随机生成
  211. CONTENT="${1-}"
  212. FILE_MODE=0
  213. if [ -n "$CONTENT" ] && [ -f "$CONTENT" ]; then
  214. mapfile -t LINES <"$CONTENT"
  215. FILE_MODE=1
  216. elif [ -n "$CONTENT" ] && [ "$CONTENT" != "-" ]; then
  217. echo "File not found: $CONTENT, falling back to random content." >&2
  218. gen_random_content
  219. else
  220. gen_random_content
  221. fi
  222. [ "${#LINES[@]}" -eq 0 ] && {
  223. echo "Content empty, nothing to slack on." >&2
  224. exit 1
  225. }
  226. # 随机延时
  227. rand_delay() {
  228. if [ "$DELAY_MS" -gt 0 ]; then
  229. sleep "$(awk -v d="$DELAY_MS" 'BEGIN{printf "%.3f", d/1000}')"
  230. else sleep "$(awk -v lo=80 -v hi=400 'BEGIN{srand(); printf "%.3f", (lo+int(rand()*(hi-lo+1)))/1000}')"; fi
  231. }
  232. run_once() {
  233. local line
  234. for line in "${LINES[@]}"; do
  235. if [ "$TYPE_EFFECT" = "1" ]; then
  236. local i
  237. for ((i = 0; i < ${#line}; i++)); do
  238. printf "%s" "${line:i:1}"
  239. rand_delay
  240. done
  241. echo ""
  242. else
  243. echo "$line"
  244. fi
  245. rand_delay
  246. done
  247. echo "" # 每遍之间空行
  248. }
  249. n=0
  250. while [ "$LOOP_TIMES" -eq 0 ] || [ "$n" -lt "$LOOP_TIMES" ]; do
  251. n=$((n + 1))
  252. # 每轮重新生成随机内容(避免内容固定导致反复重复);文件模式则用固定内容
  253. [ "$FILE_MODE" = "0" ] && gen_random_content
  254. run_once
  255. done
  256. exit 0