45 Commits

Author SHA1 Message Date
17782d5f8e 实现七月迭代公共技术基础
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m20s
2026-07-23 17:52:48 +09:00
f7c42252c0 补齐UR46后端验收测试
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 10m55s
2026-07-23 16:15:02 +09:00
cde5369b30 完成UR46后端任务收口 2026-07-23 15:09:24 +09:00
8d65b26e96 实现资产预计最终到期时间 2026-07-23 13:14:43 +09:00
5dacef57fa ur98 issues 2026-07-23 13:11:21 +09:00
3e42e70309 ur49issues修正 2026-07-23 13:03:30 +09:00
148083a405 ur49修正 2026-07-23 13:03:22 +09:00
9a44139d7a 完成UR55全部任务标记 2026-07-23 12:52:00 +09:00
b741d8af66 ur49 issues创建 2026-07-23 12:51:52 +09:00
59f920bea2 补充UR55后端测试完成标记 2026-07-23 12:50:19 +09:00
5af303df54 更新UR55已完成后端任务标记 2026-07-23 12:48:02 +09:00
9eb49654f2 ur48issues 2026-07-23 12:46:13 +09:00
f8aa0933a5 标记UR55同步购买快照任务完成 2026-07-23 12:46:01 +09:00
b2efe3bac8 ur47issues创建
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 11m35s
2026-07-23 12:29:33 +09:00
992757c056 修复套餐快照集成测试与自动购包幂等 2026-07-23 12:23:52 +09:00
2df44d8e3c ur43 issues创建 2026-07-23 12:20:41 +09:00
d5a35f6360 新增测试代码规范、修复响应体断言缺失与魔法数字
- AGENTS.md 新增测试代码专项规范:常量、fixture、触发器、HTTP断言、层边界说明
- TestUpdateAllocationExpiryBaseHTTP 补全 PATCH 响应体字段断言
- 四个集成测试文件以 testIDMask 局部常量替换 0x7fffffff 魔法数字

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 11:35:38 +09:00
4aaae07cee 修复错误消息含英文字段名:生效条件覆盖校验改为纯中文描述
AGENTS.md 要求用户可见的错误消息必须使用中文

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 11:23:13 +09:00
8dde55ea6d 修复 code review 问题:提取重复函数、补全缺失测试用例
- 提取 ResolveTermsFromTx 到 service/package,消除 order 和 auto_purchase 中的重复实现
- 补全 domain 测试:新增 from_activation 覆盖用例,现覆盖两种覆盖值
- 补全激活集成测试:新增 from_purchase 立即激活场景、历史记录兼容回退计数器验证
- 补全自动购包集成测试:新增购买后修改套餐配置不影响已有快照的验证

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 11:18:38 +09:00
147f3eb775 修复 UR#55 代码审查问题:事务隔离、错误包装、重复辅助函数
- resolvePackageTerms 接受 tx 参数并使用事务绑定的 Store,确保快照与写入同库
- auto_purchase.go 错误包装改用 pkgerrors.Wrap 而非标准库 errors
- shop_package_batch_allocation 去除 fmt 依赖改用 strconv 拼接
- shop_series_grant 提取 effectiveBase 局部变量避免重复调用
- 测试辅助函数统一迁移至 testutil.StringPointer,删除各文件本地重复定义
- 新增 testutil.NewRedisClient 和 testutil.StringPointer

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 11:09:08 +09:00
f7e0f07692 修复 code review 问题:DTO 内部字段、错误消息、重复代码与测试覆盖
- 删除 ExpiryBaseOverrideSet 字段的 description 标签(json:"-" 内部字段不进文档)
- ValidateExpiryBaseOverride 两处 CodeInvalidParam 补充中文错误消息
- 提取 initPackageExpiryBaseFields 消除 toResponse/toResponseWithAllocation 中的重复初始化
- 删除 order/service.go 中"行业卡永远直接激活"过时注释
- 补充 T01 系列授权 HTTP 集成测试(Create + ManagePackages 两个入口)
- 补充 T03 C 端购买和平台代购(无分配)快照集成测试
- 补充 T04 from_purchase 默认值、卡未实名仍立即激活的自动购包测试
- 新增 testutil.NewRedisClient 供激活接续测试使用

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 10:56:46 +09:00
9818537239 实现套餐生效条件覆盖与购买快照 2026-07-22 21:07:08 +09:00
c7f8b4c702 批量换货脚本
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m26s
2026-07-22 19:09:28 +09:00
c58773e35b 实现资产双向换货链路查询 2026-07-22 18:05:38 +09:00
7c8a4cd328 ur40issues 2026-07-22 17:49:25 +09:00
a278a80b34 ur38 issues 2026-07-22 17:25:12 +09:00
031a875ec1 ur36issues 2026-07-22 17:25:05 +09:00
86c38d46c5 ur37 issues 2026-07-22 16:58:26 +09:00
208cb19f0e ur94 issues
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m52s
2026-07-22 16:44:01 +09:00
55bdc3a8d0 实现换货资产快照与新旧独立搜索 2026-07-22 16:37:08 +09:00
785907ce85 全局通知issues 2026-07-22 16:14:59 +09:00
39cdbdcfef ur96 issues创建 2026-07-22 16:12:28 +09:00
cf5dcd28ea 全局审计相关issues 2026-07-22 15:58:28 +09:00
ce69679b21 issues提交 2026-07-22 15:43:18 +09:00
43bcb0e4ae 测试环境自动部署
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 11m35s
2026-07-22 15:18:56 +09:00
2fd11daaf0 实现店铺联系电话精确查询与索引 2026-07-22 15:06:06 +09:00
751cb46079 修复店铺列表参数校验与企业权限 2026-07-22 13:13:38 +09:00
d4d6e91256 本地测试应该走7的db 2026-07-22 13:04:17 +09:00
696d272cb5 一些规则 2026-07-22 12:48:21 +09:00
21702da413 创建相关issues 2026-07-22 12:37:05 +09:00
841ed1ceb0 同步相关内容 2026-07-22 11:34:20 +09:00
da9c805d89 更新一下prd 2026-07-22 11:08:04 +09:00
4902a02c87 更新一下 2026-07-21 15:26:07 +09:00
2823ff13bf fix: 修正排队顺延套餐激活时错误按下单时间计算生效日期
activatePendingUsage 被"前一个主套餐到期后顺延激活下一个待生效套餐"和
"等待实名认证后激活"两种场景共用,但其中 ExpiryBase=from_purchase 计时
基准分支(REALNAME-04)本来只为后者设计,却被无差别套用到前者。

导致主套餐配置为 from_purchase 且需要排队等待前一个套餐到期才能生效的
套餐,激活时错误地把生效时间算成下单时间,而不是真正开始生效的那一刻,
使到期时间提前了排队等待的天数,客户少享受了相应天数的服务。

现改为只有当 usage.PendingRealnameActivation 为 true(确实是在等实名)
时才按 ExpiryBase 选择计时基准,纯排队顺延场景一律使用当前时刻,即顺延
语义。
2026-07-20 11:58:01 +09:00
19767c4284 更新skill 2026-07-20 10:56:26 +09:00
387 changed files with 23886 additions and 1242 deletions

View File

@@ -0,0 +1,78 @@
---
name: ask-matt
description: Ask which skill or flow fits your situation. A router over the skills in this repo.
disable-model-invocation: true
---
# Ask Matt
You don't remember every skill, so ask.
A **flow** is a path through the skills. Most paths run along one **main flow**, and two **on-ramps** merge onto it. Everything else is standalone, or a vocabulary layer that runs underneath.
## The main flow: idea → ship
The route most work travels. You have an idea and want it built.
1. **`/grill-with-docs`** — sharpen the idea by interview. Start here when you **have a codebase**: it's stateful, retaining what it learns in `CONTEXT.md` and ADRs. (No codebase? Use `/grill-me` — see Standalone. Both run the same `/grilling` primitive; `grill-with-docs` is the one that leaves a paper trail.)
2. **Branch — can you settle every question in conversation?** If a question needs a runnable answer (state, business logic, a UI you have to see), detour through a prototype, bridged by **`/handoff`** in both directions (see Crossing sessions):
- **`/handoff`** out, then open a fresh session against that file,
- **`/prototype`** to answer the question with throwaway code,
- **`/handoff`** back what you learned, and reference it from the original idea thread.
3. **Branch — is this a multi-session build?**
- **Yes** → **`/to-spec`** (turn the thread into a spec), then **`/to-tickets`** to split it into tracer-bullet tickets, each declaring its **blocking edges**. On a local tracker that's one file per ticket under `.scratch/<feature>/issues/`, worked blockers-first by hand; on a real tracker the edges become native blocking links, so any ticket whose blockers are done can be grabbed — kick off **`/implement`** per ticket, **clearing context between each one**.
- **No** → **`/implement`** right here, in the same context window.
Either way, **`/implement`** builds each issue by driving **`/tdd`** internally — one red-green slice at a time — then closes out by running **`/code-review`**, a two-axis review (Standards + Spec) of the diff, before committing. Reach for **`/tdd`** on its own when you just want to build a concrete behaviour test-first without a full spec, and **`/code-review`** on its own whenever you want to review a branch or PR against a fixed point.
### Context hygiene
Keep steps 13 in **one unbroken context window** — don't compact or clear until after `/to-tickets` — so the grilling, spec, and tickets all build on the same thinking. Each `/implement` then starts fresh, working from the ticket.
The limit on this is the **[smart zone](https://www.aihero.dev/ai-coding-dictionary/smart-zone)**: the window (~120k tokens on state-of-the-art models) within which the model still reasons sharply. If a session approaches it before `/to-tickets`, don't push on degraded — `/handoff` and continue in a fresh thread.
## On-ramps
A starting situation that generates work, then merges onto the main flow.
- **Bugs and requests piling up** → **`/triage`**. It moves issues through triage roles and produces agent-ready issues, which **`/implement`** later picks up.
Triage is only for issues **you didn't create** — bug reports, incoming feature requests, anything that arrives raw. Tickets that `/to-tickets` produced are already agent-ready, so **don't triage them**.
- **Something's broken** → **`/diagnosing-bugs`**. For the hard ones: the bug that resists a first glance, the intermittent flake, the regression that crept in between two known-good states. It refuses to theorise until it has a **tight feedback loop** — one command that already goes red on *this* bug — then fixes with a regression test. Its post-mortem hands off to **`/improve-codebase-architecture`** when the real finding is that there's no good seam to lock the bug down.
- **A huge, foggy effort — a greenfield project or a huge feature build, too big for one session** → **`/wayfinder`**, the most cognitively demanding flow here. When the way from here to the destination isn't visible yet, it charts a **shared map** of **decision tickets** on the issue tracker and resolves them one at a time — producing **decisions, not deliverables** — until the fog is pushed back and the way is clear. Where **`/grill-with-docs`** sharpens an idea you can hold in one session, wayfinder is for the idea you can't — and it's slower and denser, so save it for exactly that, never a well-scoped feature.
When the map clears, **it hands off, it doesn't build**: merge onto the main flow at **`/to-spec`**, which collapses the map's linked decisions into a buildable plan, then `/to-tickets` and `/implement` as usual. Looping the map straight into `/implement` skips that collapse and throws the linked detail away — go straight to `/implement` only when the effort turned out genuinely small.
## Codebase health
Not feature work — upkeep.
- **`/improve-codebase-architecture`** — run whenever you have a spare moment to keep the codebase good for agents to operate in. It surfaces **deepening opportunities**; picking one _generates an idea_ you can take into the main flow at `/grill-with-docs`. It's the survey that finds the candidates; **`/codebase-design`** (below) is the bench you design the chosen one on.
## Vocabulary underneath
Two model-invoked references that run *beneath* the other skills — each the single source of truth for its vocabulary. Reach for them directly when the **words**, not the process, are the problem; or let the skills above pull them in.
- **`/domain-modeling`** — sharpen the project's *domain* language: challenge a fuzzy term, resolve an overloaded word ("account" doing three jobs), record a hard-to-reverse decision as an ADR. It's the active discipline `/grill-with-docs` drives to keep `CONTEXT.md` a clean glossary.
- **`/codebase-design`** — the deep-module vocabulary (module, interface, depth, seam, adapter, leverage, locality) for designing a module's *shape*: a lot of behaviour behind a small interface at a clean seam. `/tdd` and `/improve-codebase-architecture` both speak it.
## Crossing sessions
- **`/handoff`** — when a thread is full or you need to branch off (e.g. into a `/prototype` session), this compacts the conversation into a markdown file. You don't continue in place — you **open a new session and reference that file** to carry the context across. It's the bridge between context windows, in either direction. Use it when you want a **fresh session** but need the **current conversation preserved**.
- **`/compact`** (built-in) — stay in the **same conversation**, letting the earlier turns be summarized. Use it at **intentional breaks between phases**, when you don't mind losing the verbatim history. Don't compact mid-phase — the agent can lose its way. `/handoff` forks; `/compact` continues.
## Standalone
Off the main flow entirely.
- **`/grill-me`** — the same relentless interview as `/grill-with-docs`, but for when you have **no codebase**. Stateless: it saves nothing locally, builds no `CONTEXT.md`. Reach for it to sharpen any plan or design that doesn't live in a repo.
- **`/prototype`** — a small, throwaway program that answers one design question: does this state model feel right, or what should this UI look like. Throwaway from day one — keep the answer, delete the code. It's the detour in step 2 of the main flow, but reach for it any time a design question is hard to settle on paper.
- **`/research`** — delegate reading legwork to a **background agent**: it investigates a question against **primary sources**, then leaves a cited Markdown file in the repo. Keep working while it reads. The file it produces is something to take *into* the main flow at `/grill-with-docs` — research feeds the thinking, it doesn't replace it.
- **`/teach`** — learn a concept over multiple sessions, using the current directory as a stateful workspace.
- **`/writing-great-skills`** — reference for writing and editing skills well.
## Precondition
**`/setup-matt-pocock-skills`** — run before your first engineering flow to configure the issue tracker, triage labels, and doc layout the other skills assume. Custom issue trackers also work.

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Ask Matt"
short_description: "Find the right skill or workflow"
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,89 @@
---
name: code-review
description: Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes — Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/PRD asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to "review since X".
---
Two-axis review of the diff between `HEAD` and a fixed point the user supplies:
- **Standards** — does the code conform to this repo's documented coding standards?
- **Spec** — does the code faithfully implement the originating issue / PRD / spec?
Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings.
The issue tracker should have been provided to you — run `/setup-matt-pocock-skills` if `docs/agents/issue-tracker.md` is missing.
## Process
### 1. Pin the fixed point
Whatever the user said is the fixed point — a commit SHA, branch name, tag, `main`, `HEAD~5`, etc. If they didn't specify one, ask for it.
Capture the diff command once: `git diff <fixed-point>...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log <fixed-point>..HEAD --oneline`.
Before going further, confirm the fixed point resolves (`git rev-parse <fixed-point>`) and the diff is non-empty. A bad ref or empty diff should fail here — not inside two parallel sub-agents.
### 2. Identify the spec source
Look for the originating spec, in this order:
1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.) — fetch via the workflow in `docs/agents/issue-tracker.md`.
2. A path the user passed as an argument.
3. A PRD/spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature.
4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available".
### 3. Identify the standards sources
Anything in the repo that documents how code should be written, such as `CODING_STANDARDS.md` or `CONTRIBUTING.md`.
On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below — a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it:
- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell.
- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation — and, like any standard here, skip anything tooling already enforces.
Each smell reads *what it is**how to fix*; match it against the diff:
- **Mysterious Name** — a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky.
- **Duplicated Code** — the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both.
- **Feature Envy** — a method that reaches into another object's data more than its own. → move the method onto the data it envies.
- **Data Clumps** — the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that.
- **Primitive Obsession** — a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type.
- **Repeated Switches** — the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share.
- **Shotgun Surgery** — one logical change forces scattered edits across many files in the diff. → gather what changes together into one module.
- **Divergent Change** — one file or module is edited for several unrelated reasons. → split so each module changes for one reason.
- **Speculative Generality** — abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows.
- **Message Chains** — long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object.
- **Middle Man** — a class or function that mostly just delegates onward. → cut it, call the real target direct.
- **Refused Bequest** — a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition.
### 4. Spawn both sub-agents in parallel
Send a single message with two `Agent` tool calls. Use the `general-purpose` subagent for both.
**Standards sub-agent prompt** — include:
- The full diff command and commit list.
- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full — the sub-agent has no other access to it.
- The brief: "Report — per file/hunk where relevant — (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls — documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words."
**Spec sub-agent prompt** — include:
- The diff command and commit list.
- The path or fetched contents of the spec.
- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words."
If the spec is missing, skip the Spec sub-agent and note this in the final report.
### 5. Aggregate
Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings — the two axes are deliberately separate (see _Why two axes_).
End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes — that's the reranking the separation exists to prevent.
## Why two axes
A change can pass one axis and fail the other:
- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.**
- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.**
Reporting them separately stops one axis from masking the other.

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Code Review"
short_description: "Review a diff on standards and spec"

View File

@@ -0,0 +1,37 @@
# Deepening
How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md) — **module**, **interface**, **seam**, **adapter**.
## Dependency categories
When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam.
### 1. In-process
Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed.
### 2. Local-substitutable
Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface.
### 3. Remote but owned (Ports & Adapters)
Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter.
Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."*
### 4. True external (Mock)
Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter.
## Seam discipline
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection.
- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them.
## Testing strategy: replace, don't layer
- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them.
- Write new tests at the deepened module's interface. The **interface is the test surface**.
- Tests assert on observable outcomes through the interface, not internal state.
- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface.

View File

@@ -0,0 +1,44 @@
# Design It Twice
When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best.
Uses the vocabulary in [SKILL.md](SKILL.md) — **module**, **interface**, **seam**, **adapter**, **leverage**.
## Process
### 1. Frame the problem space
Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate:
- The constraints any new interface would need to satisfy
- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md))
- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete
Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel.
### 2. Spawn sub-agents
Spawn 3+ sub-agents in parallel using the Agent tool. Each must produce a **radically different** interface for the deepened module.
Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint:
- Agent 1: "Minimize the interface — aim for 13 entry points max. Maximise leverage per entry point."
- Agent 2: "Maximise flexibility — support many use cases and extension."
- Agent 3: "Optimise for the most common caller — make the default case trivial."
- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies."
Include both [SKILL.md](SKILL.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language.
Each sub-agent outputs:
1. Interface (types, methods, params — plus invariants, ordering, error modes)
2. Usage example showing how callers use it
3. What the implementation hides behind the seam
4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md))
5. Trade-offs — where leverage is high, where it's thin
### 3. Present and compare
Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**.
After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu.

View File

@@ -0,0 +1,114 @@
---
name: codebase-design
description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.
---
# Codebase Design
Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone.
## Glossary
Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point.
**Module** — anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service.
**Interface** — everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow — they refer only to the type-level surface).
**Implementation** — what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise.
**Depth** — leverage at the interface: the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation.
**Seam** _(Michael Feathers)_ — a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context).
**Adapter** — a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).
**Leverage** — what callers get from depth: more capability per unit of interface they learn. One implementation pays back across N call sites and M tests.
**Locality** — what maintainers get from depth: change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere.
## Deep vs shallow
**Deep module** = small interface + lots of implementation:
```
┌─────────────────────┐
│ Small Interface │ ← Few methods, simple params
├─────────────────────┤
│ │
│ Deep Implementation│ ← Complex logic hidden
│ │
└─────────────────────┘
```
**Shallow module** = large interface + little implementation (avoid):
```
┌─────────────────────────────────┐
│ Large Interface │ ← Many methods, complex params
├─────────────────────────────────┤
│ Thin Implementation │ ← Just passes through
└─────────────────────────────────┘
```
When designing an interface, ask:
- Can I reduce the number of methods?
- Can I simplify the parameters?
- Can I hide more complexity inside?
## Principles
- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface.
- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.
- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape.
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it.
## Designing for testability
Good interfaces make testing natural:
1. **Accept dependencies, don't create them.**
```typescript
// Testable
function processOrder(order, paymentGateway) {}
// Hard to test
function processOrder(order) {
const gateway = new StripeGateway();
}
```
2. **Return results, don't produce side effects.**
```typescript
// Testable
function calculateDiscount(cart): Discount {}
// Hard to test
function applyDiscount(cart): void {
cart.total -= discount;
}
```
3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup.
## Relationships
- A **Module** has exactly one **Interface** (the surface it presents to callers and tests).
- **Depth** is a property of a **Module**, measured against its **Interface**.
- A **Seam** is where a **Module**'s **Interface** lives.
- An **Adapter** sits at a **Seam** and satisfies the **Interface**.
- **Depth** produces **Leverage** for callers and **Locality** for maintainers.
## Rejected framings
- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead.
- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know.
- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**.
## Going deeper
- **Deepening a cluster given its dependencies** — see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing.
- **Exploring alternative interfaces** — see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement.

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Codebase Design"
short_description: "Vocabulary for deep-module design"

View File

@@ -0,0 +1,134 @@
---
name: diagnosing-bugs
description: Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.
---
# Diagnosing Bugs
A discipline for hard bugs. Skip phases only when explicitly justified.
When exploring the codebase, read `CONTEXT.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching.
## Phase 1 — Build a feedback loop
**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug — one that goes red on _this_ bug — you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you.
Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.**
### Ways to construct one — try them in roughly this order
1. **Failing test** at whatever seam reaches the bug — unit, integration, e2e.
2. **Curl / HTTP script** against a running dev server.
3. **CLI invocation** with a fixture input, diffing stdout against a known-good snapshot.
4. **Headless browser script** (Playwright / Puppeteer) — drives the UI, asserts on DOM/console/network.
5. **Replay a captured trace.** Save a real network request / payload / event log to disk; replay it through the code path in isolation.
6. **Throwaway harness.** Spin up a minimal subset of the system (one service, mocked deps) that exercises the bug code path with a single function call.
7. **Property / fuzz loop.** If the bug is "sometimes wrong output", run 1000 random inputs and look for the failure mode.
8. **Bisection harness.** If the bug appeared between two known states (commit, dataset, version), automate "boot at state X, check, repeat" so you can `git bisect run` it.
9. **Differential loop.** Run the same input through old-version vs new-version (or two configs) and diff outputs.
10. **HITL bash script.** Last resort. If a human must click, drive _them_ with `scripts/hitl-loop.template.sh` so the loop is still structured. Captured output feeds back to you.
Build the right feedback loop, and the bug is 90% fixed.
### Tighten the loop
Treat the loop as a product. Once you have _a_ loop, **tighten** it:
- Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.)
- Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".)
- Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.)
A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight — a debugging superpower.
### Non-deterministic bugs
The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not — keep raising the rate until it's debuggable.
### When you genuinely cannot build a loop
Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop.
### Completion criterion — a tight loop that goes red
Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** — a script path, a test invocation, a curl — that you have **already run at least once** (paste the invocation and its output), and that is:
- [ ] **Red-capable** — it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring" — it must be able to _catch this specific bug_.
- [ ] **Deterministic** — same verdict every run (flaky bugs: a pinned, high reproduction rate, per above).
- [ ] **Fast** — seconds, not minutes.
- [ ] **Agent-runnable** — you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`.
If you catch yourself reading code to build a theory before this command exists, **stop — jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2.
## Phase 2 — Reproduce + minimise
Run the loop. Watch it go red — the bug appears.
Confirm:
- [ ] The loop produces the failure mode the **user** described — not a different failure that happens to be nearby. Wrong bug = wrong fix.
- [ ] The failure is reproducible across multiple runs (or, for non-deterministic bugs, reproducible at a high enough rate to debug against).
- [ ] You have captured the exact symptom (error message, wrong output, slow timing) so later phases can verify the fix actually addresses it.
### Minimise
Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut — keep only what's load-bearing for the failure.
Why bother: a minimal repro shrinks the hypothesis space in Phase 3 (fewer moving parts left to suspect) and becomes the clean regression test in Phase 5.
Done when **every remaining element is load-bearing** — removing any one of them makes the loop go green.
Do not proceed until you have reproduced **and** minimised.
## Phase 3 — Hypothesise
Generate **35 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea.
Each hypothesis must be **falsifiable**: state the prediction it makes.
> Format: "If <X> is the cause, then <changing Y> will make the bug disappear / <changing Z> will make it worse."
If you cannot state the prediction, the hypothesis is a vibe — discard or sharpen it.
**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it — proceed with your ranking if the user is AFK.
## Phase 4 — Instrument
Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.**
Tool preference:
1. **Debugger / REPL inspection** if the env supports it. One breakpoint beats ten logs.
2. **Targeted logs** at the boundaries that distinguish hypotheses.
3. Never "log everything and grep".
**Tag every debug log** with a unique prefix, e.g. `[DEBUG-a4f2]`. Cleanup at the end becomes a single grep. Untagged logs survive; tagged logs die.
**Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second.
## Phase 5 — Fix + regression test
Write the regression test **before the fix** — but only if there is a **correct seam** for it.
A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence.
**If no correct seam exists, that itself is the finding.** Note it. The codebase architecture is preventing the bug from being locked down. Flag this for the next phase.
If a correct seam exists:
1. Turn the minimised repro into a failing test at that seam.
2. Watch it fail.
3. Apply the fix.
4. Watch it pass.
5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario.
## Phase 6 — Cleanup + post-mortem
Required before declaring done:
- [ ] Original repro no longer reproduces (re-run the Phase 1 loop)
- [ ] Regression test passes (or absence of seam is documented)
- [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix)
- [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location)
- [ ] The hypothesis that turned out correct is stated in the commit / PR message — so the next debugger learns
**Then ask: what would have prevented this bug?** If the answer involves architectural change (no good test seam, tangled callers, hidden coupling) hand off to the `/improve-codebase-architecture` skill with the specifics. Make the recommendation **after** the fix is in, not before — you have more information now than when you started.

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Diagnosing Bugs"
short_description: "Diagnose hard bugs and regressions"

View File

@@ -0,0 +1,41 @@
#!/usr/bin/env bash
# Human-in-the-loop reproduction loop.
# Copy this file, edit the steps below, and run it.
# The agent runs the script; the user follows prompts in their terminal.
#
# Usage:
# bash hitl-loop.template.sh
#
# Two helpers:
# step "<instruction>" → show instruction, wait for Enter
# capture VAR "<question>" → show question, read response into VAR
#
# At the end, captured values are printed as KEY=VALUE for the agent to parse.
set -euo pipefail
step() {
printf '\n>>> %s\n' "$1"
read -r -p " [Enter when done] " _
}
capture() {
local var="$1" question="$2" answer
printf '\n>>> %s\n' "$question"
read -r -p " > " answer
printf -v "$var" '%s' "$answer"
}
# --- edit below ---------------------------------------------------------
step "Open the app at http://localhost:3000 and sign in."
capture ERRORED "Click the 'Export' button. Did it throw an error? (y/n)"
capture ERROR_MSG "Paste the error message (or 'none'):"
# --- edit above ---------------------------------------------------------
printf '\n--- Captured ---\n'
printf 'ERRORED=%s\n' "$ERRORED"
printf 'ERROR_MSG=%s\n' "$ERROR_MSG"

View File

