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