docs(agents): 精简 AGENTS.md 为约束清单

AGENTS.md 只保留约束。项目介绍交给 README.md。设计细节交给 docs/design 与 docs/solutions。

删除架构、配置、CI、可观测性与关键文件五节。保留红线、命令、TDD、测试、文档、注释、提交信息。

CLAUDE.md 改为指向 AGENTS.md。规范只维护一份。

清理悬垂引用。指向已删章节的表格行删除。可观测性文档只同步 README 与设计文档。ISSUES-REPORT 的 D-2、D-3、D-6 标为已消解。

验证:git diff --stat 显示 9 个文件变更。
This commit is contained in:
2026-11-09 15:43:17 +08:00
parent 5d05c147ed
commit 7d9cb061a2
9 changed files with 70 additions and 282 deletions

315
AGENTS.md
View File

@@ -1,292 +1,89 @@
# AGENTS.md
This file provides guidance to Codex (claude.ai/code) when working with code in this repository.
本文件只写约束。项目是什么见 `README.md`,设计与决策见 `docs/design/`、`docs/solutions/`。
## Project Overview
## 红线
Short video feed system with Go 1.24 backend (Gin + GORM + MySQL + Redis + RabbitMQ) and Vue 3 + TypeScript frontend (rolldown-vite). Two backend binaries: API server and async Worker process. All domain wiring is manual constructor injection in `router.go` — no DI framework.
- 新增消费者必须实现幂等的 `process`,失败处置只走 `rabbitmq.ConsumeLoop`(Ack / 重投 / 停泊)。不要自己写重试循环,也不要新增 `ch.Consume` 调用点。
- `JWT_SECRET` 等密钥只从环境变量或 `.env` 读取,不得写入提交的 YAML。
**Documentation**: Chinese documentation available in `docs/project-construction-guide.md` (detailed build roadmap) and `feedsystem_video_go项目设计.md` (system design).
## 命令
## Commands
### Backend (run from `backend/`)
### 后端(在 `backend/` 下)
```bash
# Run all tests with race detection
go test -race -count=1 ./...
# Run a single test
go test -run TestFunctionName ./internal/package/...
# Vet
go test -race -count=1 ./... # 推送前必跑
go test -run TestName ./internal/package/...
go vet ./...
# Run API server locally
go run ./cmd
# Run worker process locally
go run ./cmd/worker
go run ./cmd # API
go run ./cmd/worker # Worker
```
### Frontend (run from `frontend/`)
### 前端(在 `frontend/` 下)
```bash
npm ci # install dependencies (clean)
npm run dev # dev server (Vite, proxies /api -> http://127.0.0.1:8080)
npm run build # production build (vue-tsc -b && vite build)
npm run preview # preview production build locally
npm ci
npm run dev # localhost:5173,/api 代理到 127.0.0.1:8080
npm run build # 前端唯一的验证手段
```
### Docker Compose (root)
### 起服务
```bash
docker compose up -d # full stack: MySQL, Redis, RabbitMQ, API, Worker, Frontend
docker compose up -d mysql redis rabbitmq # infra only, then run backend locally
```
### Local Dev Script (root)
```bash
# start.sh uses env vars to control what starts: START_REDIS, START_RABBITMQ, START_BACKEND, START_WORKER, START_FRONTEND
START_BACKEND=1 START_WORKER=1 START_FRONTEND=1 ./start.sh
# Or start infra via compose, then run backend locally with the compose-local config:
docker compose up -d mysql redis rabbitmq
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd # API
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd/worker # Worker
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd
START_BACKEND=1 START_WORKER=1 START_FRONTEND=1 ./start.sh
```
## Architecture
## TDD
### Dual Binary Split
`backend/` 下改行为默认 TDD。前端没有测试运行器,只跑 `npm run build` 再人工点页面,不要称其为 TDD。
- `backend/cmd/main.go` — Gin HTTP API server (port 8080, pprof on :6060)
- `backend/cmd/worker/main.go` — the **only** async process (pprof on :6061). Runs every RabbitMQ consumer (Social, Like, Comment, the three Notification consumers, the parked-event consumer) plus the Outbox poller and the timeline consumer, each in its own goroutine with its own AMQP channel from the shared connection manager. Interaction counts are written by the business transaction (`ApplyLike`/`ApplyUnlike`/`CreateIdempotentWithPopularity`/`DeleteWithPopularity`); the hot ranking is a derived 60-minute sliding window (`video.ApplyHotDelta`, best-effort after commit, rebuildable with `cmd/reconcile -rebuild-hot`). The API process (`backend/cmd/main.go`) only serves HTTP: it writes Outbox rows and consumes Redis push messages for SSE — it never starts a consumer or a poller.
1. **红**——写最小测试,跑,看它失败。确认失败原因是预期的那一个(值不对、没调用、状态码错),不是拼写或 fixture 坏了。
2. **绿**——写最小实现,不加「顺手」的抽象和选项。
3. **重构**——在绿的前提下清实现和测试名,每步重跑。
### Domain Layer Pattern
测试与实现同一次提交。改 bug 先写复现测试,把失败断言写进提交信息或 PR 说明。
Each domain (`account`, `video`, `social`, `feed`) follows: **Entity → Repository → Service → Handler**. `message` and `notification` are simpler — `message` has entity + handler only (no separate repo/service), `notification` is handler-only (routes in `router.go`, worker-side logic in `worker/notificationworker.go`). All wiring is manual constructor injection in `backend/internal/http/router.go` (no DI framework).
## 测试
**API Style**: All endpoints use POST (except SSE stream and health check) to simplify frontend client abstraction and unify JSON body handling.
- 测试与被测代码同包同目录(`package http`、`package rabbitmq`),一个 `*_test.go` 放在旁边。只有要用公开 API 时才用 `_test` 包。
- 命名 `TestSubject_ExpectedBehavior`。一个行为多种输入用表驱动 + `t.Run` + `name string` 字段。
- 辅助函数标 `t.Helper()`;共享 fixture 只放 `_test.go`,不进生产包。
- 保留意图注释:一句话说明这个不变量为什么存在,不复述 bug。测试注释用中文。
- 没有 mock 框架。RabbitMQ 用窄接口手写 fake(如 `fakeConn`),Redis 用 `miniredis`,handler 用 `httptest` + `gin.CreateTestContext`,MySQL 没有 mock——抽窄接口做单测,或对着真库写并注明要先起 infra。
- 断言可观察行为(状态码、响应体、落库行、发出的消息),不断言内部调用次数。
- 集成测试放 `//go:build integration` 文件,端点走环境变量。缺前置条件就 `t.Skip` 并写原因,静默通过与跳过不等价。
- 多个 MySQL fixture 包同时跑要加 `-p 1`,否则互相 `DropTable`。
- 单测不碰真实网络,不拿 `time.Sleep` 当同步。测试要过 `-race`,且与执行顺序无关。
- 不要为了让套件变快而改小文档化的时间守卫——`TestReadyz_MQEnabledButDisconnected_IsDistinguishable` 那 5 秒就是断言本身。
- 覆盖率当评审输入,不当门禁。
- 既有测试是契约:不为过审削弱、跳过或删除断言。不变量真变了,就在同一提交里改测试并说明原因。
- 新测试需要摸私有字段、睡几秒或起容器,通常是边界画错了——注入依赖,别加脚手架。
### API Route Groups
## 文档
All routes defined in `backend/internal/http/router.go`:
- `/account/*` — registration, login, refresh, profile, avatar
- `/video/*` — publish, upload (regular + chunked), detail, list by author
- `/like/*` — like/unlike, check liked, list liked videos
- `/comment/*` — publish, delete, list all
- `/social/*` — follow/unfollow, followers/following lists, counts
- `/feed/*` — latest, likes ranking, popularity, following feed, tag feed
- `/message/*` — send/list direct messages
- `/notification/*` — SSE stream, list, mark read, unread count
- `GET /healthz` — health check (process liveness; always 200)
- `GET /readyz` — dependency readiness: 503 while RabbitMQ is disconnected, reporting `mq_enabled` / `mq_connected` / `mq_generation` / `mq_reconnects` / `mq_topology`. Deliberately separate from `/healthz`: during a broker outage the API is still usable (writes fall back to direct DB), so MQ state must not cause orchestrators to restart healthy instances.
- `GET /static/*` — serves uploaded files from `backend/.run/uploads`
- 设计文档在 `docs/design/`,中文,写代码做什么、为什么。文档不是代码的规格:两者冲突时先改文档,除非代码确实坏了。
- 永远不要用行号定位代码。写文件 + 稳定符号(函数名、常量、测试名、日志原文),不写 `service.go:496`。
- 文档内引用代码片段时,头部只写文件名,不重复段落已提到的路径。
- 行为变了,同一次改动里把对应文档改掉。表格或短片段优于复述代码的散文。
### Async Write Path
## 注释
Write operations (like, comment, follow) use **MQ-first with DB fallback** pattern: publish to RabbitMQ topic exchanges (`like.events`, `comment.events`, `social.events`); if MQ fails, fall back to direct DB transaction. The worker process consumes and writes to DB. Video publishing uses the **Outbox pattern** — API writes video + `OutboxMsg` in one DB transaction, a poller publishes to `video.timeline.events`.
注释只写代码说不出来的 why:不变量、非显然的取舍、失败模式、刻意省略。
### Caching (Feed Service)
- 不复述代码,不写变更日志,不写署名。
- 一两行就够。需要五行为两行代码辩护,就去重构代码。
- 留下承载理由的(`// RENAMENX 把临时键的 1 分钟 TTL 带给了 dest`),删掉复述的(`// 返回响应`)。
- 用文件的语言:`backend/` 下用中文。
Three-tier: L1 in-process `go-cache` (3s) → L2 Redis JSON (1h) → L3 MySQL with `singleflight` dedup. Feed "latest" uses a Redis ZSET hot cache (1000 entries) with MySQL fallback. Cache stampede protection via distributed Redis locks + `singleflight`.
## 提交信息
### Middleware
- **JWT**: `JWTAuth()` (hard) and `SoftJWTAuth()` (optional) in `middleware/jwt/`. Redis-first token check, DB fallback. The signing key is injected once at startup via `auth.Configure` (see Configuration); when it is missing the middleware answers **500** (`server auth misconfigured`) instead of 401, so misconfiguration is never mistaken for an invalid token.
- **Rate Limit**: Redis sliding window via Lua script in `middleware/ratelimit/`.
- **Redis**: Wrapped client with key prefixing and distributed locking in `middleware/redis/`.
- **RabbitMQ**: Connection manager in `middleware/rabbitmq/` — owns the AMQP connection lifecycle (connection-level reconnect with exponential backoff + jitter, topology replay on every new connection, per-generation `Session{Ch,Done}` handles). Per-domain publishers and DLX live here too.
### Workers
Consumers never touch `*amqp.Connection`. Each one runs `rabbitmq.RunConsumer(ctx, mgr, name, prefetch, fn)` — the single consume loop in the project. It blocks (no polling) while the connection is down, and on recovery rebuilds the channel, re-applies per-channel QoS, and re-runs `Consume`. Channel-level exceptions (queue deleted, 406 conflicts) trigger a topology replay rather than a reconnect. Topology is registered once (`RegisterTopology`) and replayed automatically on every new connection. Notification workers consume from `notification.like`, `notification.comment`, `notification.social` queues. Note: `notification` domain is handler-only — routes in `router.go`, worker-side logic in `worker/notificationworker.go`.
`SSEHub` (`worker/ssehub.go`) is the **API-side** in-process pub/sub for connected clients; it is not the delivery path. Delivery is cross-process: the Worker's `RedisNotificationPublisher` (`worker/notificationbus.go`) publishes `{user_id, notification}` to `v1:notification:push`, and every API instance's `StartNotificationSubscriber` forwards what it receives to its own hub. Without that hop a user connected to instance A never sees a notification produced on instance B. Pub/Sub is at-most-once — the `notifications` table stays the authoritative copy, and the SSE push only makes it appear without a refresh.
Both binaries own their shutdown: `signal.NotifyContext` in `cmd/main.go` and `cmd/worker/main.go`, `http.Server.Shutdown` for the API (SSE handlers return when the process ctx is cancelled) and a `WaitGroup` for the Worker. Never reintroduce a fixed `time.Sleep` as a shutdown barrier.
Inside that callback every business worker calls `rabbitmq.ConsumeLoop(ctx, ch, parker, queue, rabbitmq.MaxAttempts, process)`. It is the only place that decides Ack / retry / park: a `nil` error acks, `rabbitmq.Permanent(err)` parks immediately, and any other error goes back through the queue's own `<queue>.retry` delay queue until `MaxAttempts` is spent. Parking publishes to `dlx.events` with routing key `parked.<source queue>`, and `FailedEventWorker` persists those messages into the `failed_events` table. Retry counts come from the broker's `x-death` header, never from process memory. A worker dispatches on the message body (`action`) rather than `d.RoutingKey`: the retry hop rewrites the routing key to the queue name.
### Frontend (Vue 3 + TypeScript on rolldown-vite)
- **Language**: Chinese UI (matching README and documentation)
- **State**: Pinia stores in `frontend/src/stores/` (auth, social, toast)
- **API layer**: `frontend/src/api/` — one module per domain (account, comment, feed, like, message, social, video). `client.ts` wraps `fetch` with automatic JWT injection and 401 → token refresh → retry
- **Composables**: `useLikeFollow`, `useVideoFeed`, `useVideoPlayer` in `frontend/src/composables/`
- **Vite dev proxy**: `/api` → `http://127.0.0.1:8080` (strips `/api` prefix)
#### Frontend Routes (defined in `frontend/src/router/index.ts`)
| Path | View | Auth |
|------|------|------|
| `/` | HomeView (feed tabs: recommend, following, likes ranking) | no |
| `/hot` | HotView (popularity ranking) | no |
| `/video` | VideoView (publish) | yes |
| `/video/:id` | VideoDetailView | no |
| `/account` | AccountView (login) | no |
| `/account/register` | RegisterView | no |
| `/account/change-password` | ChangePasswordView | no |
| `/settings` | SettingsView | yes |
| `/u/:id` | UserProfileView | no |
| `/messages` | MessageView (contact list) | yes |
| `/messages/:peerId` | MessageView (conversation) | yes |
### Supporting Packages
- `auth/` — JWT token generation/parsing (HS256, access token TTL from config, default 15min; opaque random refresh token). Requires `auth.Configure` at startup — see Configuration.
- `apierror/` — error classification → HTTP status codes
- `db/` — GORM MySQL connection setup
- `notification/` — entity for the `notifications` table. Shared by `worker` and `video` so the column tags have exactly one definition; handlers stay in `worker/ssehub.go` and `router.go`.
- `observability/` — pprof server registration
### Database Entities (auto-migrated via GORM)
`Account`, `Video`, `Like`, `Comment`, `Social`, `OutboxMsg`, `Tag`, `VideoTag`, `Message`, `Notification`, `FailedEvent`
### Chunked Upload
Redis-based session tracking for 5MB chunks with per-chunk MD5 verification, breakpoint resume, and merge on completion. See `backend/internal/video/chunk_handler.go`.
## Configuration
Config files in `backend/configs/` (YAML). Loaded by `backend/internal/config/loadconfig.go`. `CONFIG_PATH` env var selects which config file to load (default: `configs/config.yaml`). Additional env vars override YAML values — see `ApplyEnvOverrides()` for the full list (`SERVER_PORT`, `MYSQL_*`, `REDIS_*`, `RABBITMQ_*`, `JWT_SECRET`, `JWT_ACCESS_TOKEN_TTL`). Copy `.env.example` to `.env` for secrets (includes `MYSQL_ROOT_PASSWORD`, `MYSQL_DATABASE`, `REDIS_PASSWORD`, `RABBITMQ_USER`, `RABBITMQ_PASS`, `JWT_SECRET`).
**JWT config is required and fail-fast**: `JWT_SECRET` must be at least 32 bytes — both binaries call `auth.Configure(auth.Options{...})` right after config load and **refuse to start** if it is missing or too short (there is no random-key fallback). Access token lifetime comes from `jwt.access_token_ttl` (YAML, default `15m`, overridable via `JWT_ACCESS_TOKEN_TTL`). Startup logs a key fingerprint — `JWT secret loaded (fingerprint=..., access_ttl=...)` — which must match between API and Worker. Never write the secret into the committed YAML files.
Config variants:
- `config.yaml` — default, connects to localhost MySQL/Redis/RabbitMQ
- `config.compose-local.yaml` — local dev with compose infra (MySQL on port 3307)
- `config.docker.yaml` — used inside Docker containers (mounted via docker-compose)
`start.sh` env var toggles: `START_REDIS`, `START_RABBITMQ`, `START_BACKEND`, `START_WORKER`, `START_FRONTEND`, `STOP_DOCKER`
## CI/CD
Gitea Actions (`.gitea/workflows/ci.yml`) runs on pushes to `main`/`master` and deploys to production in the same job. The runner label is `aliyun` — a **host-mode** runner on the Aliyun ECS, so steps execute directly on the host (`/opt/vloop`, Docker, rsync) rather than in a disposable container.
- Backend: `golang:1.24.5` container — `go vet ./...` then `go test -race -count=1 ./...`
- Frontend: `node:24-alpine` container — `npm ci` then `npm run build`
- Deploy: validates `/opt/vloop/.env`, `rsync`s the workspace to `/opt/vloop`, then `docker compose -f docker-compose.prod.yml up -d --build --wait`
Host prerequisites: Git ≥ 2.34.1, **Node.js 22** (JavaScript actions such as `actions/checkout@v4` look up `node` on PATH), Docker + Compose v2, `rsync`. Public entrypoint: `http://goanchor.top:9000` (`APP_PORT` overridable). There is no PR gate — a push to `main` deploys immediately.
## Testing
- Redis tests use `miniredis` (in-memory)
- HTTP handler tests use `httptest` + `gin.CreateTestContext`
- No mocking framework for DB; tests that need Redis use `miniredis`
- Some tests require running MySQL — start infra first: `docker compose up -d mysql redis rabbitmq`
- Postman collection at `test/postman.json` for manual API testing
## Observability
- Health check: `GET /healthz` (always 200) and `GET /readyz` (503 when RabbitMQ is down; see `internal/http/router_test.go` for the invariant)
- pprof: API on `localhost:6060`, Worker on `localhost:6061` (enabled by default in local config)
- Frontend dev server: `localhost:5173` (proxies `/api` → `http://127.0.0.1:8080`)
- Uploads stored at `backend/.run/uploads`, served via `GET /static/`
## Key Files
- `backend/internal/http/router.go` — all route definitions and dependency wiring
- `backend/internal/middleware/rabbitmq/` — connection manager (reconnect + topology replay + `RunConsumer`), exchange declarations, DLX, per-domain MQ publishers
- `backend/internal/feed/service.go` — three-tier caching, hot/cold feed split
- `backend/internal/worker/` — all async workers, the SSE hub and the Redis notification bridge (`notificationbus.go`)
- `backend/internal/video/chunk_handler.go` — chunked upload logic
## Test-Driven Development (TDD)
TDD is the default working mode for behavior changes under `backend/`. The frontend has no test runner yet (`frontend/package.json` exposes only `dev`, `build`, `preview`), so frontend work is verified with `npm run build` plus a manual check of the affected view — do not describe it as test-driven. If a runner (e.g. Vitest) is added, extend this section in the same change.
### The loop: red → green → refactor
1. **Red** — write the smallest test that expresses the new behavior, run it, and watch it fail. Confirm it fails for the expected reason (wrong value, missing call, unexpected status) and not because of a typo, nil panic, or broken fixture.
2. **Green** — write the minimal production code that makes it pass. No speculative abstractions, no extra options "while I'm here".
3. **Refactor** — clean up implementation and test names with the suite green, re-running after each step.
4. Commit the test and the implementation together. A push that adds behavior without a test is incomplete work, not a follow-up.
Bug fixes start from a regression test that reproduces the bug — failing before the fix, green after. State the failing assertion in the commit message or PR description so reviewers can see what was actually broken.
### Placement and naming
- One `*_test.go` beside the code it covers, in the **same package** (`package http`, `package rabbitmq`, …) so unexported state and helpers are reachable. Use an external `_test` package only when the test should consume the public API.
- Name tests `TestSubject_ExpectedBehavior`, e.g. `TestReadyz_MQEnabledButDisconnected_IsDistinguishable`. Use table-driven cases with `t.Run` subtests and a `name string` field when one behavior has several inputs.
- Mark every helper with `t.Helper()`. Shared fixtures live in `_test.go` files, never in production packages.
- Keep the intent comment. Existing suites explain *why* an invariant exists (see the `/readyz` case in `backend/internal/http/router_test.go`); a test whose reason is unwritten gets deleted by the next person who finds it inconvenient. Match the surrounding file's comment language — test comments in this repo are largely Chinese.
### Test doubles
The repo deliberately has no mocking framework. Match that:
- **RabbitMQ / connection state machines** — hand-written fakes implementing the narrow interface (`fakeConn` in `backend/internal/middleware/rabbitmq/rabbitmq_test.go`). Keep them tiny: no network I/O, no timing assumptions.
- **Redis** — `miniredis`.
- **HTTP handlers** — `httptest` with `gin.SetMode(gin.TestMode)`, `gin.CreateTestContext`, or a router built via `SetRouter` as `backend/internal/http/router_test.go` does.
- **MySQL** — there is no DB mock. Either extract a narrow interface and fake it for a unit test, or write the test against real MySQL and document that the infra must be up first.
Assert on observable behavior (HTTP status and body, rows written, messages published) rather than internal call counts; call-count assertions break on harmless refactors.
### Integration tests
Anything needing a real broker or MySQL lives in a `//go:build integration` file and is excluded from the default run:
```bash
docker compose up -d rabbitmq
go test -tags integration -count=1 -timeout 300s -v ./internal/middleware/rabbitmq/
```
Configure endpoints through env vars (`RABBITMQ_TEST_URL`, …), never hardcoded hosts. When a prerequisite is missing — a restart command, a delete-queue command — `t.Skip` with the reason; a silent pass is not a substitute for a skip.
The MySQL fixtures each `DropTable` + `AutoMigrate` the shared schema, so run more than one such package at a time with `-p 1`. Without it the packages run in parallel and drop each other's tables (`Error 1050 Table already exists`, `Error 1146 doesn't exist`).
### Determinism and speed
- No real network in unit tests; no `time.Sleep` as synchronization. Prefer channels, context deadlines, or an injected clock. Tests must pass under `-race` and in any order.
- Run `go test -race -count=1 ./...` before every push. `-count=1` is required: cached results hide flakiness, and `-race` catches the concurrency bugs this codebase is full of.
- Do not shorten a documented timing guard to make the suite faster. `TestReadyz_MQEnabledButDisconnected_IsDistinguishable` takes ~5s on purpose — that wait *is* the assertion that the startup `EnsureTopology` timeout works.
- Treat coverage as review input (`go test -cover ./...`), not a gate. Chasing a percentage produces assertion-free tests; missing behavior coverage on service and branch logic is the real risk.
### Existing tests are contracts
- Never weaken, skip, or delete an assertion to get a change through. If an invariant genuinely changes, change the test in the same commit and explain why in the message.
- A new test that needs to reach into private fields, sleep for seconds, or start a container usually means the unit boundary is wrong — fix the design (inject the dependency) instead of adding scaffolding.
- When a test starts failing "because the environment changed", check whether it was ever deterministic before editing it.
## Documentation
Design docs live in `docs/design/` and are written in Chinese. They describe what the code does and why. They are not a spec the code must satisfy: when a doc and the code disagree, the doc is wrong until proven otherwise — fix the doc first, and change code only if the code is actually broken.
**Never locate code by line number.** Line numbers drift on every edit, so `service.go:496` is wrong within a week. Cite the file plus a stable symbol instead:
- good: `backend/internal/feed/service.go` 的 `listByHotWindowRedis`
- good: `backend/internal/feed/service.go` 的 `hotSnapshotTTL`
- good: test name `TestListByPopularity_StaleAsOfIsReplaced`
- good: an exact string, e.g. the log line `feed: expire hot snapshot %s failed, dropping it`
- bad: `backend/internal/feed/service.go:496-532`
Inside a code excerpt, the header comment names the file only — the block already shows which function it is. When a paragraph already names the symbol, do not add a path for it.
Keep each doc current in the same change that touches the behavior it describes. Prefer a table or a short excerpt over prose that repeats the code.
## Code Comments
Comments carry the *why* the code cannot say: an invariant, a non-obvious tradeoff, a failure mode, a deliberate omission. Everything else is noise, and noise is what makes real comments invisible.
- Do not restate the code. No `// 遍历 videos`, no comment that repeats the function name, no changelog (`// 新增于 X`), no attribution.
- One short paragraph is the budget, usually one or two lines. If a comment needs five lines to justify a two-line block, rename or restructure the code instead.
- Keep the ones that encode a reason: `// RENAMENX 把临时键的 1 分钟 TTL 带给了 dest` earns its line; `// 返回响应` does not.
- Write in the file's language — Chinese in `backend/`, matching the surrounding file.
- The same limit applies to test intent comments: one sentence saying why the invariant exists, not a recount of the bug.
## Commit Messages
Commit messages are Chinese, `type(scope): subject`, and written to the structural rules of ASD-STE100 — target roughly 80 %, which means the text reads simply. This is not a certified STE document; it is a readability standard with two hard parts: short sentences, and terms kept exactly as the code spells them.
- **One idea per sentence.** Split on `——`, `;` and `:` into separate sentences instead of chaining clauses. Aim for ≤ 30 characters; a sentence with three comma-joined clauses is a rewrite.
- **Verb first, active voice.** `只做声明` → `只声明`. No verb-less lines like `DLX 交换机 X + 唯一队列 Y parked.# 绑定`; write `包含 … 和 …` / `以 … 绑定到 …`.
- **One paragraph per topic**, opened by its claim (`每个队列必须有独立的重试入口。…`). Use `因此` / `所以` to start the conclusion sentence instead of glueing it on.
- **Identifiers stay verbatim**: exchange, queue and routing-key names, type and function names, test names. Never translate, reflow or abbreviate them.
- **A term is a fixed phrase, not a word.** A phrase that already appears in code comments or test names is project vocabulary: keep it exactly, and do not borrow one of its words to mean something else. Everything that is not a term uses plain words — do not coin new metaphors, since a metaphor that cannot be `grep`ed is one the next reader has to decode.
- When the change is verified by a command, close with a `验证:…` line naming it, e.g. `验证:go test -race -count=1 ./... 全绿`.
中文,`type(scope): subject`,按 ASD-STE100 的结构写,约 80% 即可:短句,术语照代码拼写。
- 一句话一个意思。把 `——`、`;`、`:` 拆成独立句子。目标 ≤ 30 字。
- 动词开头,主动语态。`只做声明` → `只声明`。
- 一段讲一件事,首句给结论,用 `因此` / `所以` 起结论句。
- 标识符原样保留:交换机、队列、路由键、类型名、函数名、测试名。不翻译、不改写、不缩写。
- 术语是固定短语:代码注释或测试名里已有的说法就是项目词汇,原样沿用;非术语用平实词,不要造无法 grep 的隐喻。
- 有验证命令时,结尾写一行 `验证:…`,如 `验证:go test -race -count=1 ./... 全绿`。