@@ -0,0 +1,47 @@
# ADR Format
ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
Create the `docs/adr/` directory lazily — only when the first ADR is needed.
## Template
```md
# {Short title of the decision}
{1-3 sentences: what's the context, what did we decide, and why.}
```
That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why* — not in filling out sections.
## Optional sections
Only include these when they add genuine value. Most ADRs won't need them.
- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`) — useful when decisions are revisited
- **Considered Options** — only when the rejected alternatives are worth remembering
- **Consequences** — only when non-obvious downstream effects need to be called out
## Numbering
Scan `docs/adr/` for the highest existing number and increment by one.
## When to offer an ADR
All three of these must be true:
1. **Hard to reverse** — the cost of changing your mind later is meaningful
2. **Surprising without context** — a future reader will look at the code and wonder "why on earth did they do it this way?"
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
If a decision is easy to reverse, skip it — you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
### What qualifies
- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library — just the ones that would take a quarter to swap out.
- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it — otherwise someone will suggest GraphQL again in six months.

View File

@@ -0,0 +1,60 @@
# CONTEXT.md Format
## Structure
```md
# {Context Name}
{One or two sentence description of what this context is and why it exists.}
## Language
**Order**:
{A one or two sentence description of the term}
_Avoid_: Purchase, transaction
**Invoice**:
A request for payment sent to a customer after delivery.
_Avoid_: Bill, payment request
**Customer**:
A person or organization that places orders.
_Avoid_: Client, buyer, account
```
## Rules
- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`.
- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does.
- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs.
- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine.
## Single vs multi-context repos
**Single context (most repos):** One `CONTEXT.md` at the repo root.
**Multiple contexts:** A `CONTEXT-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other:
```md
# Context Map
## Contexts
- [Ordering](./src/ordering/CONTEXT.md) — receives and tracks customer orders
- [Billing](./src/billing/CONTEXT.md) — generates invoices and processes payments
- [Fulfillment](./src/fulfillment/CONTEXT.md) — manages warehouse picking and shipping
## Relationships
- **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking
- **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices
- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money`
```
The skill infers which structure applies:
- If `CONTEXT-MAP.md` exists, read it to find contexts
- If only a root `CONTEXT.md` exists, single context
- If neither exists, create a root `CONTEXT.md` lazily when the first term is resolved
When multiple contexts exist, infer which one the current topic relates to. If unclear, ask.

View File

@@ -0,0 +1,74 @@
---
name: domain-modeling
description: Build and sharpen a project's domain model. Use when the user wants to pin down domain terminology or a ubiquitous language, record an architectural decision, or when another skill needs to maintain the domain model.
---
# Domain Modeling
Actively build and sharpen the project's domain model as you design. This is the *active* discipline — challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `CONTEXT.md` for vocabulary is not this skill — that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.)
## File structure
Most repos have a single context:
```
/
├── CONTEXT.md
├── docs/
│ └── adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```
If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:
```
/
├── CONTEXT-MAP.md
├── docs/
│ └── adr/ ← system-wide decisions
├── src/
│ ├── ordering/
│ │ ├── CONTEXT.md
│ │ └── docs/adr/ ← context-specific decisions
│ └── billing/
│ ├── CONTEXT.md
│ └── docs/adr/
```
Create files lazily — only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed.
## During the session
### Challenge against the glossary
When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y — which is it?"
### Sharpen fuzzy language
When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account' — do you mean the Customer or the User? Those are different things."
### Discuss concrete scenarios
When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.
### Cross-reference with code
When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible — which is right?"
### Update CONTEXT.md inline
When a term is resolved, update `CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
`CONTEXT.md` should be totally devoid of implementation details. Do not treat `CONTEXT.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else.
### Offer ADRs sparingly
Only offer to create an ADR when all three are true:
1. **Hard to reverse** — the cost of changing your mind later is meaningful
2. **Surprising without context** — a future reader will wonder "why did they do it this way?"
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Domain Modeling"
short_description: "Build and sharpen a domain model"

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Grill Me"
short_description: "Sharpen a plan through interview"
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Grill with Docs"
short_description: "Grill a design and write its docs"
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,12 @@
---
name: grilling
description: Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.
---
Interview me relentlessly about every aspect of this until we reach a shared understanding. Walk down each branch of the decision tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
Ask the questions one at a time, waiting for feedback on each question before continuing. Asking multiple questions at once is bewildering.
If a *fact* can be found by exploring the environment (filesystem, tools, etc.), look it up rather than asking me. The *decisions*, though, are mine — put each one to me and wait for my answer.
Do not act on it until I confirm we have reached a shared understanding.

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Grilling"
short_description: "Stress-test thinking one question at a time"

View File

@@ -9,7 +9,7 @@ Write a handoff document summarising the current conversation so a fresh agent c
Include a "suggested skills" section in the document, which suggests skills that the agent should invoke.
Do not duplicate content already captured in other artifacts (PRDs, plans, ADRs, issues, commits, diffs). Reference them by path or URL instead.
Do not duplicate content already captured in other artifacts (specs, plans, ADRs, issues, commits, diffs). Reference them by path or URL instead.
Redact any sensitive information, such as API keys, passwords, or personally identifiable information.

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Handoff"
short_description: "Compact a conversation into a handoff"
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,15 @@
---
name: implement
description: "Implement a piece of work based on a spec or set of tickets."
disable-model-invocation: true
---
Implement the work described by the user in the spec or tickets.
Use /tdd where possible, at pre-agreed seams.
Run typechecking regularly, single test files regularly, and the full test suite once at the end.
Once done, use /code-review to review the work.
Commit your work to the current branch.

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Implement"
short_description: "Build work from a spec or tickets"
policy:
allow_implicit_invocation: false

View File

@@ -17,6 +17,11 @@ This command is _informed_ by the project's domain model and built on a shared d
### 1. Explore
**Scope before you scan — YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look:
- If the user named a direction — a module, a subsystem, a pain point — take it, and skip the inference below.
- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots — the files and areas that keep coming up — and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net.
Read the project's domain glossary (`CONTEXT.md`) and any ADRs in the area you're touching first.
Then use the Agent tool with `subagent_type=Explore` to walk the codebase. Don't follow rigid heuristics — explore organically and note where you experience friction:
@@ -56,7 +61,7 @@ Do NOT propose interfaces yet. After the file is written, ask the user: "Which o
### 3. Grilling loop
Once the user picks a candidate, run the `/grilling` skill to walk the design tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
Once the user picks a candidate, run the `/grilling` skill to walk the decision tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
Side effects happen inline as decisions crystallize — run the `/domain-modeling` skill to keep the domain model current as you go:

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Improve Codebase Architecture"
short_description: "Find and grill architecture improvements"
policy:
allow_implicit_invocation: false

View File

