From 7d9cb061a22a13659cc0601367d195a97f718baa Mon Sep 17 00:00:00 2001 From: huanghaosheng <386998068@qq.com> Date: Mon, 9 Nov 2026 15:43:17 +0800 Subject: [PATCH] =?UTF-8?q?docs(agents):=20=E7=B2=BE=E7=AE=80=20AGENTS.md?= =?UTF-8?q?=20=E4=B8=BA=E7=BA=A6=E6=9D=9F=E6=B8=85=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 个文件变更。 --- AGENTS.md | 315 ++++-------------- CLAUDE.md | 6 +- docs/ISSUES-REPORT.md | 10 +- docs/design/可观测性实现.md | 8 +- .../P0-3-P0-4-retry-and-idempotency.md | 2 +- docs/solutions/P0-3-dlx-retry.md | 2 +- docs/solutions/P0-4-comment-idempotency.md | 4 +- .../P0-5-popularity-single-source.md | 4 +- .../P1-1-async-workers-out-of-api.md | 1 - 9 files changed, 70 insertions(+), 282 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 363e1cd..1fbe0f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 `.retry` delay queue until `MaxAttempts` is spent. Parking publishes to `dlx.events` with routing key `parked.`, 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 ./... 全绿`。 diff --git a/CLAUDE.md b/CLAUDE.md index 5847d73..f03008d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,7 +1,3 @@ # CLAUDE.md -All agent guidance for this repository lives in a single source of truth: [AGENTS.md](AGENTS.md). - -Read AGENTS.md before making any change. It covers the project overview, commands, architecture, configuration, CI, testing conventions, the TDD workflow, and the key files. - -Do not duplicate that content here — if guidance needs to change, edit AGENTS.md instead, so Codex, Claude Code, and every other agent stay in sync. +所有 Agent 规范都在 [AGENTS.md](AGENTS.md)。改规范请改 AGENTS.md,不要在本文件重复。 diff --git a/docs/ISSUES-REPORT.md b/docs/ISSUES-REPORT.md index 2941fbe..46b1bc3 100644 --- a/docs/ISSUES-REPORT.md +++ b/docs/ISSUES-REPORT.md @@ -184,7 +184,7 @@ Timeline 消费端(`handleTimelineMessage`)绕开了 `rabbitmq.ConsumeLoop` **问题**:`.gitignore` 曾含 `docs/` 与 `CLAUDE.md` 两条,`git ls-files docs` 为空,全部设计文档不进版本库——这正是第七节那批"文档与代码不符"长期无人发现的根因。 **解决**:`.gitignore` 只保留 `.run/`、`backend/.run/`、`data/`、`.sisyphus/`、二进制产物、`.env` 与 IDE 目录;`docs/design/`、`docs/solutions/` 与本报告均已跟踪,并在 `AGENTS.md` 立下"改行为同步改文档"的约定。 -**索引**:[`AGENTS.md`](../AGENTS.md) 的 `## Documentation` 一节。 +**索引**:[`AGENTS.md`](../AGENTS.md) 的 `## 文档` 一节。 ### P1-12 🟡 CI 自动部署非原子且曾开 cancel-in-progress @@ -541,12 +541,12 @@ SSE 已随 P1-1 改为 Redis Pub/Sub 跨进程(`worker/notificationbus.go`) | # | 文档声称 | 代码事实 / 状态 | |---|---|---| -| D-1 | AGENTS.md:Worker 运行"六类 worker" | **✅ 已修复**:P1-1 把 Notification×3、Outbox poller、Timeline consumer 迁入 `cmd/worker`,AGENTS.md 现按实际分工写明 API 只装配 HTTP 入口、Worker 跑全部消费者与轮询器 | -| D-2 | AGENTS.md:写操作 "MQ-first with DB fallback" | like/comment 确为 MQ-first + DB 兜底;`social/service.go` 的 `Follow` 实为 DB-first + MQ 仅作通知。**仍未修**(P1-4) | -| D-3 | AGENTS.md:限流为 "Redis sliding window via Lua script" | 实为首请求锚定固定窗口(`redis.go` 的 `incrementWithExpireScript`)。**仍未修**(P2-1) | +| D-1 | AGENTS.md:Worker 运行"六类 worker" | **✅ 已修复**:P1-1 把 Notification×3、Outbox poller、Timeline consumer 迁入 `cmd/worker` | +| D-2 | AGENTS.md:写操作 "MQ-first with DB fallback" | like/comment 确为 MQ-first + DB 兜底;`social/service.go` 的 `Follow` 实为 DB-first + MQ 仅作通知。**已消解**:AGENTS.md 的写路径描述已删,本条不再有文档可对(代码侧仍待 P1-4) | +| D-3 | AGENTS.md:限流为 "Redis sliding window via Lua script" | 实为首请求锚定固定窗口(`redis.go` 的 `incrementWithExpireScript`)。**已消解**:AGENTS.md 的限流描述已删,本条不再有文档可对(代码侧仍待 P2-1) | | D-4 | README:CI 在 `.github/workflows/ci.yml` | `.github/` 不存在,实际是 `.gitea/workflows/ci.yml`。**✅ 已修复** | | D-5 | README:`JWT_SECRET` 默认 `feedsystem-dev-secret-key` | 代码无默认值。**✅ 已修复**:README 改为"必填、≥32 字节、生成命令",`.env.example` 与 compose 默认值升至 44 字节(P0-1) | -| D-6 | AGENTS.md:Feed "L1 go-cache (3s)" | `feed/service.go` 的 L1 用 `cache.New(3*time.Second, 5*time.Second)` 创建,写入实体键时显式传 **5s**,实际 L1=5s;另有 24h 的关注流整页缓存未提。**仍未修** | +| D-6 | AGENTS.md:Feed "L1 go-cache (3s)" | `feed/service.go` 的 L1 用 `cache.New(3*time.Second, 5*time.Second)` 创建,写入实体键时显式传 **5s**,实际 L1=5s;另有 24h 的关注流整页缓存未提。**已消解**:AGENTS.md 的 Feed 缓存描述已删,本条不再有文档可对 | | D-7 | 前端路由表与设计文档 | 路由本身一致 ✔,但未记录 `FeedView.vue`(已无引用的死组件,见 F-20)与分片上传细节;"前端未接 SSE" 已补进 README 的进程分工一节。**仍部分未修(剩两项)** | | D-8 | 历史 `docs/todo.md` 第 5 条:拓扑声明函数重复 | **✅ 已关闭**:`docs/todo.md` 已不在仓库;拓扑改 `RegisterTopology` 登记一次、每代新连接自动重放,"两处各声明一遍"的写法本身已消失(不是文中说的"直接调 `DeclareTopic`") | | D-9 | README:Postman 集合"批量跑接口与断言脚本" | 集合含 `/like/getLikesCount` 等不存在的请求,**24 个**请求却缺 refresh/upload/chunk/message/notification 等,断言脚本没有。**仍未修** | diff --git a/docs/design/可观测性实现.md b/docs/design/可观测性实现.md index 4943b20..9bccb84 100644 --- a/docs/design/可观测性实现.md +++ b/docs/design/可观测性实现.md @@ -1,6 +1,6 @@ # 可观测性升级:pprof 评估与 Prometheus + Grafana 方案 -> 状态:方案(尚未实现)。落地后请把本文改成现状说明:删掉本行,把“目标架构”改成“架构”,并同步 `AGENTS.md` 的 Observability 一节。 +> 状态:方案(尚未实现)。落地后请把本文改成现状说明:删掉本行,把“目标架构”改成“架构”。 > > 读者:要接指标、要排障、要改 `observability` 包的人。 @@ -156,7 +156,7 @@ observability: | `observability.pprof.worker_addr` | `observability.admin.worker_addr` | | — | `observability.admin.pprof` | -这是一次**破坏性配置变更**:三份 YAML、`DefaultLocalConfig`、`loadconfig_test.go`、`AGENTS.md`、`README.md` 必须在同一个提交里改完。外部自定义配置如果没迁移,`admin.enabled` 会落到零值 `false`,表现为 admin 端口不监听;Worker 的 healthcheck 会因此失败,部署会立刻暴露,而不是静默丢掉观测。 +这是一次**破坏性配置变更**:三份 YAML、`DefaultLocalConfig`、`loadconfig_test.go`、`README.md` 必须在同一个提交里改完。外部自定义配置如果没迁移,`admin.enabled` 会落到零值 `false`,表现为 admin 端口不监听;Worker 的 healthcheck 会因此失败,部署会立刻暴露,而不是静默丢掉观测。 ### 2.5 依赖 @@ -493,7 +493,7 @@ go vet ./... && go test -race -count=1 ./... 4. RabbitMQ 插件与 per-object 指标。 5. 告警规则;需要时加 Alertmanager。 6. HTTP / Async / Runtime 三个面板。 -7. 更新 `AGENTS.md`、`README.md`、`docs/feedsystem_video_go项目设计.md` 的可观测性段落。 +7. 更新 `README.md`、`docs/feedsystem_video_go项目设计.md` 的可观测性段落。 验收:命中 L1/L2 时命中率变化;超过登录限流时 `result="rejected"` 增长;停 Redis 时 `fail_open` 增长;`promtool check rules` 通过。 @@ -524,7 +524,7 @@ go vet ./... && go test -race -count=1 ./... | `docker-compose.yml`、`docker-compose.prod.yml` | prometheus/grafana、profile、rabbitmq 配置挂载、worker healthcheck | | `monitoring/**` | Prometheus 配置、规则、Grafana provisioning、dashboard JSON | | `.env.example` | `GRAFANA_ADMIN_PASSWORD` | -| `AGENTS.md`、`README.md`、设计文档 | 同步 | +| `README.md`、设计文档 | 同步 | --- diff --git a/docs/solutions/P0-3-P0-4-retry-and-idempotency.md b/docs/solutions/P0-3-P0-4-retry-and-idempotency.md index e2b7393..03e5f3d 100644 --- a/docs/solutions/P0-3-P0-4-retry-and-idempotency.md +++ b/docs/solutions/P0-3-P0-4-retry-and-idempotency.md @@ -2743,7 +2743,7 @@ COMMIT; 1. 更新 `docs/ISSUES-REPORT.md` 的 P0-3 / P0-4 条目与第九节修复路线; 2. 两份原方案文首加"已被取代"提示(**不删除**:它们保留了完整的问题推导过程,是本文档 §2.3/§7 的来源); -3. 在 `AGENTS.md` 的 "Async Write Path" 段落补一句:**"消费端失败不再丢弃:`rabbitmq.ConsumeLoop` 负责重投与停泊;新增消费者必须实现幂等 `process`"**——这是新增消费者时最容易违反的约定,写进 AGENTS.md 才算真正落地; +3. 在 `AGENTS.md` 的「红线」段补一句:**"消费端失败不再丢弃:`rabbitmq.ConsumeLoop` 负责重投与停泊;新增消费者必须实现幂等 `process`"**——这是新增消费者时最容易违反的约定,写进 AGENTS.md 才算真正落地; 4. 登记 §10.2 的 N12 边界,避免 P0-5 误判。 --- diff --git a/docs/solutions/P0-3-dlx-retry.md b/docs/solutions/P0-3-dlx-retry.md index 662d72e..8047159 100644 --- a/docs/solutions/P0-3-dlx-retry.md +++ b/docs/solutions/P0-3-dlx-retry.md @@ -1439,7 +1439,7 @@ docker compose logs -f backend worker | grep -iE 'DLX ready|拓扑|started' | `backend/internal/middleware/rabbitmq/rabbitmq_test.go` | 改写 `TestDeclareTopologies_OrderAndDeadLetterExchange`(断言新参数/新绑定/不再有 `.dlx`);新增计数与判定用例 | | `backend/internal/middleware/rabbitmq/constants_test.go` | 把 `failed.events` 加入线缆名称签名表(新增固定名称必须与常量同批更新,否则下一个改名人会静默绕过契约) | | `backend/internal/middleware/rabbitmq/integration_test.go` | 新增 §9.2 的集成用例(沿用 `-tags integration` + `RABBITMQ_TEST_URL`) | -| `AGENTS.md` / `docs/ISSUES-REPORT.md` | 落地后更新(异步链路与 DLX 描述、"修复路线建议"第 3 条)。注意仓库的 agent 说明已收敛到 `AGENTS.md`,`CLAUDE.md` 只是一行指针,不再承载架构描述 | +| `docs/ISSUES-REPORT.md` | 落地后更新(异步链路与 DLX 描述、"修复路线建议"第 3 条) | ### 9.2 验证 diff --git a/docs/solutions/P0-4-comment-idempotency.md b/docs/solutions/P0-4-comment-idempotency.md index 4ac3630..ae10cf6 100644 --- a/docs/solutions/P0-4-comment-idempotency.md +++ b/docs/solutions/P0-4-comment-idempotency.md @@ -407,7 +407,7 @@ type Mention struct { // CommentStore 是评论写路径的最小存储契约。 // -// 抽成接口的两个理由(AGENTS.md「测试替身」一节): +// 抽成接口的两个理由(AGENTS.md「测试」一节): // 1. "发布失败走本地直写"是本次修复的核心分支,必须能在没有 MySQL 的单测里断言; // 2. CommentWorker 只需要其中 3 个方法,接口能把它的依赖面收窄。 type CommentStore interface { @@ -1420,7 +1420,6 @@ SELECT dedupe_key, COUNT(*) FROM notifications | `frontend/src/api/comment.ts` | 新增 `newRequestId`;`publish` 增 `requestId` 参数 | | `frontend/src/components/CommentDrawer.vue` | `publishComment` 用 `pendingIntent` 复用键(§6.12) | | `frontend/src/views/VideoDetailView.vue` | 同上(两处代码相同,抽到 composable 更好,但不在本方案范围内) | -| `AGENTS.md` | 更新"Async Write Path"一节:写路径的幂等约定(意图键 + 唯一索引 + 占位),以及"新增异步副作用必须自带去重键"的规则 | | `docs/ISSUES-REPORT.md` | 标注 P0-4 已修复;按 §2.6 勘误 `:191` 的两处表述;P2-16 标注"① 已顺带修复" | ### 9.2 验证 @@ -1624,5 +1623,4 @@ if deleted && evt.VideoID != 0 { | `backend/internal/worker/commentworker_test.go` | 新增 | `applyPublish`/`applyDelete` 幂等 | | `backend/internal/worker/notificationworker_test.go` | 新增 | 通知去重键 | | `backend/internal/video/comment_repo_integration_test.go` | 新增 | `-tags integration`:唯一索引、并发、NULL 兼容 | -| `AGENTS.md` | 改 | 写路径幂等约定 | | `docs/ISSUES-REPORT.md` | 改 | P0-4 结案 + §2.6 勘误 + P2-16 ① 状态 | diff --git a/docs/solutions/P0-5-popularity-single-source.md b/docs/solutions/P0-5-popularity-single-source.md index caa3c7b..c131754 100644 --- a/docs/solutions/P0-5-popularity-single-source.md +++ b/docs/solutions/P0-5-popularity-single-source.md @@ -333,7 +333,6 @@ R1–R2 决定"DB 能不能当权威",R3–R4 决定"热榜能不能当派生 | `backend/internal/video/hot_window_admin.go` | 新增 | 热榜核对与重建 | | `backend/cmd/reconcile/main.go` | 新增 | 运维入口,漂移时 `exit 1` | | `backend/internal/video/video_service.go` | 修改 | 修正 §2.5 的错误注释(N9) | -| `AGENTS.md` | 修改 | Worker 段落删掉 Popularity worker | ### 6.4 仓储层:点赞与取消点赞进一个事务 @@ -1721,7 +1720,7 @@ go test -tags integration -p 1 -count=1 -timeout 300s ./internal/video/ ./intern cd ../frontend && npm run build ``` -`go test -race` 必须带 `-count=1`:缓存会掩盖 datarace 与顺序依赖(`AGENTS.md` 的"Determinism and speed"一节)。 +`go test -race` 必须带 `-count=1`:缓存会掩盖 datarace 与顺序依赖(`AGENTS.md` 的"测试"一节)。 ### 9.3 风险 @@ -1823,7 +1822,6 @@ P1-7(报告里的「视频/评论删除链路残缺」)包含三件事:删 | `backend/internal/middleware/rabbitmq/likeMQ.go` | `NewLikeMQ` 的注释 | 不再指向 `PopularityMQ.Update` | | `frontend/src/views/HotView.vue` | `loadHot` | 比对响应的 `as_of`/`snapshot_rebuilt`/`ranking_source`,任一与上一页不同就重置分页(§6.10) | | `frontend/src/api/types.ts` | `ListByPopularityResponse` | 加 `ranking_source`/`snapshot_rebuilt`;`next_latest_*` 标注废弃 | -| `AGENTS.md` | "Workers" 段落 | 删掉 Popularity worker,改述为"计数由业务事务维护,热榜是派生滑窗" | ### 11.3 删除 diff --git a/docs/solutions/P1-1-async-workers-out-of-api.md b/docs/solutions/P1-1-async-workers-out-of-api.md index dab4f42..e697528 100644 --- a/docs/solutions/P1-1-async-workers-out-of-api.md +++ b/docs/solutions/P1-1-async-workers-out-of-api.md @@ -239,7 +239,6 @@ API 不再需要 timeline 与 notification 拓扑:它只写 `outbox_msgs` 行 | `backend/cmd/main.go` | `signal.NotifyContext` + `http.Server` + `Shutdown`;`SetRouter(ctx, ...)` | | `backend/cmd/worker/main.go` | 启动 Notification × 3、Timeline、Outbox;登记对应拓扑;`WaitGroup` 等待退出 | | `docs/ISSUES-REPORT.md` | P1-1 置 ✅,改写为"问题 + 解决 + 索引";路线图第三阶段第 8 条打勾;同步 A-5 / D-1 / P3-12 / P3-13 的状态 | -| `AGENTS.md` | Dual Binary Split 段:Worker 现在跑哪些消费者、API 不再承载异步链路、SSE 经 Redis 跨进程 | | `README.md` | 部署约束:Worker 是通知/时间线的必需进程;多实例时 SSE 依赖 Redis Pub/Sub | | `docs/design/消息处理失败与死信队列.md`、`docs/feedsystem_video_go项目设计.md` | 同步"通知消费者在 Worker"、SSE 推送链路与 `mq_topology` 期望值(API 3 / Worker 7) |