trae-coding-engine 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +91 -0
  2. package/bin/coding-engine.js +16 -0
  3. package/lib/cli.js +86 -0
  4. package/lib/index.js +6 -0
  5. package/lib/setup.js +290 -0
  6. package/package.json +32 -0
  7. package/templates/.agents/skills/coding-architecture/SKILL.md +347 -0
  8. package/templates/.agents/skills/coding-code-review/SKILL.md +95 -0
  9. package/templates/.agents/skills/coding-cve-remediation/SKILL.md +163 -0
  10. package/templates/.agents/skills/coding-db-schema/SKILL.md +273 -0
  11. package/templates/.agents/skills/coding-deploy-config/SKILL.md +129 -0
  12. package/templates/.agents/skills/coding-docs-audit/SKILL.md +285 -0
  13. package/templates/.agents/skills/coding-docs-audit-autofix/SKILL.md +33 -0
  14. package/templates/.agents/skills/coding-http-api/SKILL.md +269 -0
  15. package/templates/.agents/skills/coding-issue-autodev/SKILL.md +172 -0
  16. package/templates/.agents/skills/coding-merge-request/SKILL.md +199 -0
  17. package/templates/.agents/skills/coding-observability/SKILL.md +193 -0
  18. package/templates/.agents/skills/coding-refactor-insight/SKILL.md +89 -0
  19. package/templates/.agents/skills/coding-release-merge/SKILL.md +224 -0
  20. package/templates/.agents/skills/coding-runtime-adapter/SKILL.md +115 -0
  21. package/templates/.agents/skills/coding-testing/SKILL.md +169 -0
  22. package/templates/AGENTS.md +179 -0
  23. package/templates/MR-Template-Default.md +33 -0
  24. package/templates/Makefile +370 -0
  25. package/templates/REGISTRY.md +53 -0
  26. package/templates/scripts/check-adr.sh +283 -0
  27. package/templates/scripts/check-comment-i18n.py +209 -0
  28. package/templates/scripts/check-comment-i18n.sh +38 -0
  29. package/templates/scripts/check-doc-refs.sh +40 -0
  30. package/templates/scripts/check-docs.sh +103 -0
  31. package/templates/scripts/check-go-names.sh +59 -0
  32. package/templates/scripts/check-iam-actions.py +126 -0
  33. package/templates/scripts/check-migration-sql-immutability.sh +232 -0
  34. package/templates/scripts/check-mr-desc.sh +165 -0
  35. package/templates/scripts/check-mr-size.sh +128 -0
  36. package/templates/scripts/check-mr-title.sh +123 -0
  37. package/templates/scripts/check-openapi.py +221 -0
  38. package/templates/scripts/check-rdb-structured-queries.sh +98 -0
  39. package/templates/scripts/check-repository-transactions.sh +100 -0
  40. package/templates/scripts/check-runbooks.sh +229 -0
  41. package/templates/scripts/check-skill-router-sync.py +331 -0
  42. package/templates/scripts/check-skills.sh +243 -0
  43. package/templates/scripts/docs-audit-to-issues.py +373 -0
  44. package/templates/scripts/docs-verification-reminder.sh +63 -0
  45. package/templates/scripts/find-ci-failures.sh +133 -0
  46. package/templates/scripts/find-stale-mrs.sh +72 -0
  47. package/templates/scripts/gen-adr-index.sh +122 -0
  48. package/templates/scripts/open-mr.sh +536 -0
  49. package/templates/scripts/regen-agent-md.sh +149 -0
  50. package/templates/scripts/run-mr-hygiene.sh +140 -0
  51. package/templates/scripts/runbook.sh +91 -0
  52. package/templates/scripts/self-maintenance-digest.py +125 -0
  53. package/templates/scripts/send-self-maintenance-lark-card.py +116 -0
  54. package/templates/scripts/skill-graph.sh +114 -0
  55. package/templates/scripts/skill-impact.sh +134 -0
  56. package/templates/scripts/skill-propose.sh +302 -0
  57. package/templates/scripts/skill-router-hook.sh +152 -0