@@ -36,7 +36,7 @@ The right shape depends on the question:
Pick whichever shape best fits the question being asked, *not* whichever is easiest to wire to a TUI. Keep it pure: no I/O, no terminal code, no `console.log` for control flow. The TUI imports it and calls into it; nothing flows the other direction.
This is what makes the prototype useful past its own lifetime. When the question's been answered, the validated reducer / machine / function set can be lifted into the real module — the TUI shell gets deleted.
This is what makes the prototype useful past its own lifetime: when the question's been answered, the validated reducer / machine / function set can be lifted into the real module on its own.
### 4. Build the smallest TUI that exposes the state
@@ -66,9 +66,9 @@ If the host project has no task runner, just put the command at the top of the p
Give the user the run command. They'll drive it themselves; the interesting moments are when they say "wait, that shouldn't be possible" or "huh, I assumed X would be different" — those are the bugs in the _idea_, which is the whole point. If they want new actions added, add them. Prototypes evolve.
### 7. Capture the answer
### 7. Capture the answer and the prototype
When the prototype has done its job, the answer to the question is the only thing worth keeping. If the user is around, ask what it taught them. If not, leave a `NOTES.md` next to the prototype so the answer can be filled in (or filled in by you, if you've watched the session) before the prototype gets deleted.
Once the prototype has answered its question, capture the answer, then capture the prototype the way the [SKILL](SKILL.md) describes. The logic-specific mapping: the validated reducer / machine / function set lifts into the real module (the decision, absorbed); the TUI shell rides along to the throwaway branch that keeps the prototype as a primary source.
## Anti-patterns

View File

@@ -21,10 +21,6 @@ The two branches produce very different artifacts — getting this wrong wastes
1. **Throwaway from day one, and clearly marked as such.** Locate the prototype code close to where it will actually be used (next to the module or page it's prototyping for) so context is obvious — but name it so a casual reader can see it's a prototype, not production. For throwaway UI routes, obey whatever routing convention the project already uses; don't invent a new top-level structure.
2. **One command to run.** Whatever the project's existing task runner supports — `pnpm <name>`, `python <path>`, `bun <path>`, etc. The user must be able to start it without thinking.
3. **No persistence by default.** State lives in memory. Persistence is the thing the prototype is _checking_, not something it should depend on. If the question explicitly involves a database, hit a scratch DB or a local file with a clear "PROTOTYPE — wipe me" name.
4. **Skip the polish.** No tests, no error handling beyond what makes the prototype _runnable_, no abstractions. The point is to learn something fast and then delete it.
4. **Skip the polish.** No tests, no error handling beyond what makes the prototype _runnable_, no abstractions. The point is to learn something fast.
5. **Surface the state.** After every action (logic) or on every variant switch (UI), print or render the full relevant state so the user can see what changed.
6. **Delete or absorb when done.** When the prototype has answered its question, either delete it or fold the validated decision into the real code — don't leave it rotting in the repo.
## When done
The _answer_ is the only thing worth keeping from a prototype. Capture it somewhere durable (commit message, ADR, issue, or a `NOTES.md` next to the prototype) along with the question it was answering. If the user is around, that capture is a quick conversation; if not, leave the placeholder so they (or you, on the next pass) can fill in the verdict before deleting the prototype.
6. **Capture it when done.** Fold any validated decision into the real code, then capture the prototype itself as a **primary source**: commit it to a throwaway branch, out of main, and leave a context pointer to that branch on the implementation issue. Capture the answer too — the verdict and the question it settled — in the issue or a commit. The main branch keeps only the validated decision.

View File

@@ -97,12 +97,12 @@ Surface the URL (and the `?variant=` keys). The user will flip through whenever
### 6. Capture the answer and clean up
Once a variant has won, write down which one and why (commit message, ADR, issue, or a `NOTES.md` next to the prototype if running AFK and the user hasn't responded yet). Then:
Once a variant has won, capture the answer — which variant and why — then capture the prototype the way the [SKILL](SKILL.md) describes. Fold the winner into the real code and move the rest onto the throwaway branch, not into main:
- **Sub-shape A** — delete the losing variants and the switcher; fold the winner into the existing page.
- **Sub-shape B** — promote the winning variant to a real route, delete the throwaway route and the switcher.
- **Sub-shape A** — fold the winner into the existing page; drop the losing variants and the switcher from main.
- **Sub-shape B** — promote the winning variant to a real route; drop the throwaway route and the switcher from main.
Don't leave variant components or the switcher lying around. They rot fast and confuse the next reader.
The full set of variants is the primary source, so it lands on the throwaway branch, not the bin — variant components and the switcher left in the main branch rot fast and confuse the next reader.
## Anti-patterns

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Prototype"
short_description: "Prototype to answer a design question"

View File

@@ -0,0 +1,12 @@
---
name: research
description: Investigate a question against high-trust primary sources and capture the findings as a Markdown file in the repo. Use when the user wants a topic researched, docs or API facts gathered, or reading legwork delegated to a background agent.
---
Spin up a **background agent** to do the research, so you keep working while it reads.
Its job:
1. Investigate the question against **primary sources** — official docs, source code, specs, first-party APIs — not a secondary write-up of them. Follow every claim back to the source that owns it.
2. Write the findings to a single Markdown file, citing each claim's source.
3. Save it where the repo already keeps such notes; match the existing convention, and if there is none, put it somewhere sensible and say where.

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Research"
short_description: "Research from high-trust sources"

View File

@@ -0,0 +1,14 @@
---
name: resolving-merge-conflicts
description: "Use when you need to resolve an in-progress git merge/rebase conflict."
---
1. **See the current state** of the merge/rebase. Check git history, and the conflicting files.
2. **Find the primary sources** for each conflict. Understand deeply why each change was made, and what the original intent was. Read the commit messages, check the PRs, check original issues/tickets.
3. **Resolve each hunk.** Preserve both intents where possible. Where incompatible, pick the one matching the merge's stated goal and note the trade-off. Do **not** invent new behaviour. Always resolve; never `--abort`.
4. Discover the project's **automated checks** and run them — typically typecheck, then tests, then format. Fix anything the merge broke.
5. **Finish the merge/rebase.** Stage everything and commit. If rebasing, continue the rebase process until all commits are rebased.

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Resolving Merge Conflicts"
short_description: "Resolve merge and rebase conflicts"

View File

@@ -26,16 +26,18 @@ Look at the current repo to understand its starting state. Read whatever exists;
- `docs/adr/` and any `src/*/docs/adr/` directories
- `docs/agents/` — does this skill's prior output already exist?
- `.scratch/` — sign that a local-markdown issue tracker convention is already in use
- Is the `triage` skill installed? (a `triage` skill folder alongside this one, or `triage` in your available skills.) This decides whether Section B runs at all.
- Monorepo signals — a `pnpm-workspace.yaml`, a `workspaces` field in `package.json`, or a populated `packages/*` with its own `src/`. Present only in a genuinely large multi-package repo; their absence means single-context, which is almost every repo.
### 2. Present findings and ask
Summarise what's present and what's missing. Then walk the user through the three decisions **one at a time** — present a section, get the user's answer, then move to the next. Don't dump all three at once.
Summarise what's present and what's missing. Then take the sections in order — one section, one answer, then the next.
Assume the user does not know what these terms mean. Each section starts with a short explainer (what it is, why these skills need it, what changes if they pick differently). Then show the choices and the default.
Lead each section with the recommended answer so the user can accept it in a word. Give a one-line explainer only when the choice genuinely branches; skip the section entirely when exploration already settled it (Section B when `triage` isn't installed, Section C when there's no monorepo).
**Section A — Issue tracker.**
> Explainer: The "issue tracker" is where issues live for this repo. Skills like `to-issues`, `triage`, `to-prd`, and `qa` read from and write to it — they need to know whether to call `gh issue create`, write a markdown file under `.scratch/`, or follow some other workflow you describe. Pick the place you actually track work for this repo.
> Explainer: The "issue tracker" is where issues live for this repo. Skills like `to-tickets`, `triage`, `to-spec`, and `qa` read from and write to it — they need to know whether to call `gh issue create`, write a markdown file under `.scratch/`, or follow some other workflow you describe. Pick the place you actually track work for this repo.
Default posture: these skills were designed for GitHub. If a `git remote` points at GitHub, propose that. If a `git remote` points at GitLab (`gitlab.com` or a self-hosted host), propose GitLab. Otherwise (or if the user prefers), offer:
@@ -44,41 +46,26 @@ Default posture: these skills were designed for GitHub. If a `git remote` points
- **Local markdown** — issues live as files under `.scratch/<feature>/` in this repo (good for solo projects or repos without a remote)
- **Other** (Jira, Linear, etc.) — ask the user to describe the workflow in one paragraph; the skill will record it as freeform prose
If — and only if — the user picked **GitHub** or **GitLab**, ask one follow-up:
Record the choice in `docs/agents/issue-tracker.md`. The GitHub and GitLab templates carry a "PRs as a request surface" flag, defaulted **off** — leave it off and don't raise it; a user who wants external PRs in the triage queue can flip the flag in the file later.
> Explainer: Open-source repos often receive feature requests as pull requests, not just issues — a PR is an issue with attached code. If you turn this on, `/triage` pulls *external* PRs into the same queue and runs them through the same labels and states as issues (collaborators' in-flight PRs are left alone). Leave it off if PRs aren't a request surface for you.
**Section B — Triage label vocabulary.** Skip this section entirely if the `triage` skill isn't installed (exploration told you) — an uninstalled skill needs no labels.
- **PRs as a request surface** — yes / no (default: no). Record the answer in `docs/agents/issue-tracker.md`. For local-markdown and other trackers, skip this question — there are no PRs.
If it is installed, ask exactly one question:
**Section B — Triage label vocabulary.**
> Do you want to keep the default triage labels? (recommended: **yes**)
> Explainer: When the `triage` skill processes an incoming issue, it moves it through a state machine — needs evaluation, waiting on reporter, ready for an AFK agent to pick up, ready for a human, or won't fix. To do that, it needs to apply labels (or the equivalent in your issue tracker) that match strings *you've actually configured*. If your repo already uses different label names (e.g. `bug:triage` instead of `needs-triage`), map them here so the skill applies the right ones instead of creating duplicates.
The defaults are the five canonical roles, each label string equal to its name: `needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`. On **yes**, write them as-is. Only if the user says no — usually because their tracker already uses other names (e.g. `bug:triage` for `needs-triage`) — collect the overrides so `triage` applies existing labels instead of creating duplicates.
The five canonical roles:
**Section C — Domain docs.** Default to **single-context** — one `CONTEXT.md` + `docs/adr/` at the repo root. This fits almost every repo; write it without asking.
- `needs-triage` — maintainer needs to evaluate
- `needs-info` — waiting on reporter
- `ready-for-agent` — fully specified, AFK-ready (an agent can pick it up with no human context)
- `ready-for-human` — needs human implementation
- `wontfix` — will not be actioned
Default: each role's string equals its name. Ask the user if they want to override any. If their issue tracker has no existing labels, the defaults are fine.
**Section C — Domain docs.**
> Explainer: Some skills (`improve-codebase-architecture`, `diagnosing-bugs`, `tdd`) read a `CONTEXT.md` file to learn the project's domain language, and `docs/adr/` for past architectural decisions. They need to know whether the repo has one global context or multiple (e.g. a monorepo with separate frontend/backend contexts) so they look in the right place.
Confirm the layout:
- **Single-context** — one `CONTEXT.md` + `docs/adr/` at the repo root. Most repos are this.
- **Multi-context** — `CONTEXT-MAP.md` at the root pointing to per-context `CONTEXT.md` files (typically a monorepo).
Offer **multi-context** — a root `CONTEXT-MAP.md` pointing to per-context `CONTEXT.md` files — only when exploration found monorepo signals. Then confirm which layout they want.
### 3. Confirm and edit
Show the user a draft of:
- The `## Agent skills` block to add to whichever of `CLAUDE.md` / `AGENTS.md` is being edited (see step 4 for selection rules)
- The contents of `docs/agents/issue-tracker.md`, `docs/agents/triage-labels.md`, `docs/agents/domain.md`
- The contents of `docs/agents/issue-tracker.md`, `docs/agents/domain.md`, and `docs/agents/triage-labels.md` (the last only when `triage` is installed)
Let them edit before writing.
@@ -101,7 +88,7 @@ The block:
### Issue tracker
[one-line summary of where issues are tracked, plus whether external PRs are a triage surface]. See `docs/agents/issue-tracker.md`.
[one-line summary of where issues are tracked]. See `docs/agents/issue-tracker.md`.
### Triage labels
@@ -112,12 +99,14 @@ The block:
[one-line summary of layout — "single-context" or "multi-context"]. See `docs/agents/domain.md`.
```
Then write the three docs files using the seed templates in this skill folder as a starting point:
Include the `### Triage labels` sub-block, and write `docs/agents/triage-labels.md`, only when `triage` is installed and Section B ran. When it isn't, both are omitted.
Then write the docs files using the seed templates in this skill folder as a starting point:
- [issue-tracker-github.md](./issue-tracker-github.md) — GitHub issue tracker
- [issue-tracker-gitlab.md](./issue-tracker-gitlab.md) — GitLab issue tracker
- [issue-tracker-local.md](./issue-tracker-local.md) — local-markdown issue tracker
- [triage-labels.md](./triage-labels.md) — label mapping
- [triage-labels.md](./triage-labels.md) — label mapping (only if `triage` is installed)
- [domain.md](./domain.md) — domain doc consumer rules + layout
For "other" issue trackers, write `docs/agents/issue-tracker.md` from scratch using the user's description.

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Setup Matt Pocock Skills"
short_description: "Configure a repo for the skills"
policy:
allow_implicit_invocation: false

View File

@@ -32,3 +32,14 @@ Create a GitHub issue.
## When a skill says "fetch the relevant ticket"
Run `gh issue view <number> --comments`.
## Wayfinding operations
Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets.
- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `gh issue create --label wayfinder:map`.
- **Child ticket**: an issue linked to the map as a GitHub sub-issue (`gh api` on the sub-issues endpoint). Where sub-issues aren't enabled, add the child to a task list in the map body and put `Part of #<map>` at the top of the child body. Labels: `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
- **Blocking**: GitHub's **native issue dependencies** — the canonical, UI-visible representation. Add an edge with `gh api --method POST repos/<owner>/<repo>/issues/<child>/dependencies/blocked_by -F issue_id=<blocker-db-id>`, where `<blocker-db-id>` is the blocker's numeric **database id** (`gh api repos/<owner>/<repo>/issues/<n> --jq .id`, _not_ the `#number` or `node_id`). GitHub reports `issue_dependencies_summary.blocked_by` (open blockers only — the live gate). Where dependencies aren't available, fall back to a `Blocked by: #<n>, #<n>` line at the top of the child body. A ticket is unblocked when every blocker is closed.
- **Frontier query**: list the map's open children (`gh issue list --state open`, scoped to the map's sub-issues / task list), drop any with an open blocker (`issue_dependencies_summary.blocked_by > 0`, or an open issue in the `Blocked by` line) or an assignee; first in map order wins.
- **Claim**: `gh issue edit <n> --add-assignee @me` — the session's first write.
- **Resolve**: `gh issue comment <n> --body "<answer>"`, then `gh issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.

View File

@@ -33,3 +33,14 @@ Create a GitLab issue.
## When a skill says "fetch the relevant ticket"
Run `glab issue view <number> --comments`.
## Wayfinding operations
Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets.
- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `glab issue create --label wayfinder:map`. (On GitLab tiers with native epics, an epic may hold the map instead; a labelled issue works everywhere.)
- **Child ticket**: an issue carrying `Part of #<map>` at the top of its description and labels `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
- **Blocking**: GitLab's **native blocking link** — the canonical, UI-visible representation. Add it with the `/blocked_by #<n>` quick action, posted as a note (`glab issue note <child> --message "/blocked_by #<blocker>"`). Native blocking links are a Premium/Ultimate feature; on the free tier (or where unavailable) fall back to a `Blocked by: #<n>, #<n>` line at the top of the description. A ticket is unblocked when every blocker is closed.
- **Frontier query**: `glab issue list -F json` scoped to the map's children, drop any with an open blocker — a native `blocked_by` link to an open issue (`glab api projects/:id/issues/:iid/links`), or an open issue in the `Blocked by` line — or an assignee; first in map order wins.
- **Claim**: `glab issue update <n> --assignee @me` — the session's first write.
- **Resolve**: `glab issue note <n> --message "<answer>"`, then `glab issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.

View File

@@ -1,12 +1,12 @@
# Issue tracker: Local Markdown
Issues and PRDs for this repo live as markdown files in `.scratch/`.
Issues and specs (you may know a spec as a PRD) for this repo live as markdown files in `.scratch/`.
## Conventions
- One feature per directory: `.scratch/<feature-slug>/`
- The PRD is `.scratch/<feature-slug>/PRD.md`
- Implementation issues are `.scratch/<feature-slug>/issues/<NN>-<slug>.md`, numbered from `01`
- The spec is `.scratch/<feature-slug>/spec.md`
- Implementation issues are one file per ticket at `.scratch/<feature-slug>/issues/<NN>-<slug>.md`, numbered from `01` — never a single combined tickets file
- Triage state is recorded as a `Status:` line near the top of each issue file (see `triage-labels.md` for the role strings)
- Comments and conversation history append to the bottom of the file under a `## Comments` heading
@@ -17,3 +17,14 @@ Create a new file under `.scratch/<feature-slug>/` (creating the directory if ne
## When a skill says "fetch the relevant ticket"
Read the file at the referenced path. The user will normally pass the path or the issue number directly.
## Wayfinding operations
Used by `/wayfinder`. The **map** is a file with one **child** file per ticket.
- **Map**: `.scratch/<effort>/map.md` — the Notes / Decisions-so-far / Fog body.
- **Child ticket**: `.scratch/<effort>/issues/NN-<slug>.md`, numbered from `01`, with the question in the body. A `Type:` line records the ticket type (`research`/`prototype`/`grilling`/`task`); a `Status:` line records `claimed`/`resolved`.
- **Blocking**: a `Blocked by: NN, NN` line near the top. A ticket is unblocked when every file it lists is `resolved`.
- **Frontier**: scan `.scratch/<effort>/issues/` for files that are open, unblocked, and unclaimed; first by number wins.
- **Claim**: set `Status: claimed` and save before any work.
- **Resolve**: append the answer under an `## Answer` heading, set `Status: resolved`, then append a context pointer (gist + link) to the map's Decisions-so-far in `map.md`.

View File

@@ -5,107 +5,32 @@ description: Test-driven development. Use when the user wants to build features
# Test-Driven Development
## Philosophy
TDD is the red → green loop. This skill is the reference that makes that loop produce tests worth keeping: what a good test is, where tests go, the anti-patterns, and the rules of the loop. Every section applies on every cycle — consult them before and during the loop, not after.
**Core principle**: Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't.
When exploring the codebase, read `CONTEXT.md` (if it exists) so test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching.
**Good tests** are integration-style: they exercise real code paths through public APIs. They describe _what_ the system does, not _how_ it does it. A good test reads like a specification - "user can checkout with valid cart" tells you exactly what capability exists. These tests survive refactors because they don't care about internal structure.
## What a good test is
**Bad tests** are coupled to implementation. They mock internal collaborators, test private methods, or verify through external means (like querying a database directly instead of using the interface). The warning sign: your test breaks when you refactor, but behavior hasn't changed. If you rename an internal function and tests fail, those tests were testing implementation, not behavior.
**Tautological tests** restate the implementation inside the assertion, so they pass by construction and give zero confidence. When the expected value is computed the way the code computes it — `expect(add(a, b)).toBe(a + b)`, snapshotting a figure you derived by hand the same way the code does, asserting a constant equals itself — the test can never disagree with the code: break the code wrong and the assertion breaks wrong with it. The expected value must come from an independent source of truth — a known-good literal, a worked example, the spec.
Tests verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't. A good test reads like a specification — "user can checkout with valid cart" tells you exactly what capability exists — and survives refactors because it doesn't care about internal structure.
See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.
## Anti-Pattern: Horizontal Slices
## Seams — where tests go
**DO NOT write all tests first, then all implementation.** This is "horizontal slicing" - treating RED as "write all tests" and GREEN as "write all code."
A **seam** is the public boundary you test at: the interface where you observe behavior without reaching inside. Tests live at seams, never against internals.
This produces **crap tests**:
**Test only at pre-agreed seams.** Before writing any test, write down the seams under test and confirm them with the user. No test is written at an unconfirmed seam. You can't test everything — agreeing the seams up front is how testing effort lands on the critical paths and complex logic instead of every edge case.
- Tests written in bulk test _imagined_ behavior, not _actual_ behavior
- You end up testing the _shape_ of things (data structures, function signatures) rather than user-facing behavior
- Tests become insensitive to real changes - they pass when behavior breaks, fail when behavior is fine
- You outrun your headlights, committing to test structure before understanding the implementation
Ask: "What's the public interface, and which seams should we test?"
**Correct approach**: Vertical slices via tracer bullets. One test → one implementation → repeat. Each test responds to what you learned from the previous cycle. Because you just wrote the code, you know exactly what behavior matters and how to verify it.
## Anti-patterns
```
WRONG (horizontal):
RED: test1, test2, test3, test4, test5
GREEN: impl1, impl2, impl3, impl4, impl5
- **Implementation-coupled** — mocks internal collaborators, tests private methods, or verifies through a side channel (querying the database instead of using the interface). The tell: the test breaks when you refactor but behavior hasn't changed.
- **Tautological** — the assertion recomputes the expected value the way the code does (`expect(add(a, b)).toBe(a + b)`, a snapshot derived by hand the same way, a constant asserted equal to itself), so it passes by construction and can never disagree with the code. Expected values must come from an independent source of truth — a known-good literal, a worked example, the spec.
- **Horizontal slicing** — writing all tests first, then all implementation. Bulk tests verify _imagined_ behavior: you test the _shape_ of things rather than user-facing behavior, the tests go insensitive to real changes, and you commit to test structure before understanding the implementation. Work in **vertical slices** instead — one test → one implementation → repeat, each test a **tracer bullet** that responds to what the last cycle taught you.
RIGHT (vertical):
RED→GREEN: test1→impl1
RED→GREEN: test2→impl2
RED→GREEN: test3→impl3
...
```
## Rules of the loop
## Workflow
### 1. Planning
When exploring the codebase, read `CONTEXT.md` (if it exists) so that test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching.
Before writing any code:
- [ ] Confirm with user what interface changes are needed
- [ ] Confirm with user which behaviors to test (prioritize)
- [ ] Identify opportunities for deep modules (small interface, deep implementation) — run the `/codebase-design` skill for the vocabulary and the testability checks
- [ ] List the behaviors to test (not implementation steps)
- [ ] Get user approval on the plan
Ask: "What should the public interface look like? Which behaviors are most important to test?"
**You can't test everything.** Confirm with the user exactly which behaviors matter most. Focus testing effort on critical paths and complex logic, not every possible edge case.
### 2. Tracer Bullet
Write ONE test that confirms ONE thing about the system:
```
RED: Write test for first behavior → test fails
GREEN: Write minimal code to pass → test passes
```
This is your tracer bullet - proves the path works end-to-end.
### 3. Incremental Loop
For each remaining behavior:
```
RED: Write next test → fails
GREEN: Minimal code to pass → passes
```
Rules:
- One test at a time
- Only enough code to pass current test
- Don't anticipate future tests
- Keep tests focused on observable behavior
### 4. Refactor
After all tests pass, look for [refactor candidates](refactoring.md):
- [ ] Extract duplication
- [ ] Deepen modules (move complexity behind simple interfaces)
- [ ] Apply SOLID principles where natural
- [ ] Consider what new code reveals about existing code
- [ ] Run tests after each refactor step
**Never refactor while RED.** Get to GREEN first.
## Checklist Per Cycle
```
[ ] Test describes behavior, not implementation
[ ] Test uses public interface only
[ ] Test would survive internal refactor
[ ] Expected values are independent literals, not recomputed from the code
[ ] Code is minimal for this test
[ ] No speculative features added
```
- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features.
- **One slice at a time.** One seam, one test, one minimal implementation per cycle.
- **Refactoring is not part of the loop.** It belongs to the review stage (see the `code-review` skill), not the red → green implementation cycle.

View File

@@ -0,0 +1,3 @@
interface:
display_name: "TDD"
short_description: "Test-driven red-green-refactor"

View File

@@ -1,10 +0,0 @@
# Refactor Candidates
After TDD cycle, look for:
- **Duplication** → Extract function/class
- **Long methods** → Break into private helpers (keep tests on public interface)
- **Shallow modules** → Combine or deepen
- **Feature envy** → Move logic to where data lives
- **Primitive obsession** → Introduce value objects
- **Existing code** the new code reveals as problematic

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Teach"
short_description: "Learn a concept in a guided workspace"
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,75 @@
---
name: to-spec
description: Turn the current conversation into a spec and publish it to the project issue tracker — no interview, just synthesis of what you've already discussed.
disable-model-invocation: true
---
This skill takes the current conversation context and codebase understanding and produces a spec (you may know this document as a PRD). Do NOT interview the user — just synthesize what you already know.
The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not.
## Process
1. Explore the repo to understand the current state of the codebase, if you haven't already. Use the project's domain glossary vocabulary throughout the spec, and respect any ADRs in the area you're touching.
2. Sketch out the seams at which you're going to test the feature. Existing seams should be preferred to new ones. Use the highest seam possible. If new seams are needed, propose them at the highest point you can. The fewer seams across the codebase, the better - the ideal number is one.
Check with the user that these seams match their expectations.
3. Write the spec using the template below, then publish it to the project issue tracker. Apply the `ready-for-agent` triage label - no need for additional triage.
<spec-template>
## Problem Statement
The problem that the user is facing, from the user's perspective.
## Solution
The solution to the problem, from the user's perspective.
## User Stories
A LONG, numbered list of user stories. Each user story should be in the format of:
1. As an <actor>, I want a <feature>, so that <benefit>
<user-story-example>
1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending
</user-story-example>
This list of user stories should be extremely extensive and cover all aspects of the feature.
## Implementation Decisions
A list of implementation decisions that were made. This can include:
- The modules that will be built/modified
- The interfaces of those modules that will be modified
- Technical clarifications from the developer
- Architectural decisions
- Schema changes
- API contracts
- Specific interactions
Do NOT include specific file paths or code snippets. They may end up being outdated very quickly.
Exception: if a prototype produced a snippet that encodes a decision more precisely than prose can (state machine, reducer, schema, type shape), inline it within the relevant decision and note briefly that it came from a prototype. Trim to the decision-rich parts — not a working demo, just the important bits.
## Testing Decisions
A list of testing decisions that were made. Include:
- A description of what makes a good test (only test external behavior, not implementation details)
- Which modules will be tested
- Prior art for the tests (i.e. similar types of tests in the codebase)
## Out of Scope
A description of the things that are out of scope for this spec.
## Further Notes
Any further notes about the feature.
</spec-template>

View File

@@ -0,0 +1,5 @@
interface:
display_name: "To Spec"
short_description: "Turn a conversation into a spec"
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,107 @@
---
name: to-tickets
description: Break a plan, spec, or the current conversation into a set of tracer-bullet tickets, each declaring its blocking edges, published to the configured tracker — edges as text in one file per ticket locally, or native blocking links on a real tracker.
disable-model-invocation: true
---
# To Tickets
Break a plan, spec, or conversation into a set of **tickets** — tracer-bullet vertical slices, each declaring the tickets that **block** it.
The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not.
## Process
### 1. Gather context
Work from whatever is already in the conversation context. If the user passes a reference (a spec path, an issue number or URL) as an argument, fetch it and read its full body and comments.
### 2. Explore the codebase (optional)
If you have not already explored the codebase, do so to understand the current state of the code. Ticket titles and descriptions should use the project's domain glossary vocabulary, and respect ADRs in the area you're touching.
Look for opportunities to prefactor the code to make the implementation easier. "Make the change easy, then make the easy change."
### 3. Draft vertical slices
Break the work into **tracer bullet** tickets.
<vertical-slice-rules>
- Each slice cuts a narrow but COMPLETE path through every layer (schema, API, UI, tests) — vertical, NOT a horizontal slice of one layer
- A completed slice is demoable or verifiable on its own
- Each slice is sized to fit in a single fresh context window
- Any prefactoring should be done first
</vertical-slice-rules>
Give each ticket its **blocking edges** — the other tickets that must complete before it can start. A ticket with no blockers can start immediately.
**Wide refactors are the exception to vertical slicing.** A **wide refactor** is one mechanical change — rename a column, retype a shared symbol — whose **blast radius** fans across the whole codebase, so a single edit breaks thousands of call sites at once and no vertical slice can land green. Don't force it into a tracer bullet; sequence it as **expandcontract**. First expand: add the new form beside the old so nothing breaks. Then migrate the call sites over in batches sized by blast radius (per package, per directory), each batch its own ticket blocked by the expand, keeping CI green batch to batch because the old form still exists. Finally contract: delete the old form once no caller remains, in a ticket blocked by every migrate batch. When even the batches can't stay green alone, keep the sequence but let them share an integration branch that all block a final integrate-and-verify ticket — green is promised only there.
### 4. Quiz the user
Present the proposed breakdown as a numbered list. For each ticket, show:
- **Title**: short descriptive name
- **Blocked by**: which other tickets (if any) must complete first
- **What it delivers**: the end-to-end behaviour this ticket makes work
Ask the user:
- Does the granularity feel right? (too coarse / too fine)
- Are the blocking edges correct — does each ticket only depend on tickets that genuinely gate it?
- Should any tickets be merged or split further?
Iterate until the user approves the breakdown.
### 5. Publish the tickets to the configured tracker
Publish the approved tickets. **How** depends on the tracker `/setup-matt-pocock-skills` configured — the tickets are the same either way, only the shape of the blocking edges changes:
- **Local files** → write one file per ticket under `.scratch/<feature-slug>/issues/<NN>-<slug>.md`, numbered from `01` in dependency order (blockers first). Each file's "Blocked by" lists the numbers/titles it depends on. Use the per-ticket file template below — one ticket per file, never a single combined file.
- **A real issue tracker (GitHub, Linear, …)** → publish one issue per ticket in dependency order (blockers first) so each ticket's blocking edges can reference real identifiers. Use the platform's native blocking / sub-issue relationship where it has one; otherwise set each ticket's "Blocked by" to the blocking issues. Apply the `ready-for-agent` triage label unless instructed otherwise — the tickets are agent-grabbable by construction.
Work the **frontier**: any ticket whose blockers are all done. For a purely linear chain that means top to bottom.
Do NOT close or modify any parent issue.
<local-ticket-template>
# <NN> — <Ticket title>
**What to build:** the end-to-end behaviour this ticket makes work, from the user's perspective — not a layer-by-layer implementation list.
**Blocked by:** the numbers/titles of the tickets that gate this one, or "None — can start immediately".
**Status:** ready-for-agent
- [ ] Acceptance criterion 1
- [ ] Acceptance criterion 2
</local-ticket-template>
<issue-template>
## Parent
A reference to the parent issue on the tracker (if the source was an existing issue, otherwise omit this section).
## What to build
The end-to-end behaviour this ticket makes work, from the user's perspective — not layer-by-layer implementation.
## Acceptance criteria
- [ ] Criterion 1
- [ ] Criterion 2
## Blocked by
- A reference to each blocking ticket, or "None — can start immediately".
</issue-template>
In either form, avoid specific file paths or code snippets — they go stale fast. Exception: if a prototype produced a snippet that encodes a decision more precisely than prose can (state machine, reducer, schema, type shape), inline it and note briefly that it came from a prototype. Trim to the decision-rich parts — not a working demo, just the important bits.
Work the frontier one ticket at a time with `/implement`, clearing context between tickets.

View File

@@ -0,0 +1,5 @@
interface:
display_name: "To Tickets"
short_description: "Split a plan into tracer-bullet tickets"
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Triage"
short_description: "Move issues through triage roles"
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,128 @@
---
name: wayfinder
description: Plan a huge chunk of work — more than one agent session can hold — as a shared map of decision tickets on your issue tracker, and resolve them one at a time until the way to the destination is clear.
disable-model-invocation: true
---
A loose idea has arrived — too big for one agent session, and wrapped in fog: the way from here to the **destination** isn't visible yet. Wayfinding is about finding that way, not charging at the destination. This skill charts the way as a **shared map** on the repo's issue tracker, then works its **decision tickets** — questions whose resolution is a decision, not slices of a build to execute — one at a time until the route is clear.
The destination varies per effort, and naming it is the first act of charting — it shapes every ticket. It might be a spec to hand off and iterate on, a decision to lock before planning starts, or a change made in place like a data-structure migration. The map is domain-agnostic — engineering work, course content, whatever fits the shape.
## Plan, don't do
Wayfinder is **planning** by default: each ticket resolves a decision, and the map is done when the way is clear — nothing left to decide before someone goes and does the thing. The pull to just do the work is usually the signal you've reached the edge of the map and it's time to hand off. An effort can override this in its **Notes** — carrying execution into the map itself — but absent that, produce decisions, not deliverables.
## Refer by name
Every map and ticket is an issue, so it has a **name** — its title. In everything the human reads — narration, the map's Decisions-so-far — refer to it by that name, never by a bare id, number, or slug. A wall of `#42, #43, #44` is illegible; names read at a glance. The id and URL don't vanish — a name wraps its link — but they ride *inside* the name, never stand in for it.
## The Map
The map is a single issue on this repo's issue tracker, labelled `wayfinder:map` — the canonical artifact. Its tickets are child issues of the map.
The map is an **index**, not a store. It lists the decisions made and points at the tickets that hold their detail; a decision lives in exactly one place — its ticket — so the map never restates it, only gists it and links.
**Where the map, its child tickets, blocking, and frontier queries physically live is tracker-specific.** The issue tracker should have been provided to you — run `/setup-matt-pocock-skills` if not. Consult the tracker doc's "Wayfinding operations" section for how _this_ repo expresses them. If no tracker has been provided, default to the local-markdown tracker.
### The map body
The whole map at low resolution, loaded once per session. Open tickets are **not** listed — they are open child issues, found by query.
```markdown
## Destination
<what reaching the end of this map looks like — the spec, decision, or change this effort is finding its way to. One or two lines; every session orients to it before choosing a ticket.>
## Notes
<domain; skills every session should consult; standing preferences for this effort>
## Decisions so far
<!-- the index — one line per closed ticket: enough to judge relevance, then zoom the link for the detail the ticket holds -->
- [<closed ticket title>](link) — <one-line gist of the answer>
## Not yet specified
<!-- see "Fog of war": in-scope fog you can't ticket yet; graduates as the frontier advances -->
## Out of scope
<!-- see "Out of scope": work ruled beyond the destination; closed, never graduates -->
```
### Tickets
Each ticket is a **child issue** of the map; the tracker's issue id is its identity. Its body is the question, sized to one 100K token agent session:
```markdown
## Question
<the decision or investigation this ticket resolves>
```
Each ticket carries a `wayfinder:<type>` label — one of `research`, `prototype`, `grilling`, `task` (see [Ticket Types](#ticket-types)).
A session **claims** a ticket by assigning it to the dev driving the map, **first**, before any work, so concurrent sessions skip it. That assignee _is_ the claim: an open, unassigned ticket is unclaimed.
Blocking uses the tracker's **native** dependency relationship — essential because it renders the frontier _visually_ in the tracker's own UI, so the human sees what's takeable without opening the map. Only a tracker that lacks native blocking falls back to a body convention. A ticket is **unblocked** when every ticket blocking it is closed; the **frontier** is the open, unblocked, unclaimed children — the edge of the known.
The answer isn't part of the body — it's recorded on resolution (see [Work through the map](#work-through-the-map)). Assets created while resolving a ticket are linked from the issue, not pasted in.
## Ticket Types
Every ticket is either **HITL** — human in the loop, worked *with* a human who speaks for themselves — or **AFK**, driven by the agent alone. A HITL ticket only resolves through that live exchange; the agent never stands in for the human's side of it (a grilling agent that answers its own questions has broken this).
- **Research** (AFK): Reading documentation, third-party APIs, or local resources like knowledge bases to surface a fact a decision waits on. Resolved by a `/research` **subagent**. Use when knowledge outside the current working directory is required.
- **Prototype** (HITL): Raise the fidelity of the discussion by making a cheap, rough, concrete artifact to react to — an outline, a rough take, a stub, or UI/logic code via the /prototype skill. Links the prototype as an asset. Use when "how should it look" or "how should it behave" is the key question.
- **Grilling** (HITL): Conversation via the /grilling and /domain-modeling skills, one question at a time. The default case.
- **Task** (HITL or AFK): Manual work that must happen before a *decision* can be made — nothing to decide, prototype, or research, but the discussion is blocked until it's done. Signing up for a service so its API can be judged, provisioning access, moving data so its shape can be seen. This is the one type that *does* rather than decides — and it earns its place by unblocking a decision, not by delivering the destination. The agent drives it alone where it can (AFK); otherwise it hands the human a precise checklist (HITL). Resolved when the work is done; the answer records what was done and any resulting facts (credentials location, new URLs, row counts) later tickets depend on.
## Fog of war
The map is _deliberately_ incomplete: don't chart what you can't yet see. Beyond the live tickets lies the **fog of war** — the dim view of decisions and investigations you can tell are coming but can't yet pin down, because they hang on questions still open. Resolving a ticket clears the fog ahead of it, graduating whatever's now specifiable into fresh tickets — one at a time, until the way to the destination is clear and no tickets remain.
The map's **Not yet specified** section is where that dim view is written down: the suspected question, the area to revisit later. It's the undiscovered frontier _toward_ the destination — everything here is in scope, just not sharp enough to ticket. Write as loosely or as fully as the view allows; it doubles as a signpost for collaborators reading where the effort is headed.
**Fog or ticket?** The test is whether you can state the question precisely now — _not_ whether you can answer it now.
- **Ticket when** the question is already sharp — even if it's blocked and you can't act on it yet.
- **Not yet specified when** you can't yet phrase it that sharply. Don't pre-slice the fog into ticket-sized pieces: it's coarser than a ticket, and one patch may graduate into several tickets, or none, once the frontier reaches it.
**Not yet specified** excludes what's already decided (Decisions so far), what's already a live ticket, and what's out of scope (the next section).
## Out of scope
Fog only ever gathers _toward_ the destination. The destination fixes the scope, so work beyond it is **out of scope** — it isn't fog, and it doesn't belong in **Not yet specified**. It gets its own **Out of scope** section on the map: work you've consciously ruled out of _this_ effort. Scope, not sharpness, lands it here.
Out-of-scope work never graduates — the frontier stops at the destination — so it returns only if the destination is redrawn, and then as a fresh effort, not a resumption.
Ruling something out of scope is a scoping act, not a step on the route. When a ticket that already exists turns out to sit past the destination — mis-scoped in while charting, or exposed by a resolution — **close it** (a closed ticket is unambiguously off the frontier) and leave one line in the **Out of scope** section: the gist plus why it's out of scope, linking the closed ticket. It stays out of **Decisions so far**, which records the route actually walked — a scope boundary isn't a step on it.
## Invocation
Two modes. Either way, **never resolve more than one ticket per session** — with the exception of research tickets.
### Chart the map
User invokes with a loose idea.
1. **Name the destination.** Run a `/grilling` and `/domain-modeling` session to pin down what this map is finding its way to — the spec, decision, or change. The destination fixes the scope, so it's settled first.
2. **Map the frontier.** Grill again, **breadth-first** this time: fan out across the whole space rather than deep on any one thread, surfacing the open decisions and the first steps takeable now. **If this surfaces no fog** — the way to the destination is already clear, the whole journey small enough for one session — you don't need a map. Stop and ask the user how they'd like to proceed.
3. **Create the map** (label `wayfinder:map`): Destination and Notes filled in, Decisions-so-far empty, the fog sketched into **Not yet specified**.
4. **Create the tickets you can specify now** as child issues of the map — then wire blocking edges in a **second pass** (issues need ids before they can reference each other). Wiring sorts them into the frontier and the blocked; everything you can't yet specify stays in the fog — the **Not yet specified** section.
5. **Fire the research subagents.** For each `research` ticket you just created, spin up a `/research` subagent to resolve it in parallel, capturing its findings on a throwaway `research/<name>` branch with a context pointer from the ticket.
6. Stop — charting is one session's work; it hand-resolves nothing.
### Work through the map
User invokes with a map (URL or number). A ticket is **optional** — without one, you pick the next decision, not the user.
1. Load the **map** — the low-res view, not every ticket body.
2. Choose the ticket. If the user named one, use it. Otherwise take the first frontier ticket in order. **Claim it**: assign it to yourself before any work.
3. Resolve it — **zoom as needed**: fetch the full body of any related or closed ticket on demand; invoke the skills the `## Notes` block names. If in doubt, use `/grilling` and `/domain-modeling`.
4. Record the resolution: post the answer as a **resolution comment**, **close** the issue, and **append a context pointer** to the map's Decisions-so-far.
5. Add newly-surfaced tickets (create-then-wire); graduate any fog the answer has made specifiable, clearing each graduated patch from **Not yet specified** so it lives only as its new ticket. If the answer reveals a ticket — this one or another — sits beyond the destination, **rule it out of scope** rather than resolving it on the route. If the decision invalidates other parts of the map, update or delete those tickets.
The user may run unblocked tickets in parallel, so expect other sessions to be editing the tracker concurrently.

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Wayfinder"
short_description: "Map a large effort as decision tickets"
policy:
allow_implicit_invocation: false

View File

@@ -0,0 +1,201 @@
# Glossary — Building Great Skills
The domain model for what makes a skill great. A skill exists to wrangle determinism out of a stochastic system; the root virtue is **Predictability**, and every term below is a lever on it. This is the disclosed reference for [`writing-great-skills`](SKILL.md).
The terms are grouped by axis: **Invocation** (how a skill is reached), **Information Hierarchy** (how its content is arranged), **Steering** (how the agent's runtime behaviour is shaped), and **Pruning** (how it is kept lean). Each **failure mode** lives beside the lever that cures it, tagged _failure mode_.
**Bold terms** in any definition are themselves defined in this glossary; find them by their heading.
## Predictability
The degree to which a skill makes the agent behave the same _way_ on every run — the same process, not the same output (a brainstorming skill should _predictably_ diverge; its tokens vary, its behaviour doesn't). The root virtue every other term serves — cost and maintainability are symptoms of it, not rivals.
_Avoid_: consistency, reliability, robustness, output-determinism
## Invocation
How a skill is reached — and the two loads you pay for the choice.
### Model-Invoked
A skill that keeps its **description** field, so the agent can see it and fire it autonomously — and the human can still type its name, so model-invocation always _includes_ user reach. There is no model-only state: a description only ever _adds_ agent discovery, never removes the human's. Pays a permanent **context load** on every turn in exchange for that discoverability. Reachable by other skills, because the description that makes it agent-discoverable makes it invocable. A model-invoked skill whose content is all **reference** is also one home for shared reference: another skill can invoke it, so reference needed by several skills lives in one place. Pick model-invocation only when the agent must reach the skill on its own; if it never fires except by hand, drop the description and pay no context load.
_Avoid_: ability, tool, capability
### User-Invoked
A skill with its **description** stripped — invisible to the agent and reachable only by the human typing its name (user-_only_, where **model-invoked** is user-_and-agent_). Trades agent-discoverability for zero **context load**. Because it has no description, nothing but the human can reach it: no other skill can fire it.
_Avoid_: procedure, workflow, command
### Description
The skill's machine-readable trigger, and the one **context pointer** a **model-invoked** skill is forced to keep loaded at all times. Its mere presence _is_ the invocation axis: keep it and the skill is model-invoked (and reachable by other skills); delete it and the skill is **user-invoked**, reachable only by the human. The source of a model-invoked skill's **context load**.
_Avoid_: frontmatter, summary
### Context Pointer
A reference held in the agent's context that names some out-of-context material and encodes the condition for reaching it. The **description** is the top-level context pointer (context window → skill); pointers to disclosed files are the same object one level down. Its wording, not the target, decides _when_ the agent reaches — and _how reliably_. A must-have target behind a weakly worded pointer is a variance bug: fix the wording first, and inline the material only if sharpening fails.
_Avoid_: link, reference, import
### Context Load
The cost a **model-invoked** skill imposes on the agent's context window — its **description**, always loaded, spending both tokens and attention. What **user-invoked** skills escape by having no description, and the brake on splitting into more model-invoked skills.
_Avoid_: token cost, context bloat
### Cognitive Load
The cost a **user-invoked** skill imposes on the human — what they must hold in their head: which skills exist and when to reach for each (the human is the index). What **model-invocation** removes by being agent-discoverable, and the brake on splitting into more user-invoked skills. Not a cost to minimise: it is the price of human agency, the reason some skills stay user-invoked. Spend it where human judgement matters; remove it where it does not.
_Avoid_: human index, burden, overhead
### Router Skill
A **user-invoked** skill whose job is to point at your other user-invoked skills — naming each and when to reach for it — so the human has one skill to remember instead of many. It can only hint, never fire them: user-invoked skills have no **description**, so nothing but the human can reach them. The cure for **cognitive load** when user-invoked skills multiply.
_Avoid_: dispatcher, menu, registry, index, router procedure
### Granularity
How finely you divide skills. Finer division spends one of the two loads: more **model-invoked** skills spend **context load** (more descriptions crowding the window and competing for attention); more **user-invoked** skills spend **cognitive load** (more for the human to remember and reach for). Two cuts guide the division. By **invocation**, split off a model-invoked skill where you have a distinct **leading word** to trigger it — a trigger word you actually use in your prompts. By **sequence**, split a run of **steps** where a step's **post-completion steps** need hiding, since isolating it in its own context clears what follows. Beware the reverse: merging sequences exposes each step's post-completion steps to what follows, inviting premature completion.
_Avoid_: chunking, modularity
## Information Hierarchy
How a skill's content is arranged, and how far down the ladder each piece sits.
### Information Hierarchy
A skill's content ranked by how immediately the agent needs it — a single ladder, produced by two cuts: in-file or behind a pointer, and step or reference. The rungs:
- **Steps** — in-file, primary
- **Reference**, in-file — secondary
- **Reference**, disclosed — behind a **context pointer**
A skill with no **steps** uses just the bottom two rungs — often a legitimately flat peer-set (e.g. every rule of a review on one rung), which is a fine arrangement, not a smell. The hierarchy is independent of invocation: a skill can be model- or user-invoked whether it is all steps, all reference, or both. When a skill has steps, in-file reference that should be disclosed buries them and turns attending to them into a coin-flip — a variance lever, not just a legibility one. Keep the top of the ladder legible; push down it whatever you can.
_Avoid_: structure, organization, layout
### Steps
The ordered actions the agent performs — when a skill has them, the primary tier of its content, and the part that earns its place in SKILL.md. Not every skill has steps: a skill can be all steps (`tdd`), all **reference** (a review), or both, independent of invocation. Every step ends on a **completion criterion**, clear or vague.
_Avoid_: workflow, instructions, choreography
### Reference
Material the agent refers to on demand — definitions, facts, parameters, examples, conditional instructions. When a skill has **steps** it is secondary to them; when a skill has none it is the entire content; or it lives outside any skill entirely — see **External Reference**. Reached via **context pointers**, and the prime candidate for **progressive disclosure**.
_Avoid_: supporting material, docs, background
### External Reference
**Reference** that lives outside the skill system — a plain file, no **description**, no **steps**, not invocable — that any skill can point at. The home for shared reference that needn't fire on its own, and the only shared home two **user-invoked** skills can use, since neither has a description and so neither can fire the other.
_Avoid_: doc, resource, knowledge base
### Progressive Disclosure
Moving **reference** down the ladder — out of SKILL.md and behind a **context pointer** — so the top stays legible. Not primarily a token optimisation; it is how the **information hierarchy** is protected. Licensed by **branching**: disclose what only some branches need, inline what every path needs, and if a pointer fires unreliably on must-have material, sharpen its wording, and pull it back inline only if that fails.
_Avoid_: lazy loading, chunking
### Co-location
Keeping the material an agent needs at once in one place — a concept's definition, rules, and caveats under a single heading, not scattered across the file — so reading one part brings its neighbours with it. The within-file companion to the **Information Hierarchy**: the hierarchy ranks _how far down_ a piece sits; co-location decides _what sits beside it_ once there. There is no formula for the right format of a body of **reference**; the test is that a skill should read like documentation written for the agent, and grouped material reads that way where scattered material does not. Distinct from **Duplication**: that repeats one meaning in two places, where scattering fragments a single meaning across many.
_Avoid_: grouping, clustering, cohesion
### Sprawl
_Failure mode._ A skill that is simply too long — too many lines in SKILL.md — independent of whether they are stale or repeated. Even an all-live, all-unique skill can sprawl. It costs readability (the agent wades through more before it can act, and attention thins across the excess), maintainability (every extra line is one more to keep **relevant**), and tokens. The cure is the **information hierarchy**: push **reference** down behind **context pointers**, and split by **branch** or sequence so each path carries only what it needs. Distinct from **sediment** (length from stale accumulation) and **duplication** (length from repeated meaning) — sprawl is length itself, whatever its cause.
_Avoid_: bloat, length, size, verbosity
## Steering
The levers that shape the agent's runtime behaviour toward **Predictability**.
### Branch
A distinct way a skill can be invoked — a case the skill handles — so different runs take different paths through it. A skill with many steps may carry many branches; a linear one has none.
_Avoid_: path, case, fork
### Leading Word
A compact concept — also called a _Leitwort_ — already living in the model's pretraining, that the agent thinks with while running the skill. It encodes a behavioural principle in the fewest possible tokens by invoking priors the model already holds (e.g. _lesson_, _proximal zone of development_, _fog of war_, _tracer bullets_). Repeated as a token, never as a sentence, it accumulates a distributed definition across the skill and anchors a whole region of behaviour. Coining your own works if you define it clearly, but a made-up word recruits no priors — you pay in definition tokens what a pretrained word gives free. Reach for an existing word first.
A leading word serves **predictability** twice. In the body it anchors **execution** — the agent reaches for the same behaviour every time the concept appears, and inside flat reference it focuses attention on a class of thing to look for, recruiting the right checks each run. In the **description** it anchors **invocation** — and not only within the skill: when the same word lives in your prompts, your docs, and your codebase, the agent links that shared language to the skill and fires it more reliably. Word a description with the leading words you actually use when you want the skill.
_Avoid_: keyword, term, motif
### Completion Criterion
The condition that tells the agent a unit of work is done — the target it judges against. Two properties make it a lever, not just a quality. Its **clarity** (can the agent tell done from not-done?) resists **premature completion** — a vague bound ("understanding reached") lets the agent declare done and slip to the next step; this axis needs _steps_ to bite, since premature completion is a between-steps failure. Its **demand** (how much it requires) sets **legwork** — "every modified model accounted for" forces thorough work where "produce a change list" does not — and this axis is _not_ step-bound: it can bind a body of flat reference too, which is how a skill with no steps still carries an exhaustiveness bar ("every rule applied"). The strongest criteria are both checkable and exhaustive.
_Avoid_: done condition, exit condition, stopping rule
### Legwork
The work an agent does behind the scenes within a single step — reading files, exploring the codebase, making changes, digging up what it needs rather than offloading to the user. It lives below the step structure: never written as its own step, latent in the wording, controlled by the agent rather than the skill. The within-step counterpart to **post-completion steps**' across-step pull. Raised by a **leading word** (_comprehensive_, _thorough_) or a **completion criterion** that demands the work be exhaustive — including the demand axis applied to flat reference, which is what drives a skill of flat reference to cover all its rungs. Goes thin either when that demand is missing or when **premature completion** cuts the step short.
_Avoid_: scope, effort, diligence, coverage
### Post-Completion Steps
The **steps** that follow the current step. Visible, they pull the agent forward into **premature completion** — the more it sees, the stronger the tug; the defence is to hide them by splitting the sequence of steps into two.
_Avoid_: horizon, fog of war, lookahead
### Premature Completion
_Failure mode._ Ending the current step before it is genuinely done, because the agent's attention slips to being done rather than to the work. A between-steps failure: it needs **steps** to occur — a skill with no steps that quits early isn't premature completion but thin **legwork** under an unmet demand. A tug-of-war between two forces: visible **post-completion steps** (the pull forward) and the **completion criterion**'s clarity (the resistance — a sharp, checkable bar holds; a vague one gives way). Fuzziness is the necessary condition: a sharp bound resists the pull no matter how many later steps are visible, so a step that never rushes needs no defending. Two levers hold a step that does, but reach for them in order: **sharpen the bound first** — it is local and cheap. Only when the criterion is irreducibly fuzzy _and_ you actually observe the rush do you **hide the later steps** — and hiding only works across a real context boundary (a user-invoked hand-off or a subagent dispatch; an inline model-invoked call leaves the later steps in context and clears nothing). One cause of thin legwork, but distinct from it: legwork can be thin even when a step runs to full completion.
_Avoid_: premature closure, the rush, rushing, shortcutting
### Negation
_Failure mode._ Steering by prohibition — telling the agent what _not_ to do — which drags the forbidden behaviour into context and makes it _more_ available, not less. _Don't think of an elephant_, and the elephant is all there is; _never write verbose comments_, and verbosity is the pattern the agent has just read. The negation is a weak modifier the strongly-activated concept overruns, so the ban half-reads as an instruction to do the thing. Its **leading word** is the _elephant_: whatever a prohibition names into the frame. Cure: prompt the **positive** — describe the target behaviour ("write one-line comments") so the banned one is never spoken. A prohibition earns its place only as a hard guardrail on a behaviour you cannot phrase positively; even then, pair it with the positive target so attention lands on what to do.
_Avoid_: ironic rebound, don't-prompting, the pink elephant
## Pruning
Keeping a skill lean — each remedy paired with the failure it cures.
### Single Source of Truth
The desired state where each meaning lives in exactly one authoritative place, so a change to the skill's behaviour is a change in one place. **Duplication** is its violation.
_Avoid_: home, canonical location
### Duplication
_Failure mode._ The same meaning given more than one **single source of truth**. It costs maintenance (change one place, you must change the others), costs tokens, and inflates prominence — repeating a meaning weights it on the ladder past its real rank. The accidental inverse of a **leading word**, which raises attention on purpose by repeating a token, never the meaning.
_Avoid_: repetition, redundancy
### Relevance
Whether a line still bears on what the skill does — the lens for what to keep. A line loses relevance either by never bearing on the task (mere exposition, or a **branch** that should be disclosed) or by going stale: drifting out of date as the behaviour or world it describes changes. Shorter skills are easier to keep relevant, because each line is cheaper to check. Distinct from **no-op**: relevance asks whether a line bears on the task, not whether it changes behaviour.
_Avoid_: load-bearing, staleness, freshness
### Sediment
_Failure mode._ Layers of old content that settle in a skill and are never cleared, because adding feels safe and removing feels risky — so stale and irrelevant lines accumulate and you must core down through them to find what is still live. The default fate of any skill without a pruning discipline; the slow erosion of **relevance**, as opposed to **duplication**'s repeated meaning.
_Avoid_: accretion, bloat, cruft, rot
### No-Op
_Failure mode._ An instruction that changes nothing because the model already does it by default — you pay load to tell the agent what it would do anyway. The test: does a line change behaviour versus the default? A line can be perfectly **relevant** and still be a no-op. The same priors that make a **leading word** free make a no-op worthless.
A leading word is a _technique_; No-Op is a _verdict_ on a line — and they cross. A leading word too weak to beat the default is a no-op (_be thorough_ when the agent is already thorough-ish), and the fix is a stronger word that passes the verdict (_relentless_), not a different technique. So the No-Op test — does it change behaviour versus the default? — is also how you grade whether a leading word is earning its repetitions. This is model-relative, not reader-relative: two people disagreeing over whether a line is a no-op disagree about the default, and settle it by running the skill, not by debate.
_Avoid_: redundant instruction, restating the obvious, belaboring

View File

@@ -0,0 +1,83 @@
---
name: writing-great-skills
description: Reference for writing and editing skills well — the vocabulary and principles that make a skill predictable.
disable-model-invocation: true
---
A skill exists to wrangle determinism out of a stochastic system. **Predictability** — the agent taking the same _process_ every run, not producing the same output — is the root virtue; every lever below serves it.
**Bold terms** are defined in [`GLOSSARY.md`](GLOSSARY.md); look them up there for the full meaning.
## Invocation
Two choices, trading different costs:
- A **model-invoked** skill keeps a **description**, so the agent can fire it autonomously _and_ other skills can reach it (you can still type its name too). It contributes to **context load** — the description sits in the window every turn. Mechanics: omit `disable-model-invocation`, and write a model-facing description with rich trigger phrasing ("Use when the user wants…, mentions…").
- A **user-invoked** skill strips the description from the agent's reach: only you, typing its name, can invoke it — and no other skill can. Zero context load, but it spends **cognitive load**: _you_ are the index that must remember it exists. Mechanics: set `disable-model-invocation: true`; the `description` becomes human-facing — a one-line summary, trigger lists stripped.
Pick model-invocation only when the agent must reach the skill on its own, or another skill must. If it only ever fires by hand, make it user-invoked and pay no context load.
When user-invoked skills multiply past what you can remember, that piled-up cognitive load is cured by a **router skill**: one user-invoked skill that names the others and when to reach for each.
## Writing the description
A model-invoked **description** does two jobs — state what the skill is, and list the **branches** that should trigger it. Every word increases **context load**, so a description earns even harder pruning than the body:
- **Front-load the skill's leading word** — the description is where it does its invocation work.
- **One trigger per branch.** Synonyms that rename a single branch are **duplication** — "build features using TDD … asks for test-first development" is one branch written twice. Collapse them; keep only genuinely distinct branches.
- **Cut identity that's already in the body.** Keep the description to triggers, plus any "when another skill needs…" reach clause.
## Information hierarchy
A skill is built from two content types — **steps** and **reference** — that mix freely: a skill can be all steps, all reference, or both. The core decision is which to use and where each sits on the **information hierarchy**, a ladder ranked by how immediately the agent needs the material:
1. **In-skill step** — an ordered action in `SKILL.md`, the primary tier: what the agent does, in order. Each step ends on a **completion criterion**, the condition that tells the agent the work is done. Make it _checkable_ (can the agent tell done from not-done?) and, where it matters, _exhaustive_ ("every modified model accounted for", not "produce a change list") — a vague criterion invites **premature completion**.
2. **In-skill reference** — a definition, rule, or fact in `SKILL.md`, consulted on demand. Often a legitimately flat peer-set (every rule of a review on one rung) — a fine arrangement, not a smell. _This skill is all reference._
3. **External reference** — reference pushed out of `SKILL.md` into a separate file, reached by a **context pointer**, loaded only when the pointer fires. (Spans _disclosed_ reference — a sibling file like `GLOSSARY.md`, still part of the skill — through fully **external reference** that lives outside the skill system and any skill can point at.)
A demanding completion criterion drives thorough **legwork** — the digging the agent does within the work — whether the skill has steps or not, since "every rule applied" binds flat reference just as "every step done" binds a sequence.
Push too little down and the top bloats; push too much and you hide material the agent actually needs. That tension is the whole decision.
**Progressive disclosure** is the move down the ladder — out of `SKILL.md` into a linked file — so the top stays legible. Mechanics: a linked `.md` file in the skill folder, named for what it holds (this skill discloses its full definitions to `GLOSSARY.md`). Some skills are used in more than one way, and each distinct way is a **branch** — different runs taking different paths through the skill. Branching is the cleanest disclosure test: inline what every branch needs, and push behind a pointer what only some branches reach. A **context pointer**'s _wording_, not its target, decides when and how reliably the agent reaches the material.
Where the ladder decides _how far down_ a piece sits, **co-location** decides _what sits beside it_ once there: keep a concept's definition, rules, and caveats under one heading rather than scattered, so reading one part brings its neighbours with it.
## When to split
**Granularity** is how finely you divide skills, and each cut spends one of the two loads, so split only when the cut earns it. Two cuts:
- **By invocation** — split off a **model-invoked** skill when you have a distinct **leading word** that should trigger it on its own, or another skill must reach it. You pay **context load** for the new always-loaded **description**, so that independent reach has to be worth it.
- **By sequence** — split a run of **steps** when the steps still ahead (a step's **post-completion steps**) tempt the agent to rush the one in front of it (**premature completion**). Keeping them out of view encourages the agent to do more **legwork** on the current task.
## Pruning
Keep each meaning in a **single source of truth**: one authoritative place, so changing the behaviour is a one-place edit.
Check every line for **relevance**: does it still bear on what the skill does?
Then hunt **no-ops** sentence by sentence, not just line by line: run the no-op test on each sentence in isolation, and when one fails, delete the whole sentence rather than trim words from it. Be aggressive — most prose that fails should go, not be rewritten.
## Leading words
A **leading word** is a compact concept already living in the model's pretraining that the agent thinks with while running the skill (e.g. _lesson_, _fog of war_, _tracer bullets_). Repeated throughout the text (though not necessarily - a strong leading word might only be needed once), it accumulates a distributed definition and anchors a whole region of behaviour in the fewest tokens, by recruiting priors the model already holds.
It serves predictability twice. In the body it anchors _execution_: the agent reaches for the same behaviour every time the word appears. In the description it anchors _invocation_: when the same word lives in your prompts, docs, and code, the agent links that shared language to the skill and fires it more reliably.
Hunt for opportunities to refactor skills to use leading words. A triad spelled out at three sites (**duplication**), a description spending a sentence to gesture at one idea — each is a passage begging to **collapse** into a single token. Examples include:
- "fast, deterministic, low-overhead" -> _tight_ — one quality restated across a phase — into a single pretrained word (a _tight_ loop).
- "a loop you believe in" -> _red_ — converts a fuzzy gate into a binary observable state (the loop goes _red_ on the bug, or it doesn't).
You win twice over: fewer tokens, _and_ a sharper hook for the agent to hang its thinking on. Assume every skill is carrying restatements that leading words retire — go find them.
## Failure modes
Use these to diagnose issues the user may be having with the skill.
- **Premature completion** — ending a step before it's genuinely done, attention slipping to _being done_. Defence, in order: sharpen the completion criterion first (cheap, local); only if it is irreducibly fuzzy _and_ you observe the rush, hide the post-completion steps by splitting (the sequence cut).
- **Duplication** — the same meaning in more than one place. Costs maintenance and tokens, and inflates a meaning's prominence on the ladder past its real rank.
- **Sediment** — stale layers that settle because adding feels safe and removing feels risky. The default fate of any skill without a pruning discipline.
- **Sprawl** — a skill simply too long, even when every line is live and unique. Hurts readability and maintainability and wastes tokens. The cure is the ladder: disclose **reference** behind pointers, and split by **branch** or sequence so each path carries only what it needs.
- **No-op** — a line the model already obeys by default, so you pay load to say nothing. The test: does it change behaviour versus the default? A weak leading word (_be thorough_ when the agent is already thorough-ish) is a no-op; the fix is a stronger word (_relentless_), not a different technique.
- **Negation** — steering by prohibition backfires: _don't think of an elephant_ names the elephant and makes it more available, not less. Prompt the **positive** — state the target behaviour so the banned one is never spoken; keep a prohibition only as a hard guardrail you can't phrase positively, and even then pair it with what to do instead.

View File

@@ -0,0 +1,5 @@
interface:
display_name: "Writing Great Skills"
short_description: "Principles for predictable skills"
policy:
allow_implicit_invocation: false

1
.claude/skills/ask-matt Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/ask-matt

1
.claude/skills/code-review Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/code-review

View File

@@ -0,0 +1 @@
../../.agents/skills/codebase-design

View File

@@ -0,0 +1 @@
../../.agents/skills/diagnosing-bugs

View File

@@ -0,0 +1 @@
../../.agents/skills/domain-modeling

1
.claude/skills/grilling Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/grilling

1
.claude/skills/implement Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/implement

1
.claude/skills/research Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/research

View File

@@ -0,0 +1 @@
../../.agents/skills/resolving-merge-conflicts

1
.claude/skills/to-spec Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/to-spec

1
.claude/skills/to-tickets Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/to-tickets

1
.claude/skills/wayfinder Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/wayfinder

View File

@@ -0,0 +1 @@
../../.agents/skills/writing-great-skills

View File

@@ -24,7 +24,7 @@ export JUNHONG_DATABASE_SSLMODE="disable"
export JUNHONG_REDIS_ADDRESS="cxd.whcxd.cn"
export JUNHONG_REDIS_PORT="16299"
export JUNHONG_REDIS_PASSWORD="cpNbWtAaqgo1YJmbMp3h"
export JUNHONG_REDIS_DB="6"
export JUNHONG_REDIS_DB="7"
# ----------------------------------------------------------------------------
# JWT 配置(必填)

View File

@@ -3,7 +3,7 @@ name: 构建并部署到测试环境(无 SSH
on:
push:
branches:
- main
- Iteration/7-11
- dev
- test
@@ -30,7 +30,7 @@ jobs:
- name: 设置镜像标签
id: tag
run: |
if [ "${{ github.ref }}" = "refs/heads/main" ]; then
if [ "${{ github.ref }}" = "refs/heads/Iteration/7-11" ]; then
echo "tag=latest" >> $GITHUB_OUTPUT
elif [ "${{ github.ref }}" = "refs/heads/dev" ]; then
echo "tag=dev" >> $GITHUB_OUTPUT
@@ -61,8 +61,8 @@ jobs:
docker push ${{ env.WORKER_IMAGE }}:${{ steps.tag.outputs.tag }}
docker push ${{ env.WORKER_IMAGE }}:${{ github.sha }}
- name: 部署到本地(仅 main 分支)
if: github.ref == 'refs/heads/main'
- name: 部署到本地(仅 Iteration/7-11 分支)
if: github.ref == 'refs/heads/Iteration/7-11'
run: |
# 确保部署目录存在(仅需日志目录,配置已嵌入二进制文件)
mkdir -p ${{ env.DEPLOY_DIR }}/logs

View File

@@ -0,0 +1,159 @@
# PRDTECH 全局多视角审计与外部集成追踪
Status: ready-for-agent
---
## Problem Statement
当前系统只有账号操作日志、资产操作日志和手动轮询日志等局部实现。它们的操作者、资源、结果和查询结构不一致,账号与资产审计使用裸 goroutine 写入,进程退出或数据库短暂失败时会丢失;资金、审批、配置和跨模块业务又缺少统一审计。现有记录无法从一次请求、一个业务链路或多个受影响资源串联完整过程。
Gateway、运营商、企业微信和支付等外部交互也没有通用 Integration Log。七月迭代的状态同步、审批和资金处理如果继续各建日志将无法解释“为什么没有请求上游”“哪次回调改变了业务状态”以及“某次资金变化对应哪个审批”。
Access Log 当前只递归脱敏请求体,响应体仍原样记录,登录 Token、个人数据和敏感配置存在泄漏风险回调和文件路由也缺少专门的正文记录策略。
## Solution
一次停机发布切换到四类边界清晰的记录Access Log 负责 HTTP 调试Audit Event 负责不可变业务审计,现有钱包流水/订单/退款等 Domain Ledger 继续作为领域事实Integration Log 负责外部交互和未实际发出的同步尝试。Audit Event 通过资源关系表关联一个操作涉及的多个资源,并用 `request_id/correlation_id/parent_event_id` 串联请求和跨任务业务链路。
本次切换覆盖全部现有敏感写操作:新旧业务统一使用 Audit Writer旧账号、资产和手动轮询审计表停止新增不双写历史数据保留原表并通过 Query 只读投影到新审计中心。切换准备或验证失败则本次版本整体不放量,不能以局部模块继续写旧表作为中间态。
## User Stories
1. 作为审计人员,我希望回答谁在什么入口对哪些资源做了什么,结果、风险和前后变化是什么。
2. 作为运维人员,我希望按 `request_id``correlation_id` 查看一次请求或完整业务链路中的审计、任务、外部交互和领域流水。
3. 作为资产运营人员,我希望从卡、设备、退款、订单、钱包等资源查看跨模块时间线,而不被普通无变化轮询淹没。
4. 作为财务人员,我希望资金审计能关联审批、业务单、钱包流水和资产处理,同时明确钱包流水才是金额事实。
5. 作为安全人员,我希望集中查看失败、拒绝、高风险和严重事件,并确保敏感字段默认脱敏。
6. 作为集成运维人员,我希望看到 Gateway、运营商、企微和支付的脱敏请求结果以及合并、限流、提前完成等未发请求原因。
7. 作为历史数据查询者,我希望旧账号、资产和手动轮询记录仍可只读检索,但发布后不再出现新旧两份不一致记录。
8. 作为普通代理或企业用户,我希望只能在原业务详情看到自己有权限资源的脱敏轨迹,不能进入平台全局审计中心。
## Implementation Decisions
### 四类记录的权威边界
- Access Log 存储在现有日志文件/日志平台,只用于 HTTP 调试、性能和 `request_id` 检索,不作为业务事实或业务审计权威。
- Audit Event 存储在 PostgreSQL回答操作者、动作、资源、结果、风险和字段变化。事件创建后不可更新或删除普通读操作不创建 Audit Event敏感读取例外。
- Domain Ledger 继续由钱包流水、订单、退款、充值、企微审批实例、套餐使用记录等业务表承担。审计 Query 可以链接或投影这些记录,但 Audit Event 不替代领域事实。
- Integration Log 存储 Gateway、运营商回调、企微、微信/支付宝及其他外部交互,也记录业务同步尝试在发请求前被 `merged/rate_limited/completed/cancelled` 的解释结果。
- 普通高频轮询成功且状态未变化只写 Integration Log状态变化、人工强制触发、连续失败或高风险异常再写 Audit Event。
- Outbox 和通用异步任务状态是可靠投递/执行事实,不塞入 Audit Event JSON。审计链路 Query 通过稳定 ID 关联它们。
### Audit Event 数据模型
- 新建 `tb_audit_event`,核心字段包括:不可变唯一 `event_id``occurred_at`、类别、动作编码/名称、操作者快照、入口来源、租户/店铺/企业标签、结果、风险、摘要、错误码/摘要、前后数据、元数据、请求/关联/父事件 ID、IP/User-Agent/路径/方法、`content_hash` 和创建时间。
- `result` 为 string 类型:`success/failed/denied/partial``risk_level` 为 string`normal/warning/high/critical`。操作者、来源、类别和动作均使用集中常量或注册表,不允许各 Service 自由拼接 magic string。
- `actor_kind` 至少支持 `admin_user/agent_user/enterprise_user/personal_customer/open_api_account/system_task/carrier_callback/wecom_callback`。系统和回调允许 `actor_id=NULL`,但 `actor_name` 必须是可读快照。
- `source` 表示入口而不是人员,至少支持 `admin_api/personal_api/open_api/asynq/scheduled_job/gateway/carrier_callback.* /wecom_callback/wecom_polling/data_migration`
- 新建 `tb_audit_event_resource`,每个事件可关联多个 `primary/affected/reference` 资源;字段为事件内部 ID、资源类型、可空资源 ID、资源键快照、关系和创建时间。一个事件至少有一个 `primary` 资源。
- 资源关系使用复合唯一索引,资源 ID 和资源键各有时间线索引;不建立数据库外键或 GORM 关联标签。
- `content_hash` 基于脱敏、标准化后的不可变事件内容生成,用于完整性核对,不包含数据库自增 ID。Repository 不提供 Update/Delete 方法。
- `before_data``after_data``metadata` 分别最多 16KB超限时保存截断标志、原字节数、摘要和受控任务/制品引用,批量明细留在对应业务任务表或对象存储。
### 动作注册表与写入可靠性
- 建立 Action Registry定义稳定动作编码、中文名称、类别、默认风险、允许的资源类型和敏感字段规则DTO 枚举说明、筛选项和前端名称都从同一注册表生成。
- 至少覆盖账号/角色/权限、店铺、资产、套餐、钱包/资金、订单/退款/充值、企微、支付与系统配置、数据同步、导入导出及登录安全的本期动作。未经注册的动作不得写入生产审计。
- 钱包余额、人工退款结果、代理钱包回退、线下充值入账、账号角色/权限、支付/企微/关键系统配置、人工卡状态、敏感店铺业务员归属及手工绑定企微审批号等成功事件必须与业务变更同事务 `AppendWithTx`;审计失败则业务事务回滚。
- 旧 MVC Service 未迁移为 DDD 时通过统一 Audit Writer Adapter 接入新模型,不要求为审计一次性重构全部业务;但当前触碰的复杂资金、审批和卡状态用例仍按各自 Spec 迁入 Application/Domain。
- 业务已经回滚的 `failed/denied` 事件使用独立短事务写入,禁止裸 goroutine。该审计再失败时保留原业务错误同时写 `critical` 应用日志和监控指标。
- 异步系统事件与状态变化通过原业务事务或 Outbox 可靠关联,不使用 `go func()`。Asynq/Outbox 载荷必须传递 `event_id/request_id/correlation_id/parent_event_id`
- `request_id` 由现有中间件生成并贯穿同一 HTTP 请求;`correlation_id` 在退款、充值、审批、钱包、卡状态等跨请求业务起点生成并贯穿 Outbox/Asynq/Integration Log`parent_event_id` 表示直接因果,不用于替代 correlation。
- 对全部旧审计调用建立切换清单和自动检查。发布产物中禁止继续调用旧 `account_audit/asset_audit` 写服务或直接 Create 旧日志模型;启动装配不再注入旧 Writer。
### Integration Log
- 新建 `tb_integration_log`,至少保存唯一 `integration_id`、provider、方向、operation、外部单号、资源、触发来源/场景/序列/尝试、计划/开始时间、结果、HTTP/渠道码及摘要、脱敏请求响应摘要、耗时、是否改变状态、元数据、请求/关联 ID、可空 Audit Event ID 和创建时间。
- `direction``inbound/outbound``result` 至少支持 `success/failed/not_found/invalid_payload/ignored/merged/rate_limited/completed/cancelled`;实施可增加内部 `pending` 执行态,但公开 DTO 必须返回中文结果名称并保持终态语义明确。
- 一次外部尝试使用稳定 `integration_id`。实际调用前先持久化可恢复的尝试事实,完成后条件更新终态;若发出请求后响应未知,必须记录“结果未知”,不得伪装为普通失败并盲目重发具有副作用的外部请求。
- 数据同步按 UR#94 记录 `trigger_source/scene/series/attempt`;同序列详情一次返回 0/3/5 全部尝试。合并、互斥、限频和已达预期即使没有 HTTP 状态也必须可解释。
- 运营商/支付/企微入站回调先保存脱敏摘要和幂等标识,再进入业务处理;原始加密报文、完整回调正文、签名和附件不进入普通审计详情。
- Integration Log 只保存外部交互事实,不存业务审批/支付/卡状态的权威状态;业务改变时通过 `audit_event_id/correlation_id` 关联。
### 脱敏与 Access Log 修正
- 永不进入 Audit/Integration/Access 正文的数据包括密码、操作密码、验证码、Access/Refresh Token、Secret、回调 Token/EncodingAESKey、支付私钥/公钥原文、完整身份证、对象存储签名 URL、企微 `media_id` 和 Authorization/Cookie。Sanitizer 直接删除或只保留字段存在/长度,不把原值保存成可逆掩码。
- 手机号、IP、ICCID、钱包金额和第三方交易号允许在受控审计存储中作为业务快照但普通 Query 默认脱敏;完整查看需要 `audit:sensitive:view`,导出需要独立 `audit:export` 和字段授权。
- 查看完整敏感值本身写高风险 Audit Event携带被查看事件/资源和操作者;不能因为已有全局查看权限跳过二次审计。
- Access Log 的响应体必须和请求体使用同一递归 Sanitizer再执行 50KB 限制;当前 `truncateBody(c.Response().Body())` 原样记录行为必须移除。
- 路由级策略:登录/Token/支付或企微配置只记字段名和长度;支付、企微、运营商回调只记摘要与哈希;文件上传下载不记文件内容和签名 URL普通 JSON 脱敏后最多 50KB。
- 非 JSON 解析失败不能直接原样记录敏感回调或文件应先应用路由策略和安全文本截断。Query 参数和 Header 同样覆盖 token、secret、sign、nonce、authorization、cookie 等字段。
### 一次性切换与历史投影
- 本需求是经用户确认的全局例外:在同一次停机发布中完成新表/索引、Audit Writer、Integration Writer、现有敏感写入口、Query API 和必要前端切换。不得按模块长期双轨运行。
-`tb_account_operation_log``tb_asset_operation_log``tb_polling_manual_trigger_log` 发布后停止新写入,不删除、不回填新表。数据库权限或运行时写入护栏应使意外旧写尽快暴露,不能静默继续。
- 旧手动轮询日志当前还承担进度状态。切换时其用户可见的手动触发、进度和监控接口保持原契约,但运行状态由七月公共异步任务状态承接,外部尝试由 Integration Log 承接;不得因停写旧表使运维功能消失。
- 历史 Query 使用 `UNION ALL` 把旧账号、资产和手动轮询记录规范化为只读投影,返回 `record_source=legacy_account/legacy_asset/legacy_polling` 和确定性历史事件键;旧记录不伪造不存在的 correlation、风险或多资源关系。
- 现有 `GET /api/admin/assets/{identifier}/operation-logs` 在过渡期保留兼容响应,但读取新 Audit Event 与旧资产投影,不再直接绑定旧表;新前端以全局资源时间线为准。
- 发布门禁要求旧写入口清单为零、新旧 Query 样本对账通过、关键事务审计失败回滚通过、Access Log 脱敏通过。任一失败则在开放流量前整体停止发布。
- 数据迁移全部为增量且可回滚。新系统一旦接收生产写入,已生成 Audit/Integration/Outbox 记录不得删除回滚;应用采用前向修复,不能回到旧 Writer 形成新的分裂历史。
### 查询 API 与权限
- 全局审计中心提供:
- `GET /api/admin/audit/events``/{event_id}`
- `GET /api/admin/audit/actors``/{kind}/{id}/summary``/{kind}/{id}/events`
- `GET /api/admin/audit/resources/search``/{type}/{id}/timeline`
- `GET /api/admin/audit/requests/{request_id}/timeline`
- `GET /api/admin/audit/correlations/{correlation_id}/timeline`
- `GET /api/admin/audit/risks/overview``/events`
- `GET /api/admin/audit/integrations``/{id}`
- `GET /api/admin/audit/finance/timeline`
- `POST /api/admin/audit/exports`
- 所有列表服务端分页,默认 20、最大 100稳定时间+ID排序。公共关键词只匹配已有索引支持的摘要、资源键、操作者和请求 ID不对 JSONB 做无索引模糊扫描。
- 资源搜索先查询业务读模型返回候选 `resource_type/id/key/display_name`,再打开时间线;静态 `/resources/search` 必须先于动态资源路由。`include_related=true` 只展开事件已直接关联资源,不递归遍历图。
- Request Timeline 组合数据库中可关联的 Audit Event、Outbox/任务摘要和 Integration LogAccess Log 仍在文件/日志平台API 只返回事件内已快照的 HTTP 摘要和 `request_id` 日志检索标识,不在请求时扫描本地日志文件。
- Finance Timeline 组合 Audit Event 与钱包流水、订单、退款、充值和企微实例,每条明确 `record_source`;金额结论以 Domain Ledger 为准。
- 权限码至少拆分 `audit:global:view/actor:view/resource:view/request:view/risk:view/integration:view/finance:view/sensitive:view/export`。超级管理员拥有全量;普通平台角色按授权和原数据范围取交集。
- 代理和企业账号不能进入全局、人员、风险、资金全局或外部集成中心在业务详情查看资源轨迹时Query 必须重新执行店铺/企业权限和字段脱敏。前端隐藏 Tab 不是授权边界。
- 审计导出复用统一 Export DataSource创建时快照过滤条件、数据范围、字段授权和脱敏级别敏感查看权限不自动授予敏感导出权限权限解析失败时拒绝而非回退全字段。
### 前端审计中心
- `/operations/audit` 使用工作台式 Tab全局事件、人员行为、资源轨迹、请求/业务链路、资金审计、风险事件、外部集成Tab 和字段以后端权限为准。
- 全局事件表展示时间、风险、操作者、操作、主要资源、来源、结果和 request ID行详情抽屉分为事件摘要、操作者/入口、关联资源、结构化字段差异、请求/业务链路和错误/外部交互。
- 资源轨迹先搜索候选再选择,普通无变化轮询不进入业务时间线;外部集成 Tab 可按 provider、operation、方向、结果、资源、触发来源/场景/序列筛选,并连续展示 0/3/5 尝试。
- 人员、风险、请求和业务链路使用服务端汇总/时间线,不由前端下载全量事件再聚合。第一版不做自动封禁、风险处置工单或自由拖拽关系图。
- 敏感字段默认掩码;有权限用户点击“显示敏感数据”后重新请求受控接口并产生敏感读取审计。无权限、历史字段不存在和数据已按策略删除均使用明确但不泄密的状态。
### 保留、清理与可观测性
- 资金、权限、审批和关键配置 Audit Event 保留 5 年;普通资产/业务 Audit Event 保留 2 年Audit Event 默认不由在线应用删除。
- Integration Log 默认 180 天Gateway 无变化成功记录 30 天,异常或状态变化记录 180 天Access Log 保留 30 天。清理按时间/主键分批执行并记录结果。
- 达到单表维护阈值后按月分区并归档超期分区,本期不为尚未达到阈值预建复杂分区管理,但表和 Query 必须支持后续演进。
- 应用运行账号不提供 Audit Event Update/Delete 能力;归档/清理由独立受控维护身份执行。Integration Log 只允许执行态到终态的受控条件更新,不允许事后改写请求结果。
- 监控 Audit/Integration 写入失败、失败短事务失败、旧表意外新增、Outbox 积压、Integration Log 增长/清理、敏感读取和导出次数。
## Testing Decisions
- 领域/Application 测试覆盖事件不可变、多资源至少一个 primary、动作注册、风险默认值、内容哈希稳定、16KB 截断和禁止字段删除。
- PostgreSQL 集成测试验证唯一/查询索引、关键业务与 Audit Event 同事务、审计写入失败回滚、失败/拒绝短事务、重复事件幂等和资源时间线。
- 对账号、角色权限、资产、套餐、钱包、退款、充值、配置、导入导出、登录安全和手动同步建立切换清单;自动测试或静态检查证明生产装配不再调用旧 Writer旧三表发布后无新增。
- 历史投影测试使用旧账号/资产/手动轮询样本,验证 `UNION ALL` 的字段映射、确定性历史键、分页排序、`record_source` 和新旧交界时间无重复/漏项。
- Integration 测试覆盖 outbound 成功/失败/响应未知、inbound 回调、未发送的 merged/rate_limited/completed、同序列 0/3/5、状态变化关联 Audit Event 和重复回调。
- Access Log 测试覆盖嵌套 JSON、数组、非 JSON、登录/Token、支付/企微/运营商回调、上传下载和响应体,证明 Token、Secret、操作密码、签名 URL、Authorization、Cookie 等不落盘且 50KB 生效。
- 权限测试覆盖超级管理员、不同平台角色、代理和企业;验证 Tab、API、字段、资源范围、敏感查看与导出权限相互独立越权资源不泄露存在性。
- Query 性能测试使用代表性事件/资源/Integration 数据,验证分页和常用过滤使用索引、无 JSONB 全表模糊扫描、无资源/操作者 N+1满足项目 P95/P99 目标。
- HTTP 集成测试穿过真实 Fiber 认证、Handler、Query/GORM 和统一错误响应;新 Handler 同步注册两个 OpenAPI 文档生成器并验证静态/动态路由顺序。
- 停机发布演练覆盖暂停 Worker、迁移、旧写护栏、新 Writer 切换、样本对账、恢复 Worker、放量前失败退出和放量后的前向修复已生成审计数据不得通过清表回滚。
- 前端验收覆盖七个视角、权限空态、历史投影、资源候选、request/correlation 跳转、0/3/5 序列、敏感二次查看、导出和错误状态。
## Out of Scope
- 不把 Access Log、Audit Event、Domain Ledger 和 Integration Log 合并成一张万能日志表。
- 不把普通列表、详情和未读数查询全部写成业务审计;只审计敏感读取。
- 不在线回填旧日志到新表,不长期双写新旧审计,不删除旧历史表。
- 不为数据同步另建 `tb_card_sync_execution` 或独立同步审计页面。
- 不把整个旧业务仓库一次性迁成 DDD只统一其审计 Adapter复杂用例按各自需求迁移。
- 不建设自动风控封禁、风险处置工单、自由关系图或实时行为分析平台。
- 不在 API 请求中扫描本地 Access Log 文件,也不把日志文件升级为业务权威存储。
- 不允许应用用户修改/删除 Audit Event不在普通审计详情暴露完整外部报文和密钥。
## Further Notes
- 用户已明确确认一次性全局切换,覆盖标准稿中的“旧写停止、不双写、历史只读投影”口径;这不是可由实现阶段改回渐进双写的建议项。
- 当前已核实旧账号/资产审计使用裸 goroutineAccess Log 响应体未脱敏;这两项是发布前必须消除的现存缺陷。
- 当前手动轮询日志兼做进度存储,切断旧表时必须先由公共异步任务状态承接,不得违反 UR#94“轮询管理外部行为保持现状”的确认结论。
- 本需求较大,进入实现前应依据本 Spec 拆成可独立验证的纵向切片,但不得按“先建表、再 Service、再 Handler”的水平层级拆分也不得改变一次停机切换这一最终发布门禁。

View File

@@ -0,0 +1,18 @@
# 01 — 交付不可变 Audit Event 写入闭环
**What to build:** 业务用例可以通过统一 Audit Writer 写入不可变、多资源、可串联且默认脱敏的审计事件。成功事件能够与业务事实共用事务,失败或拒绝事件使用独立短事务保留;未注册动作、缺少主要资源或审计写入失败时按明确策略阻止错误事实落地。
**Blocked by:** `.scratch/tech-public-foundation/issues/01-public-migration-ownership-and-gates.md` — 01 — 建立公共迁移所有权与检查门禁
**Status:** ready-for-agent
**架构通道:** 主通道为 Application + Port/Adapter辅助通道为 Infrastructure。
**完整业务边界:** 本票收口 Audit Event、事件资源、动作注册表、统一 Sanitizer、内容哈希、大小控制和 Writer 可靠性,并用一个代表性敏感写操作验证公开接缝。明确不迁移其他旧 Service不提供完整审计查询中心不用 Audit Event 替代领域流水。
- [ ] Audit Event 支持稳定事件 ID、操作者与入口快照、结果、风险、前后数据、请求/关联/父事件 ID、HTTP 摘要、内容哈希和创建时间;事件资源支持 `primary/affected/reference`,且每个事件至少包含一个 `primary`
- [ ] 动作注册表集中定义稳定动作编码、中文名称、类别、默认风险、允许资源类型和敏感字段规则;未经注册的动作不能写入生产审计。
- [ ] 统一 Sanitizer 删除禁止字段;`before_data``after_data``metadata` 分别执行 16KB 上限,超限后保存截断标志、原字节数、摘要和受控制品引用。
- [ ] `content_hash` 基于脱敏、标准化后的不可变内容生成,不包含数据库自增 ID相同内容哈希稳定Repository 不提供 Update/Delete 能力。
- [ ] `AppendWithTx` 与业务事实使用同一 GORM 事务,任一步失败整体回滚;已经回滚的 `failed/denied` 使用独立短事务,二次失败保留原业务错误并产生 critical 日志和指标。
- [ ] 真实 PostgreSQL 集成测试覆盖不可变约束、多资源、动作注册、风险默认值、哈希、截断、禁止字段、重复事件幂等和事务回滚。

View File

@@ -0,0 +1,18 @@
# 02 — 交付可恢复的 Integration Log 尝试闭环
**What to build:** 外部调用和未实际发出的同步尝试都能以稳定 Integration ID 建立可恢复事实,并通过受控条件更新进入明确终态。入站回调在业务处理前保存脱敏摘要和幂等标识,出站响应未知时保留未知结论而不伪装成普通失败。
**Blocked by:** `.scratch/tech-public-foundation/issues/01-public-migration-ownership-and-gates.md` — 01 — 建立公共迁移所有权与检查门禁
**Status:** ready-for-agent
**架构通道:** 主通道为 Infrastructure辅助通道为 Application + Port/Adapter。
**完整业务边界:** 本票收口 Integration Log 模型、Writer、执行态到终态的条件更新、入站摘要和未发送结果语义。明确不接管 Gateway、支付、企微或运营商的业务状态机不把外部交互记录作为业务权威状态。
- [ ] Integration Log 支持 provider、方向、operation、外部单号、资源、触发来源/场景/序列/尝试、计划与开始时间、结果、渠道摘要、脱敏请求响应摘要、耗时、状态变化标志和关联 ID。
- [ ] 方向固定为 `inbound/outbound`;公开终态至少覆盖成功、失败、未找到、无效载荷、忽略、合并、限频、提前完成和取消,并返回对应中文名称。
- [ ] 实际外部调用前持久化稳定尝试身份,完成后使用预期状态条件更新;并发完成、重复回调或重复消费不能改写既有终态。
- [ ] 请求已发出但响应未知时记录明确的未知结论和恢复策略,不自动把具有副作用的请求当成普通失败盲目重发。
- [ ] 入站回调先保存脱敏摘要、内容哈希和幂等标识;原始密文、完整正文、签名、附件和密钥不进入普通记录。
- [ ] PostgreSQL 集成测试覆盖出站成功、明确失败、响应未知、未发送终态、入站回调、重复回调、条件更新冲突和 Audit Event 关联。

View File

@@ -0,0 +1,21 @@
# 03 — 完成 Access Log 全路由敏感信息防泄漏
**What to build:** 当前项目所有敏感 HTTP 路由均使用统一的请求、响应、Query 和 Header 脱敏及路由级安全摘要策略。即使正文不是 JSON、解析失败或属于文件载荷也不会把可复用凭证、完整回调或文件内容写入 Access Log。
**Blocked by:**
- `.scratch/tech-public-foundation/issues/09-access-log-recursive-redaction.md` — 09 — 统一 Access Log 请求与响应递归脱敏
- `.scratch/tech-public-foundation/issues/10-sensitive-route-safe-summaries.md` — 10 — 为敏感接口提供安全摘要策略
**Status:** ready-for-agent
**架构通道:** Infrastructure。
**完整业务边界:** 本票将公共 Access Log 安全能力应用到当前仓库真实路由并建立固定回归矩阵。明确不修改业务响应,不创建审计事实,不把 Access Log 升级为业务权威存储。
- [ ] 登录、Token、支付与企微配置路由只记录字段存在性、长度和安全结果不记录密码、验证码、Token、Secret、密钥或完整配置值。
- [ ] 支付、企微和运营商回调只记录事件类型、安全资源标识、大小、内容类型、摘要哈希与处理结果,不记录密文、完整正文、签名或附件。
- [ ] 上传、下载和导出路由不记录文件字节、Base64、multipart 正文、临时凭证或签名 URL只保留脱敏文件元数据和任务标识。
- [ ] Query 和 Header 覆盖 token、secret、sign、nonce、authorization、cookie 等大小写变体;请求和响应均先脱敏再执行 50KB 截断。
- [ ] 非 JSON、XML、表单、二进制及解析失败场景均按路由策略安全降级不能回退记录原文。
- [ ] 真实 Fiber 测试捕获最终 Access Log覆盖敏感路由矩阵并断言测试凭证、操作密码、回调原文、签名 URL、Authorization 和 Cookie 均未落盘。

View File

@@ -0,0 +1,18 @@
# 04 — 迁移账号、角色与权限敏感操作到统一审计
**What to build:** 账号、角色和权限敏感操作通过统一 Audit Writer 记录操作者、动作、目标资源、结果、风险和前后变化。关键成功审计与业务修改同事务,拒绝和失败审计可可靠保留,这些入口不再调用旧账号审计 Writer。
**Blocked by:** 01 — 交付不可变 Audit Event 写入闭环
**Status:** ready-for-agent
**架构通道:** 主通道为简单写 Application辅助通道为旧 MVC Adapter。
**完整业务边界:** 本票收口现有账号、角色和权限敏感写入口的统一审计接入。明确不重构整个账号模块,不迁移无关读取,不删除或回填旧账号历史表。
- [ ] 账号创建、修改、启停、删除、角色分配及权限变更使用注册动作和统一资源类型,成功、拒绝和失败语义明确。
- [ ] 账号角色或权限关键成功事件与业务事实使用同一 GORM 事务;审计失败时业务修改回滚。
- [ ] 权限拒绝与业务失败通过独立短事务记录,不向客户端泄露底层错误或资源是否存在。
- [ ] 事件包含操作者与入口快照、请求/关联标识、变更前后事实和直接受影响资源,敏感字段按统一规则删除或脱敏。
- [ ] 生产装配中的上述入口不再调用旧账号审计 Service也不直接创建旧账号日志模型静态检查和真实用例测试可证明该边界。
- [ ] 测试覆盖事务成功、审计失败回滚、拒绝、业务失败、重复请求和数据权限边界,不改变旧历史查询结果。

View File

@@ -0,0 +1,18 @@
# 05 — 迁移卡资产生命周期操作到统一审计
**What to build:** 卡分配、回收、删除、停复机、实名策略和状态变化等资产生命周期操作统一产生可关联的 Audit Event并以多资源关系表达卡、设备、店铺、订单等直接影响对象。复杂卡状态规则仍由完整业务用例收口不在审计 Adapter 中复制。
**Blocked by:** 01 — 交付不可变 Audit Event 写入闭环
**Status:** ready-for-agent
**架构通道:** 复杂卡状态用例采用 Application/Domain其他入口采用旧 MVC Adapter。
**完整业务边界:** 本票迁移现有卡资产生命周期写入口的审计能力。明确不重新设计周期轮询、队列、卡资格或重排策略,不迁移本需求未触碰的资产规则,不删除旧资产历史表。
- [ ] 卡分配、回收、删除、手工停复机、实名策略和业务状态变化均映射到已注册动作,成功、拒绝和失败结果保持一致。
- [ ] 事件至少关联一个主要卡资源,并按实际影响关联设备、来源/目标店铺、订单或其他直接资源;不递归制造资源关系。
- [ ] 关键状态变更成功审计与业务事实同事务;失败或拒绝使用独立短事务,重复状态请求不制造重复业务副作用或虚假变化。
- [ ] `request_id/correlation_id/parent_event_id` 在 HTTP、业务用例和后续异步链路中按各自职责传播。
- [ ] 当前卡资产入口不再调用旧资产审计 Writer 或直接创建旧资产日志模型,但兼容历史读取仍可工作。
- [ ] 测试覆盖权限拒绝、状态条件更新、事务回滚、多资源时间线、敏感 ICCID 默认脱敏和重复请求。

View File

@@ -0,0 +1,18 @@
# 06 — 迁移设备与资产导入操作到统一审计
**What to build:** 设备分配、回收、绑定、控制操作以及卡和设备导入任务通过统一 Audit Writer 留下稳定、脱敏、可检索的事件。批量操作只在事件中保存命令摘要和计数,逐项明细继续由业务任务或受控制品承担。
**Blocked by:** 01 — 交付不可变 Audit Event 写入闭环
**Status:** ready-for-agent
**架构通道:** 主通道为简单写 Application/旧 MVC Adapter辅助通道为 Infrastructure。
**完整业务边界:** 本票收口设备生命周期与现有资产导入入口的审计接入。明确不重构整个设备 Service不建立通用批量任务表不把大批量明细塞入 Audit Event JSON。
- [ ] 设备分配、回收、系列绑定、绑卡/解绑、停复机、限速、WiFi 设置、切卡、重启和恢复出厂映射为注册动作。
- [ ] 卡和设备导入任务创建、完成与失败事件关联任务、操作者、来源文件安全摘要和结果计数,不保存文件内容、签名 URL 或完整逐项数据。
- [ ] 批量事件超过大小限制时记录截断元数据、原始计数、摘要及受控任务/制品引用,查询仍能定位权威明细。
- [ ] 关键业务修改与成功审计同事务;拒绝和失败可靠保留,重复任务或重复控制请求不制造重复成功事件。
- [ ] 相关生产入口不再调用旧资产审计 Writer自动检查覆盖直接旧模型 Create 和隐藏装配注入。
- [ ] 真实用例测试覆盖单项与批量、事务回滚、部分结果摘要、多资源关系、权限范围和敏感字段删除。

View File

@@ -0,0 +1,18 @@
# 07 — 迁移店铺、套餐和关键配置操作到统一审计
**What to build:** 店铺敏感归属、套餐管理以及支付、企微和关键系统配置的现有写操作统一记录注册动作、操作者、目标资源和前后变化。关键配置与权限相关成功审计和业务事实同事务,敏感配置原值永不进入审计正文。
**Blocked by:** 01 — 交付不可变 Audit Event 写入闭环
**Status:** ready-for-agent
**架构通道:** 主通道为简单写 Application辅助通道为旧 MVC Adapter。
**完整业务边界:** 本票迁移当前已有店铺、套餐和关键配置敏感入口。明确不接管各业务 PRD 尚未实现的状态机,不主动迁移无关 CRUD不创建配置专用审计表。
- [ ] 店铺敏感业务员归属、关键账号关联和其他已识别敏感变更使用稳定动作及店铺/人员资源关系。
- [ ] 套餐创建、修改、上下架、授权或其他已存在敏感管理入口记录业务命令摘要和直接受影响资源。
- [ ] 支付、企微及关键系统配置变更只记录 Key、安全类型与脱敏前后摘要不保存 Secret、Token、EncodingAESKey、私钥、公钥原文或签名材料。
- [ ] 关键配置和权限相关成功审计与业务事实同事务;拒绝、校验失败和持久化失败按公共失败策略记录。
- [ ] 相关旧账号/资产审计调用与零散配置日志不再承担这些操作的权威审计,生产装配可被自动检查验证。
- [ ] 测试覆盖配置审计失败回滚、店铺越权、套餐批量摘要、敏感字段删除、重复更新和统一中文错误。

View File

@@ -0,0 +1,21 @@
# 08 — 迁移现有资金与订单敏感操作到统一审计
**What to build:** 当前钱包变更、充值、退款和订单资金敏感操作通过统一 Audit Event 关联业务单、钱包、钱包流水、操作者和完整业务链路。金额结论继续以 Domain Ledger 为准,关键成功审计与资金事实同事务且只产生一次。
**Blocked by:**
- 01 — 交付不可变 Audit Event 写入闭环
- `.scratch/tech-public-foundation/issues/02-transactional-public-outbox-write.md` — 02 — 在业务事务中可靠写入公共 Outbox
**Status:** ready-for-agent
**架构通道:** 主通道为复杂写 Application/Domain辅助通道为 Port/Adapter。
**完整业务边界:** 本票迁移仓库当前存在的钱包、充值、退款和订单资金敏感入口,完整收口所触碰用例的金额、并发、幂等和可靠事件边界。明确不用 Audit Event 替代钱包流水、订单或退款事实,不重写未触碰资金用例。
- [ ] 钱包余额变更、代理钱包回退、线下充值入账、人工退款结果及现有订单资金操作使用注册动作和稳定 correlation。
- [ ] Audit Event 关联审批或业务单、钱包、钱包流水及直接受影响资产;每条投影明确领域流水才是金额权威。
- [ ] 余额、流水、成功审计和必要 Outbox 在同一 GORM 事务内提交;审计或 Outbox 写入失败时资金事实整体回滚。
- [ ] 状态条件更新、钱包版本或稳定业务键保证重复请求、Worker 重投和并发处理不重复改变余额、流水或成功审计。
- [ ] 明确失败、拒绝和结果异常使用独立短事务记录安全摘要,不把第三方支付密钥、完整凭证或底层错误返回客户端。
- [ ] PostgreSQL 集成测试覆盖正常资金变化、审计失败、Outbox 失败、乐观锁冲突、重复业务键、并发处理和金额事实对账。

View File

@@ -0,0 +1,24 @@
# 09 — 承接手动轮询状态并记录同步外部尝试
**What to build:** 现有手动触发、进度和监控接口保持用户契约但运行状态由公共异步任务契约承接Gateway 实际请求及合并、互斥、限频、提前完成等未发送尝试进入 Integration Log只有状态变化、人工强制、连续失败或高风险异常进入 Audit Event。
**Blocked by:**
- 01 — 交付不可变 Audit Event 写入闭环
- 02 — 交付可恢复的 Integration Log 尝试闭环
- `.scratch/tech-public-foundation/issues/02-transactional-public-outbox-write.md` — 02 — 在业务事务中可靠写入公共 Outbox
- `.scratch/tech-public-foundation/issues/03-outbox-at-least-once-delivery.md` — 03 — 完成 Outbox 到 Asynq 的至少一次投递闭环
- `.scratch/tech-public-foundation/issues/06-unified-async-task-contract.md` — 06 — 冻结统一异步任务五态和查询契约
**Status:** ready-for-agent
**架构通道:** 主通道为 Application + Infrastructure辅助通道为 Query。
**完整业务边界:** 本票收口旧手动轮询日志承担的运行状态替代、外部尝试记录和兼容接口。明确不改变轮询配置、间隔、Redis 分片队列、任务类型、卡级开关、并发控制或失败重排,不新建同步专用运行表。
- [ ] 手动触发、进度与监控公开契约继续可用,状态、计数、失败摘要和恢复行为映射到公共异步任务五态。
- [ ] 实际 Gateway 请求在调用前建立 Integration Log完成后记录结果、耗时、状态变化和脱敏上游摘要。
- [ ] 合并、互斥、限频、已达预期和取消即使未产生 HTTP 请求也有可解释终态,不伪造 HTTP 状态。
- [ ] 同步序列传播 `request_id/correlation_id/series_id/attempt`同序列查询可连续看到立即、3 分钟、5 分钟的全部尝试。
- [ ] 普通无变化成功只写 Integration Log状态变化、人工强制、连续失败或高风险异常按注册规则关联 Audit Event。
- [ ] 回归测试固定现有轮询配置、队列、开关和监控基线,验证切换前后调度事实不变且旧手动轮询表不再承担新增运行状态。

View File

@@ -0,0 +1,18 @@
# 10 — 提供旧审计历史统一只读投影
**What to build:** 审计查询可以把旧账号、旧资产和旧手动轮询记录规范化为统一只读历史事件,并与新 Audit Event 稳定分页排序。现有资产操作日志兼容接口继续可用,但不再直接绑定旧资产日志表。
**Blocked by:** 01 — 交付不可变 Audit Event 写入闭环
**Status:** ready-for-agent
**架构通道:** Query。
**完整业务边界:** 本票收口三个旧历史来源的 `UNION ALL` 投影、确定性历史键和资产兼容读取。明确不在线回填新表,不修改或删除旧记录,不伪造历史中不存在的 correlation、风险或多资源关系。
- [ ] 旧账号、资产和手动轮询记录分别返回 `legacy_account/legacy_asset/legacy_polling` 来源及确定性历史事件键。
- [ ] 字段映射保留可证明的操作者、操作、资源、结果、时间和摘要;不存在的关联、风险或资源关系显式为空而非推测填充。
- [ ] 新旧记录使用稳定时间加 ID/历史键排序,分页跨越切换时间时无重复、漏项或顺序漂移。
- [ ] 资产操作日志兼容接口同时读取新 Audit Event 与旧资产投影,并保持原业务调用方所需响应兼容性。
- [ ] Query 不返回可用于业务写入的聚合对象,不对旧 JSON 做无索引模糊扫描,不产生 N+1 查询。
- [ ] PostgreSQL 投影测试覆盖三类历史样本、字段映射、确定性键、分页排序、新旧交界和兼容接口。

View File

@@ -0,0 +1,23 @@
# 11 — 交付全局事件和资源轨迹查询闭环
**What to build:** 获得授权的平台用户可以分页查看全局审计事件与详情,先搜索业务资源候选,再打开包含新事件和历史投影的资源时间线。资源权限与字段脱敏由后端重新校验,代理或企业用户只能在原业务范围查看允许的资源轨迹。
**Blocked by:**
- 01 — 交付不可变 Audit Event 写入闭环
- 05 — 迁移卡资产生命周期操作到统一审计
- 06 — 迁移设备与资产导入操作到统一审计
- 10 — 提供旧审计历史统一只读投影
**Status:** ready-for-agent
**架构通道:** Query。
**完整业务边界:** 本票收口事件列表/详情、资源候选搜索和资源时间线 API 及权限、分页、索引和 DTO 投影。明确不递归遍历资源图,不扫描 JSONB不通过聚合根读取不实现其他审计视角。
- [ ] 事件列表和详情支持注册动作、操作者、来源、结果、风险、时间、资源和请求标识等有索引过滤,默认 20、最大 100并稳定按时间与 ID 排序。
- [ ] 资源搜索先查询业务读模型返回类型、ID、Key 和显示名;静态搜索路由先于动态资源路由注册。
- [ ] 资源时间线组合新 Audit Event 和旧投影,`include_related=true` 只展开事件直接关联资源,不递归遍历关系图。
- [ ] 超级管理员、平台角色、代理和企业按权限码与原数据范围取交集;越权查询不泄露资源是否存在。
- [ ] DTO 默认脱敏并返回结果、风险等中文名称;公共关键词不对 JSONB 执行无索引模糊扫描。
- [ ] 真实 Fiber、认证、GORM 和 PostgreSQL 测试覆盖路由顺序、分页、筛选、权限、历史交界、无 N+1 和常用查询索引;新增 Handler 同步两个文档生成器。

View File

@@ -0,0 +1,21 @@
# 12 — 交付人员行为和风险事件查询闭环
**What to build:** 获得相应权限的平台用户可以查看操作者列表、行为摘要、个人事件时间线以及风险概览和风险事件列表。所有聚合均由服务端完成,并严格隔离代理、企业和无对应权限的平台角色。
**Blocked by:**
- 04 — 迁移账号、角色与权限敏感操作到统一审计
- 11 — 交付全局事件和资源轨迹查询闭环
**Status:** ready-for-agent
**架构通道:** Query。
**完整业务边界:** 本票收口人员与风险两个读取视角、服务端汇总和权限边界。明确不建设自动封禁、风险处置工单、实时行为分析或前端全量下载聚合。
- [ ] 操作者查询支持 actor kind、稳定 ID、名称快照、入口、动作、结果、风险和时间过滤并提供摘要及稳定分页事件时间线。
- [ ] 风险概览按风险等级、结果、类别、动作和时间窗口进行有索引汇总,风险事件列表可进一步检索详情。
- [ ] `audit:actor:view``audit:risk:view` 独立授权;代理和企业账号不能进入人员或风险全局视角。
- [ ] 平台角色的权限与数据范围取交集,失败、拒绝、高风险和严重事件不会因缺失可选关联而被错误过滤。
- [ ] 汇总使用服务端 SQL 和批量投影,不下载全量事件、不对 JSONB 模糊扫描、不产生操作者或资源 N+1。
- [ ] HTTP 与性能测试覆盖超级管理员、不同平台角色、代理、企业、空态、筛选空态及代表性数据量OpenAPI 文档同步更新。

View File

@@ -0,0 +1,24 @@
# 13 — 交付请求、业务链路和外部集成时间线
**What to build:** 运维人员可以按 request ID 或 correlation ID 查看同一请求或完整业务链路中的 Audit Event、Integration Log、Outbox 和异步任务摘要,并可按外部提供方、操作、方向、结果、资源、场景和序列检索外部尝试。
**Blocked by:**
- 02 — 交付可恢复的 Integration Log 尝试闭环
- 09 — 承接手动轮询状态并记录同步外部尝试
- 11 — 交付全局事件和资源轨迹查询闭环
- `.scratch/tech-public-foundation/issues/02-transactional-public-outbox-write.md` — 02 — 在业务事务中可靠写入公共 Outbox
- `.scratch/tech-public-foundation/issues/06-unified-async-task-contract.md` — 06 — 冻结统一异步任务五态和查询契约
**Status:** ready-for-agent
**架构通道:** Query。
**完整业务边界:** 本票收口请求时间线、关联时间线和 Integration Log 列表/详情查询。明确不在 API 请求中扫描本地 Access Log不复制 Outbox/任务完整载荷,不把外部交互结果解释成业务权威状态。
- [ ] Request Timeline 组合可关联的审计事件、外部尝试、Outbox 和任务安全摘要,并返回 Access Log 检索标识而不读取日志文件。
- [ ] Correlation Timeline 以稳定 correlation 串联跨请求、回调和异步处理,`parent_event_id` 只表达直接因果,不替代 correlation。
- [ ] Integration 查询支持 provider、operation、方向、结果、资源、触发来源、场景、序列、尝试和时间过滤列表默认 20、最大 100。
- [ ] 同一同步序列能够按尝试顺序连续展示立即、3 分钟、5 分钟结果,包括合并、限频和提前完成等未发送终态。
- [ ] 原始外部正文、密文、签名、附件、Outbox 载荷和任务敏感失败明细不进入普通查询 DTO。
- [ ] 真实链路测试覆盖单请求、多请求 correlation、异步传播、重复尝试、0/3/5 序列、权限隔离和常用查询索引OpenAPI 文档同步更新。

View File

@@ -0,0 +1,21 @@
# 14 — 交付资金审计时间线
**What to build:** 财务人员可以按业务单、钱包、审批、资产和时间查看组合时间线,统一展示 Audit Event、钱包流水、订单、退款、充值和审批实例并清楚区分每条记录来源及金额权威。
**Blocked by:**
- 08 — 迁移现有资金与订单敏感操作到统一审计
- 13 — 交付请求、业务链路和外部集成时间线
**Status:** ready-for-agent
**架构通道:** Query。
**完整业务边界:** 本票收口资金审计的只读组合投影、权限、分页和对账语义。明确不通过查询修改资金状态,不把 Audit Event 当作金额账本,不迁移未触碰的资金写用例。
- [ ] 时间线组合 Audit Event、钱包流水、订单、退款、充值和审批实例每条返回明确 `record_source`、时间、业务标识和安全摘要。
- [ ] 金额、余额和资金结论始终取自 Domain Ledger审计事件只解释操作者、动作、风险、前后变化和关联关系。
- [ ] 支持钱包、店铺、业务单、审批、资产、动作、结果、风险和时间等有索引过滤,并使用稳定时间加来源 ID 排序。
- [ ] `audit:finance:view` 独立授权,代理和企业不能进入全局资金视角;平台角色权限与原资金数据范围取交集。
- [ ] 金额、手机号、第三方交易号等字段默认按权限脱敏,不因某条关联缺失泄露其他资源存在性。
- [ ] 对账和性能测试覆盖多来源同链路、退款与充值、审批关联、无重复漏项、无 N+1 和代表性数据量OpenAPI 文档同步更新。

View File

@@ -0,0 +1,22 @@
# 15 — 交付敏感值二次查看与自审计闭环
**What to build:** 审计详情默认返回掩码或安全状态;具有独立敏感查看权限的用户可以针对明确事件或资源二次请求允许展示的完整值,而该查看行为本身会产生高风险 Audit Event并保留被查看对象、操作者和请求链路。
**Blocked by:**
- 01 — 交付不可变 Audit Event 写入闭环
- 11 — 交付全局事件和资源轨迹查询闭环
- 12 — 交付人员行为和风险事件查询闭环
**Status:** ready-for-agent
**架构通道:** 主通道为 Query辅助通道为简单写 Application。
**完整业务边界:** 本票收口敏感字段受控读取、字段级授权和读取自审计。明确不恢复已被策略删除的原值,不允许超级管理员绕过二次审计,不授予导出权限。
- [ ] 普通详情对手机号、IP、ICCID、钱包金额和第三方交易号等受控字段默认脱敏禁止字段始终不可恢复。
- [ ] 二次查看要求 `audit:sensitive:view`、明确目标和字段范围,并重新校验平台角色、数据范围与资源权限。
- [ ] 成功或被拒绝的敏感查看产生注册的高风险 Audit Event关联被查看事件/资源、操作者、入口和 request ID。
- [ ] 审计写入失败时敏感值不返回;重复查看每次都保留独立读取事实,不因已有全局权限跳过。
- [ ] 无权限、历史字段不存在、原值已删除和资源越权返回明确但不泄密的统一错误或状态。
- [ ] 真实 Fiber 和 PostgreSQL 测试覆盖授权查看、越权、审计失败、禁止字段、历史缺失、并发请求及自审计事件查询OpenAPI 文档同步更新。

View File

@@ -0,0 +1,24 @@
# 16 — 交付审计导出与字段授权快照
**What to build:** 获得审计导出权限的用户可以从支持的审计视角创建异步导出任务。任务创建时固化过滤条件、数据范围、字段授权和脱敏等级,后续角色变更或任务重试不会扩大导出内容。
**Blocked by:**
- 11 — 交付全局事件和资源轨迹查询闭环
- 12 — 交付人员行为和风险事件查询闭环
- 13 — 交付请求、业务链路和外部集成时间线
- 14 — 交付资金审计时间线
- 15 — 交付敏感值二次查看与自审计闭环
**Status:** ready-for-agent
**架构通道:** 主通道为 Query + Export DataSource辅助通道为 Application。
**完整业务边界:** 本票收口审计导出 Scene、字段能力、权限快照、异步任务和导出审计。明确不创建第二套导出框架不把敏感查看权限等同敏感导出权限不在权限解析失败时回退全字段。
- [ ] 审计导出复用统一 Export DataSource 和任务契约,支持经批准的事件、资源、链路、集成、风险和资金过滤条件。
- [ ] 创建任务时快照操作者、权限、数据范围、字段集合、脱敏等级和过滤条件Worker 只使用快照执行。
- [ ] `audit:export``audit:sensitive:view` 独立;导出完整敏感字段需要额外字段授权,解析失败一律拒绝。
- [ ] 文件不包含禁止字段、完整外部报文、密钥、签名 URL 或未授权业务数据;下载继续遵守安全摘要和临时访问策略。
- [ ] 创建、完成、失败和下载等敏感导出行为产生统一 Audit Event并能关联导出任务与请求链路。
- [ ] 测试覆盖权限快照、角色变更、字段空集、敏感权限分离、任务重试、导出审计、越权和文件内容检查。

View File

@@ -0,0 +1,21 @@
# 17 — 交付审计保留、清理和运行监控
**What to build:** 运维人员可以观察 Audit/Integration 写入、旧表意外新增、Integration Log 增长与清理、敏感读取和导出,并由受控维护身份按保留策略分批清理可清理记录。在线应用始终不能更新或删除 Audit Event。
**Blocked by:**
- 01 — 交付不可变 Audit Event 写入闭环
- 02 — 交付可恢复的 Integration Log 尝试闭环
**Status:** ready-for-agent
**架构通道:** 主通道为 Infrastructure辅助通道为 Query。
**完整业务边界:** 本票收口保留分类、Integration Log 分批清理、权限边界、指标与告警。明确不由在线应用删除 Audit Event不预建尚无必要的复杂分区系统不清理已有生产审计事实作为回滚手段。
- [ ] 审计事件按资金/权限/审批/关键配置与普通资产/业务分类表达 5 年或 2 年保留策略,在线应用账号无 Update/Delete 能力。
- [ ] Integration Log 默认保留 180 天Gateway 无变化成功记录保留 30 天;清理按稳定时间与主键小批量执行并记录结果。
- [ ] 清理只允许受控维护身份执行,使用条件范围和可恢复进度,不影响异常、状态变化或仍被业务链路引用的记录。
- [ ] 指标和告警覆盖 Audit/Integration 写入失败、失败短事务失败、旧三表意外新增、Outbox 积压、Integration 增长/清理、敏感读取和导出次数。
- [ ] 日志与指标标签只使用安全 ID、结果和计数不包含正文、敏感值或高基数未受控载荷。
- [ ] 测试覆盖保留边界、分批重跑、并发清理、在线账号拒绝、旧表新增告警和不删除未到期/受保护记录。

View File

@@ -0,0 +1,25 @@
# 18 — 冻结审计中心跨仓前端契约与验收包
**What to build:** 前端仓库获得稳定、框架无关的审计工作台契约和可执行验收数据,能够实现全局事件、人员行为、资源轨迹、请求/业务链路、资金审计、风险事件和外部集成七个视角,并正确处理权限、敏感查看、导出、空态与错误状态。
**Blocked by:**
- 11 — 交付全局事件和资源轨迹查询闭环
- 12 — 交付人员行为和风险事件查询闭环
- 13 — 交付请求、业务链路和外部集成时间线
- 14 — 交付资金审计时间线
- 15 — 交付敏感值二次查看与自审计闭环
- 16 — 交付审计导出与字段授权快照
**Status:** ready-for-agent
**架构通道:** Query/API 契约。
**完整业务边界:** 本票收口跨仓页面、状态、权限和验收契约以及 OpenAPI/样本数据。当前仓库不含前端源码,明确不虚构组件目录、状态库或技术栈,不在本票实现前端页面。
- [ ] 契约覆盖 `/operations/audit` 七个视角、权限控制 Tab、服务端筛选分页、稳定 URL 参数和详情抽屉字段分组。
- [ ] 资源轨迹定义先搜索候选再查看时间线;请求与 correlation 可相互跳转Integration 序列连续展示立即、3 分钟、5 分钟尝试。
- [ ] 敏感字段默认掩码,二次查看重新请求受控接口;导出、敏感查看和各视角权限分别处理。
- [ ] 明确定义加载、真实空态、筛选空态、403、404/不可见、失败重试、历史字段不存在和数据已删除等状态。
- [ ] 提供不含真实敏感数据的七视角验收样本、权限矩阵和人工验收清单,后端 OpenAPI 与真实路由保持一致。
- [ ] 文档明确前端隐藏不是授权边界,第一版不实现自动封禁、风险工单或自由拖拽关系图。

View File

@@ -0,0 +1,37 @@
# 19 — 执行一次性审计切换与停机发布门禁
**What to build:** 发布负责人可以在一次停机窗口内完成新结构、Writer、现有敏感入口、历史查询、权限、监控和跨仓契约切换并通过自动化门禁决定是否开放流量。任一关键检查失败时整体停止发布一旦新系统产生生产事实只能前向修复不能恢复旧 Writer 制造分裂历史。
**Blocked by:**
- 03 — 完成 Access Log 全路由敏感信息防泄漏
- 04 — 迁移账号、角色与权限敏感操作到统一审计
- 05 — 迁移卡资产生命周期操作到统一审计
- 06 — 迁移设备与资产导入操作到统一审计
- 07 — 迁移店铺、套餐和关键配置操作到统一审计
- 08 — 迁移现有资金与订单敏感操作到统一审计
- 09 — 承接手动轮询状态并记录同步外部尝试
- 10 — 提供旧审计历史统一只读投影
- 11 — 交付全局事件和资源轨迹查询闭环
- 12 — 交付人员行为和风险事件查询闭环
- 13 — 交付请求、业务链路和外部集成时间线
- 14 — 交付资金审计时间线
- 15 — 交付敏感值二次查看与自审计闭环
- 16 — 交付审计导出与字段授权快照
- 17 — 交付审计保留、清理和运行监控
- 18 — 冻结审计中心跨仓前端契约与验收包
- `.scratch/tech-public-foundation/issues/12-foundation-release-gate-and-integration-contract.md` — 12 — 建立公共基础发布门禁和下游接入契约
**Status:** ready-for-agent
**架构通道:** 主通道为 Infrastructure辅助通道为 Application/Query 验收。
**完整业务边界:** 本票收口全局审计一次性停机切换、迁移验证、旧写收缩、对账、性能、安全、监控和发布回滚边界。明确不允许长期双写或局部放量,不删除旧历史,不在新事实产生后通过删表回滚。
- [ ] 停机顺序明确覆盖暂停流量与 Worker、前置检查、增量迁移、权限初始化、新 Writer 装配、旧写护栏、历史对账、Worker 恢复和开放流量。
- [ ] 自动切换清单证明生产产物不再调用旧账号/资产审计 Writer、不再直接 Create 旧三表、启动装配不再注入旧 Writer旧表意外新增会立即告警或失败。
- [ ] 门禁覆盖关键业务与审计同事务、审计失败回滚、失败短事务、Integration 结果未知、历史新旧交界、Access Log 敏感矩阵和权限隔离。
- [ ] Query 性能验证常用过滤使用索引、无 JSONB 全表模糊扫描、无资源/操作者 N+1并满足项目 P95/P99 目标。
- [ ] 任一迁移、旧写清单、样本对账、事务、安全、权限、性能、监控或跨仓验收失败均在开放流量前整体终止发布,不能让局部模块继续写旧表。
- [ ] 发布与回滚说明明确:未产生新事实时可回退兼容应用;已产生 Audit/Integration/Outbox 事实后保留全部记录、停止异常生产者并前向修复,禁止恢复旧 Writer 或删除事实。
- [ ] 中文功能总结覆盖关键流程、前后端契约、异常闭环、发布回滚、监控恢复和待决策项README 增加索引;完整停机演练通过后方可放量。

View File

@@ -0,0 +1,127 @@
# PRDTECH 公共站内通知与受控跳转
Status: ready-for-agent
---
## Problem Statement
七月迭代的套餐临期、钱包低余额、企微审批结果和系统异常都需要向系统用户发送消息,但当前代码没有统一的站内通知存储、未读状态、消息中心或受控跳转能力。若每个需求自行建表和接口,会产生不同的防重、接收人、已读和权限规则;若直接把任意 URL 放进消息,又会形成越权跳转和开放重定向风险。
站内通知不承担企业微信审批待办,也不等同于旧轮询告警。业务资金、审批和套餐事务不能因为通知投递暂时失败而回滚,但通知又必须在 Outbox/Asynq 至少一次投递下保持不重不漏。
## Solution
建立一套轻量站内通知写模型业务事务只可靠发布稳定事件Notification Worker 根据受控通知类型、模板和接收人生成每人一条通知,并以事件和接收人唯一键防重。后台账号与个人客户使用各自认证上下文查询自己的未读数、分页列表和已读状态,任何接口都不接受前端传入接收人 ID。
通知只保存受控 `ref_type/ref_id/ref_key`,目标解析接口把它转换为白名单 `target_type` 和结构化目标参数,不保存、不返回任意 URL。跳转后的业务详情继续执行原资源权限校验。
## User Stories
1. 作为后台或代理账号,我希望在顶部看到可靠的未读数,并在通知中心查看自己的审批、临期、同步和系统消息。
2. 作为个人客户,我希望看到与自己订单、套餐和资产有关的简化消息,不看到平台运维消息。
3. 作为用户,我希望重复 Worker 投递不会生成重复消息,重复点击已读也不会报错。
4. 作为用户,我希望点击通知只能进入系统允许的业务页面,权限变化后不能借通知越权查看资源。
5. 作为业务开发者,我希望新增消息场景只注册常量、模板、接收人和目标类型,不复制一套通知表和 Handler。
6. 作为运维人员,我希望没有接收人、模板错误和投递失败均可追踪,不会无限重试或影响原业务提交。
7. 作为前端用户,我希望铃铛、抽屉和通知中心的未读状态一致,请求失败时不会把已有未读数闪回零。
## Implementation Decisions
### 架构与可靠投递
- 站内通知是简单写模型,采用 `Application + Query + Infrastructure`,不创建无业务价值的通知聚合根。
- 关键业务在原事务中写 Outbox提交后由 Relay 投递结构化 Asynq 载荷Notification Worker 负责解析接收人、渲染模板并幂等写通知。非关键系统告警可直接入队,但必须携带预先生成的稳定 `event_id`
- 本需求复用七月公共 `tb_outbox_event`、Relay 和处理租约,不在通知模块复制一套 Outbox。调用项目 `EnqueueTask` 时传 struct 或 map禁止传预序列化 `[]byte`
- 业务提交只依赖 Outbox 同事务成功不等待通知表写入Worker 失败按队列策略重试,不回滚已完成的资金、审批或套餐事务。
- 每个最终接收人独立一行,唯一键为 `event_id + recipient_kind + recipient_id`。同一事件重复消费不重复写,同一事件的不同接收人互不影响已读状态。
- 接收人解析失败分为:暂无可用接收人记 `no_recipient` 并成功结束;数据库/模板等瞬时失败返回任务错误;模板字段永久缺失达到最大重试后进入失败监控,禁止生成残缺正文。
### 数据与常量
- 新建 `tb_notification`,字段至少包括:`id``event_id``recipient_kind``recipient_id``category``type``severity``title``body``ref_type``ref_id``ref_key``is_read``read_at``expires_at``created_at`
- `recipient_kind` 为类型字段,使用 string`account``personal_customer`
- `category` 为 string`approval``expiry``sync``system``severity` 为 string`info``warning``error``critical`。具体 `type` 使用点分业务常量,例如 `package.expiring``wallet.low_balance``wecom.approval.approved``card_sync.failed`
- 所有常量及中文说明统一放在 `pkg/constants/`;通知类型到类别、默认级别、模板和允许目标的映射使用代码注册表,前端不得自行猜测。
- `title/body` 是发送时的纯文本快照,不保存任意 HTML。正文不得包含密码、操作密码、Token、Secret、完整证件、完整敏感回调、长期对象存储 URL 或企微 `media_id`
- 唯一索引覆盖 `event_id, recipient_kind, recipient_id`;未读和分类索引均以 `recipient_kind, recipient_id` 开头并包含 `created_at DESC`;过期时间建立部分索引。禁止数据库外键。
- 第一版未读数直接查询 PostgreSQL不维护 Redis 未读计数,避免通知表与缓存双写不一致。
### 接收人规则
- Notification Worker 只接受稳定用户 ID不按用户名、手机号等可变文本投递。具体用户由业务事件携带角色类接收人在消费时批量解析当前启用账号。
- 审批结果发送给申请人;通过后撤销且资金已执行发送给申请人和当前可用财务角色账号;企微模板/系统配置异常发送给当前可用平台超管或指定运维角色。
- 套餐临期和钱包低余额的店铺接收人为当前启用的店铺主账号及当前仍可用的店铺业务员;去重后逐账号写通知。上级代理可查看下级数据不代表自动成为通知接收人。
- 个人套餐/订单/资产通知使用 `recipient_kind=personal_customer` 和客户 ID。个人客户接口不得返回 `sync/system` 运维消息。
- 账号停用、软删除或业务员关系失效时跳过;已经生成的历史通知仍按原接收人可读,不因后续关系变化转移给其他人。
### API 契约
- 后台、平台、代理和企业账号统一使用当前认证的 `/api/admin`
- `GET /api/admin/notifications/unread-count`
- `GET /api/admin/notifications/unread-summary`
- `GET /api/admin/notifications`
- `PUT /api/admin/notifications/read-all`
- `PUT /api/admin/notifications/{id}/read`
- `GET /api/admin/notifications/{id}/target`
- 个人客户使用:
- `GET /api/c/v1/notifications/unread-count`
- `GET /api/c/v1/notifications`
- `PUT /api/c/v1/notifications/read-all`
- `PUT /api/c/v1/notifications/{id}/read`
- 静态 `/read-all` 路由必须先于 `/{id}` 动态路由注册。后台分类汇总第一版返回 `total` 与四个固定类别C 端第一版只提供总未读数。
- `unread-count` 返回 `count:int64``display_count:string`0 返回 `"0"`199 返回十进制文本,超过 99 返回 `"99+"`
- 列表过滤为 `category``type``severity``is_read``page``page_size`;固定按 `created_at DESC, id DESC`,默认每页 20最大 50。过期通知不进入列表和未读统计。
- 通知项返回 `id/category/type/severity/title/body/ref_type/ref_id/ref_key/is_read/read_at/created_at`,使用统一响应外层和 ISO 8601 时间。
- 单条已读执行带接收人的条件更新。通知不存在、属于别人或已读均幂等返回成功,不泄露通知是否存在;首次成功写同一 `read_at`,重复请求不覆盖。
- `read-all` 的可选 `category` 为空时只更新当前接收人的全部未过期未读通知,返回实际更新数量;非法类别返回参数错误。
- `/target` 先固定当前接收人查询通知,再通过后端白名单返回 `target_type``target_id/target_key``available`;不得返回 URL。目标资源不存在或当前无权访问时 `available=false`,不得泄露更多资源信息。
### 受控目标
- 第一版白名单至少覆盖本期实际场景:退款详情、代理充值详情、企微审批详情、卡详情、设备详情、临期资产列表、店铺资金概况、审计外部集成和系统配置。
- `card_sync` 不指向不存在的独立同步执行页;平台运维消息解析为统一审计中心外部集成目标,并携带受控资源或 Integration Log 标识。
- 前端维护 `target_type -> route builder` 白名单;未知类型和 `available=false` 只展示消息正文,不跳转。拥有通知不等于拥有目标资源权限。
### 前端交互
- 登录布局挂载后立即请求未读数,每 30 秒刷新;页面不可见时暂停,恢复可见时立即刷新。失败保留上次成功数值并提供静默重试,不闪回 0。
- 顶部铃铛固定宽度0 时不显示徽标199 显示数字,超过 99 显示 `99+`。点击打开最近 10 条抽屉,支持全部、审批、临期、同步/系统分类及进入 `/notifications`
- 通知中心支持类别、类型、严重级别、已读状态和服务端分页,并提供当前筛选类别的全部已读。普通消息使用中性色,错误/严重消息才使用警告视觉。
- 点击通知先进入已读视觉状态并调用已读接口,再解析受控目标;已读调用失败时以下次服务端刷新为准。目标解析或跳转失败不把通知恢复为未读。
- C 端使用简化消息列表,只展示与当前客户有关的审批结果、套餐、订单和资产消息。
### 审计、保留与发布
- 普通通知读取和已读只进入 Access Log通知模板/接收人解析失败、系统告警生成和管理性排查进入统一 Audit/Integration Log。不得使用用户通知列表作为管理员查看他人消息的入口。
- 套餐临期展示至到期并保留数据 180 天;审批结果不自动过期并保留 365 天;同步异常展示 30 天、保留 180 天;系统告警按事件指定展示期限、最长保留 365 天。
- 低峰清理任务按主键/时间分批删除超出数据保留期限的通知;用户不提供删除接口,清理不修改业务审计和领域流水。
- 未来短信或企微消息使用独立 Delivery 消费同一业务事件;不得在 Notification Handler/Worker 写完站内消息后同步循环调用外部渠道。
- 新增管理端和 C 端 Handler 后同步注册路由和两个 OpenAPI 文档生成器;公共通知能力先于 UR#33、UR#97 和企微结果通知启用。
## Testing Decisions
- Application/Worker 测试覆盖重复事件、多个接收人、接收人去重、停用/删除接收人、无接收人、模板字段缺失、Outbox/Asynq 重试和过期时间。
- PostgreSQL 集成测试验证唯一索引、未读/分类查询、固定排序、最大分页、过期排除、单条/批量条件更新和并发重复消费。
- HTTP 集成测试穿过真实后台/C 端认证、Handler、Query、GORM 和统一响应;验证前端无法传入或篡改 `recipient_id`,管理员也不能从用户接口查看别人通知。
- 越权测试对“别人通知 ID”“已删除通知”“无权目标资源”返回相同安全语义重复已读保持成功且 `read_at` 不变。
- 目标解析契约测试覆盖全部白名单、未知 `ref_type`、目标删除、权限变化和审计外部集成目标,证明响应中不存在任意 URL。
- 前端测试/人工验收覆盖 0、1、99、100 条徽标30 秒刷新、隐藏页暂停、失败保留旧数、抽屉最近 10 条、筛选、全部已读和点击顺序。
- 使用开发 PostgreSQL/Redis 与测试 Outbox Relay/Asynq Worker 验证至少一次投递;不得给真实用户生成测试通知。
- 生成 OpenAPI 并核对静态 `read-all` 路由未被动态 ID 路由吞掉。
## Out of Scope
- 不建设 WebSocket/SSE 推送,第一版使用 30 秒未读轮询。
- 不在本系统复制企业微信“待我审批”待办,不发送套餐临期企业微信消息。
- 不实现短信、企微消息或邮件 Delivery只保留独立扩展边界。
- 不允许管理员从通知接口查看、修改或删除其他用户消息。
- 不保存富文本 HTML、任意 URL、永久附件链接或外部回调原文。
- 不用 Redis 维护未读数,不让用户自行删除通知。
- 不在本需求实现各业务场景的触发规则UR#33、UR#97 和企微审批需求分别负责发布业务事件。
## Further Notes
- 当前仓库没有通知模型、接口和消息中心,只有轮询告警等运维模型,不能把后者改名充当业务通知。
- 前端仓库不在当前工作区;本 Spec 的路由、状态和错误交互是跨仓契约,实际组件目录以对应前端仓库为准。
- 公共通知和公共 Outbox 是多个单需求的依赖,但不把这些单需求合并成一份整轮迭代 PRD。

View File

@@ -0,0 +1,21 @@
# 01 — 向明确后台账号可靠投递首条站内通知
**What to build:** 业务事件携带稳定后台账号 ID 后,可以经公共 Outbox、Relay 和 Notification Worker 为该账号幂等生成一条纯文本站内通知;当前登录账号可以查询自己的未读数和分页列表,并将单条通知幂等标记为已读。重复投递不会重复写入,过期通知不进入用户视图,任何用户接口都不能指定或篡改接收人。
**Blocked by:** `.scratch/tech-public-foundation/issues/03-outbox-at-least-once-delivery.md` — 03 — 完成 Outbox 到 Asynq 的至少一次投递闭环
**Status:** ready-for-agent
**架构通道:** 主通道为简单写 Application辅助通道为 Infrastructure 与 Query。
**完整业务边界:** 本票收口后台明确账号通知的存储、受控类型注册、Worker 幂等消费、未读数、基础列表和单条已读闭环。明确不实现角色或店铺动态接收人、个人客户通知、分类汇总、全部已读、目标解析、前端组件或具体业务场景触发规则,也不复制公共 Outbox 和 Relay。
- [ ] 通知事实包含稳定事件 ID、接收人类型与 ID、类别、类型、级别、纯文本标题正文、受控资源引用、已读与过期时间并通过事件 ID、接收人类型和接收人 ID 唯一约束防止重复消费。
- [ ] 通知常量、中文说明、类型到类别、默认级别、模板和允许目标的注册关系统一管理;未注册类型、模板字段永久缺失或正文包含禁止敏感内容时不生成残缺通知。
- [ ] Worker 只接受结构化载荷,重复事件和并发消费最多为同一后台账号生成一条通知;瞬时数据库错误返回任务错误,原业务事务不因通知写入失败而回滚。
- [ ] 当前后台账号可以获得准确的 `count:int64``display_count:string`,其中 0、199、100 以上分别显示 `0`、十进制文本和 `99+`,且未读数只查询 PostgreSQL。
- [ ] 后台列表只读取当前认证账号的未过期通知,固定按创建时间和 ID 倒序,默认每页 20、最大 50并返回统一响应与 ISO 8601 时间。
- [ ] 单条已读使用接收人条件和未读条件更新;别人通知、不存在通知和已读通知均幂等成功,首次写入的 `read_at` 在重复请求中保持不变。
- [ ] PostgreSQL、Worker 和真实后台认证 HTTP 集成测试覆盖唯一约束、重复消费、过期排除、分页排序、接收人篡改、越权隔离及重复已读。
- [ ] 新增后台 Handler 后完成路由、RouteSpec 和两个 OpenAPI 文档生成器注册,且静态路由顺序不会被动态通知 ID 路由吞掉。

View File

@@ -0,0 +1,20 @@
# 02 — 交付后台通知筛选、分类汇总与全部已读
**What to build:** 当前后台账号可以按通知类别、类型、严重级别和已读状态分页查看自己的消息,获得总未读数及审批、临期、同步、系统四个固定类别的汇总,并将当前类别或全部未过期通知一次性标记为已读。筛选、汇总和更新始终绑定认证账号,不因管理员身份扩大到其他用户。
**Blocked by:** 01 — 向明确后台账号可靠投递首条站内通知
**Status:** ready-for-agent
**架构通道:** 主通道为 Query辅助通道为简单写 Application。
**完整业务边界:** 本票收口后台通知中心所需的筛选、固定分类汇总和批量已读用例。明确不实现个人客户接口、动态接收人、目标跳转、前端页面、Redis 未读计数或管理员查看他人通知能力。
- [ ] 列表支持类别、类型、严重级别、已读状态、页码和每页数量组合过滤,所有条件使用 AND 语义并保持创建时间、ID 倒序。
- [ ] 非法类别、严重级别、已读参数或越界分页返回统一参数错误,不向客户端拼接底层校验信息。
- [ ] 未读汇总固定返回 `total``approval``expiry``sync``system`,过期通知不计入任何分类。
- [ ] 全部已读在类别为空时更新当前账号全部未过期未读通知,在类别有效时只更新该类别,并返回实际更新数量。
- [ ] 批量更新使用当前接收人、未读状态、未过期和可选类别条件;重复调用返回零更新且保持成功,不覆盖既有 `read_at`
- [ ] `/read-all` 等静态路由先于 `/{id}` 动态路由注册,生成的 OpenAPI 与真实路由、请求参数和响应结构一致。
- [ ] PostgreSQL 与真实后台认证 HTTP 集成测试覆盖组合筛选、固定汇总、最大分页、过期排除、非法类别、并发批量已读及无法操作他人通知。

View File

@@ -0,0 +1,20 @@
# 03 — 向个人客户投递并提供简化通知中心
**What to build:** 业务事件携带稳定个人客户 ID 后,可以为该客户幂等生成与其订单、套餐或资产有关的站内通知;当前登录个人客户可以查询自己的未读数和分页列表,并执行单条或全部已读。个人客户永远看不到同步、系统等平台运维消息,也不能通过请求参数读取或修改其他客户通知。
**Blocked by:** 01 — 向明确后台账号可靠投递首条站内通知
**Status:** ready-for-agent
**架构通道:** 主通道为 Query辅助通道为简单写 Application 与 Infrastructure。
**完整业务边界:** 本票收口个人客户通知的投递、读取和已读闭环,复用既有通知表、注册表和 Worker。明确不实现 C 端分类汇总、后台动态接收人、平台运维消息展示、C 端受控目标接口或前端组件。
- [ ] Worker 能以 `personal_customer` 接收人类型和稳定客户 ID 幂等生成通知,同一事件的后台账号与个人客户通知相互独立。
- [ ] 个人客户通知类型注册明确允许的业务类别和资源引用;`sync``system` 及未对 C 端开放的类型不会出现在个人客户查询中。
- [ ] C 端未读数遵循 0、199、100 以上的显示规则,列表固定倒序、默认每页 20、最大 50并排除过期通知。
- [ ] 单条已读、全部已读只作用于当前认证客户;不存在、已删除、属于别人或已读的通知使用相同幂等安全语义。
- [ ] 请求 DTO 不接受接收人 ID额外或恶意接收人参数不能改变查询与更新范围。
- [ ] 真实个人客户认证、Handler、Query、GORM 集成测试覆盖重复投递、运维类别隔离、跨客户越权、分页、过期排除、重复已读和批量已读。
- [ ] 新增 C 端 Handler 后同步个人客户路由、RouteSpec 与两个 OpenAPI 文档生成器,接口统一挂载在约定认证上下文中。

View File

@@ -0,0 +1,23 @@
# 04 — 接入账号、角色与店铺动态接收人解析
**What to build:** Notification Worker 可以按业务场景把审批申请人、当前平台角色账号或目标店铺解析为一组稳定、去重且当前可用的后台账号接收人。店铺场景只包含当前启用的店铺主账号和当前仍可用的店铺业务员;账号停用、软删除或关系失效时跳过,上级代理不会因为可查看下级数据而自动收到通知。
**Blocked by:**
- 01 — 向明确后台账号可靠投递首条站内通知
- `.scratch/ur96-shop-business-owner/issues/06-shop-business-owner-notification-recipient-release.md` — 06 — 提供业务员通知接收人解析并完成发布验证
**Status:** ready-for-agent
**架构通道:** 主通道为 Infrastructure Adapter辅助通道为简单写 Application。
**完整业务边界:** 本票收口公共通知 Worker 对明确申请人、平台角色和店铺接收人的解析、可用性复核、去重及无接收人语义。明确不实现 UR#33、UR#97 或企微审批的业务触发规则,不改变账号、角色、店铺层级或业务员归属,不自动转派历史通知,也不发送短信或企微消息。
- [ ] 明确申请人场景只使用业务事件携带的稳定系统账号 ID并在消费时跳过已停用或软删除账号不使用企微代提交身份替代真实业务提交人。
- [ ] 角色场景批量解析当前启用、未删除且仍持有指定平台角色的账号,结果按稳定账号 ID 去重,不按用户名或手机号投递。
- [ ] 店铺场景解析当前启用的店铺主账号,并复用 UR#96 接缝解析当前可用业务员;不沿父店铺、祖先店铺或代理数据权限向上扩散。
- [ ] 同一账号同时以主账号、业务员或角色命中时只生成一条通知,同一事件的其他接收人仍分别拥有独立已读状态。
- [ ] 暂无可用接收人记为 `no_recipient` 并成功结束,不进入无限重试;数据库等瞬时错误继续返回任务错误。
- [ ] 已生成通知不会因账号关系后续变化而转移给新接收人,历史接收人仍可在自身认证上下文中读取原通知。
- [ ] Application、Worker 和 PostgreSQL 集成测试覆盖申请人、角色批量解析、店铺主账号与业务员去重、停用、软删除、关系失效、无接收人及重复投递。

View File

@@ -0,0 +1,23 @@
# 05 — 交付通知受控目标解析与权限复核
**What to build:** 当前后台账号点击自己的通知时,后端只返回白名单目标类型和结构化目标标识,不保存也不返回任意 URL。退款、代理充值、企微审批、卡、设备、临期资产、店铺资金、审计外部集成和系统配置等目标在解析时重新执行当前资源权限检查目标不存在或权限已经变化时统一返回 `available=false`,不泄露资源详情。
**Blocked by:**
- 01 — 向明确后台账号可靠投递首条站内通知
- `.scratch/tech-global-audit/issues/13-request-correlation-integration-timeline.md` — 13 — 交付请求、业务链路和外部集成时间线
**Status:** ready-for-agent
**架构通道:** 主通道为 Query辅助通道为 Application + Port/Adapter。
**完整业务边界:** 本票收口后台通知受控目标注册、解析、当前权限复核和安全不可用语义。明确不返回 URL、不实现前端路由构造、不把通知所有权当成目标资源权限、不创建独立卡同步执行页也不迁移各目标业务详情的既有授权规则。
- [ ] 通知只保存受控资源类型、数值 ID 或稳定 Key目标响应只包含白名单 `target_type`、结构化 `target_id/target_key``available`,任何字段均不能承载任意 URL。
- [ ] 第一版注册表至少覆盖退款详情、代理充值详情、企微审批详情、卡详情、设备详情、临期资产列表、店铺资金概况、审计外部集成和系统配置。
- [ ] 目标解析先按当前接收人固定查询通知,再调用对应业务权限 Adapter 复核资源;拥有通知不授予目标资源访问权。
- [ ] 别人通知、不存在通知和已删除通知不泄露通知事实;目标不存在、已删除或当前无权时统一返回 `available=false`,不返回资源差异信息。
- [ ] `card_sync` 等同步消息解析为统一审计中心外部集成目标并携带受控资源或 Integration Log 标识,不指向不存在的同步执行页。
- [ ] 未知通知引用或尚未支持的目标只允许展示正文,不产生开放重定向、自由路径或自动回退 URL。
- [ ] 契约与越权测试覆盖全部白名单、未知引用、通知越权、目标删除、权限变化、外部集成目标,并断言响应和持久化数据不存在任意 URL。

View File

@@ -0,0 +1,24 @@
# 06 — 交付通知保留清理与失败可观测闭环
**What to build:** 系统可以按通知场景计算展示期限和数据保留期限,并在低峰按稳定主键和时间分批删除已超过保留期的通知。无接收人、模板错误、系统告警生成和投递失败具有可追踪、有限重试和安全摘要,既不会无限重试,也不会影响已经提交的资金、审批、套餐或其他业务事实。
**Blocked by:**
- 01 — 向明确后台账号可靠投递首条站内通知
- `.scratch/tech-global-audit/issues/01-audit-event-write-loop.md` — 01 — 交付不可变 Audit Event 写入闭环
- `.scratch/tech-global-audit/issues/02-integration-log-attempt-loop.md` — 02 — 交付可恢复的 Integration Log 尝试闭环
**Status:** ready-for-agent
**架构通道:** 主通道为 Infrastructure辅助通道为简单写 Application。
**完整业务边界:** 本票收口通知展示期限、数据保留、分批清理、失败分类和统一审计/外部集成可观测接缝。明确不删除 Audit Event、Integration Log、领域流水或 Outbox不提供用户删除接口不建设管理员查看他人消息入口也不改变公共 Relay 的租约算法。
- [ ] 套餐临期、审批结果、同步异常和系统告警按约定计算展示与保留期限,审批结果不自动过期,系统告警展示期限不超过允许上限。
- [ ] 清理任务按时间和稳定主键小批量删除超过数据保留期限的通知,可中断重跑且只清理通知事实,不级联业务资源或审计记录。
- [ ] 暂无接收人记录 `no_recipient` 后成功结束;数据库、队列等瞬时错误按有限策略重试;模板永久缺失达到最大重试后进入失败监控且不写残缺正文。
- [ ] 系统告警直接入队时必须携带预先生成的稳定事件 ID重复执行仍由通知唯一键防重。
- [ ] 模板或接收人解析失败、系统告警生成和管理性排查写入统一 Audit/Integration 接缝;普通通知读取和已读只进入 Access Log。
- [ ] 日志、监控和审计只记录事件 ID、通知类型、失败类别、计数及安全资源标识不记录敏感模板数据、完整回调、Token、Secret 或任意长期 URL。
- [ ] 测试覆盖各类期限边界、分批清理可重入、无接收人、瞬时失败、永久模板失败、最大重试、系统告警重复入队和业务事实不回滚。

View File

@@ -0,0 +1,24 @@
# 07 — 冻结后台与 C 端通知前端契约及验收包
**What to build:** 前端仓库获得稳定、框架无关的后台铃铛、最近通知抽屉、通知中心和个人客户简化列表契约,以及可执行的验收数据。前端可以实现 30 秒未读轮询、页面隐藏暂停、失败保留旧值、筛选和全部已读,并按“先已读、再解析受控目标”的顺序处理点击,而无需猜测类别、级别或后端目标路径。
**Blocked by:**
- 02 — 交付后台通知筛选、分类汇总与全部已读
- 03 — 向个人客户投递并提供简化通知中心
- 05 — 交付通知受控目标解析与权限复核
**Status:** ready-for-agent
**架构通道:** 主通道为 Query/API 跨仓契约,辅助通道为前端验收契约。
**完整业务边界:** 本票收口当前后端仓库能够交付的 OpenAPI、交互状态、目标白名单说明和验收数据不在本仓库实现前端组件。明确不引入 WebSocket/SSE不承诺 Redis 未读计数,不为未知目标提供自由 URL也不代替前端仓库自身的组件测试。
- [ ] 契约明确布局挂载后立即请求、每 30 秒刷新、页面不可见暂停、恢复立即刷新,以及失败保留上次成功未读数且不闪回零。
- [ ] 徽标验收覆盖 0、1、99、1000 时隐藏、199 显示数字、100 显示 `99+`,并约定固定宽度避免布局抖动。
- [ ] 后台抽屉按最近 10 条和约定分类展示,通知中心支持类别、类型、严重级别、已读状态、服务端分页及当前类别全部已读。
- [ ] 点击顺序固定为先进入已读视觉状态并调用已读接口,再解析受控目标;已读失败以下次服务端刷新为准,目标失败不恢复未读。
- [ ] 前端目标白名单只根据 `target_type` 和结构化标识构造内部路由,未知类型或 `available=false` 只展示正文且不跳转。
- [ ] C 端契约只展示当前客户相关的审批结果、套餐、订单和资产消息,不暴露后台同步或系统运维分类。
- [ ] OpenAPI、中文契约文档、示例响应与验收矩阵保持一致并明确前端代码位于外部仓库、需按对应仓库流程实施和联调。

View File

@@ -0,0 +1,27 @@
# 08 — 完成公共通知发布门禁与下游接入契约
**What to build:** 发布负责人可以通过一套公共站内通知整体验收确认通知表、注册表、Worker、后台和 C 端接口、受控目标、清理任务及运行监控已经就绪。验收使用真实 PostgreSQL、Redis、公共 Outbox Relay 和 Asynq 接缝验证至少一次投递与重复消费,并向 UR#33、UR#97 和企微结果通知提供稳定的事件、接收人、模板和目标注册方式。
**Blocked by:**
- 02 — 交付后台通知筛选、分类汇总与全部已读
- 03 — 向个人客户投递并提供简化通知中心
- 04 — 接入账号、角色与店铺动态接收人解析
- 05 — 交付通知受控目标解析与权限复核
- 06 — 交付通知保留清理与失败可观测闭环
- 07 — 冻结后台与 C 端通知前端契约及验收包
**Status:** ready-for-agent
**架构通道:** 主通道为 Infrastructure辅助通道为 Application、Query 与跨仓契约。
**完整业务边界:** 本票收口公共通知的迁移验证、端到端可靠性、OpenAPI、文档、发布回滚和下游接入说明。明确不实现 UR#33 套餐临期、UR#97 钱包低余额或企微审批结果的业务触发规则,不发送真实用户测试通知,不引入外部 Delivery 渠道,也不借发布验收迁移未触碰旧模块。
- [ ] 空数据库和兼容环境可执行通知正向迁移、索引校验与允许的结构回滚;已有通知事实后不得通过降级删表清理,应用回滚允许保留数据。
- [ ] PostgreSQL、Redis、公共 Relay 和 Asynq 端到端测试覆盖事务事件、至少一次投递、入队成功后重复、并发 Worker、多接收人、接收人去重和最终通知唯一性。
- [ ] 真实后台与个人客户认证测试覆盖所有公开接口、统一响应、静态路由顺序、接收人不可篡改、跨用户隔离、过期排除和受控目标权限变化。
- [ ] 运行门禁覆盖 Worker 失败、永久模板错误、无接收人、Outbox 积压、清理滞后和审计/外部集成记录异常,并给出停止放量和恢复步骤。
- [ ] 下游接入契约明确稳定事件 ID、结构化载荷、受控通知类型、接收人解析、模板字段、过期策略和目标引用调用统一队列客户端时禁止传预序列化字节。
- [ ] 发布顺序明确为迁移与校验、Worker 与监控、后端 API、前端、下游生产者下游不得在消费者和监控就绪前制造不可见积压。
- [ ] 新增管理端和 C 端 Handler 已同步路由、RouteSpec、两个 OpenAPI 文档生成器,并生成 OpenAPI 核对 `/read-all` 未被动态 ID 路由吞掉。
- [ ] 中文功能总结覆盖关键流程、前后端契约、异常闭环、监控、发布回滚和待决策项README 增加入口;测试数据使用隔离标识且不向真实用户生成通知。

View File

@@ -0,0 +1,291 @@
# PRDTECH 七月迭代公共开发基础
Status: completed
## Problem Statement
七月迭代同时包含企微审批、支付与充值、钱包入账、站内通知、卡状态事件、批量订购、设备批量分配、导出和低余额预警等需求。这些需求都需要可靠事件投递、重复请求防护、异步任务状态、动态配置、增量迁移和日志脱敏,但它们不应各自实现一套互不兼容的基础设施。
当前仓库已经具备可复用的基础GORM 显式事务、PostgreSQL 唯一约束和条件更新、钱包 `version` 乐观锁、Fiber `request_id`、Redis、Asynq 客户端与 Handler、部分任务的五态常量及进度字段以及请求 JSON 的递归脱敏。与此同时,公共 `tb_outbox_event`、受控 `tb_system_config` 尚未落地已有异步任务状态并不完全一致Redis 防重、状态条件更新、乐观锁和 Worker 抢占的职责没有形成统一契约Access Log 的响应体仍可能原样记录敏感字段,非 JSON 和敏感接口也缺少明确策略。
如果没有先冻结公共责任边界,将产生以下风险:
- 同一业务事务可能只写业务事实却丢失审计或异步事件,或者在事务内直接调用外部系统,造成不可恢复的不一致。
- 各业务建立不同 Outbox 表、Relay、重试状态和 Asynq 载荷,重复投递时缺乏稳定 `event_id`,消费者无法可靠幂等。
- 将 Redis 锁、`request_id`、状态条件更新、钱包版本号和 Worker 租约误当成同一种幂等机制,甚至把 Redis 当作最终业务事实。
- 批量订购、设备分配和导出各自创造不同的“部分成功”状态、错误结构和轮询语义,前端无法形成统一交互。
- 动态配置演变成任意 Key-Value 数据库,未经注册的 Key 可被写入,类型、值域、权限、缓存失效和审计无法保证。
- Access Log 在登录、Token、支付、企微回调和文件接口中泄露凭证、签名、支付链接、回调原文或文件内容。
- 公共基础设施需求侵入 Audit Event、Integration Log、站内通知或各业务领域最终重新合成一个无法独立交付的巨型需求。
本 PRD 的目标不是重新探索业务需求,也不是统一重构全仓库,而是把已评审通过的跨需求约定归拢成一个可先行交付、可被下游复用、所有权清晰的公共基础设施边界。
## Solution
交付一个边界明确的 `tech-public-foundation`,覆盖以下八类已确认能力:
1. 公共表、索引和约束的增量迁移护栏,以及上线前检查、失败退出和数据安全回滚边界。
2. 基于现有 GORM 用法的显式事务契约,使业务事实与契约要求的 Audit Event 或 Outbox 在同一事务提交。
3. 权威公共 `tb_outbox_event`、Relay、领取租约、重试、监控、恢复及结构化 Asynq 投递契约。
4. `request_id + 请求指纹`、PostgreSQL 唯一约束、状态条件更新、钱包 `version`、Worker 租约和 Redis 防并发的公共幂等原语与选择规则。
5. 面向业务任务和前端的统一五态、结果计数、错误摘要、失败明细、恢复与轮询语义,但不建设万能任务表。
6. 受控系统配置壳层,包括 Key 注册、校验、缓存、权限、API 和统一审计接缝。
7. Access Log 请求/响应递归脱敏和敏感接口安全摘要。
8. 加载、空态、权限不足、失败重试和异步任务恢复的前端公共交互契约;当前仓库不实现前端代码。
责任边界固定如下:
| 责任方 | 拥有内容 | 复用但不拥有 |
|---|---|---|
| `tech-public-foundation` | 公共 Outbox 与 Relay、公共幂等原语、系统配置壳层、统一异步状态、迁移护栏、Access Log 脱敏 | Audit Event、Integration Log、通知和业务消费者 |
| `tech-global-audit` | Audit Event、Integration Log、多视角 Query、审计前端、旧审计 Writer 一次性切换 | 公共事务接缝、迁移护栏和共享脱敏策略 |
| `tech-inapp-notifications` | 通知表、模板、接收人解析、Notification Worker、通知 API 和前端通知中心 | 公共 Outbox、Relay、Worker 租约和统一审计 |
| 各业务 PRD | 业务事件定义、业务状态机、业务唯一键、业务任务表、失败明细和消费者行为 | 公共 Outbox、幂等选择规则、五态任务契约和系统配置壳层 |
以上三项公共需求保持独立,不把公共基础、全局审计和站内通知重新合并为一个巨型基础设施需求。
## User Stories
1. 作为发布负责人,我希望每张公共表、每个公共索引和约束都有唯一迁移所有者,以便避免多个下游 PRD 重复创建或互相回滚。
2. 作为发布负责人,我希望迁移前检查能发现重复业务键、非法状态、空值、类型不兼容和未完成任务,并在不满足前置条件时明确失败退出,而不是带病上线。
3. 作为运维人员,我希望数据迁移可重入、可观测,并能区分“可安全回滚结构”与“只能停止生产者后向前修复的数据事实”。
4. 作为业务开发者,我希望继续使用现有 GORM 显式事务在一个清晰边界内提交业务事实、Audit Event 或 Outbox而不必引入 UnitOfWork、工厂层或迁移未触碰模块。
5. 作为业务开发者,我希望通过一个权威 Outbox 模型发布事件,稳定携带 `event_id``event_type`、聚合/资源定位、`request_id``correlation_id` 和结构化载荷。
6. 作为业务开发者,我希望 Outbox 写入失败会令业务事务整体回滚,事务成功后即使 Asynq 暂时不可用,事件仍可恢复投递。
7. 作为 Relay 运维人员,我希望多个 Worker 能并发领取事件但不会长期重复处理同一行Worker 崩溃后过期租约可以自动恢复。
8. 作为 Relay 运维人员,我希望看到待投递量、最老积压时长、投递速率、重试次数、租约过期数和最终失败数,并能按受控流程恢复失败事件。
9. 作为事件消费者,我希望重复投递始终携带同一个 `event_id` 和业务关联标识,以便用业务状态、唯一约束或消费记录实现自己的幂等。
10. 作为 API 调用方,我希望同一作用域内相同 `request_id` 和相同请求指纹返回原结果,而同一 `request_id` 携带不同业务内容时获得明确冲突。
11. 作为资金业务开发者,我希望钱包 `version`、唯一流水和事务边界继续作为资金正确性来源,公共幂等能力不会用 Redis 锁替代资金约束。
12. 作为状态机业务开发者,我希望状态条件更新负责状态流转幂等,更新未命中时按当前状态判断“已处理、冲突或资源不可见”。
13. 作为批量任务开发者,我希望继续拥有本业务的任务表和逐项失败明细,同时复用固定的五态、结果计数、租约恢复和轮询语义。
14. 作为前端用户,我希望任务出现部分成功时仍显示“已完成”,并通过总数、成功数、失败数和失败明细了解结果,而不是看到一个新的“部分成功”状态。
15. 作为前端用户,我希望刷新页面后可以通过 `task_id` 恢复任务进度,页面隐藏时停止轮询,重新可见时立即刷新。
16. 作为超级管理员,我希望查询按模块组织的受控系统配置,并通过与类型匹配的控件更新已注册且允许修改的 Key。
17. 作为安全负责人,我希望未注册配置默认不可写,错误类型、越界值和只读配置更新均被拒绝并留下统一审计。
18. 作为业务模块开发者,我希望只注册本模块的配置 Key、类型和值域公共基础负责存储、缓存、权限和审计但不接管具体业务校验。
19. 作为运维人员我希望系统配置缓存失效失败会告警Redis 故障时读取可回退 PostgreSQL而不会把缓存当作唯一事实。
20. 作为安全负责人,我希望 Access Log 对请求和响应进行同一套递归脱敏,且敏感接口无法因解析失败而回退记录原文。
21. 作为排障人员,我希望脱敏后仍保留 `request_id`、方法、路径、安全查询参数、状态码、耗时、用户与终端信息及截断标记,以便关联问题。
22. 作为前端用户,我希望公共页面都有一致的加载、空态、权限不足、失败和重试反馈,不把权限不足伪装成空数据。
23. 作为测试人员,我希望通过真实 Fiber、GORM、PostgreSQL、Redis、Relay 和 Asynq Handler 验证公共外部行为,而不是依赖私有函数或目录结构。
24. 作为下游需求负责人,我希望清楚知道公共基础提供什么、不提供什么,以及哪些契约必须先冻结,避免为赶进度复制临时基础设施。
## Implementation Decisions
### 1. 架构与责任边界
- 采用触碰式渐进迁移。公共能力放在可复用的 Application、Persistence、Queue 和 Middleware 接缝中,但不主动迁移未被七月需求触碰的旧 Service。
- 复杂写操作仍由各业务 UseCase 和 Domain 收口业务不变量;简单写操作可使用 Application 事务脚本;读取继续由 Query 负责。公共基础不创建新的业务聚合。
- 不引入 Java 风格 UnitOfWork、事务工厂、Repository 工厂或全仓事务抽象。现有 GORM `Transaction` 用法和显式传递事务句柄是权威基础。
- 公共基础提供契约、模型和运行机制;事件含义、业务状态、消费者副作用、业务唯一键和失败明细始终由业务 PRD 所有。
- 数据库关联使用 ID 显式维护,不建立外键约束,不通过 GORM 关联标签扩大耦合。
### 2. 增量迁移与发布基础
- `tech-public-foundation``tb_outbox_event``tb_system_config` 及其公共索引、唯一约束和必要初始化数据的唯一迁移所有者。
- `tech-global-audit``tech-inapp-notifications` 和各业务 PRD 分别拥有自己的表、字段、业务索引、业务唯一约束和数据迁移。公共基础不得接管所有业务迁移。
- 发布清单必须维护数据库对象所有权。同一表、字段、索引或约束只能在一个迁移中创建或修改;下游只能声明依赖,不得复制公共 DDL。
- 每个增量迁移包含正向和回滚边界。结构创建、兼容字段和未产生业务数据的初始化可按验证结果回滚已经产生的业务事实、Audit Event、Outbox、通知和任务结果不得通过降级删除。
- 上线前检查至少覆盖:目标对象是否存在且定义一致、唯一键冲突、必填字段空值、枚举非法值、待处理/处理中任务、未投递 Outbox、长租约和依赖版本。任何破坏正确性的异常都必须非零退出并阻断发布。
- 数据回填按稳定主键分批、可重复执行并记录进度;重复执行不能生成重复事实。`IF NOT EXISTS` 只能用于安全重入,不能掩盖已有对象定义不一致。
- 正向迁移完成后执行后置校验,包括约束生效、行数守恒、异常计数归零、关键索引可用和读写冒烟。检查输出只包含计数与安全标识,不泄露敏感数据。
- 推荐发布顺序为:迁移及前后置检查、兼容 API、Outbox Relay/Worker、依赖消费者、前端。生产者不得早于消费者和监控就绪而开始制造不可见积压。
- 回滚优先顺序为:停止新写入和 Relay 领取、保留已有事实与 Outbox、回滚无数据风险的应用版本、修复后向前恢复。公共表已有生产数据后不允许通过删除表完成回滚。
- 发布必须设置停止条件迁移异常、Outbox 持续积压或租约大量过期、系统配置读写不一致、Access Log 脱敏回归失败、关键任务无法恢复时停止继续放量。
### 3. GORM 事务边界
- 事务由 Application UseCase 或简单写事务脚本开启Handler 不拼接事务逻辑Domain 不依赖 GORM。
- 一次事务只包含需要原子提交的 PostgreSQL 写入。业务事实与契约要求的 Audit Event、Outbox 必须使用同一事务句柄;任一写入失败,整体回滚。
- 是否写 Audit Event、Outbox 或两者,由业务契约决定:需要同步查询的不可变审计事实写 Audit Event需要跨进程消费的可靠事件写 Outbox同一用例同时需要时两者同事务写入。Audit Event 的模型和 Writer 仍归 `tech-global-audit`
- Redis、Asynq、HTTP、企微、支付、Gateway、运营商和对象存储调用不得放进数据库事务。事务提交后由 Relay 或后置动作执行;缓存失效在提交成功后发生。
- 事务内生成并持久化稳定 `event_id`、业务唯一键和必要快照,禁止由 Relay 或消费者在重试时重新生成身份标识。
- 事务应短小,避免在事务内解析大文件、渲染报表或执行慢查询。并发正确性由唯一约束、条件更新、行锁或版本号承担,而不是扩大事务范围。
### 4. 公共 Outbox
#### 权威模型
- 全仓只使用公共 `tb_outbox_event` 表承载需要跨进程可靠投递的领域/应用事件。业务模块不得再创建自己的 Outbox 表或 Relay。
- 权威字段语义至少包括:内部主键;全局稳定且唯一的 `event_id`;稳定的 `event_type`;载荷版本;来源聚合类型与标识;主要资源类型、标识和可选业务键;`request_id``correlation_id`;结构化 JSON payload投递状态重试次数下次可领取时间租约所有者和过期时间最后错误码与脱敏摘要创建、更新和成功投递时间。
- Outbox 状态是 Relay 内部生命周期,使用整数:`1=待投递、2=投递中、3=已投递、4=投递失败`。它不等同于面向用户的五态业务任务,也不产生“部分成功”状态。
- `event_id` 建立最终唯一约束;领取路径按状态、下次可领取时间和租约到期时间建立索引;聚合/资源和关联标识建立满足排障与恢复的查询索引。所有索引归公共基础所有。
- `event_type` 和 payload schema 归发布事件的业务 PRD 所有公共基础只要求事件类型稳定、payload 带版本且能够向后兼容。禁止把任意业务对象完整序列化后无约束写入。
- `request_id` 表示本次入口请求或命令标识;`correlation_id` 表示跨事务、跨队列和外部交互的业务链路。没有 HTTP 请求的定时任务使用稳定命令标识,并以其或 `event_id` 建立关联链路。Relay 和消费者必须原样传播这些标识。
#### 写入、Relay 与至少一次投递
- 业务 UseCase 在保存业务事实的同一 GORM 事务内插入 Outbox。不能先提交业务再补写 Outbox也不能在事务内直接入 Asynq。
- Relay 按小批量领取到期的待投递或可重试事件,通过数据库条件更新/跳锁机制取得有期限的处理权。领取、续租、完成和失败都必须校验当前状态与租约所有者。
- Relay 将公共事件信封作为 struct 或 map 调用项目 `EnqueueTask`;禁止传入预序列化 `[]byte`,避免二次序列化成为 Base64 字符串。直接使用 Asynq 原生任务构造器的既有代码不属于该调用方式,必须自行且只序列化一次。
- Asynq 入队成功后将 Outbox 标记为已投递。若进程在“入队成功、数据库标记前”崩溃,同一事件会再次投递,这是被接受的至少一次语义。
- 入队失败记录安全错误码与摘要,按有上限的指数退避设置下次领取时间;达到最大重试或判定永久错误后保持失败并告警,不删除记录。
- 处理中 Worker 超过租约未完成时,可由恢复扫描重新置为可领取;恢复保留原 `event_id`、payload 和关联标识,不生成新事件。
- 受控重放只能作用于明确选择的失败/滞留事件,记录操作者、原因和批次,不修改已投递事件内容。重放仍使用原 `event_id`,因此消费者必须幂等。
- 监控至少提供待投递量、最老待投递年龄、处理中与过期租约数、投递成功率、重试分布、最终失败数和按 `event_type` 的积压。阈值越界进入现有告警通道。
- 公共 Outbox 只保证“事件最终至少被送达队列”不保证业务副作用只发生一次。消费者仍需用业务状态、PostgreSQL 唯一约束、消费记录或稳定业务键实现自己的幂等。
### 5. 公共幂等原语
- 公共基础提供选择规则和可复用构件,不建设要求所有请求进入同一张表的万能幂等平台。
- 创建类命令采用调用方稳定提供的 `request_id`作用域至少包含调用主体与操作类型。请求指纹由会影响业务结果的规范化字段计算排除时间戳、签名、Token 等易变传输字段,并带算法版本。
- 同一作用域内,`request_id + 相同指纹` 返回已存在结果;`request_id + 不同指纹` 返回幂等冲突,不覆盖原事实;并发首次写入由 PostgreSQL 唯一约束裁决。
- PostgreSQL 唯一约束、业务状态和账务流水是最终正确性来源。应用层预查只用于友好返回,不能替代数据库约束。
- 状态流转使用 `WHERE 当前状态=预期状态` 的条件更新;影响行数为零时重新读取当前状态,区分已完成、非法转换和统一资源不可见语义。
- 钱包余额、冻结金额和其他并发数值写使用 `version` 乐观锁或业务明确要求的行锁并与唯一流水、业务事实、Audit Event/Outbox 同事务。公共基础不拥有钱包规则。
- Worker 租约只解决“谁在这一时刻处理”,不证明业务副作用未发生。领取条件、租约所有者、过期时间和完成条件必须落在 PostgreSQL消费者仍执行自己的业务幂等检查。
- Redis `SETNX`、分布式锁和短期防重键只用于减少重复并发和热点压力。Redis 缺失、过期、故障或主从切换不能造成重复业务事实;锁必须设置过期并确保释放。
- 稳定 `event_id` 解决事件身份,稳定业务唯一键解决副作用身份,`request_id` 解决入口命令身份,三者不得混为一个万能键。
### 6. 统一异步任务契约
- 面向业务和前端的任务状态固定为:`1=待处理、2=处理中、3=已完成、4=已失败、5=已取消`。响应同时提供对应中文状态名。
- “已完成”表示任务已到达处理终点,不表示每个业务项都成功。部分成功由 `total_count``success_count``failed_count` 表达,禁止增加“部分成功”状态。
- 业务数据逐项完成但存在业务校验失败时,任务状态为已完成;只有文件无法解析、任务无法建立、关键基础设施持续失败或整体执行无法到达业务终点时,任务状态才为已失败。
- 每类任务继续拥有自己的业务任务表、业务项表和失败明细。批量订购、设备批量分配和导出不得为了统一状态而迁移到一张万能任务表。
- 公共查询语义至少统一 `task_id`、状态与状态名、总数/成功数/失败数、进度、脱敏失败摘要、开始时间、完成时间和更新时间。失败明细由业务定义字段并分页或受限返回。
- 失败摘要使用稳定错误码与用户可见中文说明,不暴露 SQL、堆栈、外部密钥、回调原文或内部网络信息。可下载失败文件时只返回受控短期访问能力不写永久公开地址。
- 待处理任务通过条件更新领取为处理中处理中任务必须具有租约或等价的可恢复执行记录。Worker 崩溃、进程重启或队列重复投递后,过期任务可以重新领取并从业务事实恢复。
- 终态只能通过满足预期状态的条件更新进入。重复 Handler 看到已完成、已失败或已取消时不得重新制造业务副作用。
- 取消只适用于业务明确支持取消的任务;不支持取消的业务仍返回五态中的实际状态,不能把失败伪装成取消。
- Asynq 载荷使用最小结构化标识,通常只包含 `task_id`、必要分片标识和关联标识;调用 `EnqueueTask` 时必须传 struct 或 map禁止传 `[]byte`
### 7. 公共系统配置
- 新建公共 `tb_system_config`,至少保存唯一 `config_key`、字符串化 `config_value``value_type`、所属模块、中文说明、只读标记、创建/更新人与时间。`value_type` 限定为 `string``int``bool``json`
- Key 使用稳定的 `module.group.name` 命名。代码中的受控 Key 注册表是可写配置的权威来源,定义 Key、模块、类型、值域/枚举、默认值、是否只读、是否敏感和前端控件提示。
- 未注册 Key 默认不可写;数据库中已存在但未注册的 Key 最多按只读、可诊断方式展示。禁止通过 API 创建任意 Key禁止提供原始 JSON 自由编辑器把它扩展成通用 Key-Value 配置中心。
- 注册表重复 Key、类型冲突或不合法默认值必须在启动或验证阶段失败不能以后注册者静默覆盖前者。
- 查询 API 为已认证超级管理员提供按模块过滤的配置列表,返回脱敏后的值、类型、值域、说明、只读状态和更新时间。更新 API 按 Key 修改单项配置,不提供无约束批量覆盖。
- 更新流程依次执行认证与超级管理员授权、Key 注册检查、类型解析、值域/业务边界校验、GORM 事务更新和统一 Audit Event。审计模型与 Writer 复用 `tech-global-audit`,公共基础不另建配置审计表。
- Redis Key 固定按配置 Key 生成默认缓存五分钟。PostgreSQL 是唯一事实来源;读取缓存未命中或 Redis 不可用时查询数据库并尝试回填。
- 配置更新提交成功后立即失效对应 Redis 缓存。失效失败不回滚已提交事实,但必须告警;短 TTL 限制旧值持续时间,后续读取可按版本/更新时间避免回填旧值。
- 数据库值无法解析、越界或读取失败时不得静默使用错误值。按注册策略使用最后一个已验证值或代码安全默认值,并产生可定位告警。
- UR#48 负责注册具体支付方式 Key、支付业务值域和启停校验本 PRD 只负责存储、注册、权限、缓存、API 和审计壳层。
### 8. Access Log 脱敏
- Access Log 对 query、请求体和响应体执行同一套递归脱敏覆盖嵌套对象与数组。字段匹配大小写不敏感并支持公共敏感字段注册表与路由级策略。
- 通用敏感字段至少覆盖密码/口令、Token、Authorization、Cookie、密钥/Secret、签名、Nonce、验证码、支付凭证和私密 URL。脱敏值不可逆不允许只遮盖中间几位后保留可复用凭证。
- 登录和 Token 接口:请求中的密码、验证码全部替换;响应中的访问令牌、刷新令牌、会话标识全部替换,只保留成功状态和必要主体标识。
- 支付接口:不记录支付凭证、银行卡敏感信息、二维码原文、支付跳转链接、渠道密钥和完整签名;保留安全订单号、渠道类型、结果码和金额等排障摘要。
- 企微回调不记录原始加密包、解密正文、签名、Nonce、通讯录敏感字段或完整回调响应保留事件类型、安全资源标识、载荷大小、摘要哈希和处理结果。
- 文件上传、下载和导出接口:不记录 multipart/binary、Base64 内容、文件字节、临时凭证和签名下载地址;只记录脱敏文件名、类型、大小、数量、任务标识和结果。
- 敏感路由的 JSON/XML/表单解析失败时采用“字段存在性、长度、内容类型、安全哈希和截断标记”的摘要策略,禁止回退记录原始 body。普通非敏感文本接口也必须经过路由策略后才可记录。
- 保留方法、路径、脱敏 query、状态码、耗时、`request_id`、IP、User-Agent、用户标识以及请求/响应摘要。请求体和响应体分别遵守现有 50KB 上限,先脱敏再截断,并明确记录截断状态。
- 脱敏器是公共可复用能力Access Log 中间件归本 PRD。Audit Event 和 Integration Log 的模型、Writer、查询、保留策略及其字段级脱敏仍归 `tech-global-audit`,本 PRD 不重复实现。
### 9. 前端公共交互契约
- 当前仓库没有前端源码,本 PRD 只冻结跨仓 API 与交互验收契约,不虚构前端目录、组件名或状态管理实现。
- 加载态:首次加载展示明确占位并阻止重复提交;已有数据刷新时保留可辨识的旧内容和刷新提示,不闪回空白或零值。
- 空态:只有成功请求且确实无数据时展示空态;筛选无结果与系统暂无数据使用不同文案,并提供清除筛选或返回入口。
- 权限不足:按统一 403 语义展示无权限,不展示重试按钮,不用 404/空列表泄露资源是否存在。
- 失败与重试:瞬时网络或服务错误保留用户输入和已有结果,展示安全错误摘要与显式重试;参数错误定位可修正字段,不自动无限重试。
- 创建异步任务成功后,前端保存 `task_id` 到刷新后可恢复的页面状态,不能只存在内存。重新进入页面时通过 `task_id` 或业务任务列表恢复最新状态。
- 轮询状态为待处理或处理中时继续;建议间隔按 2 秒、3 秒、5 秒逐步退避,最长 10 秒。到达已完成、已失败或已取消后停止。
- 页面进入隐藏状态时暂停轮询;恢复可见时立即刷新一次,再按当前状态恢复退避。网络恢复或页面刷新不能创建重复任务。
- 已完成且 `failed_count > 0` 时展示部分成功摘要和失败明细入口;已失败展示失败摘要与业务允许的重试/重建入口;已取消展示取消原因且不自动重建。
### 10. 可观测性与故障恢复
- 公共日志和指标使用 `request_id``correlation_id``event_id``task_id` 和安全资源标识串联,但不得把完整 payload 或敏感配置值作为标签或日志字段。
- Outbox、系统配置缓存和 Access Log 脱敏失败均需提供中文、可操作告警;告警内容包含组件、错误码、时间窗口和安全标识。
- Worker 和 Relay 重启后以 PostgreSQL 状态和租约恢复,不依赖进程内内存或 Redis 锁推断任务是否完成。
- 恢复工具只暴露受控的查询、重试和租约释放能力,所有人工操作写统一 Audit Event禁止直接删除 Outbox、篡改业务终态或跳过消费者幂等检查。
## Testing Decisions
### 1. 测试层级与真实接缝
- 系统配置通过真实 Fiber 路由、认证、Application、GORM 和 Redis 验证,覆盖查询、更新、超级管理员权限、未注册 Key、只读 Key、类型/值域错误、事务回滚、缓存命中与更新后失效。
- Outbox 通过“业务事务写入 → Relay → Asynq Handler → 可观察消费结果”的完整链路验证。断言基于数据库事实、队列可观察结果和消费者公开结果,不直接调用 Relay 私有函数完成测试。
- PostgreSQL 集成测试验证事务回滚、`event_id`/业务键唯一约束、状态条件领取、并发领取、租约恢复、重试调度和重复投递。
- Access Log 使用真实 Fiber 测试请求和响应,捕获最终 JSON 日志检查递归脱敏、敏感接口特殊策略、解析失败安全降级、50KB 截断及 `request_id`/状态/耗时保留。
- Redis 和 PostgreSQL 使用隔离测试数据、唯一前缀或独立测试空间,测试只清理自己创建的数据,不执行全库/全缓存清空。
- 不依赖真实支付、企微、Gateway 或运营商网络;外部边界使用可观察的测试 Adapter。公共链路仍使用真实 PostgreSQL、Redis 和 Asynq 组件。
- 只测试公共外部行为和稳定契约,不绑定私有函数、未导出类型或内部文件组织。
### 2. 迁移与事务测试
- 在空数据库和带兼容存量数据的数据库分别执行正向迁移、后置校验和允许的回滚,验证公共对象只创建一次、定义一致且迁移版本可继续前进。
- 构造重复 `event_id`、非法配置、唯一键冲突、处理中任务和未投递事件,验证前置检查明确失败退出且不执行破坏性写入。
- 数据回填中断后重复运行,验证已完成批次不重复、未完成批次继续、行数守恒且错误报告不含敏感值。
- 在业务事实、Audit Event、Outbox 任一步注入失败,验证同一 GORM 事务完全回滚;提交成功后再模拟 Redis、Asynq 或外部 Adapter 失败,验证业务事实不回滚且可恢复。
### 3. Outbox 与幂等测试
- 验证业务提交成功时 Outbox 与业务事实同时可见业务回滚时二者均不可见Relay 不读取未提交事务中的事件。
- 并发启动多个 Relay 领取同一批事件,验证同一时刻只有租约所有者可完成该行;终止 Worker 后等待租约过期,验证其他 Worker 使用原 `event_id` 恢复。
- 模拟入队成功但 Outbox 未标记成功,验证再次投递同一 `event_id`,消费者通过业务唯一约束或状态检查只产生一次业务副作用。
- 覆盖瞬时失败退避、最大重试、永久失败告警、受控重放、积压年龄和不同 `event_type` 的监控聚合。
- 直接向 `EnqueueTask``[]byte` 必须失败;传 struct/map 能由公开 Handler 正确解析。重复 Marshal 造成 Base64 的回归必须被测试阻止。
-`request_id + 指纹` 覆盖相同请求重放、同 ID 不同内容冲突、不同主体同 ID、并发首次提交和 Redis 不可用,验证 PostgreSQL 约束始终裁决最终结果。
- 分别验证状态条件更新、钱包版本冲突和 Worker 租约,证明三者只承担各自并发职责,不能相互替代。
### 4. 异步任务契约测试
- 对所有新接入的批量订购、设备分配和导出公开 DTO 做契约测试,状态只能为 1 至 5 且状态名一致。
- 覆盖全成功、部分成功、全部业务项失败、整体执行失败和取消:部分/全部业务项处理完均为已完成并由计数表达;整体无法执行才为已失败。
- 验证 `total_count = success_count + failed_count` 的业务终态守恒;若业务存在明确跳过项,必须在业务 PRD 中定义其归类,不能由公共层凭空新增状态。
- 验证失败摘要不泄露内部错误,失败明细分页/受限,终态重复消费不改变计数,过期处理中任务能够恢复。
- 前端契约验收覆盖加载、真实空态、筛选空态、权限不足、失败重试、2/3/5 秒退避、页面隐藏暂停、恢复立即刷新和通过 `task_id` 恢复。
### 5. 系统配置与脱敏测试
- 系统配置测试覆盖 `string/int/bool/json` 类型、枚举/范围校验、未注册和只读 Key、超级管理员与非授权用户、并发更新、审计事实和安全默认值。
- 模拟 Redis 未命中、超时、写入失败和失效失败,验证 PostgreSQL 仍为事实来源、更新不丢失、旧缓存有期限且告警可观察。
- Access Log 使用嵌套对象、数组、大小写变体、query、JSON/XML/表单、二进制、超长 body 和无法解析内容建立测试矩阵。
- 登录/Token、支付、企微回调和文件接口分别有固定回归样例日志中不得出现测试密码、Token、签名、Nonce、支付链接、回调原文、文件字节或临时凭证。
- 验证脱敏后仍保留方法、路径、安全 query、状态、耗时、`request_id`、用户标识、body 摘要和截断标记,可用于从 Access Log 关联到 Audit/Integration 记录。
## Out of Scope
- Audit Event 和 Integration Log 的具体模型、Writer、查询、前端、保留策略及旧审计 Writer 一次性切换;这些归 `tech-global-audit`
- 站内通知业务包括通知表、模板、接收人、Notification Worker、通知 API 和前端通知中心;这些归 `tech-inapp-notifications`
- 企微、支付、Gateway 和运营商 Adapter以及其签名、协议映射、回调业务和外部补偿逻辑。
- 钱包、退款、充值、支付、套餐订购、卡状态、低余额预警等领域规则、状态机、金额校验和业务消费者行为。
- 各业务表、业务索引、业务唯一键和业务数据迁移;它们继续由对应业务 PRD 所有。
- 所有旧模块的全仓事务重构、DDD 重构、Repository 重写或异步任务迁移。
- 万能任务表、万能幂等表、全请求幂等平台和任意 Key-Value 配置中心。
- 强制所有任务使用同一个业务任务模型,或把批量订购、设备分配、导出迁移到公共表。
- 精确一次投递承诺。公共 Outbox 提供至少一次投递,消费者幂等由业务负责。
- 在当前仓库实现前端组件或虚构前端目录;这里只冻结跨仓交互和验收契约。
- 真实支付、企微、Gateway、运营商网络或生产数据上的集成测试。
## Further Notes
### 已确认的仓库基础
- GORM 已关闭默认事务并普遍使用显式事务;公共实现应沿用这一方式,不新增平行事务框架。
- 项目 Asynq 客户端已经统一使用 Redis 配置,并拒绝 `EnqueueTask` 接收 `[]byte`;仍存在直接使用 Asynq 原生客户端并自行序列化的业务代码,迁移时需区分两种调用契约。
- Fiber 已生成并传播 `request_id`;仓库已有 PostgreSQL 条件更新、钱包 `version`、Redis 防并发和导出任务五态的可复用实践,但尚未形成完整公共契约。
- 当前没有公共 Outbox 和受控系统配置实现。Access Log 已对 JSON 请求递归脱敏并限制 50KB但响应体仍直接截断记录敏感非 JSON/文件接口也缺少安全降级策略。
- 当前仓库没有前端源码,前端交付由对应前端仓库按本 PRD 的公开契约验收。
### 下游依赖与阻塞关系
本 PRD 是公共契约和发布顺序的前置项,但只阻塞下游对公共接缝的集成与上线,不接管下游业务设计:
| 下游 PRD | 被本 PRD 阻塞的公共接缝 | 下游仍自行负责 |
|---|---|---|
| `tech-global-audit` | 公共迁移所有权、同事务写入接缝、关联标识和共享脱敏策略 | Audit Event、Integration Log、Query、前端和旧 Writer 切换 |
| `tech-inapp-notifications` | `tb_outbox_event`、Relay、结构化载荷和租约恢复 | 通知模型、模板、接收人、Worker、API 和前端 |
| UR#37 企微审批基础 | Outbox、至少一次投递、Worker 租约、关联标识 | 企微场景、实例状态机、扫码绑定和 Adapter |
| UR#34 代理充值 | `request_id + 指纹`、Outbox、两阶段投递和任务恢复 | 支付事实、充值状态机、钱包入账和唯一流水 |
| UR#94 卡状态事件与回调 | 公共事件信封、Outbox、结构化 Asynq 载荷 | 卡状态规则、事件类型、消费者和外部回调行为 |
| UR#97 钱包低余额预警 | Outbox 与可靠消费接缝 | 阈值规则、钱包变更事件、接收人和通知内容 |
| UR#36 批量订购 | 五态任务、计数、失败语义、幂等和租约契约 | 批量任务/明细表、逐行校验、订购行为 |
| UR#42 统一导出字段权限 | 五态、结构化任务载荷、轮询和恢复语义 | 导出 DataSource、字段权限、文件生成和业务任务表 |
| UR#49 设备批量分配 CSV | 五态、部分成功、失败明细和租约契约 | 设备分配规则、CSV 校验和业务任务表 |
| UR#38 代理主钱包授信 | GORM 事务、PostgreSQL 最终幂等和 `version` 职责边界 | 钱包规则、授信/扣款、流水与领域事件 |
| UR#48 支付方式配置 | `tb_system_config`、受控 Key 注册、缓存、权限、API 和审计壳层 | 具体支付 Key、值域、支付业务校验和生效规则 |
上述下游可以在公共契约稳定后并行开发自己的领域部分;在公共 Outbox、任务状态或系统配置接缝尚未可用时不得复制临时 Outbox、万能任务表、幂等表、通知表或配置中心作为替代。
### 交付判定
- 公共能力的公开契约、迁移所有权、故障恢复和可观测性全部通过本 PRD 的真实接缝测试后,才可认为公共基础就绪。
- `tech-global-audit``tech-inapp-notifications` 保持独立交付;公共基础就绪不等于审计或通知业务已经完成。
- 下游业务 PRD 的领域测试、外部 Adapter 测试和业务前端验收仍是各自发布门槛,不能用公共基础测试替代。

View File

@@ -0,0 +1,18 @@
# 01 — 建立公共迁移所有权与检查门禁
**What to build:** 发布负责人能够通过统一清单确认公共数据库对象的唯一迁移所有者,并在迁移前后运行可重入检查。对象定义冲突、唯一键冲突、非法状态、必填字段空值、未完成任务、未投递事件、长租约或依赖版本不满足时,检查以中文安全摘要和非零状态阻断发布;正常结果给出可核对的计数与安全标识。
**Blocked by:** None — can start immediately
**Status:** completed
**架构通道:** Infrastructure。
**完整业务边界:** 本票收口公共数据库对象的所有权登记、迁移前置检查、后置检查、失败退出、可重入和安全输出契约。明确不创建下游业务表,不迁移历史业务数据,不接管审计、通知或业务 PRD 拥有的迁移。
- [x] 公共 Outbox、系统配置及其公共索引、约束和初始化数据均有唯一迁移所有者下游只能声明依赖不能复制公共 DDL。
- [x] 检查能够发现目标对象定义不一致、唯一键冲突、必填字段空值、非法枚举、未完成任务、未投递事件、长租约和依赖版本问题,并以非零状态阻断发布。
- [x] 前置和后置检查可以重复运行;重复执行不产生新业务事实,`IF NOT EXISTS` 不会掩盖已有对象定义不一致。
- [x] 后置检查验证约束、关键索引、异常计数和读写冒烟,输出仅包含计数、错误码与安全标识,不泄露敏感值。
- [x] 发布说明明确哪些结构可安全回滚、哪些已有事实只能停止生产者后向前修复,以及迁移异常时的停止条件。
- [x] 自动化验证覆盖空数据库、兼容存量数据库、异常数据和重复执行场景,不执行全库清理。

View File

@@ -0,0 +1,18 @@
# 02 — 在业务事务中可靠写入公共 Outbox
**What to build:** 业务开发者可以沿用现有 GORM 显式事务,在提交业务事实的同一事务中写入权威公共 Outbox 事件。事件身份和关联标识在事务内稳定持久化,业务写入或 Outbox 写入任一步失败都会整体回滚,事务中不会调用 Redis、Asynq 或外部系统。
**Blocked by:** 01 — 建立公共迁移所有权与检查门禁
**Status:** completed
**架构通道:** Application + Port/Adapter。
**完整业务边界:** 本票收口公共 Outbox 模型、事件信封、事务内追加 Port 和一个可观察的示例写入链路。明确不定义下游业务事件含义,不实现业务消费者,不引入 UnitOfWork、事务工厂或全仓事务重构。
- [x] 公共 Outbox 具有稳定唯一的事件 ID、事件类型、载荷版本、聚合与资源定位、请求与关联标识、结构化载荷、投递生命周期、重试、租约和安全错误摘要字段。
- [x] Outbox 内部状态固定为 `1=待投递、2=投递中、3=已投递、4=投递失败`,常量、模型注释和公开说明保持一致。
- [x] 业务事实和 Outbox 使用同一 GORM 事务句柄;任一写入失败时二者均不可见,未提交事件不会被投递侧读取。
- [x] 事件 ID、业务键及必要快照在事务内生成并持久化重试过程中不会重新生成事件身份。
- [x] 事务内不执行 Redis、Asynq、HTTP、对象存储或其他外部调用Domain 不依赖 GORM。
- [x] PostgreSQL 集成测试覆盖事务成功、业务写入失败、Outbox 写入失败、事件 ID 唯一约束和回滚行为。

View File

@@ -0,0 +1,18 @@
# 03 — 完成 Outbox 到 Asynq 的至少一次投递闭环
**What to build:** 多个 Relay 实例可以并发领取到期 Outbox 事件,并通过有期限租约把公共事件信封可靠投递到 Asynq。瞬时失败会退避重试进程崩溃后过期租约可恢复入队成功但数据库标记前崩溃时允许重复投递但始终传播原事件 ID 和关联标识。
**Blocked by:** 02 — 在业务事务中可靠写入公共 Outbox
**Status:** completed
**架构通道:** Infrastructure。
**完整业务边界:** 本票收口 Relay 的领取、租约、续租、投递、完成、失败、退避与恢复闭环,并通过公开 Asynq Handler 验证结构化信封。明确不实现业务消费者副作用,不承诺精确一次,不迁移未触碰的旧队列生产者。
- [x] Relay 以小批量条件领取或跳锁方式取得处理权,领取、续租、完成和失败均校验当前状态与租约所有者。
- [x] Relay 调用统一队列客户端时传 struct 或 map传入 `[]byte` 被明确拒绝并有回归测试防止二次序列化为 Base64。
- [x] 入队成功后事件标记为已投递;模拟入队成功但标记前崩溃时,恢复投递仍使用原事件 ID、载荷和关联标识。
- [x] 瞬时失败按有上限的指数退避安排下次领取,达到最大重试或永久失败时保留记录并产生中文安全告警。
- [x] 多 Relay 并发时同一时刻只有租约所有者能够完成事件Worker 崩溃后其他实例可在租约过期后恢复领取。
- [x] 真实 PostgreSQL、Redis 和 Asynq 链路测试覆盖事务写入、Relay、公开 Handler 与可观察消费结果,不依赖 Relay 私有函数断言。

Some files were not shown because too many files have changed in this diff Show More