@@ -0,0 +1,347 @@
1
+ ---
2
+ name: coding-architecture
3
+ description: Use when adding features, new aggregates, new ports, or architecture-level adapters to coding_engine.
4
+ ---
5
+
6
+ # coding-architecture: DDD Architecture Reference
7
+
8
+ ## Layer Map
9
+
10
+ ```
11
+ internal/
12
+ domain/<aggregate>/ ← pure production Go; no framework imports
13
+ application/<domain>/ ← orchestrates domain; owns ports
14
+ application/port/ ← secondary port interfaces (non-persistence)
15
+ adapters/inbound/http/ ← Hertz HTTP handlers
16
+ adapters/outbound/<name>/ ← concrete port/repository implementations
17
+ bootstrap/<binary>/ ← wiring: fx Module (server, gateway, worker, daemon, cli)
18
+ ```
19
+
20
+ Dependency direction: `bootstrap` → `adapters` → `application` → `domain`.
21
+ Imports point inward only. Never import outward/upward; in particular, never
22
+ import `adapters` or concrete external clients from `application`.
23
+
24
+
25
+ ## Layer Responsibilities
26
+
27
+ ### `domain/<aggregate>/`
28
+ | File | Contents |
29
+ |------|----------|
30
+ | `entity.go` | Aggregate root, entities, value objects |
31
+ | `repository.go` | Persistence port interface (CRUD, List) |
32
+ | `types.go` / `status.go` | Enums and type aliases |
33
+
34
+ - No framework imports in production domain files — pure Go structs and interfaces. The only allowed
35
+ `pkg/platform/*` dependency is `pkg/platform/uuid` as the shared ID value
36
+ type; see ADR 0049.
37
+ - `_test.go` files and generated mocks under `internal/domain/**` may depend
38
+ on test infrastructure such as `go.uber.org/mock`, `github.com/stretchr/testify`,
39
+ and `internal/testutil`; those dependencies must not leak into non-test
40
+ domain files.
41
+ - Cross-cutting types (IDs, shared enums) live in `domain/shared/`.
42
+ - Domain events live in `domain/events/`.
43
+ - Domain-local validation or serialization failures use
44
+ `domain/shared.DomainError`; application/adapter boundaries map those errors
45
+ to `pkg/platform/errno`.
46
+ - Do not create aggregate-local sentinel errors (`domain/<agg>/errors.go`,
47
+ `port.ErrXxx`, adapter-local `ErrXxx`) for business semantics.
48
+
49
+ ### `application/<domain>/`
50
+ | File | Contents |
51
+ |------|----------|
52
+ | `service.go` | `Service` interface + `ServiceDeps` struct + `NewService(ServiceDeps) Service` |
53
+ | `dto.go` | Request/response structs |
54
+ | `mapper.go` | `domain ↔ DTO` conversion functions |
55
+
56
+ Boundary review rule:
57
+ - `application` code may use shared value/helper packages such as
58
+ `pkg/platform/logger`, `pkg/platform/errno`, `pkg/platform/uuid`,
59
+ `pkg/platform/retry`, and `pkg/platform/validate`. Do not flag those imports
60
+ alone as a hexagonal-architecture violation.
61
+ - Flag a violation when application code imports `internal/adapters/**`,
62
+ concrete infrastructure packages such as `pkg/platform/redis`,
63
+ `pkg/platform/gormdb`, or `pkg/platform/telemetrydb`,
64
+ database/Redis/Kubernetes/HTTP SDK clients, or a third-party service SDK as
65
+ an external capability. Model that capability behind a domain repository or
66
+ `application/port` interface and implement it in an outbound adapter.
67
+
68
+ Service constructor pattern (always this shape):
69
+ ```go
70
+ type ServiceDeps struct {
71
+ Repo domain.Repository
72
+ SomePt port.SomePort // only what this service actually needs
73
+ Log logger.Logger // required when the service logs
74
+ }
75
+ func NewService(deps ServiceDeps) Service { ... }
76
+ ```
77
+
78
+ Logger injection rule:
79
+ - Application/business code must not silently replace a missing logger with `logger.NewNop()`.
80
+ - If a service/use case needs logging, include `Log logger.Logger` in deps and fail fast in the constructor when it is nil.
81
+ - Wire real loggers from `bootstrap/*`; tests may pass `logger.NewNop()` explicitly.
82
+ - `make check-skills` fails on `logger.NewNop()` in non-test `internal/application/**` code.
83
+
84
+ Context propagation rule:
85
+ - Public service, port, repository, handler, and adapter methods that receive
86
+ `ctx context.Context` must pass that ctx through to helper methods, outbound
87
+ calls, logs, Redis/DB operations, and cleanup that still belongs to the same
88
+ request or worker message.
89
+ - Do not introduce `context.Background()` or `context.TODO()` to bypass a
90
+ caller's cancellation, deadline, tenant/log fields, or trace values. For
91
+ cleanup that must outlive caller cancellation, prefer
92
+ `context.WithoutCancel(ctx)` plus a bounded timeout so values still propagate.
93
+ - If a call chain loses ctx because an interface, port, callback wrapper, or
94
+ helper signature does not expose it, update that signature and its callers.
95
+ Do not add an allowlist entry just to preserve a ctx-less interface.
96
+ - Allowed root contexts are narrow: binary entrypoints, component lifecycle
97
+ roots, detached periodic workers, third-party callbacks with no inbound Go
98
+ context, and best-effort shutdown/cleanup paths. New exceptions must be
99
+ explicitly allowlisted in `scripts/check-context-propagation.py` with a
100
+ rationale. Keep allowlist rules narrow (specific path + line pattern) and
101
+ delete them when the code can use `context.WithoutCancel(ctx)` instead.
102
+ - Run `make check-context-propagation` after touching context flow, background
103
+ workers, lifecycle glue, or any new use of `context.Background()` /
104
+ `context.TODO()`.
105
+ - `make check-context-nil` is a separate guard: it catches `nil` passed to
106
+ `context.Context` parameters, including tests. `golangci-lint` context
107
+ linters do not replace either custom guard.
108
+
109
+ Error handling rule:
110
+ - In this section, `should` / `prefer` mark the review default; `must` marks a hard gate.
111
+ - `errno.BizError` is the only business error type crossing backend layers
112
+ outside `internal/domain/**`. Domain methods return
113
+ `shared.DomainError`; map them with the helper in
114
+ `internal/application/domainerr/errors.go` before crossing
115
+ application/adapter boundaries.
116
+ - Do not define layered business errors and then translate them later. Repos,
117
+ adapters, ports, services, and handlers should use `errno.New`,
118
+ `errno.NewWithMessage`, `errno.WrapWithMessage`, or `errno.Ensure` when they
119
+ own stable business semantics.
120
+ - Prefer converting raw errors at the lowest boundary where the semantics are
121
+ known. Log exactly once at that same boundary when a logger is available, then
122
+ return the `BizError`. If the lowest repo/helper has no logger, it can still
123
+ return an `errno.BizError`; the first owning service/adapter with a logger logs
124
+ it once.
125
+ - Upper layers that receive an existing `BizError` should return it unchanged
126
+ unless they are intentionally changing business classification. Avoid wrapping
127
+ an already-classified `BizError` only to add context.
128
+ - Go-native `fmt.Errorf("...: %w")` wrapping is acceptable for internal
129
+ control-flow errors, retry markers, redelivery / poison decisions, protocol
130
+ control errors, and debugging context where no stable business code is owned
131
+ yet. Debugging context means internal logs, audit fields, run metadata, and
132
+ similar internal carriers; it must not bypass `BizError` / generic-copy
133
+ boundaries at HTTP/TOP or user-visible payload exits.
134
+ - Upper layers branch with `errno.IsCode(err, code)` / `errno.CodeOf(err)`;
135
+ never with `errors.Is(err, domain.ErrXxx)` for business semantics.
136
+ - Use existing semantic codes first: `InvalidArgument`, `NotFound`, `Conflict`, module NotFound / Publisher / WebChat codes. Use broad infrastructure codes only when no domain code fits:
137
+ - `PersistenceError` for database / repository non-business failures.
138
+ - `RedisDependencyError` for Redis, Redis Streams, session lease / presence failures.
139
+ - `ModelDependencyError` for AIGW / LLM / model service failures.
140
+ - `ObjectStorageDependencyError` for artifact / object storage failures.
141
+ - `SkillHubDependencyError` for Ark Skill Hub failures.
142
+ - `ExecutionLaneDependencyError` for run dispatch lane failures.
143
+ - `FileDependencyError` for filesystem failures.
144
+ - `ChannelDependencyError` for Feishu / WeCom channel platform failures.
145
+ - `ExternalDependencyError` only as a temporary fallback for dependencies that are not yet split.
146
+ - `RuntimeProviderError` for runtime executor/controller/provider failures.
147
+ - `ConfigurationError` for runtime config missing/invalid.
148
+ - `SerializationError` for JSON/protobuf/thrift/event payload encode/decode failures.
149
+ - Prefer `errno.Ensure(code, err)` at migration boundaries: it preserves an existing `BizError` and wraps only raw errors.
150
+ - Prefer `errno.Log(ctx, log, msg, err, fields...)` for classified failures so logs carry consistent `error_code` / `biz_code` fields.
151
+ - HTTP/TOP exits must not rewrite existing `BizError`; they return `BizError.Message`, or the code default message when empty. Non-`BizError` exits fall back to `InternalError`.
152
+ - User-visible text must not expose raw dependency/provider/network error strings. Surface product-reviewed `BizError.Message` when available; otherwise use generic copy and keep the raw cause in logs or internal audit fields.
153
+
154
+ ### `application/port/`
155
+ Secondary ports for external capabilities that are NOT persistence. Current inventory:
156
+
157
+ | File | Interface | Used by |
158
+ |------|-----------|---------|
159
+ | `event_bus.go` | `Bus (+ Publisher, Subscriber)` | domain event fan-out |
160
+ | `event_publisher.go` | `EventPublisher` | one-way event emission (decoupled from bus impl) |
161
+ | `execution_lane.go` | `ExecutionLane` | run dispatch lane (locallane / redislane) |
162
+ | `message_bus.go` | `MessageBus` | inbound/outbound message transport |
163
+ | `message_reader.go` | `MessageReader` | read-side of the message bus |
164
+ | `transaction.go` | `TransactionManager` | application service transaction boundary |
165
+ | `artifact_server.go` | `ArtifactServer` | Artifact storage backed by UP SDK |
166
+ | `aigw.go` | `AIGWProvider` | AIGW model gateway access |
167
+ | `llm.go` | `LLM` | LLM invocation |
168
+ | `session_lease.go` | `SessionLease` | session lease (Redis-backed) |
169
+ | `trace_store.go` | `TraceStore` | run trace persistence |
170
+ | `user_resolver.go` | `UserResolver` | resolve identity from request context |
171
+ | `ark_skill_hub.go` | `ArkSkillHub` | Ark Skill Hub access |
172
+ | `channel.go` | `ChannelInterface (+ StreamingChannel, WebhookChannel, BlockReplyChannel, GroupMemberProvider)` | gateway channel manager + feishu/wecom channel adapters |
173
+ | `clawsentry.go` | `ClawSentry (+ ClawSentryFactory)` | security ClawSentry provisioner (OpenTOP API, per-agent credentials) |
174
+ | `cron_event_publisher.go` | `CronEventPublisher` | agent + task services (cron-triggered event emission) |
175
+ | `hiagent_up.go` | `HiAgentUPUploader` | evolution service (HiAgent UP artifact upload) |
176
+ | `mcp.go` | `MCPConnectionTester` | mcp service (test MCP server connectivity) |
177
+ | `metrics.go` | `Metrics (+ NoopMetrics)` | observability counters/histograms across worker, message buses, repos |
178
+ | `presence.go` | `PresenceWriter`, `PresenceReader` | worker presence maintainer + agent ownership lookup (ADR 0018) |
179
+ | `session_key_locker.go` | `SessionKeyLocker (+ NoopSessionKeyLocker)` | session service cross-replica session-key uniqueness (ADR 0069) |
180
+ | `user_password_verifier.go` | `UserPasswordVerifier` | runtime API key handler + IAM adapter |
181
+ | `workspace_spec.go` | `SpecCatalog` | env service + gateway spec resolution (ADR 0057) |
182
+
183
+ Conventions:
184
+ - Each interface file has `//go:generate go run go.uber.org/mock/mockgen ...` at the top.
185
+ - Mocks land in `application/port/mocks/`. Run `make generate` after adding a new interface.
186
+ - Helper-only files live alongside ports so callers don't reach into adapters.
187
+ - Helper / type-only files in this directory carry no port interface (so no
188
+ mockgen): `channel_health.go` (shared `ChannelHealth` snapshot types +
189
+ `ClassifyChannelError` for the `channels.status` surface), `retryable.go`
190
+ (`Retryable` / `IsRetryable` markers tagging transient `ExecutionLane`
191
+ failures for redelivery), and `wakeup.go` (`Wakeup` signal type that nudges a
192
+ worker to drain a session's durable inbox — L2 ordering).
193
+ - This directory holds **infrastructure capability ports only**. Cross-context
194
+ consumer ports live with the consumer context (see below).
195
+
196
+ #### Cross-Context Consumer Ports (ADR 0058)
197
+
198
+ When context A consumes context B's application service in-process (e.g.
199
+ evolution → agent/message/skill), the port and its anti-corruption adapter are
200
+ **consumer-owned** and live under the consumer:
201
+
202
+ ```
203
+ application/<consumer>/port/ ← narrow interfaces + consumer-vocabulary types; mockgen → port/mocks/
204
+ application/<consumer>/acl/ ← ACL adapters wrapping B's application service (forwarding + DTO→port mapping only)
205
+ ```
206
+
207
+ Rules:
208
+ - `acl/` is the only package in the consumer subtree allowed to import other
209
+ contexts' application packages; business files depend on `<consumer>/port`
210
+ interfaces only.
211
+ - No Go `internal/` segment on `acl/` — bootstrap must import it for wiring.
212
+ - Never inject another context's `Service` interface or domain repository
213
+ directly across a context boundary; never bypass B's service to write its
214
+ repositories.
215
+ - Canonical example: `application/evolution/{port,acl}` wired in
216
+ `bootstrap/evoworker`.
217
+
218
+ #### Artifact Skill Storage
219
+
220
+ `port.ArtifactServer` is backed by the UP SDK. Skill artifacts are addressed by UP object ID / sha256, not by S3-style paths. Runtime workspace sync resolves enabled `agent_skills` bindings to presigned artifact download URLs and lets runtime init-container / hot-sync Job download zip packages directly into the agent PVC.
221
+
222
+ Canonical example — `application/agent/workspace_sync.go`:
223
+ ```go
224
+ type WorkspaceSyncDeps struct {
225
+ SkillStore port.ArtifactServer
226
+ }
227
+ ```
228
+
229
+ The factory that wires the right provider per binary is shared: `internal/bootstrap/app/storage.go`. Both server and worker call into it; do **not** re-derive provider selection logic in `bootstrap/server/module.go` or `bootstrap/worker/registry.go`.
230
+
231
+ ### `adapters/outbound/<name>/`
232
+ Implements one or more domain/port interfaces.
233
+ - RDB repos: `adapters/outbound/persistence/rdb/repository/<aggregate>_repository.go`
234
+ - Repository test doubles belong in test packages or generated domain mocks, not under `adapters/outbound/persistence/`
235
+ - Runtime provider adapter details live in `coding-runtime-adapter`.
236
+ - Port impls: `adapters/outbound/<capability>/` (e.g. `artifact/`, `aigw/`, `arkskillhub/`)
237
+
238
+ RDB repository transaction rule:
239
+ - Repositories do not open, commit, roll back, or branch on transactions. All
240
+ SQL transaction boundaries belong in application services/use cases through
241
+ `port.TransactionManager`.
242
+ - Main rdb repositories use one DB/context entrypoint: `rdb.DB(ctx, r.db)` or a
243
+ local `conn(ctx)` wrapper that delegates to it. Do not expose secondary
244
+ public helpers for transaction-aware DB selection.
245
+ - Repository methods that require an existing transaction because they use row
246
+ locks or multi-statement read-modify-write must call
247
+ `rdb.RequireTransaction(ctx)` and use the returned DB handle.
248
+ - Any rdb repository / PO / mapper / constructor change must run
249
+ `make check-repository-transactions`; see `coding-db-schema` and
250
+ `coding-testing` Strategy 5.
251
+
252
+ #### Redis Deployment Compatibility
253
+
254
+ Every Redis-backed adapter must support all configured Redis modes: `single`,
255
+ `sentinel`, and `cluster`. Sentinel command semantics are single-primary, but
256
+ Cluster enforces hash-slot rules.
257
+
258
+ - Multi-key commands, transactions, and Lua scripts must keep all keys in the
259
+ same slot with an explicit hash tag, e.g. `lease:session:{sessionID}` and
260
+ `lease:session:{sessionID}:gen`.
261
+ - Lua scripts must receive every Redis key through `KEYS`; do not build hidden
262
+ Redis key names inside the script body.
263
+ - Pipelines may batch independent single-key operations, but must not assume
264
+ cross-key atomicity unless the keys share a hash tag and the command itself is
265
+ Cluster-safe.
266
+ - Redis Streams commands should operate on one stream key per command. If a new
267
+ operation needs multiple streams/keys in one Redis command, add a shared hash
268
+ tag or redesign the operation.
269
+ - Use `pkg/platform/redis` only for shared Redis invariants, not as a blanket
270
+ wrapper around go-redis:
271
+ - `Tagged(prefix, tag, suffix...)` for newly constructed hash-tagged keys when
272
+ invalid identity data should fail before Redis is called.
273
+ - `AssertSameSlot` for logical multi-key operations.
274
+ - `NewScript` for Lua scripts that should fail fast on cross-slot `KEYS`.
275
+ - `Tagged` is strict by design: callers must handle `(string, error)` and must
276
+ not trim, normalize, hash, strip braces, or silently replace invalid tags.
277
+ Existing legacy key formats may stay local when changing them would split
278
+ locks, leases, channels, or live data during rolling upgrades; document that
279
+ compatibility reason near the helper.
280
+ - Keep adapters close to `github.com/redis/go-redis/v9`. Direct go-redis imports
281
+ are fine; do not add platform-level type aliases or thin wrappers unless they
282
+ enforce a real shared invariant.
283
+ - When adding or materially changing Redis Streams consumer logic, first check
284
+ whether it should share infrastructure with eventbus/messagebus. Do not copy
285
+ claim, retry, dead-letter, consumer group, or ordered-lane machinery into a
286
+ third implementation without an explicit reason.
287
+ - Tests must assert cluster-safe key naming for Lua or any logical operation
288
+ that touches more than one Redis key.
289
+ - Redis-backed code changes must also compile all integration tests and run the
290
+ corresponding `tests/integration/redis_*` coverage against real Redis
291
+ testcontainers; see `coding-testing` Strategy 3 and Strategy 5.
292
+
293
+ #### Persistence Implementation Rule
294
+
295
+ `persistence/rdb` is the canonical implementation of domain repository contracts. Do not add a second repository implementation under `internal/adapters/outbound/persistence/` for local mode or unit tests.
296
+
297
+ Minimum bar:
298
+ - New persisted aggregates implement the domain repository contract in `internal/adapters/outbound/persistence/rdb/repository/`.
299
+ - RDB repository behavior is proved by integration coverage under `tests/integration/`.
300
+ - Application unit tests use generated domain mocks or narrow same-package fakes for pure service validation. Use package-local RDB / sqlite fixtures only when the application workflow materially depends on persistence semantics such as transaction boundaries, SQL ordering/filtering, uniqueness, or cross-repository state. Do not add reusable persistence adapters or a shared application-level RDB testutil just for convenience.
301
+ - Local / all-in-one runtime modes may use in-process buses and lanes, but still use the normal database for persistence.
302
+
303
+ ### `bootstrap/<binary>/`
304
+ - **All binaries use `go.uber.org/fx`.** Each `bootstrap/<binary>/module.go` declares a root `var Module = fx.Module(...)` composed of sub-modules; `Build()` builds the graph via `fx.New(...)`, calls `Start`, and returns an `app.Hook` wrapping `Stop`. `provide*` functions return typed **interfaces**, not structs. The fx event logger is shared via `app.NewFxLogger`.
305
+ - **coding-worker** has a local/distributed transport split: `LocalInfraModule` uses RDB repositories with in-process buses/lanes, while `DistributedInfraModule` uses RDB repositories with Redis buses/lanes. The split is picked at build time based on `cfg.Worker.Mode`. `ProvideProviderRegistry(...)` (in `registry.go`) is wrapped by an fx provider that binds the InstanceWatcher context to the fx Lifecycle; it stays directly callable from `registry_test.go`.
306
+ - **coding-cli** wraps each cobra subcommand invocation in a per-process `fx.App` so config + logger (and any future deps) live on the same DI graph as the long-running services.
307
+ - All binaries use `app.Runtime[C]` from `bootstrap/app/`. Config embeds `app.BaseConfig` by **value** (not pointer). Implement `app.Validator` for semantic validation.
308
+
309
+
310
+ ## Adding a New Aggregate Checklist
311
+
312
+ - [ ] `domain/<agg>/entity.go` — aggregate root, no framework
313
+ - [ ] `domain/<agg>/repository.go` — persistence interface
314
+ - [ ] Use `domain/shared.DomainError` for domain-local errors; map to
315
+ `pkg/platform/errno` at application/adapter boundaries; do not add
316
+ `domain/<agg>/errors.go`
317
+ - [ ] `adapters/outbound/persistence/rdb/po/<agg>.go` — GORM model, if this aggregate is persisted in SQL
318
+ - [ ] `adapters/outbound/persistence/rdb/repository/<agg>_repository.go` — GORM impl
319
+ - [ ] `tests/integration/<agg>_repository_test.go` — persisted behavior across supported DBs
320
+ - [ ] `application/<agg>/service.go` — `Service` interface + `ServiceDeps` + `NewService`
321
+ - [ ] `application/<agg>/dto.go` + `mapper.go`
322
+ - [ ] `adapters/inbound/http/handlers/<agg>_handler.go` — Hertz handler
323
+ - [ ] `bootstrap/server/module.go` — add `provide<Agg>Repository` + `provide<Agg>Service` + `provide<Agg>Handler` to `Module`
324
+
325
+
326
+ ## Adding a New Port Checklist
327
+
328
+ - [ ] Define interface in `application/port/<capability>.go`
329
+ - [ ] Add `//go:generate mockgen` directive; run `go generate ./internal/application/port/...`
330
+ - [ ] Implement in `adapters/outbound/<capability>/<impl>/`
331
+ - [ ] Wire in `bootstrap/server/module.go` with a `provide<Capability>` function
332
+
333
+ For a **cross-context consumer port** (context A calling context B's
334
+ application service), use `application/<consumer>/port/` +
335
+ `application/<consumer>/acl/` instead — see "Cross-Context Consumer Ports"
336
+ above (ADR 0058).
337
+
338
+
339
+ ## Key Types Quick Reference
340
+
341
+ | Symbol | Package | Purpose |
342
+ |--------|---------|---------|
343
+ | `shared.TenantID` | `domain/shared` | Tenant identifier (string alias) |
344
+ | `shared.AgentID` | `domain/shared` | Agent identifier (uuid.UUID alias) |
345
+ | `app.Runtime[C]` | `bootstrap/app` | Entry point for all binaries |
346
+ | `app.Component` | `bootstrap/app` | `Run(ctx) error` + `Shutdown(ctx) error` |
347
+ | `app.BaseConfig` | `bootstrap/app` | Embed by value in every service `Config` |
@@ -0,0 +1,95 @@
1
+ ---
2
+ name: coding-code-review
3
+ description: General-purpose diff-based code review orchestration for clean canonical diff generation, reviewer dispatch, and report consolidation without re-reviewing code.
4
+ ---
5
+
6
+ # coding-code-review
7
+
8
+ This file is only the orchestration layer. Keep the hot path short: prepare `code-review/`, generate the branch diff, canonicalize it, dispatch scoped reviewer subagents, then consolidate existing reviewer reports.
9
+
10
+ ## Default Entry
11
+
12
+ Direct `/coding-code-review` runs a branch pre-MR review.
13
+
14
+ Default input is the committed branch delta:
15
+
16
+ - base: `origin/release`
17
+ - scope: `merge-base(origin/release, HEAD)..HEAD`
18
+ - worktree requirement: clean
19
+ - artifacts:
20
+ - raw diff: `./code-review/raw-diff.txt`
21
+ - canonical diff: `./code-review/diff.txt`
22
+ - reviewer reports:
23
+ - `./code-review/correctness-code-review-report.md`
24
+ - `./code-review/architecture-code-review-report.md`
25
+ - `./code-review/compatibility-ops-code-review-report.md`
26
+ - `./code-review/test-code-review-report.md`
27
+ - final report: `./code-review/final-code-review-report.md`
28
+
29
+ If the worktree has staged, unstaged, or untracked changes, `get-diff.sh` fails. Stop immediately. Do not auto-commit, stash, restore, clean, switch to `git diff`, or reuse old `code-review/` artifacts.
30
+
31
+ ## Workflow
32
+
33
+ ### 1. Prepare Diff
34
+
35
+ Do not read old reports or inspect source before this step. Start by replacing the old `code-review/` directory and running the helper scripts:
36
+
37
+ ```bash
38
+ rm -rf code-review
39
+ mkdir -p code-review
40
+ bash .agents/skills/coding-code-review/scripts/get-diff.sh --base-ref origin/release --output code-review/raw-diff.txt &&
41
+ cp code-review/raw-diff.txt code-review/diff.txt &&
42
+ bash .agents/skills/coding-code-review/scripts/canonical-diff.sh code-review/diff.txt
43
+ ```
44
+
45
+ If `get-diff.sh` exits non-zero, stop. Do not continue to reviewer dispatch or final consolidation.
46
+
47
+ If `raw-diff.txt` is empty, write `No changes to review` to `final-code-review-report.md` and stop. If `diff.txt` becomes empty after canonicalization, write `No reviewable changes after canonicalization` to `final-code-review-report.md` and stop.
48
+
49
+ ### 2. Dispatch Reviewers
50
+
51
+ Load `references/reviewer-profiles.md` before dispatching reviewers. Reviewer identity is a review scope, not a model choice. Use these default reviewer profiles:
52
+
53
+ - `correctness-code-reviewer`
54
+ - `architecture-code-reviewer`
55
+ - `compatibility-ops-code-reviewer`
56
+ - `test-code-reviewer`
57
+
58
+ Each scoped reviewer must focus on its assigned profile. Cross-scope findings are allowed only when needed to explain impact; otherwise mark unrelated dimensions as `N/A` or briefly defer to the responsible reviewer.
59
+
60
+ For CLI environments with subagents:
61
+
62
+ 1. Dispatch every default reviewer profile in parallel against `./code-review/diff.txt`, then wait for all available reviewer reports or timeouts.
63
+ 2. Each reviewer must write only its own scoped report file listed above.
64
+ 3. Each reviewer report must be written in Chinese. Keep fixed severity labels (`[Critical]` / `[Major]` / `[Minor]` / `[Suggestion]`) and check status values (`PASS` / `RISK` / `N/A`) unchanged.
65
+ 4. Each reviewer has a 3 minute limit.
66
+
67
+ For coco / Trae CLI:
68
+
69
+ - List `.coco/agents/*-code-reviewer.md`; these files are tool-specific wrappers for the same reviewer profiles.
70
+ - Do not dispatch reviewer agents named by model provider. Model selection belongs to the tool wrapper, not to reviewer identity.
71
+
72
+ For Codex:
73
+
74
+ - Use the project-scoped custom agents in `.codex/agents/*-code-reviewer.toml`.
75
+ - Spawn the same default reviewer profiles in parallel, wait for all reviewer reports, then consolidate them.
76
+ - Codex reviewer agents inherit the parent sandbox so they can write their own report artifact. They must not edit repository source files.
77
+
78
+ For Claude Code:
79
+
80
+ - Use the project-scoped custom agents in `.claude/agents/*-code-reviewer.md`.
81
+ - Spawn the same default reviewer profiles in parallel, wait for all reviewer reports, then consolidate them.
82
+ - Claude reviewer agents should use only read/search tools plus `Write` for their own report artifact. They must not edit repository source files.
83
+
84
+ For CLI environments without subagents:
85
+
86
+ - Load `references/reviewer-guidelines.md` and run one single-model review using the same artifact paths and output format.
87
+
88
+ ### 3. Consolidate Reports
89
+
90
+ Only after reviewer reports exist, load `references/final-consolidation.md`.
91
+
92
+ Final consolidation merges existing reviewer reports. It is not a new review pass. Do not re-read source, re-check the diff, search for new issues, or add findings not present in reviewer reports.
93
+
94
+ Write the final report to `./code-review/final-code-review-report.md`.
95
+ The final report must be written in Chinese, except for fixed severity labels and check status values.
@@ -0,0 +1,163 @@
1
+ ---
2
+ name: coding-cve-remediation
3
+ description: 处理 coding_engine 的 Codebase 镜像漏洞扫描结果。适用于查看 scan-image-* 镜像扫描 job、读取 image-scanner 报告、分类 CVE,并只修复 coding-engine、coding-inner-mcp-sidecar、coding-collector 中可由 Go 依赖升级解决的漏洞;OS/base image 漏洞只报告为范围外。
4
+ ---
5
+
6
+ # coding-cve-remediation:镜像 CVE 修复
7
+
8
+ 当 coding_engine MR 中的 Codebase `scan-image-*` 镜像扫描 job 报告漏洞时使用本 skill。
9
+
10
+ ## CI 凭证
11
+
12
+ CVE 报告读取只需要本 skill 自己的 `IMAGE_SCANNER_TOKEN`,作为 HTTP header `Image-Scanner-Token`。
13
+ `bytedcli` / `codebase` 的 CI bot 凭证按仓库通用 Codebase 自动化约定配置,不在本 skill 中重复展开。
14
+
15
+ ## 范围
16
+
17
+ 只处理评分 `>= 7` 的漏洞。
18
+
19
+ 范围内:
20
+
21
+ - 根模块、collector build manifest 中的 Go module 漏洞。
22
+
23
+ 范围外:
24
+
25
+ - OS package、Debian/apt、发行版包、静态 base image 漏洞。
26
+ - Dockerfile base image tag 修改。
27
+ - 共享 base image 重建。
28
+
29
+ 如果评分 `>= 7` 的漏洞全部是 OS/base-image 类漏洞,输出:
30
+
31
+ ```text
32
+ 当前无可由 Go 依赖修复的 CVE
33
+ ```
34
+
35
+ 此时关闭第一步创建的 CVE 自动扫描 MR,不保留空 MR。
36
+
37
+ 除非用户另行明确要求,不要修改 Dockerfile 或 base image tag。
38
+
39
+ ## 创建扫描 MR
40
+
41
+ 先创建一个空的 CVE 修复 MR,用于触发 image build / scan-image 流水线:
42
+
43
+ ```bash
44
+ bash scripts/cve-remediation-open-mr.sh
45
+ ```
46
+
47
+ 脚本会从 `origin/release` 创建唯一 bot 分支,并写入 `cve-remediation-mr.md`。后续修复必须继续推到这个 bot 分支对应的同一个 MR,不要另开第二个 MR。
48
+
49
+ ## 收集扫描报告
50
+
51
+ 1. 从 `cve-remediation-mr.md` 或 Codebase 响应中拿到 MR 号和 bot 分支。
52
+
53
+ 2. 查询 MR 状态和 checks:
54
+
55
+ ```bash
56
+ bytedcli --json codebase mr status <mr>
57
+ bytedcli --json codebase checks list --branch <branch> --mr <mr>
58
+ ```
59
+
60
+ 3. 定位三个扫描 job。
61
+ - `scan-image-coding-engine`
62
+ - `scan-image-coding-inner-mcp-sidecar`
63
+ - `scan-image-coding-collector`
64
+ - 自动等待目标扫描 job 完成;不要要求用户手工确认。
65
+ - 如果它依赖的 image build job 失败,报告对应镜像构建失败并停止处理该镜像。
66
+ - 从每个扫描 job 的输出 URL 中提取 `group_id`,URL 形态通常为 `.../task_center/report/<group_id>?original=1&fixed_version=0`。
67
+
68
+ 4. 拉取并汇总 image-scanner 报告:
69
+
70
+ ```bash
71
+ python3 .agents/skills/coding-cve-remediation/scripts/image_scanner_report.py <group_id> --summary
72
+ ```
73
+
74
+ CI 使用 `IMAGE_SCANNER_TOKEN`。本地调试仍兼容 `~/.config/image-scanner/token`。
75
+
76
+ ## 镜像到模块的映射
77
+
78
+ 固定使用以下修复映射:
79
+
80
+ | 镜像 | 修复目标 |
81
+ |---|---|
82
+ | `coding-engine` | 根目录 `go.mod` |
83
+ | `coding-inner-mcp-sidecar` | 根目录 `go.mod` |
84
+ | `coding-collector` | `configs/otelcol-build-config.yaml` |
85
+
86
+ 对于 `coding-collector`,不要直接手改生成的 `coding-otelcol/go.mod`。
87
+
88
+ ## 修复 Go 依赖
89
+
90
+ 根模块:
91
+
92
+ 1. 从报告中确认漏洞涉及的模块和 fixed version,只升级相关模块。
93
+ 2. 在对应模块目录运行:
94
+
95
+ ```bash
96
+ go get <module>@<fixed_version>
97
+ go mod tidy
98
+ ```
99
+
100
+ Collector:
101
+
102
+ 1. 在 `configs/otelcol-build-config.yaml` 中升级直接 collector component 版本。
103
+ 2. 如果传递依赖必须强制到 fixed version,在 manifest 的 `replaces` 中增加覆盖。
104
+ 3. 重新生成 collector:
105
+
106
+ ```bash
107
+ make gen-collector
108
+ ```
109
+
110
+ ## 更新同一个 MR
111
+
112
+ 完成依赖修复和本地验证后,把修复 diff 推回第一步创建的 bot 分支:
113
+
114
+ ```bash
115
+ bash scripts/cve-remediation-open-mr.sh --branch <bot/cve-remediation-...>
116
+ ```
117
+
118
+ 如果扫描后确认没有需要提交的 Go 依赖或 collector manifest 修复,也运行同一命令;脚本会关闭这个无需修复的 MR。不要重新创建新的 CVE 修复 MR。
119
+
120
+ ## 验证
121
+
122
+ 按变更面运行最窄必要检查:
123
+
124
+ | 变更面 | 必跑检查 |
125
+ |---|---|
126
+ | 只改 CI YAML / skill | `make lint-yaml`、`make check-skills` |
127
+ | 根目录 `go.mod` / `go.sum` | `make test` |
128
+ | collector manifest | `make gen-collector`、`make build-collector` |
129
+
130
+ 运行 `make regen-agent-md` 后,确认 worktree 只有预期文件变化。
131
+
132
+ ## 自动提交 MR 脚本
133
+
134
+ CI 场景使用 bot 提交 MR,不使用人类 credential,不运行 `bytedcli auth status`,也不走 `make open-mr`。
135
+
136
+ 第一次运行用于创建空提交 MR 并触发扫描;带 `--branch <bot/cve-remediation-...>` 再次运行用于更新同一个 MR。
137
+
138
+ 该脚本复用 `scripts/lib/codebase-mr-bot.sh`,行为边界:
139
+
140
+ - 从 `origin/release` 创建唯一 bot 分支。
141
+ - 只允许提交 CVE Go 依赖修复相关文件:根 `go.mod` / `go.sum`、`configs/otelcol-build-config.yaml`、`coding-otelcol` 生成的 Go module / Go 文件。
142
+ - 用 Codebase bot 身份执行 `codebase mr create`,不检查人类登录态。
143
+ - 有修复 diff 时提交修复;没有修复 diff 时提交空 commit 触发首次 scan-image。
144
+ - `--branch` 且没有修复 diff 时关闭同一个 MR。
145
+ - 后处理失败应写入 `cve-remediation-mr.md` 并报告,不要求人工介入。
146
+ - Git author 固定为 `coding-cve-remediation-bot <coding-cve-remediation-bot@bytedance.com>`。
147
+
148
+ 推送后的 CI 验证:
149
+
150
+ - 确认三个 image build job 都成功。
151
+ - 确认三个 `scan-image-*` job 分别在对应 image build job 之后运行,且彼此不互相依赖。
152
+ - 确认扫描报告中不再包含评分 `>= 7` 的 Go 依赖漏洞。
153
+
154
+ ## 最终输出
155
+
156
+ 最终只报告:
157
+
158
+ - 评分 `>= 7` 的漏洞。
159
+ - 分类:Go 依赖 / OS-base image / 未分类。
160
+ - 修改过的文件。
161
+ - 已执行的依赖升级。
162
+ - 验证命令和结果。
163
+ - 剩余阻塞项。