Compare commits
387 Commits
e81d3a58ad
...
Iteration/
| Author | SHA1 | Date | |
|---|---|---|---|
| d022cc8788 | |||
| bcf3e31db6 | |||
| c4f430ccb3 | |||
| 1a9db9328e | |||
| 2e130b98f5 | |||
| 5cdcdad534 | |||
| d2e08dbbec | |||
| 026d4908d8 | |||
| 31232ea899 | |||
| b38df737e1 | |||
| 346156ee9b | |||
| 0d79130e07 | |||
| b3fb8c7a82 | |||
| 44fb21eb6a | |||
| 8f738ffbe8 | |||
| 6db152bb2f | |||
| fc6af43baa | |||
| 52bdbbae25 | |||
| 76f657c986 | |||
| a2793f7bec | |||
| b5b7f9a41e | |||
| b930662817 | |||
| ab9da7bb33 | |||
| 781e82441d | |||
| f4b6a55b27 | |||
| 8cf921f11c | |||
| c5871b59a1 | |||
| c0b9604515 | |||
| 5c2ef97c24 | |||
| 2885b503b3 | |||
| 062f5a436f | |||
| ba435dd6a6 | |||
| 3f21f7a7d6 | |||
| 5f960daf78 | |||
| 3b7b856e48 | |||
| cf36f1447f | |||
|
|
1f634eb465 | ||
|
|
84ab3bad99 | ||
|
|
6c8594633a | ||
|
|
064961471b | ||
|
|
e37aad9e1d | ||
|
|
7ec84fbc0f | ||
|
|
2f0b24ce88 | ||
|
|
e56649e5be | ||
|
|
1c492fe8db | ||
|
|
e139f5e227 | ||
|
|
016e7bee79 | ||
|
|
c437593a8c | ||
|
|
134021c91e | ||
|
|
5c779cb6e0 | ||
|
|
32c9859b38 | ||
|
|
283e3e3eb3 | ||
|
|
6a70713b30 | ||
|
|
4ccbf13197 | ||
|
|
0ae8148689 | ||
|
|
9a802c04e5 | ||
|
|
4d419a1966 | ||
|
|
fe2041bcf5 | ||
|
|
6ac19d6565 | ||
|
|
cce27975a1 | ||
|
|
d86ac46761 | ||
|
|
420f3d83f9 | ||
|
|
27fba9160c | ||
|
|
5089a71764 | ||
|
|
5f57429fb0 | ||
|
|
46ede81aef | ||
|
|
36e68e6672 | ||
|
|
a6cd550b94 | ||
|
|
c6e65fde9b | ||
|
|
1b47fb8f32 | ||
|
|
c5126c583b | ||
|
|
918b9b4f25 | ||
|
|
944526d9ef | ||
|
|
6c8352491c | ||
|
|
1ee554daec | ||
|
|
34a7cf0f3c | ||
|
|
6a3fffc46c | ||
|
|
872769e69e | ||
|
|
1550ef3cb1 | ||
|
|
58863e8ec5 | ||
|
|
0d96a94e5f | ||
|
|
cf689beceb | ||
|
|
f4d92f99a2 | ||
|
|
e131d6ba77 | ||
|
|
bcbc290bad | ||
| 4c1e4f428a | |||
| 20b5d70af9 | |||
| 226474b434 | |||
| 860f589b9a | |||
| 2adbc87a52 | |||
| 6e564d1d1a | |||
| 3d28e29eaa | |||
| 0948494b1c | |||
| 599289a94e | |||
| b988f99a95 | |||
| 56adc30409 | |||
| 53e95751b1 | |||
| 58bdb2f18e | |||
| a03ba5d396 | |||
| 2768deb0b6 | |||
| e2301d5f3b | |||
| 9f5c5c3680 | |||
| 5e7e68cce7 | |||
| ca939ff617 | |||
| 8de9c59b1c | |||
| 631c5392b6 | |||
| af5a21ed1e | |||
| 480d4c4583 | |||
| ed071918ed | |||
| d597a25c69 | |||
| 81aa3c2b11 | |||
| a5388446d3 | |||
| 8f3a68a673 | |||
| 95fc0b0a1b | |||
| b7369a9c71 | |||
| 05a5694a5f | |||
| 1350a9ed79 | |||
| 93200a9074 | |||
| 02d522564f | |||
| b6d21b81e3 | |||
| 98ff88d5c3 | |||
| a9eaf1d697 | |||
| 97851c2595 | |||
| ebaf112c80 | |||
| 09cf0be86e | |||
| 6a6672d0e4 | |||
| 0b86720534 | |||
| a93acc0784 | |||
| 7c85a8cf29 | |||
| 348cb4e670 | |||
| e77bb0d09b | |||
| 73a3a04204 | |||
| 573e887ca5 | |||
| 29d3d48dbe | |||
| d42fe2b0ca | |||
| eb74dd7849 | |||
| 3a2e3f2571 | |||
| b0bd37ec12 | |||
| 001f8caf35 | |||
| 21b73a750d | |||
| ee7bfb81f0 | |||
| b4a9e0c1c9 | |||
| 948243b13d | |||
| 5425e2ce19 | |||
| 70fb7dadef | |||
| 8a3c45c577 | |||
| 9238eeb56e | |||
| 9674e0d0d9 | |||
| 248ed55f4e | |||
| 66e12e9629 | |||
| 4f4e42f27e | |||
| 6b3b33b2f0 | |||
| 74c7b27327 | |||
| 37b4483183 | |||
| 516a7f5bdf | |||
| fe4c545308 | |||
| bb33232b1b | |||
| c3ae7fcfbc | |||
| 66cec7515a | |||
| cb75b5668b | |||
| 95104100c9 | |||
| 02ccf57aa3 | |||
| 60debb7505 | |||
| 531de3c760 | |||
| a887f91686 | |||
| 7efcea2b54 | |||
| 85bef83752 | |||
| bc344f892c | |||
| 41db5b56af | |||
| 15cd26c81a | |||
| 3f2cf31543 | |||
| ba73913a41 | |||
| a44c88005d | |||
| f177c26016 | |||
| 4bde09837a | |||
| c250a47651 | |||
| a7f2c4480a | |||
| 37e113bbf4 | |||
| 5442dcbeda | |||
| b9fc828567 | |||
| 327c72ca74 | |||
| 32f03cd2c1 | |||
| 8d2e8faa84 | |||
| 1f1f31a7cb | |||
| 52d883d8a0 | |||
| 6b1fbf4a92 | |||
| 10a35625a5 | |||
| a207c51bfb | |||
| 6eb6d381f7 | |||
| e27758cce3 | |||
| 7137ed087f | |||
| a9690a49db | |||
| 0f58886454 | |||
| 9f8173e124 | |||
| 1d930cc82d | |||
| 1b21d4dafa | |||
| e573a82120 | |||
| e049080f6c | |||
| 9942bbc74e | |||
| fc9f819787 | |||
| 33a4d25ca9 | |||
| e9862a67ba | |||
| 868f5a8ef3 | |||
| fd795d8742 | |||
| 2b3a9cb33f | |||
| 4b8784d5e7 | |||
| 2413c2fe14 | |||
| e52671eaed | |||
| 716e9f5971 | |||
| 28ac58ea18 | |||
| 8e61cb1a54 | |||
| 4aab0bcbf2 | |||
| 6caf0f6141 | |||
| 6e15e1b853 | |||
| ad30f5d41b | |||
| b538e45bd9 | |||
| 1033d7666b | |||
| 0d2baabcf1 | |||
| 9d8e3926ff | |||
| c5ed040359 | |||
| 363e0efb34 | |||
| 1363797378 | |||
| 71498883b5 | |||
| 1d75a4c31a | |||
| 89eec1406a | |||
| 9a625f51ef | |||
| 2d6456c4a3 | |||
| 9bd1d60e85 | |||
| 908c5fa1de | |||
| 505b30aa8f | |||
| e0a37f4a11 | |||
| 4c284c422c | |||
| 44e4f03957 | |||
| 0a2961ecd6 | |||
| fa554c3930 | |||
| 1125701329 | |||
| ed1facc1b8 | |||
| 0cba6fd6d5 | |||
| 94f20ce8c7 | |||
| aef20d2ab1 | |||
| 0ec16d4afa | |||
| 7e4c61e6e9 | |||
| 2d0b4e9bc0 | |||
| 520b126ecf | |||
| 5d9be1d7e4 | |||
| 5065d925ad | |||
| 97d6319b64 | |||
| 0a27a78d97 | |||
| fc995187df | |||
| 8bf1282378 | |||
| 854330a4b4 | |||
| e40ad462e1 | |||
| 647d78309d | |||
| c7f486ae09 | |||
| 71559547b6 | |||
| 6292443f69 | |||
| 97c196b7c6 | |||
| cb328f3ec2 | |||
| 9992e82a3c | |||
| e2003eb9e3 | |||
| 71048e31d4 | |||
| 4a1e44f9e1 | |||
| dd408fcdca | |||
| 516bb92a16 | |||
| 023a4309eb | |||
| b972a776d9 | |||
| d26010b29d | |||
| 8706247436 | |||
| 8154a61453 | |||
| d9de704d73 | |||
| 4ea4a1e53f | |||
| 041856dc8c | |||
| 7cdb66cbe4 | |||
| 5410181e77 | |||
| 548ec0cd6b | |||
| 5e9e41db21 | |||
| c35542f911 | |||
| 42c5ec912f | |||
| c0b64c9e30 | |||
| 37706bc7ce | |||
| 7308afe801 | |||
| c1456f3c54 | |||
| 640ea8ec99 | |||
| 8569873690 | |||
| 5196472d7e | |||
| 814a2956b3 | |||
| 4879d9bf07 | |||
| 8d8d426e2e | |||
| 246ae5e123 | |||
| 7e613a0d2b | |||
| 510a5bfb21 | |||
| decb7a10ec | |||
| 5588c7c762 | |||
| eebc7194d8 | |||
| e945a672ed | |||
| 41d3667df2 | |||
| 8f66ca7bcb | |||
| e9ff14df0e | |||
| c807b99a91 | |||
| 677d6239ce | |||
| d0989c66bb | |||
| 67f3286e09 | |||
| a8b52f8ae1 | |||
| 5496cb58aa | |||
| 3cb16804a4 | |||
| 2a7ac3f86e | |||
| ef8ec025bd | |||
| 23e12d8a73 | |||
| 4a18aac6ce | |||
| 51fa027eb8 | |||
| afc6d7fc76 | |||
| cd807e58e3 | |||
| ff7e749bf2 | |||
| 0627ffec42 | |||
| 1d6535b81b | |||
| 0f6fd42aff | |||
| c1cec0aede | |||
| 6dfc5c0301 | |||
| fce35e8a2d | |||
| 81ba84cf05 | |||
| 384a54164b | |||
| a7dfe858c7 | |||
| e9df1e7ded | |||
| cc56e27c01 | |||
| 78d6aded9b | |||
| 14a8ea5a2c | |||
| 38ef73fd7f | |||
| 303bffbe84 | |||
| 80c6f6c756 | |||
| 7e489a19fb | |||
| 434a8b0349 | |||
| 10fcc0b3c9 | |||
| c0c32c62f4 | |||
| a8a91fe04e | |||
| 8980e6d999 | |||
| 322ded0012 | |||
| ecfa417c15 | |||
| 4770e053ee | |||
| 138f08ddd7 | |||
| 950c0bfb8f | |||
| 724967b8b8 | |||
| 1c6f8ed07b | |||
| 58eb047433 | |||
| 045aa4fa3a | |||
| 69ee754c19 | |||
| 9d50424edc | |||
| 302664404b | |||
| 619f029a5a | |||
| 31e147495c | |||
| ad095d73f3 | |||
| 8b5cd50576 | |||
| 8227ab2f20 | |||
| 6457ffa6f9 | |||
| 8d69858413 | |||
| 49e8ebed60 | |||
| bb5a5ec6ef | |||
| cf602ab5be | |||
| d7ade821f4 | |||
| 7f42d198eb | |||
| ebc3e78ba9 | |||
| 00cae60fe1 | |||
| 67e0840695 | |||
| bc2dbcb416 | |||
| dc4f3cb7ba | |||
| 121462c00f | |||
| 5b283285a2 | |||
| 4e65cf95d1 | |||
| 2b408230a6 | |||
| 48ad0844ae | |||
| 2ef8b8a705 | |||
| 33e7f99fdc | |||
| 06ee422e34 | |||
| 30d6743310 | |||
| a97462dd69 | |||
| d56b841443 | |||
| 8296742cce | |||
| 0c82ae2b73 | |||
| f339fb1987 | |||
| 40809d11c5 | |||
| 50dbc52432 | |||
| cebcada950 | |||
| f5dd2ce4ab | |||
| 02b10f87cf | |||
| 5e64c64ce3 | |||
| a2fd1dfd62 | |||
| 623a622298 | |||
| 65e461eff7 |
30
.agents/rules/ponytail.md
Normal file
30
.agents/rules/ponytail.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# Ponytail, lazy senior dev mode
|
||||
|
||||
You are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written.
|
||||
|
||||
Before writing any code, stop at the first rung that holds:
|
||||
|
||||
1. Does this need to be built at all? (YAGNI)
|
||||
2. Does it already exist in this codebase? Reuse the helper, util, or pattern that's already here, don't re-write it.
|
||||
3. Does the standard library already do this? Use it.
|
||||
4. Does a native platform feature cover it? Use it.
|
||||
5. Does an already-installed dependency solve it? Use it.
|
||||
6. Can this be one line? Make it one line.
|
||||
7. Only then: write the minimum code that works.
|
||||
|
||||
The ladder runs after you understand the problem, not instead of it: read the task and the code it touches, trace the real flow end to end, then climb.
|
||||
|
||||
Bug fix = root cause, not symptom: a report names a symptom. Grep every caller of the function you touch and fix the shared function once — one guard there is a smaller diff than one per caller, and patching only the path the ticket names leaves a sibling caller still broken.
|
||||
|
||||
Rules:
|
||||
|
||||
- No abstractions that weren't explicitly requested.
|
||||
- No new dependency if it can be avoided.
|
||||
- No boilerplate nobody asked for.
|
||||
- Deletion over addition. Boring over clever. Fewest files possible.
|
||||
- Shortest working diff wins, but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug.
|
||||
- Question complex requests: "Do you actually need X, or does Y cover it?"
|
||||
- Pick the edge-case-correct option when two stdlib approaches are the same size, lazy means less code, not the flimsier algorithm.
|
||||
- Mark intentional simplifications with a `ponytail:` comment. If the shortcut has a known ceiling (global lock, O(n²) scan, naive heuristic), the comment names the ceiling and the upgrade path.
|
||||
|
||||
Not lazy about: understanding the problem (read it fully and trace the real flow before picking a rung, a small diff you don't understand is just laziness dressed up as efficiency), input validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs (the platform is never the spec ideal, a clock drifts, a sensor reads off), anything explicitly requested. Lazy code without its check is unfinished: non-trivial logic leaves ONE runnable check behind, the smallest thing that fails if the logic breaks (an assert-based demo/self-check or one small test file; no frameworks, no fixtures). Trivial one-liners need no test.
|
||||
49
.agents/skills/caveman/SKILL.md
Normal file
49
.agents/skills/caveman/SKILL.md
Normal file
@@ -0,0 +1,49 @@
|
||||
---
|
||||
name: caveman
|
||||
description: >
|
||||
Ultra-compressed communication mode. Cuts token usage ~75% by dropping
|
||||
filler, articles, and pleasantries while keeping full technical accuracy.
|
||||
Use when user says "caveman mode", "talk like caveman", "use caveman",
|
||||
"less tokens", "be brief", or invokes /caveman.
|
||||
---
|
||||
|
||||
Respond terse like smart caveman. All technical substance stay. Only fluff die.
|
||||
|
||||
## Persistence
|
||||
|
||||
ACTIVE EVERY RESPONSE once triggered. No revert after many turns. No filler drift. Still active if unsure. Off only when user says "stop caveman" or "normal mode".
|
||||
|
||||
## Rules
|
||||
|
||||
Drop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not "implement a solution for"). Abbreviate common terms (DB/auth/config/req/res/fn/impl). Strip conjunctions. Use arrows for causality (X -> Y). One word when one word enough.
|
||||
|
||||
Technical terms stay exact. Code blocks unchanged. Errors quoted exact.
|
||||
|
||||
Pattern: `[thing] [action] [reason]. [next step].`
|
||||
|
||||
Not: "Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by..."
|
||||
Yes: "Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:"
|
||||
|
||||
### Examples
|
||||
|
||||
**"Why React component re-render?"**
|
||||
|
||||
> Inline obj prop -> new ref -> re-render. `useMemo`.
|
||||
|
||||
**"Explain database connection pooling."**
|
||||
|
||||
> Pool = reuse DB conn. Skip handshake -> fast under load.
|
||||
|
||||
## Auto-Clarity Exception
|
||||
|
||||
Drop caveman temporarily for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question. Resume caveman after clear part done.
|
||||
|
||||
Example -- destructive op:
|
||||
|
||||
> **Warning:** This will permanently delete all rows in the `users` table and cannot be undone.
|
||||
>
|
||||
> ```sql
|
||||
> DROP TABLE users;
|
||||
> ```
|
||||
>
|
||||
> Caveman resume. Verify backup exist first.
|
||||
117
.agents/skills/diagnose/SKILL.md
Normal file
117
.agents/skills/diagnose/SKILL.md
Normal file
@@ -0,0 +1,117 @@
|
||||
---
|
||||
name: diagnose
|
||||
description: Disciplined diagnosis loop for hard bugs and performance regressions. Reproduce → minimise → hypothesise → instrument → fix → regression-test. Use when user says "diagnose this" / "debug this", reports a bug, says something is broken/throwing/failing, or describes a performance regression.
|
||||
---
|
||||
|
||||
# Diagnose
|
||||
|
||||
A discipline for hard bugs. Skip phases only when explicitly justified.
|
||||
|
||||
When exploring the codebase, use the project's domain glossary 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 fast, deterministic, agent-runnable pass/fail signal for the bug, you will find the cause — bisection, hypothesis-testing, and instrumentation all just consume that signal. 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.
|
||||
|
||||
### Iterate on the loop itself
|
||||
|
||||
Treat the loop as a product. Once you have _a_ loop, ask:
|
||||
|
||||
- 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 loop is 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.
|
||||
|
||||
Do not proceed to Phase 2 until you have a loop you believe in.
|
||||
|
||||
## Phase 2 — Reproduce
|
||||
|
||||
Run the loop. Watch the bug appear.
|
||||
|
||||
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.
|
||||
|
||||
Do not proceed until you reproduce the bug.
|
||||
|
||||
## Phase 3 — Hypothesise
|
||||
|
||||
Generate **3–5 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.
|
||||
41
.agents/skills/diagnose/scripts/hitl-loop.template.sh
Normal file
41
.agents/skills/diagnose/scripts/hitl-loop.template.sh
Normal 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"
|
||||
7
.agents/skills/grill-me/SKILL.md
Normal file
7
.agents/skills/grill-me/SKILL.md
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
name: grill-me
|
||||
description: A relentless interview to sharpen a plan or design.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
Run a `/grilling` session.
|
||||
7
.agents/skills/grill-with-docs/SKILL.md
Normal file
7
.agents/skills/grill-with-docs/SKILL.md
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
name: grill-with-docs
|
||||
description: A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
Run a `/grilling` session, using the `/domain-modeling` skill.
|
||||
16
.agents/skills/handoff/SKILL.md
Normal file
16
.agents/skills/handoff/SKILL.md
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: handoff
|
||||
description: Compact the current conversation into a handoff document for another agent to pick up.
|
||||
argument-hint: "What will the next session be used for?"
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
Write a handoff document summarising the current conversation so a fresh agent can continue the work. Save to the temporary directory of the user's OS - not the current workspace.
|
||||
|
||||
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.
|
||||
|
||||
Redact any sensitive information, such as API keys, passwords, or personally identifiable information.
|
||||
|
||||
If the user passed arguments, treat them as a description of what the next session will focus on and tailor the doc accordingly.
|
||||
123
.agents/skills/improve-codebase-architecture/HTML-REPORT.md
Normal file
123
.agents/skills/improve-codebase-architecture/HTML-REPORT.md
Normal file
@@ -0,0 +1,123 @@
|
||||
# HTML Report Format
|
||||
|
||||
The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two — don't lean on Mermaid for everything, it'll start to look generic.
|
||||
|
||||
## Scaffold
|
||||
|
||||
```html
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Architecture review — {{repo name}}</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script type="module">
|
||||
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
|
||||
mermaid.initialize({ startOnLoad: true, theme: "neutral", securityLevel: "loose" });
|
||||
</script>
|
||||
<style>
|
||||
/* small custom layer for things Tailwind doesn't cover cleanly:
|
||||
dashed seam lines, hand-drawn-feeling arrow heads, etc. */
|
||||
.seam { stroke-dasharray: 4 4; }
|
||||
.leak { stroke: #dc2626; }
|
||||
.deep { background: linear-gradient(135deg, #0f172a, #1e293b); }
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-stone-50 text-slate-900 font-sans">
|
||||
<main class="max-w-5xl mx-auto px-6 py-12 space-y-12">
|
||||
<header>...</header>
|
||||
<section id="candidates" class="space-y-10">...</section>
|
||||
<section id="top-recommendation">...</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## Header
|
||||
|
||||
Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph — straight into the candidates.
|
||||
|
||||
## Candidate card
|
||||
|
||||
The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony.
|
||||
|
||||
Each candidate is one `<article>`:
|
||||
|
||||
- **Title** — short, names the deepening (e.g. "Collapse the Order intake pipeline").
|
||||
- **Badge row** — recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`).
|
||||
- **Files** — monospaced list, `font-mono text-sm`.
|
||||
- **Before / After diagram** — the centrepiece. Two columns, side by side. See patterns below.
|
||||
- **Problem** — one sentence. What hurts.
|
||||
- **Solution** — one sentence. What changes.
|
||||
- **Wins** — bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers".
|
||||
- **ADR callout** (if applicable) — one line in an amber-tinted box.
|
||||
|
||||
No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram.
|
||||
|
||||
## Diagram patterns
|
||||
|
||||
Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same — variety is part of the point.
|
||||
|
||||
### Mermaid graph (the workhorse for dependencies / call flow)
|
||||
|
||||
Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1."
|
||||
|
||||
```html
|
||||
<div class="rounded-lg border border-slate-200 bg-white p-4">
|
||||
<pre class="mermaid">
|
||||
flowchart LR
|
||||
A[OrderHandler] --> B[OrderValidator]
|
||||
B --> C[OrderRepo]
|
||||
C -.leak.-> D[PricingClient]
|
||||
classDef leak stroke:#dc2626,stroke-width:2px;
|
||||
class C,D leak
|
||||
</pre>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Hand-built boxes-and-arrows (when Mermaid's layout fights you)
|
||||
|
||||
Modules as `<div>`s with borders and labels. Arrows as inline SVG `<line>` or `<path>` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals — Mermaid won't render that with the right weight.
|
||||
|
||||
### Cross-section (good for layered shallowness)
|
||||
|
||||
Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility.
|
||||
|
||||
### Mass diagram (good for "interface as wide as implementation")
|
||||
|
||||
Two rectangles per module — one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep).
|
||||
|
||||
### Call-graph collapse
|
||||
|
||||
Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it.
|
||||
|
||||
## Style guidance
|
||||
|
||||
- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate).
|
||||
- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings.
|
||||
- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling.
|
||||
- Use `text-xs uppercase tracking-wider` for module labels inside diagrams — they should read as schematic, not as UI.
|
||||
- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static — no app code, no interactivity beyond Mermaid's own rendering.
|
||||
|
||||
## Top recommendation section
|
||||
|
||||
One larger card. Candidate name, one sentence on why, anchor link to its card. That's it.
|
||||
|
||||
## Tone
|
||||
|
||||
Plain English, concise — but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift.
|
||||
|
||||
**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality.
|
||||
|
||||
**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module).
|
||||
|
||||
**Phrasings that fit the style:**
|
||||
|
||||
- "Order intake module is shallow — interface nearly matches the implementation."
|
||||
- "Pricing leaks across the seam."
|
||||
- "Deepen: one interface, one place to test."
|
||||
- "Two adapters justify the seam: HTTP in prod, in-memory in tests."
|
||||
|
||||
**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"* — those terms aren't in the glossary and don't earn their place.
|
||||
|
||||
No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one.
|
||||
66
.agents/skills/improve-codebase-architecture/SKILL.md
Normal file
66
.agents/skills/improve-codebase-architecture/SKILL.md
Normal file
@@ -0,0 +1,66 @@
|
||||
---
|
||||
name: improve-codebase-architecture
|
||||
description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Improve Codebase Architecture
|
||||
|
||||
Surface architectural friction and propose **deepening opportunities** — refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
|
||||
|
||||
This command is _informed_ by the project's domain model and built on a shared design vocabulary:
|
||||
|
||||
- Run the `/codebase-design` skill for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion — don't drift into "component," "service," "API," or "boundary."
|
||||
- The domain language in `CONTEXT.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate.
|
||||
|
||||
## Process
|
||||
|
||||
### 1. Explore
|
||||
|
||||
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:
|
||||
|
||||
- Where does understanding one concept require bouncing between many small modules?
|
||||
- Where are modules **shallow** — interface nearly as complex as the implementation?
|
||||
- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)?
|
||||
- Where do tightly-coupled modules leak across their seams?
|
||||
- Which parts of the codebase are untested, or hard to test through their current interface?
|
||||
|
||||
Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want.
|
||||
|
||||
### 2. Present candidates as an HTML report
|
||||
|
||||
Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `<tmpdir>/architecture-review-<timestamp>.html` so each run gets a fresh file. Open it for the user — `xdg-open <path>` on Linux, `open <path>` on macOS, `start <path>` on Windows — and tell them the absolute path.
|
||||
|
||||
The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals — use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual.
|
||||
|
||||
For each candidate, render a card with:
|
||||
|
||||
- **Files** — which files/modules are involved
|
||||
- **Problem** — why the current architecture is causing friction
|
||||
- **Solution** — plain English description of what would change
|
||||
- **Benefits** — explained in terms of locality and leverage, and how tests would improve
|
||||
- **Before / After diagram** — side-by-side, custom-drawn, illustrating the shallowness and the deepening
|
||||
- **Recommendation strength** — one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge
|
||||
|
||||
End the report with a **Top recommendation** section: which candidate you'd tackle first and why.
|
||||
|
||||
**Use CONTEXT.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module" — not "the FooBarHandler," and not "the Order service."
|
||||
|
||||
**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007 — but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids.
|
||||
|
||||
See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance.
|
||||
|
||||
Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?"
|
||||
|
||||
### 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.
|
||||
|
||||
Side effects happen inline as decisions crystallize — run the `/domain-modeling` skill to keep the domain model current as you go:
|
||||
|
||||
- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md`. Create the file lazily if it doesn't exist.
|
||||
- **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there.
|
||||
- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing — skip ephemeral reasons ("not worth it right now") and self-evident ones.
|
||||
- **Want to explore alternative interfaces for the deepened module?** Run the `/codebase-design` skill and use its design-it-twice parallel sub-agent pattern.
|
||||
79
.agents/skills/prototype/LOGIC.md
Normal file
79
.agents/skills/prototype/LOGIC.md
Normal file
@@ -0,0 +1,79 @@
|
||||
# Logic Prototype
|
||||
|
||||
A tiny interactive terminal app that lets the user drive a state model by hand. Use this when the question is about **business logic, state transitions, or data shape** — the kind of thing that looks reasonable on paper but only feels wrong once you push it through real cases.
|
||||
|
||||
## When this is the right shape
|
||||
|
||||
- "I'm not sure if this state machine handles the edge case where X then Y."
|
||||
- "Does this data model actually let me represent the case where..."
|
||||
- "I want to feel out what the API should look like before writing it."
|
||||
- Anything where the user wants to **press buttons and watch state change**.
|
||||
|
||||
If the question is "what should this look like" — wrong branch. Use [UI.md](UI.md).
|
||||
|
||||
## Process
|
||||
|
||||
### 1. State the question
|
||||
|
||||
Before writing code, write down what state model and what question you're prototyping. One paragraph, in the prototype's README or a comment at the top of the file. A logic prototype that answers the wrong question is pure waste — make the question explicit so it can be checked later, whether the user is watching now or returning to it AFK.
|
||||
|
||||
### 2. Pick the language
|
||||
|
||||
Use whatever the host project uses. If the project has no obvious runtime (e.g. a docs repo), ask.
|
||||
|
||||
Match the project's existing conventions for tooling — don't add a new package manager or runtime just for the prototype.
|
||||
|
||||
### 3. Isolate the logic in a portable module
|
||||
|
||||
Put the actual logic — the bit that's answering the question — behind a small, pure interface that could be lifted out and dropped into the real codebase later. The TUI around it is throwaway; the logic module shouldn't be.
|
||||
|
||||
The right shape depends on the question:
|
||||
|
||||
- **A pure reducer** — `(state, action) => state`. Good when actions are discrete events and state is a single value.
|
||||
- **A state machine** — explicit states and transitions. Good when "which actions are even legal right now" is part of the question.
|
||||
- **A small set of pure functions** over a plain data type. Good when there's no implicit current state — just transformations.
|
||||
- **A class or module with a clear method surface** when the logic genuinely owns ongoing internal state.
|
||||
|
||||
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.
|
||||
|
||||
### 4. Build the smallest TUI that exposes the state
|
||||
|
||||
Build it as a **lightweight TUI** — on every tick, clear the screen (`console.clear()` / `print("\033[2J\033[H")` / equivalent) and re-render the whole frame. The user should always see one stable view, not an ever-growing scrollback.
|
||||
|
||||
Each frame has two parts, in this order:
|
||||
|
||||
1. **Current state**, pretty-printed and diff-friendly (one field per line, or formatted JSON). Use **bold** for field names or section headers and **dim** for less important context (timestamps, IDs, derived values). Native ANSI escape codes are fine — `\x1b[1m` bold, `\x1b[2m` dim, `\x1b[0m` reset. No need to pull in a styling library unless one is already in the project.
|
||||
2. **Keyboard shortcuts**, listed at the bottom: `[a] add user [d] delete user [t] tick clock [q] quit`. Bold the key, dim the description, or vice-versa — whatever reads cleanly.
|
||||
|
||||
Behaviour:
|
||||
|
||||
1. **Initialise state** — a single in-memory object/struct. Render the first frame on start.
|
||||
2. **Read one keystroke (or one line)** at a time, dispatch to a handler that mutates state.
|
||||
3. **Re-render** the full frame after every action — don't append, replace.
|
||||
4. **Loop until quit.**
|
||||
|
||||
The whole frame should fit on one screen.
|
||||
|
||||
### 5. Make it runnable in one command
|
||||
|
||||
Add a script to the project's existing task runner (`package.json` scripts, `Makefile`, `justfile`, `pyproject.toml`). The user should run `pnpm run <prototype-name>` or equivalent — never need to remember a path.
|
||||
|
||||
If the host project has no task runner, just put the command at the top of the prototype's README.
|
||||
|
||||
### 6. Hand it over
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- **Don't add tests.** A prototype that needs tests is no longer a prototype.
|
||||
- **Don't wire it to the real database.** Use an in-memory store unless the question is specifically about persistence.
|
||||
- **Don't generalise.** No "what if we wanted to support X later." The prototype answers one question.
|
||||
- **Don't blur the logic and the TUI together.** If the reducer / state machine references `console.log`, prompts, or terminal escape codes, it's no longer portable. Keep the TUI as a thin shell over a pure module.
|
||||
- **Don't ship the TUI shell into production.** The shell is optimised for being driven by hand from a terminal. The logic module behind it is the bit worth keeping.
|
||||
30
.agents/skills/prototype/SKILL.md
Normal file
30
.agents/skills/prototype/SKILL.md
Normal file
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: prototype
|
||||
description: Build a throwaway prototype to answer a design question. Use when the user wants to sanity-check whether a state model or logic feels right, or explore what a UI should look like.
|
||||
---
|
||||
|
||||
# Prototype
|
||||
|
||||
A prototype is **throwaway code that answers a question**. The question decides the shape.
|
||||
|
||||
## Pick a branch
|
||||
|
||||
Identify which question is being answered — from the user's prompt, the surrounding code, or by asking if the user is around:
|
||||
|
||||
- **"Does this logic / state model feel right?"** → [LOGIC.md](LOGIC.md). Build a tiny interactive terminal app that pushes the state machine through cases that are hard to reason about on paper.
|
||||
- **"What should this look like?"** → [UI.md](UI.md). Generate several radically different UI variations on a single route, switchable via a URL search param and a floating bottom bar.
|
||||
|
||||
The two branches produce very different artifacts — getting this wrong wastes the whole prototype. If the question is genuinely ambiguous and the user isn't reachable, default to whichever branch better matches the surrounding code (a backend module → logic; a page or component → UI) and state the assumption at the top of the prototype.
|
||||
|
||||
## Rules that apply to both
|
||||
|
||||
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.
|
||||
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.
|
||||
112
.agents/skills/prototype/UI.md
Normal file
112
.agents/skills/prototype/UI.md
Normal file
@@ -0,0 +1,112 @@
|
||||
# UI Prototype
|
||||
|
||||
Generate **several radically different UI variations** on a single route, switchable from a floating bottom bar. The user flips between variants in the browser, picks one (or steals bits from each), then throws the rest away.
|
||||
|
||||
If the question is about logic/state rather than what something looks like — wrong branch. Use [LOGIC.md](LOGIC.md).
|
||||
|
||||
## When this is the right shape
|
||||
|
||||
- "What should this page look like?"
|
||||
- "I want to see a few options for this dashboard before committing."
|
||||
- "Try a different layout for the settings screen."
|
||||
- Any time the user would otherwise spend a day picking between three vague mockups in their head.
|
||||
|
||||
## Two sub-shapes — strongly prefer sub-shape A
|
||||
|
||||
A UI prototype is much easier to judge when it's **butting up against the rest of the app** — real header, real sidebar, real data, real density. A throwaway route on its own is a vacuum: every variant looks fine in isolation. Default to sub-shape A whenever there's a plausible existing page to host the variants. Only reach for sub-shape B if the prototype genuinely has no nearby home.
|
||||
|
||||
### Sub-shape A — adjustment to an existing page (preferred)
|
||||
|
||||
The route already exists. Variants are rendered **on the same route**, gated by a `?variant=` URL search param. The existing data fetching, params, and auth all stay — only the rendering swaps. This is the default; pick it unless there's a specific reason not to.
|
||||
|
||||
If the prototype is for something that doesn't yet have a page but *would naturally live inside one* (a new section of the dashboard, a new card on the settings screen, a new step in an existing flow) — that's still sub-shape A. Mount the variants inside the host page.
|
||||
|
||||
### Sub-shape B — a new page (last resort)
|
||||
|
||||
Only use this when the thing being prototyped genuinely has no existing page to live inside — e.g. an entirely new top-level surface, or a flow that can't be embedded anywhere sensible.
|
||||
|
||||
Create a **throwaway route** following whatever routing convention the project already uses — don't invent a new top-level structure. Name it so it's obviously a prototype (e.g. include the word `prototype` in the path or filename). Same `?variant=` pattern.
|
||||
|
||||
Before committing to sub-shape B, sanity-check: is there really no existing page this could be embedded in? An empty route hides design problems that a populated one would expose.
|
||||
|
||||
In both sub-shapes the floating bottom bar is identical.
|
||||
|
||||
## Process
|
||||
|
||||
### 1. State the question and pick N
|
||||
|
||||
Default to **3 variants**. More than 5 stops being radically different and starts being noise — cap there.
|
||||
|
||||
Write down the plan in one line, in the prototype's location or a top-of-file comment:
|
||||
|
||||
> "Three variants of the settings page, switchable via `?variant=`, on the existing `/settings` route."
|
||||
|
||||
This works whether the user is here to push back or not.
|
||||
|
||||
### 2. Generate radically different variants
|
||||
|
||||
Draft each variant. Hold each one to:
|
||||
|
||||
- The page's purpose and the data it has access to.
|
||||
- The project's component library / styling system (TailwindCSS, shadcn, MUI, plain CSS, whatever).
|
||||
- A clear exported component name, e.g. `VariantA`, `VariantB`, `VariantC`.
|
||||
|
||||
Variants must be **structurally different** — different layout, different information hierarchy, different primary affordance, not just different colours. Three slightly-tweaked card grids isn't a UI prototype, it's wallpaper. If two drafts come out too similar, redo one with explicit "do not use a card grid" guidance.
|
||||
|
||||
### 3. Wire them together
|
||||
|
||||
Create a single switcher component on the route:
|
||||
|
||||
```tsx
|
||||
// pseudo-code — adapt to the project's framework
|
||||
const variant = searchParams.get('variant') ?? 'A';
|
||||
return (
|
||||
<>
|
||||
{variant === 'A' && <VariantA {...data} />}
|
||||
{variant === 'B' && <VariantB {...data} />}
|
||||
{variant === 'C' && <VariantC {...data} />}
|
||||
<PrototypeSwitcher variants={['A','B','C']} current={variant} />
|
||||
</>
|
||||
);
|
||||
```
|
||||
|
||||
For sub-shape A (existing page): keep all the existing data fetching above the switcher; only the rendered subtree changes per variant.
|
||||
|
||||
For sub-shape B (new page): the throwaway route under `/prototype/<name>` mounts the same switcher.
|
||||
|
||||
### 4. Build the floating switcher
|
||||
|
||||
A small fixed-position bar at the bottom-centre of the screen with three pieces:
|
||||
|
||||
- **Left arrow** — cycles to the previous variant (wraps around).
|
||||
- **Variant label** — shows the current variant key and, if the variant exports a name, that name too. e.g. `B — Sidebar layout`.
|
||||
- **Right arrow** — cycles forward (wraps around).
|
||||
|
||||
Behaviour:
|
||||
|
||||
- Clicking an arrow updates the URL search param (use the framework's router — `router.replace` on Next, `navigate` on React Router, etc) so the variant is shareable and reload-stable.
|
||||
- Keyboard: `←` and `→` arrow keys also cycle. Don't intercept arrow keys when an `<input>`, `<textarea>`, or `[contenteditable]` is focused.
|
||||
- Visually distinct from the page (e.g. high-contrast pill, subtle shadow) so it's obviously not part of the design being evaluated.
|
||||
- Hidden in production builds — gate on `process.env.NODE_ENV !== 'production'` or an equivalent check, so a stray prototype merge can't ship the bar to users.
|
||||
|
||||
Put the switcher in a single shared component so both sub-shapes can reuse it. Locate it wherever shared UI lives in the project.
|
||||
|
||||
### 5. Hand it over
|
||||
|
||||
Surface the URL (and the `?variant=` keys). The user will flip through whenever they get to it. The interesting feedback is usually **"I want the header from B with the sidebar from C"** — that's the actual design they want.
|
||||
|
||||
### 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:
|
||||
|
||||
- **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.
|
||||
|
||||
Don't leave variant components or the switcher lying around. They rot fast and confuse the next reader.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- **Variants that differ only in colour or copy.** That's a tweak, not a prototype. Real variants disagree about structure.
|
||||
- **Sharing too much code between variants.** A shared `<Header>` is fine; a shared `<Layout>` defeats the point. Each variant should be free to throw out the layout.
|
||||
- **Wiring variants to real mutations.** Read-only prototypes are fine. If a variant needs to mutate, point it at a stub — the question is "what should this look like", not "does the backend work".
|
||||
- **Promoting the prototype directly to production.** The variant code was written under prototype constraints (no tests, minimal error handling). Rewrite it properly when you fold it in.
|
||||
127
.agents/skills/setup-matt-pocock-skills/SKILL.md
Normal file
127
.agents/skills/setup-matt-pocock-skills/SKILL.md
Normal file
@@ -0,0 +1,127 @@
|
||||
---
|
||||
name: setup-matt-pocock-skills
|
||||
description: Configure this repo for the engineering skills — set up its issue tracker, triage label vocabulary, and domain doc layout. Run once before first use of the other engineering skills.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Setup Matt Pocock's Skills
|
||||
|
||||
Scaffold the per-repo configuration that the engineering skills assume:
|
||||
|
||||
- **Issue tracker** — where issues live (GitHub by default; local markdown is also supported out of the box)
|
||||
- **Triage labels** — the strings used for the five canonical triage roles
|
||||
- **Domain docs** — where `CONTEXT.md` and ADRs live, and the consumer rules for reading them
|
||||
|
||||
This is a prompt-driven skill, not a deterministic script. Explore, present what you found, confirm with the user, then write.
|
||||
|
||||
## Process
|
||||
|
||||
### 1. Explore
|
||||
|
||||
Look at the current repo to understand its starting state. Read whatever exists; don't assume:
|
||||
|
||||
- `git remote -v` and `.git/config` — is this a GitHub repo? Which one?
|
||||
- `AGENTS.md` and `CLAUDE.md` at the repo root — does either exist? Is there already an `## Agent skills` section in either?
|
||||
- `CONTEXT.md` and `CONTEXT-MAP.md` at the repo root
|
||||
- `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
|
||||
|
||||
### 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.
|
||||
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
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:
|
||||
|
||||
- **GitHub** — issues live in the repo's GitHub Issues (uses the `gh` CLI)
|
||||
- **GitLab** — issues live in the repo's GitLab Issues (uses the [`glab`](https://gitlab.com/gitlab-org/cli) CLI)
|
||||
- **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:
|
||||
|
||||
> 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.
|
||||
|
||||
- **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.
|
||||
|
||||
**Section B — Triage label vocabulary.**
|
||||
|
||||
> 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 five canonical roles:
|
||||
|
||||
- `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).
|
||||
|
||||
### 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`
|
||||
|
||||
Let them edit before writing.
|
||||
|
||||
### 4. Write
|
||||
|
||||
**Pick the file to edit:**
|
||||
|
||||
- If `CLAUDE.md` exists, edit it.
|
||||
- Else if `AGENTS.md` exists, edit it.
|
||||
- If neither exists, ask the user which one to create — don't pick for them.
|
||||
|
||||
Never create `AGENTS.md` when `CLAUDE.md` already exists (or vice versa) — always edit the one that's already there.
|
||||
|
||||
If an `## Agent skills` block already exists in the chosen file, update its contents in-place rather than appending a duplicate. Don't overwrite user edits to the surrounding sections.
|
||||
|
||||
The block:
|
||||
|
||||
```markdown
|
||||
## Agent skills
|
||||
|
||||
### Issue tracker
|
||||
|
||||
[one-line summary of where issues are tracked, plus whether external PRs are a triage surface]. See `docs/agents/issue-tracker.md`.
|
||||
|
||||
### Triage labels
|
||||
|
||||
[one-line summary of the label vocabulary]. See `docs/agents/triage-labels.md`.
|
||||
|
||||
### Domain docs
|
||||
|
||||
[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:
|
||||
|
||||
- [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
|
||||
- [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.
|
||||
|
||||
### 5. Done
|
||||
|
||||
Tell the user the setup is complete and which engineering skills will now read from these files. Mention they can edit `docs/agents/*.md` directly later — re-running this skill is only necessary if they want to switch issue trackers or restart from scratch.
|
||||
51
.agents/skills/setup-matt-pocock-skills/domain.md
Normal file
51
.agents/skills/setup-matt-pocock-skills/domain.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Domain Docs
|
||||
|
||||
How the engineering skills should consume this repo's domain documentation when exploring the codebase.
|
||||
|
||||
## Before exploring, read these
|
||||
|
||||
- **`CONTEXT.md`** at the repo root, or
|
||||
- **`CONTEXT-MAP.md`** at the repo root if it exists — it points at one `CONTEXT.md` per context. Read each one relevant to the topic.
|
||||
- **`docs/adr/`** — read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.
|
||||
|
||||
If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.
|
||||
|
||||
## File structure
|
||||
|
||||
Single-context repo (most repos):
|
||||
|
||||
```
|
||||
/
|
||||
├── CONTEXT.md
|
||||
├── docs/adr/
|
||||
│ ├── 0001-event-sourced-orders.md
|
||||
│ └── 0002-postgres-for-write-model.md
|
||||
└── src/
|
||||
```
|
||||
|
||||
Multi-context repo (presence of `CONTEXT-MAP.md` at the root):
|
||||
|
||||
```
|
||||
/
|
||||
├── CONTEXT-MAP.md
|
||||
├── docs/adr/ ← system-wide decisions
|
||||
└── src/
|
||||
├── ordering/
|
||||
│ ├── CONTEXT.md
|
||||
│ └── docs/adr/ ← context-specific decisions
|
||||
└── billing/
|
||||
├── CONTEXT.md
|
||||
└── docs/adr/
|
||||
```
|
||||
|
||||
## Use the glossary's vocabulary
|
||||
|
||||
When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `CONTEXT.md`. Don't drift to synonyms the glossary explicitly avoids.
|
||||
|
||||
If the concept you need isn't in the glossary yet, that's a signal — either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).
|
||||
|
||||
## Flag ADR conflicts
|
||||
|
||||
If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:
|
||||
|
||||
> _Contradicts ADR-0007 (event-sourced orders) — but worth reopening because…_
|
||||
@@ -0,0 +1,34 @@
|
||||
# Issue tracker: GitHub
|
||||
|
||||
Issues and PRDs for this repo live as GitHub issues. Use the `gh` CLI for all operations.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies.
|
||||
- **Read an issue**: `gh issue view <number> --comments`, filtering comments by `jq` and also fetching labels.
|
||||
- **List issues**: `gh issue list --state open --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'` with appropriate `--label` and `--state` filters.
|
||||
- **Comment on an issue**: `gh issue comment <number> --body "..."`
|
||||
- **Apply / remove labels**: `gh issue edit <number> --add-label "..."` / `--remove-label "..."`
|
||||
- **Close**: `gh issue close <number> --comment "..."`
|
||||
|
||||
Infer the repo from `git remote -v` — `gh` does this automatically when run inside a clone.
|
||||
|
||||
## Pull requests as a triage surface
|
||||
|
||||
**PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_
|
||||
|
||||
When set to `yes`, PRs run through the same labels and states as issues, using the `gh pr` equivalents:
|
||||
|
||||
- **Read a PR**: `gh pr view <number> --comments` and `gh pr diff <number>` for the diff.
|
||||
- **List external PRs for triage**: `gh pr list --state open --json number,title,body,labels,author,authorAssociation,comments` then keep only `authorAssociation` of `CONTRIBUTOR`, `FIRST_TIME_CONTRIBUTOR`, or `NONE` (drop `OWNER`/`MEMBER`/`COLLABORATOR`).
|
||||
- **Comment / label / close**: `gh pr comment`, `gh pr edit --add-label`/`--remove-label`, `gh pr close`.
|
||||
|
||||
GitHub shares one number space across issues and PRs, so a bare `#42` may be either — resolve with `gh pr view 42` and fall back to `gh issue view 42`.
|
||||
|
||||
## When a skill says "publish to the issue tracker"
|
||||
|
||||
Create a GitHub issue.
|
||||
|
||||
## When a skill says "fetch the relevant ticket"
|
||||
|
||||
Run `gh issue view <number> --comments`.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Issue tracker: GitLab
|
||||
|
||||
Issues and PRDs for this repo live as GitLab issues. Use the [`glab`](https://gitlab.com/gitlab-org/cli) CLI for all operations.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Create an issue**: `glab issue create --title "..." --description "..."`. Use a heredoc for multi-line descriptions. Pass `--description -` to open an editor.
|
||||
- **Read an issue**: `glab issue view <number> --comments`. Use `-F json` for machine-readable output.
|
||||
- **List issues**: `glab issue list -F json` with appropriate `--label` filters.
|
||||
- **Comment on an issue**: `glab issue note <number> --message "..."`. GitLab calls comments "notes".
|
||||
- **Apply / remove labels**: `glab issue update <number> --label "..."` / `--unlabel "..."`. Multiple labels can be comma-separated or by repeating the flag.
|
||||
- **Close**: `glab issue close <number>`. `glab issue close` does not accept a closing comment, so post the explanation first with `glab issue note <number> --message "..."`, then close.
|
||||
- **Merge requests**: GitLab calls PRs "merge requests". Use `glab mr create`, `glab mr view`, `glab mr note`, etc. — the same shape as `gh pr ...` with `mr` in place of `pr` and `note`/`--message` in place of `comment`/`--body`.
|
||||
|
||||
Infer the repo from `git remote -v` — `glab` does this automatically when run inside a clone.
|
||||
|
||||
## Merge requests as a triage surface
|
||||
|
||||
**MRs as a request surface: no.** _(Set to `yes` if this repo treats external merge requests as feature requests; `/triage` reads this flag.)_
|
||||
|
||||
When set to `yes`, MRs run through the same labels and states as issues, using the `glab mr` equivalents:
|
||||
|
||||
- **Read an MR**: `glab mr view <number> --comments` and `glab mr diff <number>` for the diff.
|
||||
- **List external MRs for triage**: `glab mr list -F json`, then keep only MRs whose author is not a project member/owner (a contributor's MR, not a maintainer's in-flight work).
|
||||
- **Comment / label / close**: `glab mr note`, `glab mr update --label`/`--unlabel`, `glab mr close`.
|
||||
|
||||
Unlike GitHub, GitLab numbers issues and MRs separately, so `#42` is unambiguous once you know which surface the maintainer means.
|
||||
|
||||
## When a skill says "publish to the issue tracker"
|
||||
|
||||
Create a GitLab issue.
|
||||
|
||||
## When a skill says "fetch the relevant ticket"
|
||||
|
||||
Run `glab issue view <number> --comments`.
|
||||
@@ -0,0 +1,19 @@
|
||||
# Issue tracker: Local Markdown
|
||||
|
||||
Issues and PRDs 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`
|
||||
- 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
|
||||
|
||||
## When a skill says "publish to the issue tracker"
|
||||
|
||||
Create a new file under `.scratch/<feature-slug>/` (creating the directory if needed).
|
||||
|
||||
## 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.
|
||||
15
.agents/skills/setup-matt-pocock-skills/triage-labels.md
Normal file
15
.agents/skills/setup-matt-pocock-skills/triage-labels.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Triage Labels
|
||||
|
||||
The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.
|
||||
|
||||
| Label in mattpocock/skills | Label in our tracker | Meaning |
|
||||
| -------------------------- | -------------------- | ---------------------------------------- |
|
||||
| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
|
||||
| `needs-info` | `needs-info` | Waiting on reporter for more information |
|
||||
| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
|
||||
| `ready-for-human` | `ready-for-human` | Requires human implementation |
|
||||
| `wontfix` | `wontfix` | Will not be actioned |
|
||||
|
||||
When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.
|
||||
|
||||
Edit the right-hand column to match whatever vocabulary you actually use.
|
||||
111
.agents/skills/tdd/SKILL.md
Normal file
111
.agents/skills/tdd/SKILL.md
Normal file
@@ -0,0 +1,111 @@
|
||||
---
|
||||
name: tdd
|
||||
description: Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
|
||||
---
|
||||
|
||||
# Test-Driven Development
|
||||
|
||||
## Philosophy
|
||||
|
||||
**Core principle**: Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.
|
||||
|
||||
## Anti-Pattern: Horizontal Slices
|
||||
|
||||
**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."
|
||||
|
||||
This produces **crap tests**:
|
||||
|
||||
- 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
|
||||
|
||||
**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.
|
||||
|
||||
```
|
||||
WRONG (horizontal):
|
||||
RED: test1, test2, test3, test4, test5
|
||||
GREEN: impl1, impl2, impl3, impl4, impl5
|
||||
|
||||
RIGHT (vertical):
|
||||
RED→GREEN: test1→impl1
|
||||
RED→GREEN: test2→impl2
|
||||
RED→GREEN: test3→impl3
|
||||
...
|
||||
```
|
||||
|
||||
## 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
|
||||
```
|
||||
59
.agents/skills/tdd/mocking.md
Normal file
59
.agents/skills/tdd/mocking.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# When to Mock
|
||||
|
||||
Mock at **system boundaries** only:
|
||||
|
||||
- External APIs (payment, email, etc.)
|
||||
- Databases (sometimes - prefer test DB)
|
||||
- Time/randomness
|
||||
- File system (sometimes)
|
||||
|
||||
Don't mock:
|
||||
|
||||
- Your own classes/modules
|
||||
- Internal collaborators
|
||||
- Anything you control
|
||||
|
||||
## Designing for Mockability
|
||||
|
||||
At system boundaries, design interfaces that are easy to mock:
|
||||
|
||||
**1. Use dependency injection**
|
||||
|
||||
Pass external dependencies in rather than creating them internally:
|
||||
|
||||
```typescript
|
||||
// Easy to mock
|
||||
function processPayment(order, paymentClient) {
|
||||
return paymentClient.charge(order.total);
|
||||
}
|
||||
|
||||
// Hard to mock
|
||||
function processPayment(order) {
|
||||
const client = new StripeClient(process.env.STRIPE_KEY);
|
||||
return client.charge(order.total);
|
||||
}
|
||||
```
|
||||
|
||||
**2. Prefer SDK-style interfaces over generic fetchers**
|
||||
|
||||
Create specific functions for each external operation instead of one generic function with conditional logic:
|
||||
|
||||
```typescript
|
||||
// GOOD: Each function is independently mockable
|
||||
const api = {
|
||||
getUser: (id) => fetch(`/users/${id}`),
|
||||
getOrders: (userId) => fetch(`/users/${userId}/orders`),
|
||||
createOrder: (data) => fetch('/orders', { method: 'POST', body: data }),
|
||||
};
|
||||
|
||||
// BAD: Mocking requires conditional logic inside the mock
|
||||
const api = {
|
||||
fetch: (endpoint, options) => fetch(endpoint, options),
|
||||
};
|
||||
```
|
||||
|
||||
The SDK approach means:
|
||||
- Each mock returns one specific shape
|
||||
- No conditional logic in test setup
|
||||
- Easier to see which endpoints a test exercises
|
||||
- Type safety per endpoint
|
||||
10
.agents/skills/tdd/refactoring.md
Normal file
10
.agents/skills/tdd/refactoring.md
Normal file
@@ -0,0 +1,10 @@
|
||||
# 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
|
||||
77
.agents/skills/tdd/tests.md
Normal file
77
.agents/skills/tdd/tests.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# Good and Bad Tests
|
||||
|
||||
## Good Tests
|
||||
|
||||
**Integration-style**: Test through real interfaces, not mocks of internal parts.
|
||||
|
||||
```typescript
|
||||
// GOOD: Tests observable behavior
|
||||
test("user can checkout with valid cart", async () => {
|
||||
const cart = createCart();
|
||||
cart.add(product);
|
||||
const result = await checkout(cart, paymentMethod);
|
||||
expect(result.status).toBe("confirmed");
|
||||
});
|
||||
```
|
||||
|
||||
Characteristics:
|
||||
|
||||
- Tests behavior users/callers care about
|
||||
- Uses public API only
|
||||
- Survives internal refactors
|
||||
- Describes WHAT, not HOW
|
||||
- One logical assertion per test
|
||||
|
||||
## Bad Tests
|
||||
|
||||
**Implementation-detail tests**: Coupled to internal structure.
|
||||
|
||||
```typescript
|
||||
// BAD: Tests implementation details
|
||||
test("checkout calls paymentService.process", async () => {
|
||||
const mockPayment = jest.mock(paymentService);
|
||||
await checkout(cart, payment);
|
||||
expect(mockPayment.process).toHaveBeenCalledWith(cart.total);
|
||||
});
|
||||
```
|
||||
|
||||
Red flags:
|
||||
|
||||
- Mocking internal collaborators
|
||||
- Testing private methods
|
||||
- Asserting on call counts/order
|
||||
- Test breaks when refactoring without behavior change
|
||||
- Test name describes HOW not WHAT
|
||||
- Verifying through external means instead of interface
|
||||
|
||||
```typescript
|
||||
// BAD: Bypasses interface to verify
|
||||
test("createUser saves to database", async () => {
|
||||
await createUser({ name: "Alice" });
|
||||
const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]);
|
||||
expect(row).toBeDefined();
|
||||
});
|
||||
|
||||
// GOOD: Verifies through interface
|
||||
test("createUser makes user retrievable", async () => {
|
||||
const user = await createUser({ name: "Alice" });
|
||||
const retrieved = await getUser(user.id);
|
||||
expect(retrieved.name).toBe("Alice");
|
||||
});
|
||||
```
|
||||
|
||||
**Tautological tests**: Expected value restates the implementation, so the test passes by construction.
|
||||
|
||||
```typescript
|
||||
// BAD: Expected value is recomputed the way the code computes it
|
||||
test("calculateTotal sums line items", () => {
|
||||
const items = [{ price: 10 }, { price: 5 }];
|
||||
const expected = items.reduce((sum, i) => sum + i.price, 0);
|
||||
expect(calculateTotal(items)).toBe(expected);
|
||||
});
|
||||
|
||||
// GOOD: Expected value is an independent, known literal
|
||||
test("calculateTotal sums line items", () => {
|
||||
expect(calculateTotal([{ price: 10 }, { price: 5 }])).toBe(15);
|
||||
});
|
||||
```
|
||||
35
.agents/skills/teach/GLOSSARY-FORMAT.md
Normal file
35
.agents/skills/teach/GLOSSARY-FORMAT.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# GLOSSARY.md Format
|
||||
|
||||
`GLOSSARY.md` is the canonical language for this teaching workspace. All explainers, exercises, and learning records should adhere to its terminology. Building it is itself part of learning: compressing a concept into a tight definition is evidence the user understands it.
|
||||
|
||||
## Structure
|
||||
|
||||
```md
|
||||
# {Topic} Glossary
|
||||
|
||||
{One or two sentence description of the topic this glossary covers.}
|
||||
|
||||
## Terms
|
||||
|
||||
**Hypertrophy**:
|
||||
Muscle growth driven by mechanical tension and metabolic stress over repeated training sessions.
|
||||
_Avoid_: Bulking, getting big
|
||||
|
||||
**Progressive overload**:
|
||||
Systematically increasing the demand on a muscle over time — via load, volume, or intensity.
|
||||
_Avoid_: Pushing harder, levelling up
|
||||
|
||||
**RPE (Rate of Perceived Exertion)**:
|
||||
A 1–10 self-rating of how hard a set felt, where 10 is failure and 8 means two reps left in the tank.
|
||||
_Avoid_: Effort score, intensity rating
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
- **Add a term only when the user understands it.** The glossary is a record of compressed knowledge, not a dictionary the user reads to learn. If the user has just been introduced to a concept, wait until they can use it correctly before promoting it here.
|
||||
- **Be opinionated.** When several words exist for the same concept, pick the best one and list the rest as aliases to avoid. This is how language compresses.
|
||||
- **Keep definitions tight.** One or two sentences. Define what the term IS, not what it does or how to do it.
|
||||
- **Use the glossary's own terms inside definitions.** Once a term is in the glossary, prefer it everywhere — including inside other definitions. This is what makes complex terms easier to grasp later.
|
||||
- **Group under subheadings** when natural clusters emerge (e.g. `## Anatomy`, `## Programming`). A flat list is fine when terms cohere.
|
||||
- **Flag ambiguities explicitly.** If a term is used loosely in the wider field, note the resolution: "In this workspace, 'set' always means a working set — warm-ups are tracked separately."
|
||||
- **Revise as understanding deepens.** A definition the user wrote in week one may be wrong by week six. Update in place; do not leave stale entries.
|
||||
46
.agents/skills/teach/LEARNING-RECORD-FORMAT.md
Normal file
46
.agents/skills/teach/LEARNING-RECORD-FORMAT.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# Learning Record Format
|
||||
|
||||
Learning records live in `./learning-records/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc. Create the directory lazily — only when the first record is written.
|
||||
|
||||
They are the teaching equivalent of ADRs: they capture non-obvious lessons, key insights, and stated prior knowledge that will steer future sessions. They are used to calculate the zone of proximal development.
|
||||
|
||||
## Template
|
||||
|
||||
```md
|
||||
# {Short title of what was learned or established}
|
||||
|
||||
{1-3 sentences: what was learned (or what prior knowledge was established), and why it matters for future sessions.}
|
||||
```
|
||||
|
||||
That is the whole format. A learning record can be a single paragraph. The value is recording _that_ this is now known and _why_ it changes what to teach next — not in filling out sections.
|
||||
|
||||
## Optional sections
|
||||
|
||||
Only include these when they add genuine value. Most records won't need them.
|
||||
|
||||
- **Status** frontmatter (`active | superseded by LR-NNNN`) — useful when an earlier understanding turns out to be wrong and is replaced.
|
||||
- **Evidence** — how the user demonstrated the understanding (a question answered, an exercise completed, prior experience cited). Useful when the claim might be revisited.
|
||||
- **Implications** — what this unlocks or rules out for future sessions. Worth recording when non-obvious.
|
||||
|
||||
## Numbering
|
||||
|
||||
Scan `./learning-records/` for the highest existing number and increment by one.
|
||||
|
||||
## When to write a learning record
|
||||
|
||||
Write one when any of these is true:
|
||||
|
||||
1. **The user demonstrated genuine understanding of something non-trivial** — not just exposure, but evidence they can use the concept correctly. This sets a new floor for what to teach next.
|
||||
2. **The user disclosed prior knowledge** — "I already know X." Record it so future sessions don't re-teach it. Also record the _depth_ claimed.
|
||||
3. **A misconception was corrected** — the user previously believed something wrong and now sees why. These are high-value: they predict future stumbling blocks for related topics.
|
||||
4. **The mission shifted in response to learning** — the user discovered they cared about something different than they thought. Cross-link to [[MISSION.md]] and update it.
|
||||
|
||||
### What does _not_ qualify
|
||||
|
||||
- Material that was merely covered. Coverage is not learning. Wait for evidence.
|
||||
- Anything already captured tersely in [[GLOSSARY.md]] as a term definition. Don't duplicate.
|
||||
- Session-by-session activity logs. Learning records are not a journal — they are decision-grade insights.
|
||||
|
||||
## Supersession
|
||||
|
||||
When a later record contradicts an earlier one (the user's understanding deepened or corrected), mark the old record `Status: superseded by LR-NNNN` rather than deleting it. The history of how understanding evolved is itself useful signal.
|
||||
31
.agents/skills/teach/MISSION-FORMAT.md
Normal file
31
.agents/skills/teach/MISSION-FORMAT.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# MISSION.md Format
|
||||
|
||||
`MISSION.md` lives at the workspace root. It captures the _reason_ the user is learning this topic. Every teaching decision — what to teach next, which resources to surface, which exercises to design — should trace back to this document.
|
||||
|
||||
## Template
|
||||
|
||||
```md
|
||||
# Mission: {Topic}
|
||||
|
||||
## Why
|
||||
{1-3 sentences. The concrete real-world goal the user is chasing. What changes in their life or work when they have this skill? Avoid abstract framings like "to understand X" — push for the underlying outcome.}
|
||||
|
||||
## Success looks like
|
||||
- {A specific, observable thing the user will be able to do}
|
||||
- {Another specific thing}
|
||||
- {…}
|
||||
|
||||
## Constraints
|
||||
- {Time, budget, prior commitments, learning preferences, anything that bounds the approach}
|
||||
|
||||
## Out of scope
|
||||
- {Adjacent topics the user explicitly does not want to chase right now — protects the zone of proximal development}
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
- **One mission per workspace.** If the user wants to learn two unrelated things, that is two workspaces.
|
||||
- **Concrete over abstract.** "Run a half marathon by October" beats "get fitter." "Ship a Rust CLI to my team" beats "learn Rust."
|
||||
- **Push back on vagueness.** If the user cannot articulate why, interview them before writing anything. A bad mission is worse than no mission.
|
||||
- **Revise when reality shifts.** Missions change. When the user's goal moves, update this file — don't leave a stale mission steering future sessions.
|
||||
- **Keep it short.** If `MISSION.md` runs past a screen, it has stopped being a compass and started being a plan.
|
||||
32
.agents/skills/teach/RESOURCES-FORMAT.md
Normal file
32
.agents/skills/teach/RESOURCES-FORMAT.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# RESOURCES.md Format
|
||||
|
||||
`RESOURCES.md` is the curated set of trusted sources for this topic. Knowledge for explainers should be drawn from here, not from parametric guesses. Wisdom comes from the communities listed here.
|
||||
|
||||
## Structure
|
||||
|
||||
```md
|
||||
# {Topic} Resources
|
||||
|
||||
## Knowledge
|
||||
|
||||
- [Book: _The Science and Practice of Strength Training_ — Zatsiorsky & Kraemer](https://example.com)
|
||||
Foundational text on programming and adaptation. Use for: anything to do with periodisation, recovery, intensity zones.
|
||||
- [Article: "How Much Should I Train?" — Greg Nuckols (Stronger By Science)](https://example.com)
|
||||
Evidence-based review of volume landmarks. Use for: weekly set targets per muscle group.
|
||||
|
||||
## Wisdom (Communities)
|
||||
|
||||
- [r/weightroom](https://reddit.com/r/weightroom)
|
||||
High-signal subreddit, moderated against bro-science. Use for: programme critique, plateau troubleshooting.
|
||||
- Local: Tuesday strength class at {gym name}
|
||||
Use for: real-time coaching feedback on lifts.
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
- **High-trust only.** Prefer primary sources, recognised experts, peer-reviewed work, and communities with strong moderation. If a resource is marketing dressed as education, leave it out.
|
||||
- **Annotate every entry.** A bare link is useless in three months. Add one line: what it covers and when to reach for it.
|
||||
- **Group by Knowledge / Wisdom.** Mirrors the philosophy in [SKILL.md](./SKILL.md). It is fine for a resource to appear in only one group.
|
||||
- **Surface gaps explicitly.** If no good resource exists for an area the mission needs, write a `## Gaps` section listing what is missing. This drives future search.
|
||||
- **Prune ruthlessly.** A resource that turned out to be wrong, shallow, or off-mission should be removed, not buried. Better five sharp sources than thirty mediocre ones.
|
||||
- **Record community preferences.** If the user has opted out of joining communities, note it here so future sessions don't keep proposing them.
|
||||
140
.agents/skills/teach/SKILL.md
Normal file
140
.agents/skills/teach/SKILL.md
Normal file
@@ -0,0 +1,140 @@
|
||||
---
|
||||
name: teach
|
||||
description: Teach the user a new skill or concept, within this workspace.
|
||||
disable-model-invocation: true
|
||||
argument-hint: "What would you like to learn about?"
|
||||
---
|
||||
|
||||
The user has asked you to teach them something. This is a stateful request - they intend to learn the topic over multiple sessions.
|
||||
|
||||
## Teaching Workspace
|
||||
|
||||
Treat the current directory as a teaching workspace. The state of their learning is captured in this directory in several files:
|
||||
|
||||
- `MISSION.md`: A document capturing the _reason_ the user is interested in the topic. This should be used to ground all teaching. Use the format in [MISSION-FORMAT.md](./MISSION-FORMAT.md).
|
||||
- `./reference/*.html`: A directory of reference materials. These are the compressed learnings from the lessons - cheat sheets, reference algorithms, syntax, yoga poses, glossaries. They are the raw units of learning. They should be beautiful documents which print out well, and are designed for quick reference.
|
||||
- `RESOURCES.md`: A list of resources which can be explored to ground your teaching in contextual knowledge, or to acquire knowledge and wisdom. Use the format in [RESOURCES-FORMAT.md](./RESOURCES-FORMAT.md).
|
||||
- `./learning-records/*.md`: A directory of learning records, which capture what the user has learned. These are loosely equivalent to architectural decision records in software development - they capture non-obvious lessons and key insights that may need to be revised later, or drive future sessions. These should be used to calculate the zone of proximal development. They are titled `0001-<dash-case-name>.md`, where the number increments each time. Use the format in [LEARNING-RECORD-FORMAT.md](./LEARNING-RECORD-FORMAT.md).
|
||||
- `./lessons/*.html`: A directory of lessons. A **lesson** is a single, self-contained HTML output that teaches one tightly-scoped thing tied to the mission. This is the primary unit of teaching in this workspace.
|
||||
- `./assets/*`: Reusable **components** shared across lessons. See [Assets](#assets).
|
||||
- `NOTES.md`: A scratchpad for you to jot down user preferences, or working notes.
|
||||
|
||||
## Philosophy
|
||||
|
||||
To learn at a deep level, the user needs three things:
|
||||
|
||||
- **Knowledge**, captured from high-quality, high-trust resources
|
||||
- **Skills**, acquired through highly-relevant interactive lessons devised by you, based on the knowledge
|
||||
- **Wisdom**, which comes from interacting with other learners and practitioners
|
||||
|
||||
Before the `RESOURCES.md` is well-populated, your focus should be to find high-quality resources which will help the user acquire knowledge. Never trust your parametric knowledge.
|
||||
|
||||
Some topics may require more skills than knowledge. Learning more about theoretical physics might be more knowledge-based. For yoga, more skills-based.
|
||||
|
||||
### Fluency vs Storage Strength
|
||||
|
||||
You should be careful to split between two types of learning:
|
||||
|
||||
- **Fluency strength**: in-the-moment retrieval of knowledge
|
||||
- **Storage strength**: long-term retention of knowledge
|
||||
|
||||
Fluency can give the user an illusory sense of mastery, but storage strength is the real goal. Try to design lessons which build long-term retention by desirable difficulty:
|
||||
|
||||
- Using retrieval practice (recall from memory)
|
||||
- Spacing (distributing practice over time)
|
||||
- Interleaving (mixing up different but related topics in practice - for skills practice only)
|
||||
|
||||
## Lessons
|
||||
|
||||
A lesson is the main thing you produce — the unit in which knowledge and skills reach the user. Each lesson is one self-contained HTML file, saved to `./lessons/` and titled `0001-<dash-case-name>.html` where the number increments each time.
|
||||
|
||||
A lesson should be **beautiful** — clean, readable typography and layout — since the user will return to these later to review. Think Tufte.
|
||||
|
||||
The lesson should be short, and completable very quickly. Learners' working memory is very small, and we need to stay within it. But each lesson should give the user a single tangible win that they can build on. It should be directly tied to the mission, and should be in the user's zone of proximal development.
|
||||
|
||||
If possible, open the lesson file for the user by running a CLI command.
|
||||
|
||||
Each lesson should link via HTML anchors to other lessons and reference documents.
|
||||
|
||||
Each lesson should recommend a primary source for the user to read or watch. This should be the most high-quality, high-trust resource you found on the topic.
|
||||
|
||||
Each lesson should contain a reminder to ask followup questions to the agent. The agent is their teacher, and can assist with anything that's unclear.
|
||||
|
||||
## Assets
|
||||
|
||||
Lessons are built from reusable **components**, stored in `./assets/`: stylesheets, quiz widgets, simulators, diagram helpers — anything a second lesson could reuse.
|
||||
|
||||
Reuse is the default, not the exception. Before authoring a lesson, read `./assets/` and build from the components already there. When a lesson needs something new and reusable, write it as a component in `./assets/` and link to it — never inline code a future lesson would duplicate.
|
||||
|
||||
A shared stylesheet is the first component every workspace earns: every lesson links it, so the lessons look like one consistent course rather than a pile of one-offs. As the workspace grows, so should the component library.
|
||||
|
||||
## The Mission
|
||||
|
||||
Every lesson should be tied into the mission - the reason that the user is interested in learning about the topic.
|
||||
|
||||
If the user is unclear about the mission, or the `MISSION.md` is not populated, your first job should be to question the user on why they want to learn this.
|
||||
|
||||
Failing to understand the mission will mean knowledge acquisition is not grounded in real-world goals. Lessons will feel too abstract. You will have no way of judging what the user should do next.
|
||||
|
||||
Missions may change as the user develops more skills and knowledge. This is normal - make sure to update the `MISSION.md` and add a learning record to capture the change. Confirm with the user before changing the mission.
|
||||
|
||||
## Zone Of Proximal Development
|
||||
|
||||
Each lesson, the user should always feel as if they are being challenged 'just enough'.
|
||||
|
||||
The user may specify an exact thing they want to learn. If they don't, figure out their zone of proximal development by:
|
||||
|
||||
- Reading their `learning-records`
|
||||
- Figuring out the right thing to teach them based on their mission
|
||||
- Teach the most relevant thing that fits in their zone of proximal development
|
||||
|
||||
## Knowledge
|
||||
|
||||
Lessons should be designed around a skill the user is going to learn. The knowledge in the lesson should be only what's required to acquire that skill. You teach the knowledge first, then get the user to practice the skills via an interactive feedback loop.
|
||||
|
||||
Knowledge should first be gathered from trusted resources. Use `RESOURCES.md` to keep track of them. Lessons should be littered with citations - links to external resources to back up any claim made. This increases the trustworthiness of the lesson.
|
||||
|
||||
For acquiring knowledge, difficulty is the enemy. It eats working memory you need for understanding.
|
||||
|
||||
## Skills
|
||||
|
||||
If knowledge is all about acquisition, skills are about durability and flexibility. Make the knowledge stick.
|
||||
|
||||
For skill acquisition, difficulty is the tool. Effortful retrieval is what builds storage strength. Skills should be taught through interactive lessons. There are several tools at your disposal:
|
||||
|
||||
- Interactive lessons, using quizzes and light in-browser tasks
|
||||
- Lessons which guide the user through a list of real-world steps to take (for instance, yoga poses)
|
||||
|
||||
Each of these should be based on a **feedback loop**, where the user receives feedback on their performance. This feedback loop should be as tight as possible, giving feedback immediately - and ideally automatically.
|
||||
|
||||
For quizzes, each answer should be exactly the same number of words (and characters, if possible). Don't give the user any clues about the answer through formatting.
|
||||
|
||||
## Acquiring Wisdom
|
||||
|
||||
Wisdom comes from true real-world interaction - testing your skills outside the learning environment.
|
||||
|
||||
When the user asks a question that appears to require wisdom, your default posture should be to attempt to answer - but to ultimately delegate to a **community**.
|
||||
|
||||
A community is a place (online or offline) where the user can test their skills in the real world. This might be a forum, a subreddit, a real-world class (budget permitting) or a local interest group.
|
||||
|
||||
You should attempt to find high-reputation communities the user can join. If the user expresses a preference that they don't want to join a community, respect it.
|
||||
|
||||
## Reference Documents
|
||||
|
||||
While creating lessons, you should also create reference documents. Lessons can reference these documents - they are useful for tracking raw units of knowledge useful across lessons.
|
||||
|
||||
Lessons will rarely be revisited later - reference documents will be. They should be the compressed essence of the lesson, in a format designed for quick reference.
|
||||
|
||||
Some learning topics lend themselves to reference:
|
||||
|
||||
- Syntax and code snippets for programming
|
||||
- Algorithms and flowcharts for processes
|
||||
- Yoga poses and sequences for yoga
|
||||
- Exercises and routines for fitness
|
||||
- Glossaries for any topic with its own nomenclature
|
||||
|
||||
Glossaries, in particular, are an essential reference. Once one is created, it should be adhered to in every lesson.
|
||||
|
||||
## `NOTES.md`
|
||||
|
||||
The user will sometimes express preferences of how they want to be taught, or things you should keep in mind. This is the place to record those preferences, so you can refer back to them when designing lessons or working with the user.
|
||||
84
.agents/skills/to-issues/SKILL.md
Normal file
84
.agents/skills/to-issues/SKILL.md
Normal file
@@ -0,0 +1,84 @@
|
||||
---
|
||||
name: to-issues
|
||||
description: Break a plan, spec, or PRD into independently-grabbable issues on the project issue tracker using tracer-bullet vertical slices.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# To Issues
|
||||
|
||||
Break a plan into independently-grabbable issues using vertical slices (tracer bullets).
|
||||
|
||||
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 an issue reference (issue number, URL, or path) as an argument, fetch it from the issue tracker 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. Issue 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 plan into **tracer bullet** issues. Each issue is a thin vertical slice that cuts through ALL integration layers end-to-end, NOT a horizontal slice of one layer.
|
||||
|
||||
<vertical-slice-rules>
|
||||
|
||||
- Each slice delivers a narrow but COMPLETE path through every layer (schema, API, UI, tests)
|
||||
- A completed slice is demoable or verifiable on its own
|
||||
- Any prefactoring should be done first
|
||||
|
||||
</vertical-slice-rules>
|
||||
|
||||
### 4. Quiz the user
|
||||
|
||||
Present the proposed breakdown as a numbered list. For each slice, show:
|
||||
|
||||
- **Title**: short descriptive name
|
||||
- **Blocked by**: which other slices (if any) must complete first
|
||||
- **User stories covered**: which user stories this addresses (if the source material has them)
|
||||
|
||||
Ask the user:
|
||||
|
||||
- Does the granularity feel right? (too coarse / too fine)
|
||||
- Are the dependency relationships correct?
|
||||
- Should any slices be merged or split further?
|
||||
|
||||
Iterate until the user approves the breakdown.
|
||||
|
||||
### 5. Publish the issues to the issue tracker
|
||||
|
||||
For each approved slice, publish a new issue to the issue tracker. Use the issue body template below. These issues are considered ready for AFK agents, so publish them with the correct triage label unless instructed otherwise.
|
||||
|
||||
Publish issues in dependency order (blockers first) so you can reference real issue identifiers in the "Blocked by" field.
|
||||
|
||||
<issue-template>
|
||||
## Parent
|
||||
|
||||
A reference to the parent issue on the issue tracker (if the source was an existing issue, otherwise omit this section).
|
||||
|
||||
## What to build
|
||||
|
||||
A concise description of this vertical slice. Describe the end-to-end behavior, not layer-by-layer implementation.
|
||||
|
||||
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 here and note briefly that it came from a prototype. Trim to the decision-rich parts — not a working demo, just the important bits.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Criterion 1
|
||||
- [ ] Criterion 2
|
||||
- [ ] Criterion 3
|
||||
|
||||
## Blocked by
|
||||
|
||||
- A reference to the blocking ticket (if any)
|
||||
|
||||
Or "None - can start immediately" if no blockers.
|
||||
|
||||
</issue-template>
|
||||
|
||||
Do NOT close or modify any parent issue.
|
||||
75
.agents/skills/to-prd/SKILL.md
Normal file
75
.agents/skills/to-prd/SKILL.md
Normal file
@@ -0,0 +1,75 @@
|
||||
---
|
||||
name: to-prd
|
||||
description: Turn the current conversation into a PRD 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 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 PRD, 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 PRD using the template below, then publish it to the project issue tracker. Apply the `ready-for-agent` triage label - no need for additional triage.
|
||||
|
||||
<prd-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 PRD.
|
||||
|
||||
## Further Notes
|
||||
|
||||
Any further notes about the feature.
|
||||
|
||||
</prd-template>
|
||||
207
.agents/skills/triage/AGENT-BRIEF.md
Normal file
207
.agents/skills/triage/AGENT-BRIEF.md
Normal file
@@ -0,0 +1,207 @@
|
||||
# Writing Agent Briefs
|
||||
|
||||
An agent brief is a structured comment posted on a GitHub issue or PR when it moves to `ready-for-agent`. It is the authoritative specification that an AFK agent will work from. The original body and discussion are context — the agent brief is the contract.
|
||||
|
||||
The brief states **what the agent should do**, which stretches to both surfaces: for an issue, that's building the change from nothing; for a PR, it's what's left to do *to the existing diff* — finish it, close gaps, address review points. Same principles either way; the PR example below shows the difference.
|
||||
|
||||
## Principles
|
||||
|
||||
### Durability over precision
|
||||
|
||||
The issue may sit in `ready-for-agent` for days or weeks. The codebase will change in the meantime. Write the brief so it stays useful even as files are renamed, moved, or refactored.
|
||||
|
||||
- **Do** describe interfaces, types, and behavioral contracts
|
||||
- **Do** name specific types, function signatures, or config shapes that the agent should look for or modify
|
||||
- **Don't** reference file paths — they go stale
|
||||
- **Don't** reference line numbers
|
||||
- **Don't** assume the current implementation structure will remain the same
|
||||
|
||||
### Behavioral, not procedural
|
||||
|
||||
Describe **what** the system should do, not **how** to implement it. The agent will explore the codebase fresh and make its own implementation decisions.
|
||||
|
||||
- **Good:** "The `SkillConfig` type should accept an optional `schedule` field of type `CronExpression`"
|
||||
- **Bad:** "Open src/types/skill.ts and add a schedule field on line 42"
|
||||
- **Good:** "When a user runs `/triage` with no arguments, they should see a summary of issues needing attention"
|
||||
- **Bad:** "Add a switch statement in the main handler function"
|
||||
|
||||
### Complete acceptance criteria
|
||||
|
||||
The agent needs to know when it's done. Every agent brief must have concrete, testable acceptance criteria. Each criterion should be independently verifiable.
|
||||
|
||||
- **Good:** "Running `gh issue list --label needs-triage` returns issues that have been through initial classification"
|
||||
- **Bad:** "Triage should work correctly"
|
||||
|
||||
### Explicit scope boundaries
|
||||
|
||||
State what is out of scope. This prevents the agent from gold-plating or making assumptions about adjacent features.
|
||||
|
||||
## Template
|
||||
|
||||
```markdown
|
||||
## Agent Brief
|
||||
|
||||
**Category:** bug / enhancement
|
||||
**Summary:** one-line description of what needs to happen
|
||||
|
||||
**Current behavior:**
|
||||
Describe what happens now. For bugs, this is the broken behavior.
|
||||
For enhancements, this is the status quo the feature builds on.
|
||||
|
||||
**Desired behavior:**
|
||||
Describe what should happen after the agent's work is complete.
|
||||
Be specific about edge cases and error conditions.
|
||||
|
||||
**Key interfaces:**
|
||||
- `TypeName` — what needs to change and why
|
||||
- `functionName()` return type — what it currently returns vs what it should return
|
||||
- Config shape — any new configuration options needed
|
||||
|
||||
**Acceptance criteria:**
|
||||
- [ ] Specific, testable criterion 1
|
||||
- [ ] Specific, testable criterion 2
|
||||
- [ ] Specific, testable criterion 3
|
||||
|
||||
**Out of scope:**
|
||||
- Thing that should NOT be changed or addressed in this issue
|
||||
- Adjacent feature that might seem related but is separate
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Good agent brief (bug)
|
||||
|
||||
```markdown
|
||||
## Agent Brief
|
||||
|
||||
**Category:** bug
|
||||
**Summary:** Skill description truncation drops mid-word, producing broken output
|
||||
|
||||
**Current behavior:**
|
||||
When a skill description exceeds 1024 characters, it is truncated at exactly
|
||||
1024 characters regardless of word boundaries. This produces descriptions
|
||||
that end mid-word (e.g. "Use when the user wants to confi").
|
||||
|
||||
**Desired behavior:**
|
||||
Truncation should break at the last word boundary before 1024 characters
|
||||
and append "..." to indicate truncation.
|
||||
|
||||
**Key interfaces:**
|
||||
- The `SkillMetadata` type's `description` field — no type change needed,
|
||||
but the validation/processing logic that populates it needs to respect
|
||||
word boundaries
|
||||
- Any function that reads SKILL.md frontmatter and extracts the description
|
||||
|
||||
**Acceptance criteria:**
|
||||
- [ ] Descriptions under 1024 chars are unchanged
|
||||
- [ ] Descriptions over 1024 chars are truncated at the last word boundary
|
||||
before 1024 chars
|
||||
- [ ] Truncated descriptions end with "..."
|
||||
- [ ] The total length including "..." does not exceed 1024 chars
|
||||
|
||||
**Out of scope:**
|
||||
- Changing the 1024 char limit itself
|
||||
- Multi-line description support
|
||||
```
|
||||
|
||||
### Good agent brief (enhancement)
|
||||
|
||||
```markdown
|
||||
## Agent Brief
|
||||
|
||||
**Category:** enhancement
|
||||
**Summary:** Add `.out-of-scope/` directory support for tracking rejected feature requests
|
||||
|
||||
**Current behavior:**
|
||||
When a feature request is rejected, the issue is closed with a `wontfix` label
|
||||
and a comment. There is no persistent record of the decision or reasoning.
|
||||
Future similar requests require the maintainer to recall or search for the
|
||||
prior discussion.
|
||||
|
||||
**Desired behavior:**
|
||||
Rejected feature requests should be documented in `.out-of-scope/<concept>.md`
|
||||
files that capture the decision, reasoning, and links to all issues that
|
||||
requested the feature. When triaging new issues, these files should be
|
||||
checked for matches.
|
||||
|
||||
**Key interfaces:**
|
||||
- Markdown file format in `.out-of-scope/` — each file should have a
|
||||
`# Concept Name` heading, a `**Decision:**` line, a `**Reason:**` line,
|
||||
and a `**Prior requests:**` list with issue links
|
||||
- The triage workflow should read all `.out-of-scope/*.md` files early
|
||||
and match incoming issues against them by concept similarity
|
||||
|
||||
**Acceptance criteria:**
|
||||
- [ ] Closing a feature as wontfix creates/updates a file in `.out-of-scope/`
|
||||
- [ ] The file includes the decision, reasoning, and link to the closed issue
|
||||
- [ ] If a matching `.out-of-scope/` file already exists, the new issue is
|
||||
appended to its "Prior requests" list rather than creating a duplicate
|
||||
- [ ] During triage, existing `.out-of-scope/` files are checked and surfaced
|
||||
when a new issue matches a prior rejection
|
||||
|
||||
**Out of scope:**
|
||||
- Automated matching (human confirms the match)
|
||||
- Reopening previously rejected features
|
||||
- Bug reports (only enhancement rejections go to `.out-of-scope/`)
|
||||
```
|
||||
|
||||
### Good agent brief (PR)
|
||||
|
||||
For a PR, "Current behavior" describes the state of the diff, and the brief asks the agent to finish or fix it rather than build from scratch.
|
||||
|
||||
```markdown
|
||||
## Agent Brief
|
||||
|
||||
**Category:** enhancement
|
||||
**Summary:** Finish the contributor's `--json` output flag for `triage list`
|
||||
|
||||
**Current behavior:**
|
||||
The PR adds a `--json` flag that serializes the issue list to JSON. The happy
|
||||
path works and the diff matches the project's command structure. Two gaps
|
||||
remain: errors are still printed as human text (not JSON), and the new flag has
|
||||
no test coverage.
|
||||
|
||||
**Desired behavior:**
|
||||
With `--json`, all output — including errors — is well-formed JSON on stdout,
|
||||
and the command's exit codes are unchanged. The existing human-readable output
|
||||
is untouched when the flag is absent.
|
||||
|
||||
**Key interfaces:**
|
||||
- The command's error path should emit `{ "error": string }` under `--json`
|
||||
instead of the plain-text error
|
||||
- Reuse the existing serializer the PR already added; don't introduce a second
|
||||
|
||||
**Acceptance criteria:**
|
||||
- [ ] `triage list --json` emits valid JSON for both success and error cases
|
||||
- [ ] Exit codes match the non-JSON command
|
||||
- [ ] A test covers the `--json` success output and one error case
|
||||
- [ ] Default (non-JSON) output is byte-for-byte unchanged
|
||||
|
||||
**Out of scope:**
|
||||
- Adding `--json` to any other command
|
||||
- Changing the JSON shape of the success payload the PR already defined
|
||||
```
|
||||
|
||||
### Bad agent brief
|
||||
|
||||
```markdown
|
||||
## Agent Brief
|
||||
|
||||
**Summary:** Fix the triage bug
|
||||
|
||||
**What to do:**
|
||||
The triage thing is broken. Look at the main file and fix it.
|
||||
The function around line 150 has the issue.
|
||||
|
||||
**Files to change:**
|
||||
- src/triage/handler.ts (line 150)
|
||||
- src/types.ts (line 42)
|
||||
```
|
||||
|
||||
This is bad because:
|
||||
- No category
|
||||
- Vague description ("the triage thing is broken")
|
||||
- References file paths and line numbers that will go stale
|
||||
- No acceptance criteria
|
||||
- No scope boundaries
|
||||
- No description of current vs desired behavior
|
||||
105
.agents/skills/triage/OUT-OF-SCOPE.md
Normal file
105
.agents/skills/triage/OUT-OF-SCOPE.md
Normal file
@@ -0,0 +1,105 @@
|
||||
# Out-of-Scope Knowledge Base
|
||||
|
||||
The `.out-of-scope/` directory in a repo stores persistent records of rejected feature requests. It serves two purposes:
|
||||
|
||||
1. **Institutional memory** — why a feature was rejected, so the reasoning isn't lost when the issue is closed
|
||||
2. **Deduplication** — when a new issue comes in that matches a prior rejection, the skill can surface the previous decision instead of re-litigating it
|
||||
|
||||
## Directory structure
|
||||
|
||||
```
|
||||
.out-of-scope/
|
||||
├── dark-mode.md
|
||||
├── plugin-system.md
|
||||
└── graphql-api.md
|
||||
```
|
||||
|
||||
One file per **concept**, not per issue. Multiple issues requesting the same thing are grouped under one file.
|
||||
|
||||
## File format
|
||||
|
||||
The file should be written in a relaxed, readable style — more like a short design document than a database entry. Use paragraphs, code samples, and examples to make the reasoning clear and useful to someone encountering it for the first time.
|
||||
|
||||
```markdown
|
||||
# Dark Mode
|
||||
|
||||
This project does not support dark mode or user-facing theming.
|
||||
|
||||
## Why this is out of scope
|
||||
|
||||
The rendering pipeline assumes a single color palette defined in
|
||||
`ThemeConfig`. Supporting multiple themes would require:
|
||||
|
||||
- A theme context provider wrapping the entire component tree
|
||||
- Per-component theme-aware style resolution
|
||||
- A persistence layer for user theme preferences
|
||||
|
||||
This is a significant architectural change that doesn't align with the
|
||||
project's focus on content authoring. Theming is a concern for downstream
|
||||
consumers who embed or redistribute the output.
|
||||
|
||||
```ts
|
||||
// The current ThemeConfig interface is not designed for runtime switching:
|
||||
interface ThemeConfig {
|
||||
colors: ColorPalette; // single palette, resolved at build time
|
||||
fonts: FontStack;
|
||||
}
|
||||
```
|
||||
|
||||
## Prior requests
|
||||
|
||||
- #42 — "Add dark mode support"
|
||||
- #87 — "Night theme for accessibility"
|
||||
- #134 — "Dark theme option"
|
||||
```
|
||||
|
||||
### Naming the file
|
||||
|
||||
Use a short, descriptive kebab-case name for the concept: `dark-mode.md`, `plugin-system.md`, `graphql-api.md`. The name should be recognizable enough that someone browsing the directory understands what was rejected without opening the file.
|
||||
|
||||
### Writing the reason
|
||||
|
||||
The reason should be substantive — not "we don't want this" but why. Good reasons reference:
|
||||
|
||||
- Project scope or philosophy ("This project focuses on X; theming is a downstream concern")
|
||||
- Technical constraints ("Supporting this would require Y, which conflicts with our Z architecture")
|
||||
- Strategic decisions ("We chose to use A instead of B because...")
|
||||
|
||||
The reason should be durable. Avoid referencing temporary circumstances ("we're too busy right now") — those aren't real rejections, they're deferrals.
|
||||
|
||||
## When to check `.out-of-scope/`
|
||||
|
||||
During triage (Step 1: Gather context), read all files in `.out-of-scope/`. When evaluating a new issue:
|
||||
|
||||
- Check if the request matches an existing out-of-scope concept
|
||||
- Matching is by concept similarity, not keyword — "night theme" matches `dark-mode.md`
|
||||
- If there's a match, surface it to the maintainer: "This is similar to `.out-of-scope/dark-mode.md` — we rejected this before because [reason]. Do you still feel the same way?"
|
||||
|
||||
The maintainer may:
|
||||
|
||||
- **Confirm** — the new issue gets added to the existing file's "Prior requests" list, then closed
|
||||
- **Reconsider** — the out-of-scope file gets deleted or updated, and the issue proceeds through normal triage
|
||||
- **Disagree** — the issues are related but distinct, proceed with normal triage
|
||||
|
||||
## When to write to `.out-of-scope/`
|
||||
|
||||
Only when an **enhancement** (not a bug) is *rejected* as `wontfix`. This applies to enhancement PRs exactly as it does to issues — a rejected PR is recorded here so the same request doesn't return as fresh code.
|
||||
|
||||
Do **not** write here when something is closed as `wontfix` because it's **already implemented**. That's a built feature, not a rejected one; recording it would poison the dedup checks with false rejections. Instead, the closing comment points to where the feature already lives.
|
||||
|
||||
The flow:
|
||||
|
||||
1. Maintainer decides a feature request is out of scope
|
||||
2. Check if a matching `.out-of-scope/` file already exists
|
||||
3. If yes: append the new issue to the "Prior requests" list
|
||||
4. If no: create a new file with the concept name, decision, reason, and first prior request
|
||||
5. Post a comment on the issue explaining the decision and mentioning the `.out-of-scope/` file
|
||||
6. Close the issue with the `wontfix` label
|
||||
|
||||
## Updating or removing out-of-scope files
|
||||
|
||||
If the maintainer changes their mind about a previously rejected concept:
|
||||
|
||||
- Delete the `.out-of-scope/` file
|
||||
- The skill does not need to reopen old issues — they're historical records
|
||||
- The new issue that triggered the reconsideration proceeds through normal triage
|
||||
112
.agents/skills/triage/SKILL.md
Normal file
112
.agents/skills/triage/SKILL.md
Normal file
@@ -0,0 +1,112 @@
|
||||
---
|
||||
name: triage
|
||||
description: Move issues and external PRs through a state machine of triage roles — categorise, verify, grill if needed, and write agent-ready briefs.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Triage
|
||||
|
||||
Move issues on the project issue tracker through a small state machine of triage roles.
|
||||
|
||||
If this repo treats external pull requests as a request surface (see the issue-tracker config), triage covers them too: **a PR is an issue with attached code** — same roles, same states, same machine, with a few deltas marked "for a PR" below. Resolve a bare `#42` to an issue or PR per the tracker config.
|
||||
|
||||
Every comment or issue posted to the issue tracker during triage **must** start with this disclaimer:
|
||||
|
||||
```
|
||||
> *This was generated by AI during triage.*
|
||||
```
|
||||
|
||||
## Reference docs
|
||||
|
||||
- [AGENT-BRIEF.md](AGENT-BRIEF.md) — how to write durable agent briefs
|
||||
- [OUT-OF-SCOPE.md](OUT-OF-SCOPE.md) — how the `.out-of-scope/` knowledge base works
|
||||
|
||||
## Roles
|
||||
|
||||
Two **category** roles:
|
||||
|
||||
- `bug` — something is broken
|
||||
- `enhancement` — new feature or improvement
|
||||
|
||||
Five **state** roles:
|
||||
|
||||
- `needs-triage` — maintainer needs to evaluate
|
||||
- `needs-info` — waiting on reporter for more information
|
||||
- `ready-for-agent` — fully specified, ready for an AFK agent
|
||||
- `ready-for-human` — needs human implementation
|
||||
- `wontfix` — will not be actioned
|
||||
|
||||
For a PR, the same states read against the attached code: `ready-for-agent` means a brief is attached and an agent should take the next step on the diff; `ready-for-human` means it's ready for a human to merge.
|
||||
|
||||
Every triaged issue should carry exactly one category role and one state role. If state roles conflict, flag it and ask the maintainer before doing anything else.
|
||||
|
||||
These are canonical role names — the actual label strings used in the issue tracker may differ. The mapping should have been provided to you - run `/setup-matt-pocock-skills` if not.
|
||||
|
||||
State transitions: an unlabeled issue normally goes to `needs-triage` first; from there it moves to `needs-info`, `ready-for-agent`, `ready-for-human`, or `wontfix`. `needs-info` returns to `needs-triage` once the reporter replies. The maintainer can override at any time — flag transitions that look unusual and ask before proceeding.
|
||||
|
||||
## Invocation
|
||||
|
||||
The maintainer invokes `/triage` and describes what they want in natural language. Interpret the request and act. Examples:
|
||||
|
||||
- "Show me anything that needs my attention"
|
||||
- "Let's look at #42" (issue or PR)
|
||||
- "Move #42 to ready-for-agent"
|
||||
- "What's ready for agents to pick up?"
|
||||
|
||||
## Show what needs attention
|
||||
|
||||
Query the issue tracker and present three buckets, oldest first:
|
||||
|
||||
1. **Unlabeled** — never triaged.
|
||||
2. **`needs-triage`** — evaluation in progress.
|
||||
3. **`needs-info` with reporter activity since the last triage notes** — needs re-evaluation.
|
||||
|
||||
When PRs are in scope, include external PRs in these buckets and tag each line `[PR]` or `[issue]`. Discovery surfaces only *external* PRs (the tracker config defines who counts as external) — a collaborator's in-flight PR is not triage work. This filter is discovery-only; an explicitly named PR is always triaged regardless of author.
|
||||
|
||||
Show counts and a one-line summary per item. Let the maintainer pick.
|
||||
|
||||
## Triage a specific issue or PR
|
||||
|
||||
1. **Gather context.** Read the full issue or PR (body, comments, labels, author, dates; for a PR, the diff too). Parse any prior triage notes so you don't re-ask resolved questions. Explore the codebase using the project's domain glossary, respecting ADRs in the area. Run two checks against the codebase: (a) **redundancy** — search for an existing implementation of the requested behavior by domain concept (not just the request's wording), and report where you looked. If found, it's an already-implemented `wontfix` (step 5). (b) **prior rejection** — read `.out-of-scope/*.md` and surface any that resembles this request.
|
||||
|
||||
2. **Recommend.** Tell the maintainer your category and state recommendation with reasoning, plus a brief codebase summary relevant to the request — including whether it's already implemented. Wait for direction.
|
||||
|
||||
3. **Verify the claim.** Before any grilling, check that the claim holds up. For a bug, reproduce it from the reporter's steps. For a PR, confirm the diff does what it claims — check it out, run the relevant tests or commands. Report what happened: confirmed (with code path), failed, or insufficient detail (a strong `needs-info` signal). A confirmed verification makes a much stronger agent brief.
|
||||
|
||||
4. **Grill (if needed).** If the request needs fleshing out, run the `/grilling` and `/domain-modeling` skills together — grill it into shape one question at a time, sharpening domain terms and updating `CONTEXT.md`/ADRs inline as decisions land.
|
||||
|
||||
5. **Apply the outcome:**
|
||||
- `ready-for-agent` — post an agent brief comment ([AGENT-BRIEF.md](AGENT-BRIEF.md)).
|
||||
- `ready-for-human` — same structure as an agent brief, but note why it can't be delegated (judgment calls, external access, design decisions, manual testing).
|
||||
- `needs-info` — post triage notes (template below).
|
||||
- `wontfix` — close, with the comment depending on *why*:
|
||||
- **Already implemented** — the change already exists in the codebase. Point to where it lives; do **not** write to `.out-of-scope/` (that KB is for *rejected* requests, not built ones).
|
||||
- **Rejected (bug)** — polite explanation, then close.
|
||||
- **Rejected (enhancement)** — write to `.out-of-scope/`, link to it from a comment, then close ([OUT-OF-SCOPE.md](OUT-OF-SCOPE.md)).
|
||||
- `needs-triage` — apply the role. Optional comment if there's partial progress.
|
||||
|
||||
## Quick state override
|
||||
|
||||
If the maintainer says "move #42 to ready-for-agent", trust them and apply the role directly. Confirm what you're about to do (role changes, comment, close), then act. Skip grilling. If moving to `ready-for-agent` without a grilling session, ask whether they want to write an agent brief.
|
||||
|
||||
## Needs-info template
|
||||
|
||||
```markdown
|
||||
## Triage Notes
|
||||
|
||||
**What we've established so far:**
|
||||
|
||||
- point 1
|
||||
- point 2
|
||||
|
||||
**What we still need from you (@reporter):**
|
||||
|
||||
- question 1
|
||||
- question 2
|
||||
```
|
||||
|
||||
Capture everything resolved during grilling under "established so far" so the work isn't lost. Questions must be specific and actionable, not "please provide more info".
|
||||
|
||||
## Resuming a previous session
|
||||
|
||||
If prior triage notes exist on the issue or PR, read them, check whether the reporter has answered any outstanding questions, and present an updated picture before continuing. Don't re-ask resolved questions.
|
||||
117
.agents/skills/write-a-skill/SKILL.md
Normal file
117
.agents/skills/write-a-skill/SKILL.md
Normal file
@@ -0,0 +1,117 @@
|
||||
---
|
||||
name: write-a-skill
|
||||
description: Create new agent skills with proper structure, progressive disclosure, and bundled resources. Use when user wants to create, write, or build a new skill.
|
||||
---
|
||||
|
||||
# Writing Skills
|
||||
|
||||
## Process
|
||||
|
||||
1. **Gather requirements** - ask user about:
|
||||
- What task/domain does the skill cover?
|
||||
- What specific use cases should it handle?
|
||||
- Does it need executable scripts or just instructions?
|
||||
- Any reference materials to include?
|
||||
|
||||
2. **Draft the skill** - create:
|
||||
- SKILL.md with concise instructions
|
||||
- Additional reference files if content exceeds 500 lines
|
||||
- Utility scripts if deterministic operations needed
|
||||
|
||||
3. **Review with user** - present draft and ask:
|
||||
- Does this cover your use cases?
|
||||
- Anything missing or unclear?
|
||||
- Should any section be more/less detailed?
|
||||
|
||||
## Skill Structure
|
||||
|
||||
```
|
||||
skill-name/
|
||||
├── SKILL.md # Main instructions (required)
|
||||
├── REFERENCE.md # Detailed docs (if needed)
|
||||
├── EXAMPLES.md # Usage examples (if needed)
|
||||
└── scripts/ # Utility scripts (if needed)
|
||||
└── helper.js
|
||||
```
|
||||
|
||||
## SKILL.md Template
|
||||
|
||||
```md
|
||||
---
|
||||
name: skill-name
|
||||
description: Brief description of capability. Use when [specific triggers].
|
||||
---
|
||||
|
||||
# Skill Name
|
||||
|
||||
## Quick start
|
||||
|
||||
[Minimal working example]
|
||||
|
||||
## Workflows
|
||||
|
||||
[Step-by-step processes with checklists for complex tasks]
|
||||
|
||||
## Advanced features
|
||||
|
||||
[Link to separate files: See [REFERENCE.md](REFERENCE.md)]
|
||||
```
|
||||
|
||||
## Description Requirements
|
||||
|
||||
The description is **the only thing your agent sees** when deciding which skill to load. It's surfaced in the system prompt alongside all other installed skills. Your agent reads these descriptions and picks the relevant skill based on the user's request.
|
||||
|
||||
**Goal**: Give your agent just enough info to know:
|
||||
|
||||
1. What capability this skill provides
|
||||
2. When/why to trigger it (specific keywords, contexts, file types)
|
||||
|
||||
**Format**:
|
||||
|
||||
- Max 1024 chars
|
||||
- Write in third person
|
||||
- First sentence: what it does
|
||||
- Second sentence: "Use when [specific triggers]"
|
||||
|
||||
**Good example**:
|
||||
|
||||
```
|
||||
Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when user mentions PDFs, forms, or document extraction.
|
||||
```
|
||||
|
||||
**Bad example**:
|
||||
|
||||
```
|
||||
Helps with documents.
|
||||
```
|
||||
|
||||
The bad example gives your agent no way to distinguish this from other document skills.
|
||||
|
||||
## When to Add Scripts
|
||||
|
||||
Add utility scripts when:
|
||||
|
||||
- Operation is deterministic (validation, formatting)
|
||||
- Same code would be generated repeatedly
|
||||
- Errors need explicit handling
|
||||
|
||||
Scripts save tokens and improve reliability vs generated code.
|
||||
|
||||
## When to Split Files
|
||||
|
||||
Split into separate files when:
|
||||
|
||||
- SKILL.md exceeds 100 lines
|
||||
- Content has distinct domains (finance vs sales schemas)
|
||||
- Advanced features are rarely needed
|
||||
|
||||
## Review Checklist
|
||||
|
||||
After drafting, verify:
|
||||
|
||||
- [ ] Description includes triggers ("Use when...")
|
||||
- [ ] SKILL.md under 100 lines
|
||||
- [ ] No time-sensitive info
|
||||
- [ ] Consistent terminology
|
||||
- [ ] Concrete examples included
|
||||
- [ ] References one level deep
|
||||
7
.agents/skills/zoom-out/SKILL.md
Normal file
7
.agents/skills/zoom-out/SKILL.md
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
name: zoom-out
|
||||
description: Tell the agent to zoom out and give broader context or a higher-level perspective. Use when you're unfamiliar with a section of code or need to understand how it fits into the bigger picture.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
I don't know this area of code well. Go up a layer of abstraction. Give me a map of all the relevant modules and callers, using the project's domain glossary vocabulary.
|
||||
1
.claude/skills/caveman
Symbolic link
1
.claude/skills/caveman
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/caveman
|
||||
139
.claude/skills/comment-standards/SKILL.md
Normal file
139
.claude/skills/comment-standards/SKILL.md
Normal file
@@ -0,0 +1,139 @@
|
||||
---
|
||||
name: comment-standards
|
||||
description: Go 注释规范。编写 Go 代码注释、文档注释时使用。包含包注释、结构体注释、接口注释、函数注释、内联注释的完整规范与示例。
|
||||
---
|
||||
|
||||
# Go 注释规范
|
||||
|
||||
**基本原则**:
|
||||
- **所有注释使用中文**
|
||||
- **导出符号必须有文档注释**(包、函数、方法、类型、接口、常量、变量)
|
||||
- **复杂逻辑必须有实现注释**(解释"为什么",而不是"做了什么")
|
||||
- **禁止废话注释**(不要用注释复述代码本身)
|
||||
- **修改代码时必须同步更新注释**
|
||||
|
||||
---
|
||||
|
||||
## 包注释
|
||||
|
||||
每个包的入口文件(通常是主文件或 `doc.go`)必须有包注释:
|
||||
|
||||
```go
|
||||
// Package account 提供账号管理的业务逻辑服务
|
||||
// 包含账号创建、修改、删除、权限分配等功能
|
||||
package account
|
||||
```
|
||||
|
||||
## 结构体注释
|
||||
|
||||
所有导出结构体必须有文档注释,说明该结构体代表什么:
|
||||
|
||||
```go
|
||||
// Service 账号业务服务
|
||||
// 负责账号的 CRUD、角色分配、密码管理等业务逻辑
|
||||
type Service struct {
|
||||
store *Store
|
||||
auditService AuditServiceInterface
|
||||
}
|
||||
```
|
||||
|
||||
## 接口注释
|
||||
|
||||
导出接口必须注释接口用途,每个方法必须说明契约:
|
||||
|
||||
```go
|
||||
// PermissionChecker 权限检查器接口
|
||||
// 用于查询用户的权限列表
|
||||
type PermissionChecker interface {
|
||||
// CheckPermission 检查用户是否拥有指定权限
|
||||
// userID: 用户ID
|
||||
// permCode: 权限编码(格式: module:action)
|
||||
// platform: 端口类型 (all/web/h5)
|
||||
CheckPermission(ctx context.Context, userID uint, permCode string, platform string) (bool, error)
|
||||
}
|
||||
```
|
||||
|
||||
## 函数和方法注释
|
||||
|
||||
**导出函数/方法**必须以函数名开头,说明功能:
|
||||
|
||||
```go
|
||||
// Create 创建账号
|
||||
// POST /api/admin/accounts
|
||||
func (h *AccountHandler) Create(c *fiber.Ctx) error {
|
||||
```
|
||||
|
||||
**复杂方法**(超过 30 行或包含复杂业务逻辑)必须额外说明实现思路:
|
||||
|
||||
```go
|
||||
// ActivateByRealname 首次实名激活套餐
|
||||
// 当用户完成实名认证后,自动激活处于"囤货待实名"状态的套餐:
|
||||
// 1. 查找该卡所有 status=3(待实名激活)的套餐
|
||||
// 2. 按创建时间排序,第一个主套餐立即激活(status=1)
|
||||
// 3. 其余主套餐进入排队状态(status=4)
|
||||
// 4. 加油包如果绑定了已激活的主套餐则一并激活
|
||||
func (s *UsageService) ActivateByRealname(ctx context.Context, cardID uint) error {
|
||||
```
|
||||
|
||||
**未导出函数/方法**:
|
||||
- 简单逻辑(< 15 行):可以不加注释
|
||||
- 复杂逻辑(≥ 15 行)或非显而易见的算法:必须加注释
|
||||
|
||||
```go
|
||||
// buildPermissionTree 递归构建权限树
|
||||
// 采用 map 索引 + 单次遍历算法,时间复杂度 O(n)
|
||||
func (s *Service) buildPermissionTree(permissions []*model.Permission) []*dto.PermissionTreeNode {
|
||||
```
|
||||
|
||||
## 常量和枚举注释
|
||||
|
||||
分组常量必须有组注释,每个值必须有行内注释:
|
||||
|
||||
```go
|
||||
// 用户类型常量
|
||||
const (
|
||||
UserTypeSuperAdmin = 1 // 超级管理员
|
||||
UserTypePlatform = 2 // 平台用户
|
||||
UserTypeAgent = 3 // 代理账号
|
||||
UserTypeEnterprise = 4 // 企业账号
|
||||
)
|
||||
```
|
||||
|
||||
## 内联注释规范
|
||||
|
||||
**必须添加内联注释的场景**:
|
||||
|
||||
| 场景 | 要求 |
|
||||
|------|------|
|
||||
| 复杂条件判断 | 解释判断的业务含义 |
|
||||
| 多步骤业务流程 | 用编号注释标明每一步 |
|
||||
| 非显而易见的设计决策 | 解释"为什么这样做"而不是"做了什么" |
|
||||
| 缓存/事务/并发处理 | 说明策略和原因 |
|
||||
| 临时方案/兼容逻辑 | 标注 TODO 或说明背景 |
|
||||
|
||||
**✅ 好的内联注释(解释为什么)**:
|
||||
|
||||
```go
|
||||
// 使用 Redis 分布式锁防止并发重复创建,锁超时 10 秒
|
||||
if !s.acquireLock(ctx, lockKey, 10*time.Second) {
|
||||
return errors.New(errors.CodeTooManyRequests, "操作过于频繁,请稍后重试")
|
||||
}
|
||||
|
||||
// 先冻结佣金再扣款,保证资金安全(失败时佣金自动解冻)
|
||||
if err := s.freezeCommission(ctx, tx, orderID); err != nil {
|
||||
return err
|
||||
}
|
||||
```
|
||||
|
||||
**❌ 废话注释(禁止)**:
|
||||
|
||||
```go
|
||||
// 获取用户ID ← 禁止:代码本身已经很清楚
|
||||
userID := middleware.GetUserIDFromContext(ctx)
|
||||
|
||||
// 创建账号 ← 禁止:变量名已说明意图
|
||||
account := &model.Account{}
|
||||
|
||||
// 返回错误 ← 禁止:return err 不需要注释
|
||||
return err
|
||||
```
|
||||
1
.claude/skills/diagnose
Symbolic link
1
.claude/skills/diagnose
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/diagnose
|
||||
@@ -14,6 +14,8 @@ description: DTO 数据传输对象规范。创建或修改 DTO 文件、请求/
|
||||
- 创建 `XXXRequest`、`XXXResponse`、`XXXReq`、`XXXResp` 结构体
|
||||
- 添加或修改 API 接口的输入输出参数
|
||||
|
||||
---
|
||||
|
||||
## 必须项(MUST)
|
||||
|
||||
### 1. Description 标签规范
|
||||
@@ -36,59 +38,150 @@ type CreateUserRequest struct {
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 枚举字段必须列出所有可能值(中文)
|
||||
### 2. 枚举字段:int vs string 选择
|
||||
|
||||
**所有枚举类型字段必须在 `description` 中列出所有可能值和对应的中文含义**
|
||||
**必须按以下规则选择类型,禁止混用:**
|
||||
|
||||
| 场景 | 类型 | 示例 |
|
||||
|------|------|------|
|
||||
| 状态类(生命周期阶段) | `int` | 待支付→已完成→已关闭 |
|
||||
| 布尔状态(启用/禁用) | `int` | `0=禁用, 1=启用` |
|
||||
| 类型/方式类(种类) | `string` | `"wechat"`, `"single_card"` |
|
||||
| 平台/标识符类 | `string` | `"web"`, `"h5"`, `"all"` |
|
||||
|
||||
```go
|
||||
// 用户类型
|
||||
UserType int `json:"user_type" description:"用户类型 (1:超级管理员, 2:平台用户, 3:代理账号, 4:企业账号)"`
|
||||
// ✅ 状态 → int
|
||||
Status int `json:"status"`
|
||||
PaymentStatus int `json:"payment_status"`
|
||||
|
||||
// 角色类型
|
||||
RoleType int `json:"role_type" description:"角色类型 (1:平台角色, 2:客户角色)"`
|
||||
|
||||
// 权限类型
|
||||
PermType int `json:"perm_type" description:"权限类型 (1:菜单, 2:按钮)"`
|
||||
|
||||
// 状态字段
|
||||
Status int `json:"status" description:"状态 (0:禁用, 1:启用)"`
|
||||
|
||||
// 适用端口
|
||||
Platform string `json:"platform" description:"适用端口 (all:全部, web:Web后台, h5:H5端)"`
|
||||
// ✅ 类型/方式 → string
|
||||
PaymentMethod string `json:"payment_method" validate:"required,oneof=wechat offline"`
|
||||
OrderType string `json:"order_type" validate:"required,oneof=single_card device"`
|
||||
```
|
||||
|
||||
❌ **禁止使用英文枚举值**:
|
||||
### 3. Int 状态值约定
|
||||
|
||||
#### 3.1 通用禁用/启用
|
||||
|
||||
**必须用全局常量,禁止自定义(尤其禁止 1=启用 2=禁用 这种反向写法)**:
|
||||
|
||||
```go
|
||||
UserType int `json:"user_type" description:"用户类型 (1:SuperAdmin, 2:Platform)"` // 错误!
|
||||
// pkg/constants/constants.go 已定义,直接使用
|
||||
StatusDisabled = 0 // 禁用
|
||||
StatusEnabled = 1 // 启用
|
||||
```
|
||||
|
||||
### 3. 验证标签与 OpenAPI 标签一致
|
||||
✅ 正确:`description:"状态 (0:禁用, 1:启用)"`
|
||||
❌ 禁止:`description:"状态 (1:启用, 2:禁用)"`
|
||||
|
||||
**所有验证约束必须同时在 `validate` 和 OpenAPI 标签中声明**
|
||||
#### 3.2 生命周期状态
|
||||
|
||||
从 **1** 开始递增,0 不使用(避免与 Go 零值混淆):
|
||||
|
||||
```go
|
||||
const (
|
||||
RechargeStatusPending = 1 // 待支付
|
||||
RechargeStatusPaid = 2 // 已支付
|
||||
RechargeStatusCompleted = 3 // 已完成
|
||||
RechargeStatusClosed = 4 // 已关闭
|
||||
)
|
||||
```
|
||||
|
||||
### 4. 枚举列表必须从 constants 原文抄写
|
||||
|
||||
**DTO description 的枚举列表必须与 `pkg/constants/` 定义完全一致,不可凭记忆填写。**
|
||||
|
||||
操作步骤:
|
||||
1. 先查/定义 `pkg/constants/` 中的枚举常量
|
||||
2. 将常量注释**原文抄写**到 description
|
||||
|
||||
```go
|
||||
// constants.go 中:
|
||||
RechargeStatusPending = 1 // 待支付
|
||||
RechargeStatusPaid = 2 // 已支付
|
||||
RechargeStatusCompleted = 3 // 已完成
|
||||
RechargeStatusClosed = 4 // 已关闭
|
||||
RechargeStatusRefunded = 5 // 已退款
|
||||
|
||||
// DTO description 从上面抄:
|
||||
Status int `json:"status" description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款)"`
|
||||
```
|
||||
|
||||
❌ 禁止(description 与 constants 不一致,是历史 bug 的根因):
|
||||
```go
|
||||
// constants 说 3=已完成,description 却写 3:已取消
|
||||
Status int `json:"status" description:"状态 (1:待支付, 2:已完成, 3:已取消)"`
|
||||
```
|
||||
|
||||
### 5. description 格式标准
|
||||
|
||||
**统一格式**:`字段含义 (值1:中文含义1, 值2:中文含义2)`
|
||||
|
||||
- 值与含义之间用**冒号** `:`(禁止用等号 `=`)
|
||||
- 多个值之间用**逗号加空格** `, `
|
||||
- 含义必须是**中文**
|
||||
|
||||
```go
|
||||
// ✅ 统一格式
|
||||
Status int `description:"状态 (1:待支付, 2:已支付, 3:已完成)"`
|
||||
Platform string `description:"适用端口 (all:全部, web:Web后台, h5:H5端)"`
|
||||
|
||||
// ❌ 格式混乱
|
||||
Status int `description:"状态 (0=禁用, 1=启用)"` // 用等号
|
||||
Status int `description:"0=禁用 1=启用"` // 无括号无逗号
|
||||
```
|
||||
|
||||
### 6. Response DTO 的状态字段必须同时返回 int 和 text
|
||||
|
||||
**所有 Response DTO 中的 int 状态字段,必须同时提供对应的 `_name` 文字字段。**
|
||||
|
||||
原因:防止前端维护映射表出错(历史上已有因此产生 bug 的案例)。
|
||||
|
||||
```go
|
||||
// ✅ Response DTO 标准写法
|
||||
type XxxResponse struct {
|
||||
Status int `json:"status" description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
}
|
||||
|
||||
// toResponse 函数中赋值
|
||||
func rechargeStatusName(status int) string {
|
||||
switch status {
|
||||
case constants.RechargeStatusPending:
|
||||
return "待支付"
|
||||
case constants.RechargeStatusCompleted:
|
||||
return "已完成"
|
||||
// ...
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
字段命名约定:`status` → `status_name`,`payment_status` → `payment_status_name`
|
||||
|
||||
**例外**:Request DTO(查询过滤、创建请求)不需要 `_name` 字段。
|
||||
|
||||
### 7. 验证标签与 OpenAPI 标签一致
|
||||
|
||||
```go
|
||||
Username string `json:"username" validate:"required,min=3,max=50" required:"true" minLength:"3" maxLength:"50" description:"用户名"`
|
||||
```
|
||||
|
||||
**标签对照表**:
|
||||
| validate 标签 | OpenAPI 标签 |
|
||||
|--------------|--------------|
|
||||
| `required` | `required:"true"` |
|
||||
| `min=N,max=M`(数值) | `minimum:"N" maximum:"M"` |
|
||||
| `min=N,max=M`(字符串) | `minLength:"N" maxLength:"M"` |
|
||||
| `oneof=A B C` | description 中说明枚举值 |
|
||||
|
||||
| validate 标签 | OpenAPI 标签 | 说明 |
|
||||
|--------------|--------------|------|
|
||||
| `required` | `required:"true"` | 必填字段 |
|
||||
| `min=N,max=M` | `minimum:"N" maximum:"M"` | 数值范围 |
|
||||
| `min=N,max=M` (字符串) | `minLength:"N" maxLength:"M"` | 字符串长度 |
|
||||
| `len=N` | `minLength:"N" maxLength:"N"` | 固定长度 |
|
||||
| `oneof=A B C` | `description` 中说明 | 枚举值 |
|
||||
|
||||
### 4. 请求参数类型标签
|
||||
|
||||
**Query 参数和 Path 参数必须添加对应标签**
|
||||
### 8. 请求参数类型标签
|
||||
|
||||
```go
|
||||
// Query 参数
|
||||
type ListRequest struct {
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码"`
|
||||
UserType *int `json:"user_type" query:"user_type" validate:"omitempty,min=1,max=4" minimum:"1" maximum:"4" description:"用户类型 (1:超级管理员, 2:平台用户, 3:代理账号, 4:企业账号)"`
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码"`
|
||||
Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=4" minimum:"1" maximum:"4" description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭)"`
|
||||
}
|
||||
|
||||
// Path 参数
|
||||
@@ -97,43 +190,50 @@ type IDReq struct {
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 响应 DTO 完整性
|
||||
|
||||
**所有响应 DTO 的字段都必须有完整的 `description` 标签**
|
||||
### 9. 响应 DTO 完整性
|
||||
|
||||
```go
|
||||
type AccountResponse struct {
|
||||
ID uint `json:"id" description:"账号ID"`
|
||||
Username string `json:"username" description:"用户名"`
|
||||
UserType int `json:"user_type" description:"用户类型 (1:超级管理员, 2:平台用户, 3:代理账号, 4:企业账号)"`
|
||||
Status int `json:"status" description:"状态 (0:禁用, 1:启用)"`
|
||||
CreatedAt string `json:"created_at" description:"创建时间"`
|
||||
UpdatedAt string `json:"updated_at" description:"更新时间"`
|
||||
ID uint `json:"id" description:"账号ID"`
|
||||
Username string `json:"username" description:"用户名"`
|
||||
UserType int `json:"user_type" description:"用户类型 (1:超级管理员, 2:平台用户, 3:代理账号, 4:企业账号)"`
|
||||
Status int `json:"status" description:"状态 (0:禁用, 1:启用)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
CreatedAt string `json:"created_at" description:"创建时间"`
|
||||
UpdatedAt string `json:"updated_at" description:"更新时间"`
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## AI 助手必须执行的检查
|
||||
|
||||
**在创建或修改任何 DTO 文件后,必须执行以下检查:**
|
||||
|
||||
1. ✅ 检查所有字段是否有 `description` 标签
|
||||
2. ✅ 检查枚举字段是否列出了所有可能值(中文)
|
||||
3. ✅ 检查状态字段是否说明了 0 和 1 的含义
|
||||
4. ✅ 检查 validate 标签与 OpenAPI 标签是否一致
|
||||
5. ✅ 检查是否禁止使用行内注释替代 description
|
||||
6. ✅ 检查枚举值是否使用中文而非英文
|
||||
7. ✅ 重新生成 OpenAPI 文档验证:`go run cmd/gendocs/main.go`
|
||||
1. ✅ 所有字段有 `description` 标签(无行内注释)
|
||||
2. ✅ 枚举类型选择正确(状态用 int,类型/方式用 string)
|
||||
3. ✅ 禁用/启用使用 `0=禁用, 1=启用`(禁止 1=启用 2=禁用)
|
||||
4. ✅ description 枚举列表已从 `pkg/constants/` 原文抄写,无遗漏
|
||||
5. ✅ description 格式统一(冒号 `:`,括号,逗号)
|
||||
6. ✅ Response DTO 有 `_name` 伴生字段
|
||||
7. ✅ validate 标签与 OpenAPI 标签一致
|
||||
8. ✅ 重新生成 OpenAPI 文档验证:`go run cmd/gendocs/main.go`
|
||||
|
||||
**详细检查清单**: 参见 `docs/code-review-checklist.md`
|
||||
**完整枚举规范**: 参见 [`docs/enum-status-standards.md`](../../docs/enum-status-standards.md)
|
||||
|
||||
---
|
||||
|
||||
## 常见枚举字段标准值
|
||||
|
||||
```go
|
||||
// 用户类型
|
||||
// 用户类型(从 constants.UserType* 抄)
|
||||
description:"用户类型 (1:超级管理员, 2:平台用户, 3:代理账号, 4:企业账号)"
|
||||
|
||||
// 角色类型
|
||||
description:"角色类型 (1:平台角色, 2:客户角色)"
|
||||
// 通用启用/禁用(从 constants.StatusEnabled/Disabled 抄)
|
||||
description:"状态 (0:禁用, 1:启用)"
|
||||
|
||||
// 充值状态(从 constants.RechargeStatus* 抄)
|
||||
description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款)"
|
||||
|
||||
// 权限类型
|
||||
description:"权限类型 (1:菜单, 2:按钮)"
|
||||
@@ -141,9 +241,6 @@ description:"权限类型 (1:菜单, 2:按钮)"
|
||||
// 适用端口
|
||||
description:"适用端口 (all:全部, web:Web后台, h5:H5端)"
|
||||
|
||||
// 状态
|
||||
description:"状态 (0:禁用, 1:启用)"
|
||||
|
||||
// 店铺层级
|
||||
description:"店铺层级 (1-7级)"
|
||||
```
|
||||
|
||||
1
.claude/skills/grill-me
Symbolic link
1
.claude/skills/grill-me
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/grill-me
|
||||
1
.claude/skills/grill-with-docs
Symbolic link
1
.claude/skills/grill-with-docs
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/grill-with-docs
|
||||
1
.claude/skills/handoff
Symbolic link
1
.claude/skills/handoff
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/handoff
|
||||
777
.claude/skills/hurl-test/SKILL.md
Normal file
777
.claude/skills/hurl-test/SKILL.md
Normal file
@@ -0,0 +1,777 @@
|
||||
---
|
||||
name: hurl-test
|
||||
description: Hurl 接口测试生成器。用户描述要测试的接口或业务流程,自动探索代码、确认需求、生成完整的 .hurl 测试文件(含 DTO 驱动的字段完整性断言)。触发词:测试、hurl、写测试、接口测试。
|
||||
---
|
||||
|
||||
# Hurl 接口测试生成器
|
||||
|
||||
**用户描述要测试什么,你来读代码、问确认、生成 .hurl 文件。**
|
||||
|
||||
适用于任何后端项目(Go / Python / Node / Java 等),不预设框架和目录结构。
|
||||
|
||||
---
|
||||
|
||||
## 触发条件
|
||||
|
||||
以下情况必须使用本 Skill:
|
||||
- 用户说"测试 XX 接口"、"写 hurl 测试"、"给 XX 加测试"
|
||||
- 用户说"测试 XX 流程"、"测试 XX 的业务逻辑"
|
||||
- 用户说"验证 XX 接口的字段"、"测试接口契约"
|
||||
- 用户提到 hurl、.hurl、接口测试、集成测试、冒烟测试
|
||||
|
||||
---
|
||||
|
||||
## 四阶段工作流(必须按顺序执行)
|
||||
|
||||
```
|
||||
Phase 1: 探索 → Phase 2: 确认 → Phase 3: 生成 → Phase 4: 验证
|
||||
读代码搞清楚 展示给用户确认 输出 .hurl 文件 语法检查 + 试跑
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Phase 1: 探索(Explore)
|
||||
|
||||
**目标:读代码,搞清楚项目约定 + 涉及的接口 + 字段 + 依赖。**
|
||||
|
||||
#### 1.1 项目画像(首次使用时必须执行,后续复用)
|
||||
|
||||
首次为项目生成 Hurl 测试时,先回答以下问题(通过读代码,不要猜):
|
||||
|
||||
| 问题 | 怎么找 |
|
||||
|------|--------|
|
||||
| **语言/框架** | 看 go.mod / package.json / requirements.txt / pom.xml |
|
||||
| **路由注册在哪** | 搜索 `router`、`app.Get`、`@GetMapping`、`@app.route` 等关键词 |
|
||||
| **请求/响应 schema 定义在哪** | 搜索 DTO / schema / serializer / model 目录,看 json tag 或装饰器 |
|
||||
| **统一响应格式是什么** | 找 response helper 文件(如 `response.go`、`response.py`),记录 JSON 结构 |
|
||||
| **认证方式是什么** | 找 auth middleware,确定是 Bearer Token / Cookie / API Key / Basic Auth |
|
||||
| **登录接口是什么** | 找登录 handler,记录路径、请求体、响应中 token 的位置 |
|
||||
| **分页格式是什么** | 找列表接口的响应结构,记录 items/total/page 等字段名 |
|
||||
| **已有 hurl 测试吗** | 搜索 `*.hurl` 文件,复用已有的约定 |
|
||||
|
||||
将画像结果**写入 `tests/hurl/.project-profile.md` 文件持久化保存**。
|
||||
|
||||
#### 画像持久化(关键机制)
|
||||
|
||||
**首次使用时**:完成 1.1 探索后,将画像写入 `tests/hurl/.project-profile.md`,格式如下:
|
||||
|
||||
```markdown
|
||||
# 项目画像(Hurl 测试自动生成用)
|
||||
<!-- 由 hurl-test skill 自动生成,请勿手动修改 -->
|
||||
<!-- 如需刷新,删除此文件后重新运行 skill -->
|
||||
|
||||
## 技术栈
|
||||
- 语言: Go 1.25
|
||||
- 框架: Fiber v2
|
||||
- ORM: GORM
|
||||
|
||||
## 路由定义位置
|
||||
- 路由注册入口: internal/routes/routes.go
|
||||
- 按模块拆分: internal/routes/{module}.go
|
||||
- 路由注册函数: Register(router, doc, basePath, method, path, handler, spec)
|
||||
|
||||
## Schema 定义位置
|
||||
- DTO 目录: internal/model/dto/
|
||||
- 命名规则: {module}_dto.go
|
||||
- 字段标签: json / validate / description
|
||||
|
||||
## 统一响应格式
|
||||
{code: int, msg: string, data: any, timestamp: string(RFC3339)}
|
||||
- 成功: code=0, msg="success"
|
||||
- 错误: code!=0
|
||||
|
||||
## 分页格式
|
||||
{items: [], total: int, page: int, size: int}
|
||||
- 包裹在 data 字段内: $.data.items / $.data.total
|
||||
|
||||
## 认证方式
|
||||
- 后台: POST /api/auth/admin-login → $.data.access_token → Authorization: Bearer {token}
|
||||
- C端: JWT → Authorization: Bearer {token}
|
||||
|
||||
## 默认测试账号
|
||||
- 用户名: admin
|
||||
- 密码: Admin@123456
|
||||
|
||||
## 服务端口
|
||||
- 默认: 3000
|
||||
```
|
||||
|
||||
**后续使用时**:检查 `tests/hurl/.project-profile.md` 是否存在:
|
||||
- **存在** → 直接读取,跳过 1.1 的探索步骤,节省时间
|
||||
- **不存在** → 执行 1.1 完整探索,然后生成此文件
|
||||
- **用户说"刷新画像"** → 删除旧文件,重新执行 1.1
|
||||
|
||||
#### 1.2 找接口定义
|
||||
|
||||
根据用户要测的模块,定位路由注册代码,提取:
|
||||
|
||||
- **HTTP 方法**(GET / POST / PUT / DELETE / PATCH)
|
||||
- **路由路径**(含路径参数格式,如 `/users/:id` 或 `/users/{id}`)
|
||||
- **接口说明**(注释、Summary、装饰器描述)
|
||||
- **是否需要认证**
|
||||
- **请求 schema 类型名**(Input / Request DTO)
|
||||
- **响应 schema 类型名**(Output / Response DTO)
|
||||
|
||||
#### 1.3 读 schema 定义(DTO / struct / class / type)
|
||||
|
||||
定位请求和响应的 schema 定义文件,提取每个字段的:
|
||||
|
||||
- **字段名**:JSON 序列化后的名称(json tag / @JsonProperty / serializer field)
|
||||
- **语言类型**:string / int / bool / 数组 / 嵌套对象 / 可空等
|
||||
- **是否必填**:validate tag / required 装饰器 / 非空标注
|
||||
- **是否可空**:指针类型 / Optional / nullable
|
||||
- **是否参与序列化**:`json:"-"` / @JsonIgnore / exclude
|
||||
- **是否 omitempty**:`json:",omitempty"` / 条件序列化
|
||||
- **字段描述**:description tag / docstring / 注释
|
||||
|
||||
#### 1.4 识别业务依赖
|
||||
|
||||
读 service / business logic 层,识别:
|
||||
|
||||
- 创建操作需要哪些前置数据(如创建订单需要先有商品和用户)
|
||||
- 是否有唯一性约束(如用户名不能重复)
|
||||
- 是否依赖外部服务(支付网关、短信、OAuth 等)
|
||||
- 业务流转逻辑(状态机、级联操作)
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: 确认(Clarify)
|
||||
|
||||
**目标:向用户展示发现的内容,确认模糊点。不要闷头生成。**
|
||||
|
||||
#### 2.1 必须展示的内容
|
||||
|
||||
```
|
||||
我梳理了相关代码,发现以下信息:
|
||||
|
||||
📋 涉及接口:
|
||||
- [方法] [路径] - [说明](认证: 是/否)
|
||||
- ...
|
||||
|
||||
📦 响应字段(基于 {SchemaName}):
|
||||
- [字段名]: [类型] - [说明]
|
||||
- ...(共 N 个字段,将全部生成断言)
|
||||
|
||||
🔗 依赖关系:
|
||||
- [创建 X 需要先创建 Y]
|
||||
- ...
|
||||
|
||||
⚠️ 特殊情况:
|
||||
- [涉及外部服务 / 文件上传 / 特殊认证等]
|
||||
```
|
||||
|
||||
#### 2.2 按需确认(只问有歧义的)
|
||||
|
||||
| 场景 | 要问的 |
|
||||
|------|--------|
|
||||
| 流程范围不明确 | "要测到哪一步?" |
|
||||
| 多种用户角色 | "用哪种身份测?" |
|
||||
| 是否测异常 | "需要包含异常 case 吗?(参数校验失败、权限不足等)" |
|
||||
| 是否测数据隔离 | "需要验证不同用户间数据不可见吗?" |
|
||||
| 涉及第三方 | "XX 部分怎么处理?绕过 / 模拟回调 / 跳过?" |
|
||||
| 前置数据来源 | "XX 依赖数据是通过 API 创建还是假设已存在?" |
|
||||
|
||||
**如果用户说"越完整越好"或"都要"→ 默认全部包含,不再追问。**
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: 生成(Generate)
|
||||
|
||||
**目标:生成完整的 .hurl 文件,字段断言基于 schema 代码,不能编造。**
|
||||
|
||||
#### 3.1 文件头注释
|
||||
|
||||
```hurl
|
||||
# ============================================================
|
||||
# 测试:{测试名称}
|
||||
# 生成时间:{日期}
|
||||
# 涉及模块:{module1, module2, ...}
|
||||
# 涉及接口:{N} 个
|
||||
# 断言数量:{N} 条
|
||||
# 前置条件:{服务运行 + 必要的前置条件}
|
||||
# ============================================================
|
||||
# 流程:
|
||||
# 1. {步骤描述}
|
||||
# 2. {步骤描述}
|
||||
# ...
|
||||
# ============================================================
|
||||
```
|
||||
|
||||
#### 3.2 请求生成规则
|
||||
|
||||
**认证**:
|
||||
|
||||
- 根据 Phase 1 画像中的登录接口和 token 位置生成
|
||||
- token 必须通过 `[Captures]` 捕获,后续请求引用
|
||||
- 如果是 Cookie 认证,用 `[Cookies]` 或 cookie capture
|
||||
|
||||
**CRUD 标准模式**:
|
||||
|
||||
| 操作 | 生成要求 |
|
||||
|------|---------|
|
||||
| **创建(POST)** | capture 返回的 ID;唯一字段用 `{{newUuid}}` 防冲突 |
|
||||
| **查询详情(GET)** | **逐字段断言**(类型 + 值,见 3.3) |
|
||||
| **查询列表(GET)** | 分页结构断言 + items[0] 逐字段断言 |
|
||||
| **修改(PUT/PATCH)** | 修改后**紧跟一个 GET 验证修改生效** |
|
||||
| **删除(DELETE)** | 删除后**紧跟一个 GET 验证已删除** |
|
||||
|
||||
**业务流程模式**:
|
||||
|
||||
- 按用户描述的流程顺序编排请求
|
||||
- 上一步的输出(ID、状态等)通过 `[Captures]` 传给下一步
|
||||
- 关键步骤加中间状态验证(如创建订单后验证状态为"待支付")
|
||||
|
||||
#### 3.3 schema 到断言的映射
|
||||
|
||||
读到 schema 字段后,按以下规则生成 jsonpath 断言:
|
||||
|
||||
**通用类型映射(所有语言)**:
|
||||
|
||||
| Schema 类型特征 | Hurl 断言 |
|
||||
|----------------|-----------|
|
||||
| 字符串(string / str / String) | `isString` |
|
||||
| 整数(int / integer / long / Int) | `isInteger` |
|
||||
| 浮点(float / double / decimal / Float) | `isNumber` |
|
||||
| 布尔(bool / boolean / Boolean) | `isBoolean` |
|
||||
| 数组 / 列表([] / List / Array) | `isList` |
|
||||
| 嵌套对象(struct / class / dict / object) | `isObject`,并递归检查子字段 |
|
||||
| 可空类型(指针 / Optional / nullable) | `exists`(不强制类型,因为可能是 null) |
|
||||
| 不参与序列化(json:"-" / @JsonIgnore / exclude=True) | **跳过,不生成断言** |
|
||||
| 条件序列化(omitempty / if not None) | `exists` 或不生成(取决于场景) |
|
||||
|
||||
**Go 特定映射**:
|
||||
|
||||
| Go 类型 | Hurl 断言 |
|
||||
|---------|-----------|
|
||||
| `string` | `isString` |
|
||||
| `int`, `int8/16/32/64`, `uint`, `uint8/16/32/64` | `isInteger` |
|
||||
| `float32`, `float64` | `isNumber` |
|
||||
| `bool` | `isBoolean` |
|
||||
| `[]T` | `isList` |
|
||||
| `*string`, `*int`, `*uint` 等指针 | `exists` |
|
||||
| `time.Time` | `isString`(通常序列化为字符串) |
|
||||
| `map[string]any` | `isObject` |
|
||||
|
||||
**Python 特定映射(Pydantic / Django / FastAPI)**:
|
||||
|
||||
| Python 类型 | Hurl 断言 |
|
||||
|------------|-----------|
|
||||
| `str` | `isString` |
|
||||
| `int` | `isInteger` |
|
||||
| `float`, `Decimal` | `isNumber` |
|
||||
| `bool` | `isBoolean` |
|
||||
| `list[T]`, `List[T]` | `isList` |
|
||||
| `Optional[T]`, `T | None` | `exists` |
|
||||
| `dict`, `Dict` | `isObject` |
|
||||
| `datetime`, `date` | `isString` |
|
||||
|
||||
**TypeScript/JavaScript 特定映射**:
|
||||
|
||||
| TS/JS 类型 | Hurl 断言 |
|
||||
|-----------|-----------|
|
||||
| `string` | `isString` |
|
||||
| `number`(整数上下文) | `isInteger` |
|
||||
| `number`(通用) | `isNumber` |
|
||||
| `boolean` | `isBoolean` |
|
||||
| `T[]`, `Array<T>` | `isList` |
|
||||
| `T \| null`, `T \| undefined` | `exists` |
|
||||
| `object`, `Record<>` | `isObject` |
|
||||
| `Date` | `isString` |
|
||||
|
||||
**Java 特定映射**:
|
||||
|
||||
| Java 类型 | Hurl 断言 |
|
||||
|----------|-----------|
|
||||
| `String` | `isString` |
|
||||
| `Integer`, `Long`, `int`, `long` | `isInteger` |
|
||||
| `Double`, `Float`, `BigDecimal` | `isNumber` |
|
||||
| `Boolean`, `boolean` | `isBoolean` |
|
||||
| `List<T>` | `isList` |
|
||||
| `@Nullable`, `Optional<T>` | `exists` |
|
||||
| `Map<K,V>` | `isObject` |
|
||||
| `LocalDateTime`, `Instant` | `isString` |
|
||||
|
||||
#### 3.4 统一响应格式断言
|
||||
|
||||
根据 Phase 1 画像中发现的统一响应格式,为**每个成功响应**添加格式断言。
|
||||
|
||||
示例:如果项目的统一格式是 `{code, msg, data, timestamp}`:
|
||||
|
||||
```hurl
|
||||
[Asserts]
|
||||
jsonpath "$.code" == 0
|
||||
jsonpath "$.msg" == "success"
|
||||
jsonpath "$.timestamp" isIsoDate
|
||||
```
|
||||
|
||||
示例:如果项目的格式是 `{status, message, result}`:
|
||||
|
||||
```hurl
|
||||
[Asserts]
|
||||
jsonpath "$.status" == "ok"
|
||||
jsonpath "$.message" isString
|
||||
```
|
||||
|
||||
示例:如果项目无统一包装,直接返回数据:
|
||||
|
||||
```hurl
|
||||
[Asserts]
|
||||
# 直接断言业务字段
|
||||
jsonpath "$.id" isInteger
|
||||
jsonpath "$.name" isString
|
||||
```
|
||||
|
||||
**不要假设响应格式,必须从代码中确认。**
|
||||
|
||||
#### 3.5 分页断言
|
||||
|
||||
根据 Phase 1 画像中发现的分页结构生成。
|
||||
|
||||
示例:如果是 `{items, total, page, size}` 格式:
|
||||
|
||||
```hurl
|
||||
jsonpath "$.data.items" isList
|
||||
jsonpath "$.data.total" isInteger
|
||||
jsonpath "$.data.total" >= 1
|
||||
jsonpath "$.data.page" isInteger
|
||||
jsonpath "$.data.size" isInteger
|
||||
# items 内元素逐字段断言
|
||||
jsonpath "$.data.items[0].{field}" {type_assert}
|
||||
```
|
||||
|
||||
示例:如果是 `{results, count, next, previous}` 格式(Django 风格):
|
||||
|
||||
```hurl
|
||||
jsonpath "$.results" isList
|
||||
jsonpath "$.count" isInteger
|
||||
jsonpath "$.count" >= 1
|
||||
# results 内元素逐字段断言
|
||||
jsonpath "$.results[0].{field}" {type_assert}
|
||||
```
|
||||
|
||||
**根据实际代码调整字段名,不硬编码。**
|
||||
|
||||
#### 3.6 异常 Case 模板
|
||||
|
||||
**参数校验失败**:
|
||||
|
||||
```hurl
|
||||
# ── 异常:参数校验失败 ──
|
||||
POST {{base_url}}/{path}
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
{
|
||||
"required_field": ""
|
||||
}
|
||||
HTTP {expected_error_status}
|
||||
[Asserts]
|
||||
# 断言错误响应格式(根据项目约定调整)
|
||||
```
|
||||
|
||||
> HTTP 状态码根据项目实际返回确定:有的项目错误也返回 200 + 业务错误码,有的返回 400/422。
|
||||
|
||||
**未认证访问**:
|
||||
|
||||
```hurl
|
||||
# ── 异常:未认证访问 ──
|
||||
GET {{base_url}}/{protected_path}
|
||||
HTTP {expected_unauth_status}
|
||||
```
|
||||
|
||||
**越权访问**(如果用户要求):
|
||||
|
||||
```hurl
|
||||
# ── 异常:用户 B 不能访问用户 A 的资源 ──
|
||||
GET {{base_url}}/{path}/{{user_a_resource_id}}
|
||||
Authorization: Bearer {{user_b_token}}
|
||||
HTTP {expected_forbidden_status}
|
||||
```
|
||||
|
||||
#### 3.7 特殊场景处理
|
||||
|
||||
| 场景 | 处理策略 |
|
||||
|------|---------|
|
||||
| **短信/邮件验证码** | 建议服务端加 test_mode 开关,固定验证码写入 env 文件;注释提醒用户 |
|
||||
| **第三方支付** | 优先用项目内部支付方式(如钱包支付);如需测回调,直接 POST 回调接口模拟 |
|
||||
| **OAuth 登录(微信/Google/GitHub)** | 建议服务端加 test_mode 支持直接传 openid/email;注释提醒用户 |
|
||||
| **文件上传** | 用 Hurl 的 `[Multipart]` 语法 + testdata 目录下的样本文件 |
|
||||
| **外部 API 依赖** | 只测参数校验和错误响应格式,不断言业务结果;注释说明依赖 |
|
||||
| **WebSocket** | Hurl 不支持,注释说明跳过 |
|
||||
| **异步任务结果** | 用 Hurl 的 `retry` + `retry-interval` 轮询直到状态变更 |
|
||||
|
||||
异步轮询示例:
|
||||
|
||||
```hurl
|
||||
# 等待异步任务完成(最多重试 10 次,间隔 500ms)
|
||||
GET {{base_url}}/{path}/{{task_id}}
|
||||
Authorization: Bearer {{token}}
|
||||
[Options]
|
||||
retry: 10
|
||||
retry-interval: 500ms
|
||||
HTTP 200
|
||||
[Asserts]
|
||||
jsonpath "$.data.status" == "completed"
|
||||
```
|
||||
|
||||
#### 3.8 文件输出
|
||||
|
||||
**目录结构**(首次使用时创建,如不存在):
|
||||
|
||||
```
|
||||
tests/hurl/
|
||||
├── env/
|
||||
│ └── dev.env # 环境变量
|
||||
├── testdata/ # 测试用的样本文件
|
||||
├── flows/ # 业务流程测试
|
||||
├── modules/ # 按模块的接口测试
|
||||
│ └── {module}/
|
||||
│ └── 01-crud.hurl
|
||||
├── negative/ # 异常/边界测试
|
||||
├── contract/ # 接口契约验证
|
||||
└── Makefile # 快捷命令
|
||||
```
|
||||
|
||||
文件放置规则:
|
||||
|
||||
| 用户描述 | 输出路径 |
|
||||
|---------|---------|
|
||||
| 测试 XX 流程 / 业务流程 | `tests/hurl/flows/{flow-name}.hurl` |
|
||||
| 测试 XX 模块的 CRUD / 接口 | `tests/hurl/modules/{module}/01-crud.hurl` |
|
||||
| 测试异常/边界/权限 | `tests/hurl/negative/{name}.hurl` |
|
||||
| 测试接口契约/字段对齐 | `tests/hurl/contract/{name}.hurl` |
|
||||
|
||||
**如果项目已有 hurl 测试目录结构,沿用已有约定,不要另起炉灶。**
|
||||
|
||||
#### 3.9 env 和 Makefile
|
||||
|
||||
**env/dev.env**(首次创建时生成,内容基于 Phase 1 画像):
|
||||
|
||||
```properties
|
||||
# 服务地址
|
||||
base_url=http://localhost:{port}
|
||||
|
||||
# 认证信息(根据项目实际填写)
|
||||
admin_username={默认用户名}
|
||||
admin_password={默认密码}
|
||||
|
||||
# 测试模式变量(如果有特殊场景)
|
||||
# test_sms_code=888888
|
||||
# test_openid=test_openid_001
|
||||
```
|
||||
|
||||
**Makefile**(首次创建时生成):
|
||||
|
||||
```makefile
|
||||
SHELL := /bin/bash
|
||||
ENV ?= dev
|
||||
HURL_OPTS := --variables-file env/$(ENV).env --test
|
||||
|
||||
.PHONY: test test-flows test-modules test-negative report
|
||||
|
||||
test: ## 运行所有测试
|
||||
hurl $(HURL_OPTS) .
|
||||
|
||||
test-flows: ## 运行业务流程测试
|
||||
hurl $(HURL_OPTS) flows/
|
||||
|
||||
test-modules: ## 运行模块接口测试
|
||||
hurl $(HURL_OPTS) modules/
|
||||
|
||||
test-negative: ## 运行异常测试
|
||||
hurl $(HURL_OPTS) negative/
|
||||
|
||||
report: ## 生成 HTML 报告
|
||||
hurl $(HURL_OPTS) --report-html build/report/ .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Phase 4: 验证(Verify)
|
||||
|
||||
**目标:确保生成的 .hurl 文件语法正确、可运行。**
|
||||
|
||||
#### 4.1 语法自检
|
||||
|
||||
- [ ] 每个请求之间有空行分隔
|
||||
- [ ] `[Captures]` 和 `[Asserts]` 拼写正确(大小写敏感)
|
||||
- [ ] 所有 `{{变量}}` 引用都有来源(env 文件定义 或 上游 `[Captures]`)
|
||||
- [ ] JSON body 无尾逗号、格式正确
|
||||
- [ ] `HTTP {status}` 在请求之后、`[Captures]` / `[Asserts]` 之前
|
||||
- [ ] 请求和断言之间没有多余空行(`HTTP` 行必须紧跟请求)
|
||||
- [ ] 文件上传路径相对于 hurl 文件位置正确
|
||||
|
||||
#### 4.2 运行测试
|
||||
|
||||
```bash
|
||||
hurl --variables-file tests/hurl/env/dev.env --test tests/hurl/{生成的文件}
|
||||
```
|
||||
|
||||
- 服务在跑 → 执行,如有失败分析修正
|
||||
- 服务没跑 → 跳过,告知用户手动验证命令
|
||||
|
||||
---
|
||||
|
||||
## 红线规则
|
||||
|
||||
| 规则 | 说明 |
|
||||
|------|------|
|
||||
| **不跳过 Phase 1** | 必须读代码确认接口路径和字段,不能凭记忆或猜测 |
|
||||
| **不跳过 Phase 2** | 必须向用户展示发现的接口和字段,确认后再生成 |
|
||||
| **不编造字段** | 所有断言的字段名必须来自实际 schema 代码 |
|
||||
| **不编造路径** | 所有接口路径必须来自实际路由代码 |
|
||||
| **不遗漏字段** | schema 中每个参与序列化的字段都必须有对应断言 |
|
||||
| **不硬编码 ID** | 所有依赖的 ID 通过 `[Captures]` 从上游请求获取 |
|
||||
| **不假设响应格式** | 统一响应结构必须从代码中确认,不同项目格式不同 |
|
||||
| **唯一值防冲突** | 创建类请求的唯一字段使用 `{{newUuid}}` 或 `{{newDate}}` |
|
||||
| **自给自足** | 每个 .hurl 文件自己创建测试数据,不依赖外部数据准备 |
|
||||
|
||||
---
|
||||
|
||||
## AI 助手检查清单
|
||||
|
||||
生成 .hurl 文件后自检:
|
||||
|
||||
1. ✅ 文件头注释包含流程描述和前置条件
|
||||
2. ✅ 认证步骤正确 capture 了 token / cookie
|
||||
3. ✅ 所有依赖数据通过 API 链式创建(自给自足)
|
||||
4. ✅ 每个成功响应断言了项目的统一响应格式
|
||||
5. ✅ 查询详情接口**逐字段断言**(类型 + 值,基于 schema)
|
||||
6. ✅ 分页接口断言了分页结构 + 第一条记录的字段
|
||||
7. ✅ 修改操作后紧跟 GET 验证修改生效
|
||||
8. ✅ 删除操作后紧跟 GET 验证已删除
|
||||
9. ✅ 唯一字段使用了 `{{newUuid}}`
|
||||
10. ✅ `{{变量}}` 引用无悬空(都有 env 或 capture 来源)
|
||||
11. ✅ 文件放在了正确的目录位置
|
||||
12. ✅ 特殊场景有明确的处理策略和注释提醒
|
||||
|
||||
---
|
||||
|
||||
## 附录:Hurl 语法速查
|
||||
|
||||
**生成 .hurl 文件时必须参照本速查,不可凭记忆编造语法。**
|
||||
|
||||
### 文件结构
|
||||
|
||||
一个 .hurl 文件由多个 entry 组成,每个 entry = 请求 + 可选响应:
|
||||
|
||||
```
|
||||
请求1
|
||||
响应1(可选)
|
||||
|
||||
请求2
|
||||
响应2(可选)
|
||||
```
|
||||
|
||||
entry 之间用空行分隔。
|
||||
|
||||
### 请求格式
|
||||
|
||||
```hurl
|
||||
METHOD URL
|
||||
Header1: value1
|
||||
Header2: value2
|
||||
[Options]
|
||||
key: value
|
||||
[Query]
|
||||
param1: value1
|
||||
[Form]
|
||||
field1: value1
|
||||
[Multipart]
|
||||
file1: file,path/to/file;
|
||||
[BasicAuth]
|
||||
username: password
|
||||
[Cookies]
|
||||
name: value
|
||||
BODY(JSON / XML / multiline string / file)
|
||||
```
|
||||
|
||||
**规则**:
|
||||
- Method + URL 是第一行,必须
|
||||
- Headers 紧跟 URL 之后(无 section 标记)
|
||||
- Sections(`[Query]`、`[Form]`、`[Options]` 等)顺序任意
|
||||
- Body 必须在最后
|
||||
- JSON body 直接写 `{ }` 即可,自动设置 Content-Type: application/json
|
||||
|
||||
### 响应格式
|
||||
|
||||
```hurl
|
||||
HTTP {status_code}
|
||||
Header1: expected_value1
|
||||
[Captures]
|
||||
var_name: jsonpath "$.path"
|
||||
[Asserts]
|
||||
jsonpath "$.field" == "value"
|
||||
```
|
||||
|
||||
**规则**:
|
||||
- `HTTP {status}` 紧跟请求之后(中间不能有空行)
|
||||
- `HTTP *` 表示不检查状态码
|
||||
- Headers 检查紧跟 HTTP 行之后
|
||||
- `[Captures]` 和 `[Asserts]` 顺序任意
|
||||
|
||||
### 变量和模板
|
||||
|
||||
```hurl
|
||||
# 引用变量(从 env 文件、命令行或上游 capture 获取)
|
||||
GET {{base_url}}/api/users/{{user_id}}
|
||||
|
||||
# 内置函数
|
||||
POST {{base_url}}/api/users
|
||||
{
|
||||
"email": "{{newUuid}}@test.com",
|
||||
"created_at": "{{newDate}}"
|
||||
}
|
||||
```
|
||||
|
||||
可用函数:
|
||||
- `{{newUuid}}` — 生成 UUID v4
|
||||
- `{{newDate}}` — 生成 RFC 3339 UTC 时间戳
|
||||
|
||||
### Capture 语法
|
||||
|
||||
```hurl
|
||||
[Captures]
|
||||
# JSONPath
|
||||
token: jsonpath "$.data.access_token"
|
||||
user_id: jsonpath "$.data.id"
|
||||
first_item: jsonpath "$.items[0].name"
|
||||
|
||||
# Header
|
||||
location: header "Location"
|
||||
|
||||
# Cookie
|
||||
session: cookie "SESSIONID"
|
||||
|
||||
# Body(整个响应体作为字符串)
|
||||
full_body: body
|
||||
|
||||
# Status code
|
||||
code: status
|
||||
|
||||
# 正则表达式
|
||||
csrf: regex "name=\"csrf\" value=\"([^\"]+)\""
|
||||
|
||||
# 响应时间(毫秒)
|
||||
response_time: duration
|
||||
```
|
||||
|
||||
### Assert 语法
|
||||
|
||||
```hurl
|
||||
[Asserts]
|
||||
# ── 状态码 ──
|
||||
status == 200
|
||||
status >= 200
|
||||
status < 300
|
||||
|
||||
# ── JSONPath 断言 ──
|
||||
jsonpath "$.name" == "Alice" # 等于
|
||||
jsonpath "$.name" != "Bob" # 不等于
|
||||
jsonpath "$.age" > 18 # 大于
|
||||
jsonpath "$.age" >= 18 # 大于等于
|
||||
jsonpath "$.count" < 100 # 小于
|
||||
jsonpath "$.items" count == 5 # 集合长度
|
||||
jsonpath "$.name" startsWith "Al" # 前缀
|
||||
jsonpath "$.name" endsWith "ce" # 后缀
|
||||
jsonpath "$.name" contains "lic" # 包含
|
||||
jsonpath "$.date" matches /\\d{4}-\\d{2}-\\d{2}/ # 正则
|
||||
|
||||
# ── 类型断言 ──
|
||||
jsonpath "$.name" isString
|
||||
jsonpath "$.age" isInteger
|
||||
jsonpath "$.score" isFloat
|
||||
jsonpath "$.count" isNumber # 整数或浮点
|
||||
jsonpath "$.active" isBoolean
|
||||
jsonpath "$.items" isList
|
||||
jsonpath "$.meta" isObject
|
||||
jsonpath "$.id" isUuid
|
||||
jsonpath "$.created_at" isIsoDate # RFC 3339 格式
|
||||
jsonpath "$.field" isEmpty # 空集合
|
||||
|
||||
# ── 存在性 ──
|
||||
jsonpath "$.field" exists
|
||||
jsonpath "$.field" not exists
|
||||
|
||||
# ── 否定 ──
|
||||
jsonpath "$.name" not contains "Bob"
|
||||
jsonpath "$.status" not == "deleted"
|
||||
|
||||
# ── Header 断言 ──
|
||||
header "Content-Type" contains "application/json"
|
||||
header "X-Request-Id" exists
|
||||
|
||||
# ── 性能 ──
|
||||
duration < 1000 # 响应时间(毫秒)
|
||||
|
||||
# ── Body 断言 ──
|
||||
body contains "Hello"
|
||||
bytes count == 1024
|
||||
```
|
||||
|
||||
### Options(逐请求配置)
|
||||
|
||||
```hurl
|
||||
GET {{base_url}}/api/task/{{task_id}}
|
||||
[Options]
|
||||
retry: 10 # 最大重试次数(-1 = 无限)
|
||||
retry-interval: 500ms # 重试间隔
|
||||
delay: 2s # 请求前等待
|
||||
location: true # 跟随重定向
|
||||
insecure: true # 允许不安全 SSL
|
||||
verbose: true # 输出详细日志
|
||||
very-verbose: true # 输出更详细日志
|
||||
skip: true # 跳过此请求
|
||||
variable: key=value # 定义变量
|
||||
HTTP 200
|
||||
```
|
||||
|
||||
### Multipart 文件上传
|
||||
|
||||
```hurl
|
||||
POST {{base_url}}/api/upload
|
||||
[Multipart]
|
||||
file: file,testdata/sample.xlsx;
|
||||
field1: value1
|
||||
# 指定 Content-Type
|
||||
file2: file,testdata/data.bin; application/octet-stream
|
||||
```
|
||||
|
||||
### 运行命令
|
||||
|
||||
```bash
|
||||
# 运行单个文件
|
||||
hurl --test file.hurl
|
||||
|
||||
# 带变量文件
|
||||
hurl --variables-file env/dev.env --test file.hurl
|
||||
|
||||
# 运行目录下所有 .hurl
|
||||
hurl --test tests/hurl/
|
||||
|
||||
# 生成 HTML 报告
|
||||
hurl --test --report-html build/report/ tests/hurl/
|
||||
|
||||
# 生成 JUnit 报告(CI 用)
|
||||
hurl --test --report-junit build/report.xml tests/hurl/
|
||||
|
||||
# 并行执行(--test 默认并行,同文件内串行)
|
||||
hurl --test --jobs 4 tests/hurl/
|
||||
|
||||
# 指定单个变量
|
||||
hurl --variable base_url=http://localhost:3000 --test file.hurl
|
||||
|
||||
# 失败后继续执行
|
||||
hurl --test --continue-on-error tests/hurl/
|
||||
```
|
||||
|
||||
### 常见错误
|
||||
|
||||
| 错误 | 原因 | 修正 |
|
||||
|------|------|------|
|
||||
| `HTTP 200` 和请求之间有空行 | 空行会被当作 entry 分隔符 | 删除空行,HTTP 行紧跟请求 |
|
||||
| JSON body 有尾逗号 | Hurl 严格解析 JSON | 删除最后一个逗号 |
|
||||
| `jsonpath` 写成 `json_path` 或 `JsonPath` | 关键字大小写敏感 | 必须小写 `jsonpath` |
|
||||
| `[Captures]` 写成 `[Capture]` | 必须是复数 | `[Captures]`、`[Asserts]`、`[Options]` |
|
||||
| 变量 `{{ var }}` 有空格 | 允许,但建议统一 | `{{var}}` 或 `{{ var }}` 都可以 |
|
||||
| `isIsoDate` 用在非 RFC 3339 格式 | 只认 `YYYY-MM-DDTHH:mm:ss` 格式 | 如果是其他格式用 `matches` |
|
||||
| `file,path;` 路径含 `..` | Hurl 禁止相对父目录 | 用 `--file-root` 或调整路径 |
|
||||
1
.claude/skills/improve-codebase-architecture
Symbolic link
1
.claude/skills/improve-codebase-architecture
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/improve-codebase-architecture
|
||||
97
.claude/skills/openspec-api-contract/SKILL.md
Normal file
97
.claude/skills/openspec-api-contract/SKILL.md
Normal file
@@ -0,0 +1,97 @@
|
||||
---
|
||||
name: openspec-api-contract
|
||||
description: OpenSpec API 契约规范。创建涉及接口的 OpenSpec 提案时使用。探索阶段提供业务与契约引导清单,提案文档要求 API 契约设计、错误码与完成标准等必填章节。
|
||||
---
|
||||
|
||||
# OpenSpec API 契约规范
|
||||
|
||||
**适用场景**:创建涉及 API/接口的 OpenSpec 提案时,探索和提案两个阶段均须遵守本规范。
|
||||
|
||||
---
|
||||
|
||||
## 一、探索阶段引导清单
|
||||
|
||||
在 `openspec-explore` 阶段,当内容涉及接口时,讨论必须覆盖以下所有维度。
|
||||
|
||||
### 业务与契约确认
|
||||
|
||||
**输入与输出**
|
||||
- 请求方是谁?用户类型(SuperAdmin/Platform/Agent/Enterprise/Personal)?
|
||||
- 输入参数:必填/选填字段、格式约束、参数来源(路径/查询/Body)?
|
||||
- 输出结构:哪些字段必须返回?是否需要分页?
|
||||
|
||||
**业务规则**
|
||||
- 核心业务规则与边界条件?
|
||||
- 是否涉及状态流转?状态机的完整定义?
|
||||
- 依赖外部服务时,外部异常的降级行为?
|
||||
|
||||
**权限与资源所有权**
|
||||
- 哪些用户类型可以访问?
|
||||
- 是否涉及跨用户/跨店铺/跨企业的资源访问?(需三层越权防护)
|
||||
- 资源所有权校验方式:`CanManageShop` / `CanManageEnterprise` / 自有资源?
|
||||
|
||||
**幂等性**
|
||||
- 操作类型:查询(天然幂等)/ 创建 / 更新 / 删除?
|
||||
- 写操作幂等策略:状态条件更新 / Redis 业务键防重 + 分布式锁 / 乐观锁(version)?
|
||||
- 异步任务是否需要任务锁?
|
||||
|
||||
**数据模型变更**
|
||||
- 是否需要新建表、修改现有表或数据回填?
|
||||
- 迁移策略:上线顺序、兼容旧数据的方式?
|
||||
- 是否影响 GORM Callback 自动数据权限过滤?
|
||||
|
||||
**错误码与异常语义**
|
||||
- 预期错误场景及对应错误码?
|
||||
- 错误响应是否泄露敏感信息?(参数校验失败统一返回 `CodeInvalidParam`)
|
||||
|
||||
---
|
||||
|
||||
## 二、提案文档必填章节
|
||||
|
||||
在 `openspec-propose` 生成的提案(`proposal.md` / `design.md`)中,涉及接口时以下内容**不可缺失**。
|
||||
|
||||
### API 契约设计
|
||||
|
||||
**接口定义**
|
||||
|
||||
| 项 | 内容 |
|
||||
|---|---|
|
||||
| Endpoint | `METHOD /api/{scope}/{resource}[/:id]` |
|
||||
| 请求参数 | 字段名、类型、必填/选填、说明 |
|
||||
| 响应结构 | `data` 字段的完整结构定义 |
|
||||
| 鉴权要求 | 允许的用户类型 |
|
||||
| 资源所有权 | 所有权校验方式 |
|
||||
|
||||
**列表接口额外要求**
|
||||
- 分页:`page` + `page_size`(默认 20,最大 100)
|
||||
- 排序:默认排序字段与方向
|
||||
- 过滤:支持的过滤条件列表
|
||||
|
||||
**错误码清单**
|
||||
|
||||
| 场景 | 错误码 | 说明 |
|
||||
|---|---|---|
|
||||
| 参数校验失败 | `CodeInvalidParam` | 统一返回,不泄露细节 |
|
||||
| 资源不存在/越权 | `CodeForbidden` | 不区分两者,防止信息泄露 |
|
||||
| (业务错误场景...) | (对应错误码) | (说明) |
|
||||
|
||||
### 完成标准
|
||||
|
||||
**最小验证步骤**(按顺序列出可操作的验证步骤)
|
||||
|
||||
1. (例:调用创建接口,验证返回 `code=0`)
|
||||
2. (例:查询接口确认数据存在且字段正确)
|
||||
3. (例:PostgreSQL MCP 查询确认数据库记录符合预期)
|
||||
|
||||
**影响范围说明**
|
||||
- 新增/修改的表:
|
||||
- 影响的现有接口:
|
||||
- 影响的权限与数据过滤范围:
|
||||
|
||||
---
|
||||
|
||||
## 约束(必须遵守)
|
||||
|
||||
- **优先复用现有架构与库**:不引入新依赖,错误码优先复用已有定义
|
||||
- **不做顺手重构**:提案范围严格限定在目标功能;发现可优化点,记录到 backlog 但不执行
|
||||
- **数据库设计**:禁止外键约束,禁止 GORM 关联标签,关联通过 ID 字段手动维护
|
||||
1
.claude/skills/prototype
Symbolic link
1
.claude/skills/prototype
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/prototype
|
||||
1
.claude/skills/setup-matt-pocock-skills
Symbolic link
1
.claude/skills/setup-matt-pocock-skills
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/setup-matt-pocock-skills
|
||||
@@ -1,260 +0,0 @@
|
||||
---
|
||||
name: systematic-debugging
|
||||
description: 遇到任何 bug、异常行为、报错时必须使用。在提出任何修复方案之前,强制执行根因分析流程。适用于 API 报错、数据异常、业务逻辑错误、性能问题等所有技术问题。
|
||||
---
|
||||
|
||||
# 系统化调试方法论
|
||||
|
||||
## 铁律
|
||||
|
||||
```
|
||||
没有找到根因,禁止提出任何修复方案。
|
||||
```
|
||||
|
||||
改之前先搞懂为什么坏了。猜测不是调试,验证假设才是。
|
||||
|
||||
---
|
||||
|
||||
## 什么时候用
|
||||
|
||||
**所有技术问题都用这个流程**:
|
||||
- API 接口报错(4xx / 5xx)
|
||||
- 业务数据异常(金额不对、状态流转错误)
|
||||
- 性能问题(接口慢、数据库慢查询)
|
||||
- 异步任务失败(Asynq 任务报错/卡住)
|
||||
- 构建失败、启动失败
|
||||
|
||||
**尤其是以下场景**:
|
||||
- 时间紧迫(越急越不能瞎猜)
|
||||
- "很简单的问题"(简单问题也有根因)
|
||||
- 已经试了一次修复但没解决
|
||||
- 不完全理解为什么出问题
|
||||
|
||||
---
|
||||
|
||||
## 四阶段流程
|
||||
|
||||
必须按顺序完成每个阶段,不可跳过。
|
||||
|
||||
### 阶段一:根因调查
|
||||
|
||||
**这是最重要的阶段,占整个调试时间的 60%。没完成本阶段,禁止进入阶段二。**
|
||||
|
||||
#### 1. 仔细阅读错误信息
|
||||
|
||||
- 完整阅读 stack trace,不要跳过
|
||||
- 注意行号、文件路径、错误码
|
||||
- 很多时候答案就在错误信息里
|
||||
- 检查 `logs/app.log` 和 `logs/access.log` 中的上下文
|
||||
|
||||
#### 2. 稳定复现
|
||||
|
||||
- 能稳定触发吗?精确的请求参数是什么?
|
||||
- 用 curl 或 Postman 复现,记录完整的请求和响应
|
||||
- 不能复现 → 收集更多数据(检查日志、Redis 状态、数据库记录),**不要瞎猜**
|
||||
|
||||
#### 3. 检查最近改动
|
||||
|
||||
- `git diff` / `git log --oneline -10` 看最近改了什么
|
||||
- 新加了什么依赖?改了什么配置?改了什么 SQL?
|
||||
- 对比改动前后的行为差异
|
||||
|
||||
#### 4. 逐层诊断(针对本项目架构)
|
||||
|
||||
本项目有明确的分层架构,问题一定出在某一层的边界:
|
||||
|
||||
```
|
||||
请求 → Fiber Middleware → Handler → Service → Store → PostgreSQL/Redis
|
||||
↑ ↑ ↑ ↑ ↑
|
||||
认证/限流 参数解析 业务逻辑 SQL/缓存 数据本身
|
||||
```
|
||||
|
||||
**在每个层边界确认数据是否正确**:
|
||||
|
||||
```go
|
||||
// Handler 层 — 请求进来的参数对不对?
|
||||
logger.Info("Handler 收到请求",
|
||||
zap.Any("params", req),
|
||||
zap.String("request_id", requestID),
|
||||
)
|
||||
|
||||
// Service 层 — 传给业务逻辑的数据对不对?
|
||||
logger.Info("Service 开始处理",
|
||||
zap.Uint("user_id", userID),
|
||||
zap.Any("input", input),
|
||||
)
|
||||
|
||||
// Store 层 — SQL 查询/写入的数据对不对?
|
||||
// 开启 GORM Debug 模式查看实际 SQL
|
||||
db.Debug().Where(...).Find(&result)
|
||||
|
||||
// Redis 层 — 缓存的数据对不对?
|
||||
// 用 redis-cli 直接检查 key 的值
|
||||
// GET auth:token:{token}
|
||||
// GET sim:status:{iccid}
|
||||
```
|
||||
|
||||
**跑一次 → 看日志 → 找到断裂的那一层 → 再深入该层排查。**
|
||||
|
||||
#### 5. 追踪数据流
|
||||
|
||||
如果错误深藏在调用链中:
|
||||
- 坏数据从哪来的?
|
||||
- 谁调用了这个函数,传了什么参数?
|
||||
- 一直往上追,直到找到数据变坏的源头
|
||||
- **修源头,不修症状**
|
||||
|
||||
---
|
||||
|
||||
### 阶段二:模式分析
|
||||
|
||||
**找到参照物,对比差异。**
|
||||
|
||||
#### 1. 找能用的参照
|
||||
|
||||
项目里有没有类似的、能正常工作的代码?
|
||||
|
||||
| 如果问题在... | 参照物在... |
|
||||
|-------------|-----------|
|
||||
| Handler 参数解析 | 其他 Handler 的相同模式 |
|
||||
| Service 业务逻辑 | 同模块其他方法的实现 |
|
||||
| Store SQL 查询 | 同 Store 文件中类似的查询 |
|
||||
| Redis 操作 | `pkg/constants/redis.go` 中的 Key 定义 |
|
||||
| 异步任务 | `internal/task/` 中其他任务处理器 |
|
||||
| GORM Callback | `pkg/database/` 中的 callback 实现 |
|
||||
|
||||
#### 2. 逐行对比
|
||||
|
||||
完整阅读参考代码,不要跳读。列出每一处差异。
|
||||
|
||||
#### 3. 不要假设"这个不重要"
|
||||
|
||||
小差异经常是 bug 的根因:
|
||||
- 字段标签 `gorm:"column:xxx"` 拼写不对
|
||||
- `errors.New()` 用了错误的错误码
|
||||
- Redis Key 函数参数传反了
|
||||
- Context 里的 UserID 没取到(中间件没配)
|
||||
|
||||
---
|
||||
|
||||
### 阶段三:假设和验证
|
||||
|
||||
**科学方法:一次只验证一个假设。**
|
||||
|
||||
#### 1. 形成单一假设
|
||||
|
||||
明确写下:
|
||||
|
||||
> "我认为根因是 X,因为 Y。验证方法是 Z。"
|
||||
|
||||
#### 2. 最小化验证
|
||||
|
||||
- 只改一个地方
|
||||
- 一次只验证一个变量
|
||||
- 不要同时修多处
|
||||
|
||||
#### 3. 验证结果
|
||||
|
||||
- 假设成立 → 进入阶段四
|
||||
- 假设不成立 → 回到阶段一,用新信息重新分析
|
||||
- **绝对不能在失败的修复上再叠加修复**
|
||||
|
||||
#### 4. 三次失败 → 停下来
|
||||
|
||||
如果连续 3 次假设都不成立:
|
||||
|
||||
**这不是 bug,是架构问题。**
|
||||
|
||||
- 停止一切修复尝试
|
||||
- 整理已知信息
|
||||
- 向用户说明情况,讨论是否需要重构
|
||||
- 不要再试第 4 次
|
||||
|
||||
---
|
||||
|
||||
### 阶段四:实施修复
|
||||
|
||||
**确认根因后,一次性修好。**
|
||||
|
||||
#### 1. 修根因,不修症状
|
||||
|
||||
```
|
||||
❌ 症状修复:在 Handler 里加个 if 把坏数据过滤掉
|
||||
✅ 根因修复:修 Service 层生成坏数据的逻辑
|
||||
```
|
||||
|
||||
#### 2. 一次只改一个地方
|
||||
|
||||
- 不搞"顺手优化"
|
||||
- 不在修 bug 的同时重构代码
|
||||
- 修完 bug 就停
|
||||
|
||||
#### 3. 验证修复
|
||||
|
||||
- `go build ./...` 编译通过
|
||||
- `lsp_diagnostics` 无新增错误
|
||||
- 用原来复现 bug 的请求再跑一次,确认修好了
|
||||
- 用 PostgreSQL MCP 工具检查数据库中的数据状态
|
||||
|
||||
#### 4. 清理诊断代码
|
||||
|
||||
- 删除阶段一加的临时诊断日志(除非它们本身就该保留)
|
||||
- 确保没有 `db.Debug()` 残留在代码里
|
||||
|
||||
---
|
||||
|
||||
## 本项目常见调试场景速查
|
||||
|
||||
| 场景 | 首先检查 |
|
||||
|------|---------|
|
||||
| API 返回 401 | `logs/access.log` 中该请求的 token → Redis 中 `auth:token:{token}` 是否存在 |
|
||||
| API 返回 403 | 用户类型是什么 → GORM Callback 自动过滤的条件对不对 → `middleware.CanManageShop()` 的参数 |
|
||||
| 数据查不到 | GORM 数据权限过滤有没有生效 → `shop_id` / `enterprise_id` 是否正确 → 是否需要 `SkipDataPermission` |
|
||||
| 金额/余额不对 | 乐观锁 version 字段 → `RowsAffected` 是否为 0 → 并发场景下的锁竞争 |
|
||||
| 状态流转错误 | `WHERE status = expected` 条件更新 → 状态机是否有遗漏的路径 |
|
||||
| 异步任务不执行 | Asynq Dashboard → `RedisTaskLockKey` 有没有残留 → Worker 日志 |
|
||||
| 异步任务重复执行 | `RedisTaskLockKey` 的 TTL → 任务幂等性检查 |
|
||||
| 分佣计算错误 | 佣金类型(差价/一次性) → 套餐级别的佣金率 → 设备级防重复分佣 |
|
||||
| 套餐激活异常 | 卡状态 → 实名状态 → 主套餐排队逻辑 → 加油包绑定关系 |
|
||||
| Redis 缓存不一致 | Key 的 TTL → 缓存更新时机 → 是否有手动 `Del` 清除 |
|
||||
| 微信支付回调失败 | 签名验证 → 幂等性处理 → 回调 URL 是否可达 |
|
||||
| GORM 查询慢 | `db.Debug()` 看实际 SQL → 是否 N+1 → 是否缺少索引 |
|
||||
|
||||
---
|
||||
|
||||
## 红线规则
|
||||
|
||||
如果你发现自己在想以下任何一条,**立刻停下来,回到阶段一**:
|
||||
|
||||
| 想法 | 为什么是错的 |
|
||||
|------|------------|
|
||||
| "先快速修一下,回头再查" | 快速修 = 猜测。猜测 = 浪费时间。 |
|
||||
| "试试改这个看看行不行" | 一次只验证一个假设,不是随机改。 |
|
||||
| "大概是 X 的问题,我直接改了" | "大概"不是根因。先验证再改。 |
|
||||
| "这个很简单,不用走流程" | 简单问题走流程只需要 5 分钟。不走流程可能浪费 2 小时。 |
|
||||
| "我不完全理解但这应该行" | 不理解 = 没找到根因。回阶段一。 |
|
||||
| "再试一次"(已经失败 2 次) | 3 次失败 = 架构问题。停下来讨论。 |
|
||||
| "同时改这几个地方应该能修好" | 改多处 = 无法确认哪个是根因。一次只改一处。 |
|
||||
|
||||
---
|
||||
|
||||
## 常见借口和真相
|
||||
|
||||
| 借口 | 真相 |
|
||||
|------|------|
|
||||
| "问题很简单,不需要走流程" | 简单问题也有根因。走流程对简单问题只花 5 分钟。 |
|
||||
| "太紧急了,没时间分析" | 系统化调试比乱猜快 3-5 倍。越急越要走流程。 |
|
||||
| "先改了验证一下" | 这叫猜测,不叫验证。先确认根因再改。 |
|
||||
| "我看到问题了,直接修" | 看到症状 ≠ 理解根因。症状修复是技术债。 |
|
||||
| "改了好几个地方,反正能用了" | 不知道哪个改动修的,下次还会出问题。 |
|
||||
|
||||
---
|
||||
|
||||
## 快速参考
|
||||
|
||||
| 阶段 | 核心动作 | 完成标准 |
|
||||
|------|---------|---------|
|
||||
| **一、根因调查** | 读错误日志、复现、检查改动、逐层诊断、追踪数据流 | 能说清楚"因为 X 所以 Y" |
|
||||
| **二、模式分析** | 找参照代码、逐行对比、列出差异 | 知道正确的应该长什么样 |
|
||||
| **三、假设验证** | 写下假设、最小改动、单变量验证 | 假设被证实或推翻 |
|
||||
| **四、实施修复** | 修根因、编译检查、请求验证、清理诊断代码 | bug 消失,无新增问题 |
|
||||
1
.claude/skills/tdd
Symbolic link
1
.claude/skills/tdd
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/tdd
|
||||
1
.claude/skills/teach
Symbolic link
1
.claude/skills/teach
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/teach
|
||||
1
.claude/skills/to-issues
Symbolic link
1
.claude/skills/to-issues
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/to-issues
|
||||
1
.claude/skills/to-prd
Symbolic link
1
.claude/skills/to-prd
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/to-prd
|
||||
1
.claude/skills/triage
Symbolic link
1
.claude/skills/triage
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/triage
|
||||
1
.claude/skills/write-a-skill
Symbolic link
1
.claude/skills/write-a-skill
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/write-a-skill
|
||||
1
.claude/skills/zoom-out
Symbolic link
1
.claude/skills/zoom-out
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.agents/skills/zoom-out
|
||||
198
.codex/skills/export-datasource/SKILL.md
Normal file
198
.codex/skills/export-datasource/SKILL.md
Normal file
@@ -0,0 +1,198 @@
|
||||
---
|
||||
name: export-datasource
|
||||
description: Project-specific guide for implementing, modifying, or reviewing export data sources in junhong_cmp_fiber. Use when Codex needs to add a new export scene, extend filters or dynamic columns, register an export scene, change export task query behavior, or explain/debug the DataSource-based export system.
|
||||
---
|
||||
|
||||
# Export Datasource
|
||||
|
||||
Use this skill to work on this project's DataSource-based export system. It covers developer-facing export scene implementation, not one-off manual export operations.
|
||||
|
||||
## First Reads
|
||||
|
||||
Before editing export code, read the relevant current files:
|
||||
|
||||
- `internal/exporter/datasource.go`
|
||||
- `internal/exporter/query_params.go`
|
||||
- `internal/exporter/filter_helpers.go`
|
||||
- `internal/exporter/registry.go`
|
||||
- Existing scene closest to the new scene:
|
||||
- `internal/exporter/device_scene.go`
|
||||
- `internal/exporter/iot_card_scene.go`
|
||||
- For request/scene validation:
|
||||
- `internal/model/dto/export_task_dto.go`
|
||||
- `pkg/constants/constants.go`
|
||||
- For behavior across worker stages:
|
||||
- `internal/task/export_dispatch.go`
|
||||
- `internal/task/export_shard.go`
|
||||
- `internal/task/export_finalize.go`
|
||||
|
||||
Read `references/export-scene-template.md` when adding a new scene or when a concrete code skeleton is useful.
|
||||
|
||||
## Mental Model
|
||||
|
||||
The framework owns async execution, sharding, file generation, OSS upload, and download URLs. A scene implementation owns only data semantics:
|
||||
|
||||
```go
|
||||
type DataSource interface {
|
||||
Scene() string
|
||||
Count(ctx context.Context, params ExportParams) (int, error)
|
||||
Headers(ctx context.Context, params ExportParams) ([]string, error)
|
||||
Fetch(ctx context.Context, params ExportParams, offset, limit int) ([][]string, error)
|
||||
}
|
||||
```
|
||||
|
||||
Execution flow:
|
||||
|
||||
1. Admin API creates `tb_export_task` and enqueues `export:dispatch`.
|
||||
2. Dispatch parses `query_json.filters` plus permission snapshot into `ExportParams`.
|
||||
3. Dispatch calls `Headers` once and stores `query_json.resolved_headers`.
|
||||
4. Dispatch calls `Count` and creates `tb_export_shard_task` rows with `shard_offset` and `shard_limit`.
|
||||
5. Shard calls `Fetch`, writes headerless CSV shard files, and uploads them.
|
||||
6. Finalize downloads shard CSV files in shard order, writes one header row, uploads final CSV or converts CSV to XLSX.
|
||||
|
||||
Do not reintroduce keyset cursor logic. New scenes must use offset/limit through `Fetch`.
|
||||
|
||||
## Implementation Workflow
|
||||
|
||||
1. Add a scene constant in `pkg/constants/constants.go`.
|
||||
2. Update `internal/model/dto/export_task_dto.go` validation and descriptions for `scene`.
|
||||
3. Implement `internal/exporter/<scene>_scene.go` with `DataSource`.
|
||||
4. Register the source in `NewDefaultRegistry`.
|
||||
5. Update `IsSupportedScene` if it is used by the current code path.
|
||||
6. Add or update migrations only if the exported domain needs schema/index changes. Do not change export task tables unless the framework contract changes.
|
||||
7. Build and manually verify. This repository forbids automated tests unless the user explicitly requests them.
|
||||
|
||||
## DataSource Rules
|
||||
|
||||
- `Scene` must return the constant, not a string literal.
|
||||
- `Count` and `Fetch` must apply the same filters and permission scope.
|
||||
- `Headers` defines the exact column contract for the whole task. Dispatch stores it once; shards and finalize reuse it.
|
||||
- `Fetch` must return rows aligned to `Headers`; the framework pads/truncates as a fallback, but the source should be correct.
|
||||
- `Fetch` must use stable ordering, normally `ORDER BY id ASC`.
|
||||
- Return string values only. Format time as `2006-01-02 15:04:05` unless the surrounding scene establishes another convention.
|
||||
- Use GORM only. Do not use `database/sql`.
|
||||
- Keep SQL parameters bound through GORM placeholders. Do not concatenate user-controlled values into SQL.
|
||||
- Keep comments, logs, errors, and documentation in Chinese per project rules.
|
||||
|
||||
## Filters And Permissions
|
||||
|
||||
Incoming task query shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"filters": {
|
||||
"status": 1,
|
||||
"shop_id": 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`ParseExportParams` exposes:
|
||||
|
||||
- `Filters`: `query_json.filters`
|
||||
- `ScopeShopIDs`: shop permission snapshot captured at task creation
|
||||
- `UserType`: creator user type snapshot
|
||||
|
||||
Apply permission scope inside each DataSource:
|
||||
|
||||
```go
|
||||
query = applyExportShopScope(query, params, "shop_id")
|
||||
```
|
||||
|
||||
For aliased queries:
|
||||
|
||||
```go
|
||||
query = applyExportShopScope(query, params, "o.shop_id")
|
||||
```
|
||||
|
||||
Use helpers from `filter_helpers.go`:
|
||||
|
||||
- `filterInt`
|
||||
- `filterUint`
|
||||
- `filterString`
|
||||
- `filterBool`
|
||||
- `filterTime`
|
||||
- `formatOptionalUint`
|
||||
- `formatOptionalTime`
|
||||
|
||||
Do not read live permissions from context inside a DataSource. Export tasks must use the permission snapshot stored at creation time.
|
||||
|
||||
## Dynamic Columns
|
||||
|
||||
Use dynamic headers only when the task parameters or data require it. If `Headers` changes based on filters, `Fetch` must produce the same shape for every shard under the same `ExportParams`.
|
||||
|
||||
Example pattern:
|
||||
|
||||
```go
|
||||
headers := []string{"ID", "ICCID", "状态"}
|
||||
if filterBool(params.Filters, "with_package") {
|
||||
headers = append(headers, "套餐名称", "套餐状态")
|
||||
}
|
||||
return headers, nil
|
||||
```
|
||||
|
||||
## Join Queries
|
||||
|
||||
JOIN-based exports are allowed. Keep these constraints:
|
||||
|
||||
- Preserve one output row per intended exported entity unless the scene explicitly exports detail rows.
|
||||
- If a JOIN can multiply rows, make `Count` match the exported row semantics exactly.
|
||||
- Use table aliases consistently in filters and scope columns.
|
||||
- Prefer explicit `Select` into a local row struct for multi-table exports.
|
||||
- Keep `Order`, `Limit`, and `Offset` on the final query used by `Fetch`.
|
||||
|
||||
## User-Facing API Notes
|
||||
|
||||
Current API group:
|
||||
|
||||
- `POST /api/admin/export-tasks`
|
||||
- `GET /api/admin/export-tasks`
|
||||
- `GET /api/admin/export-tasks/:id`
|
||||
- `POST /api/admin/export-tasks/:id/cancel`
|
||||
|
||||
Creation request:
|
||||
|
||||
```json
|
||||
{
|
||||
"scene": "iot_card",
|
||||
"format": "csv",
|
||||
"query": {
|
||||
"filters": {
|
||||
"shop_id": 1,
|
||||
"with_package": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Formats are `csv` and `xlsx`. Final download URLs are returned from task detail after completion.
|
||||
|
||||
## Verification
|
||||
|
||||
This project forbids automated tests and `_test.go` files unless the user explicitly asks for tests. Use manual verification:
|
||||
|
||||
```bash
|
||||
go build ./internal/exporter/...
|
||||
go build ./internal/task/...
|
||||
go build ./...
|
||||
```
|
||||
|
||||
Then create an export task through the API and inspect:
|
||||
|
||||
- `tb_export_task.query_json` contains original `filters` and generated `resolved_headers`.
|
||||
- `tb_export_task.total_rows` matches the filtered query.
|
||||
- `tb_export_shard_task.shard_offset` and `shard_limit` are filled.
|
||||
- Shards reach success and final task reaches completed status.
|
||||
- Downloaded file has one header row, expected row count, correct filtering, and valid CSV/XLSX format.
|
||||
|
||||
Use PostgreSQL MCP/manual SQL for data validation when needed.
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
- Updating only `Fetch` and forgetting `Count`, causing wrong shard planning.
|
||||
- Returning dynamic rows whose column count does not match `Headers`.
|
||||
- Filtering by requested `shop_id` without also applying `ScopeShopIDs`.
|
||||
- Using context/user middleware inside worker DataSource logic.
|
||||
- Registering the source but forgetting DTO `oneof`, so API rejects the new scene.
|
||||
- Writing XLSX shard files. Shards should be CSV; finalize handles final format.
|
||||
- Adding automated tests despite the repository ban.
|
||||
4
.codex/skills/export-datasource/agents/openai.yaml
Normal file
4
.codex/skills/export-datasource/agents/openai.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "导出数据源开发"
|
||||
short_description: "指导新增和维护项目导出数据源场景"
|
||||
default_prompt: "Use $export-datasource to add a new export scene for this project."
|
||||
@@ -0,0 +1,222 @@
|
||||
# Export Scene Template
|
||||
|
||||
Use this reference when adding a new export scene.
|
||||
|
||||
## Minimal Checklist
|
||||
|
||||
- Add `ExportTaskSceneXxx` in `pkg/constants/constants.go`.
|
||||
- Add the scene to `CreateExportTaskRequest.Scene` and `ListExportTaskRequest.Scene` validation/description.
|
||||
- Create `internal/exporter/<scene>_scene.go`.
|
||||
- Register `NewXxxDataSource(db)` in `internal/exporter/registry.go`.
|
||||
- Update `IsSupportedScene`.
|
||||
- Run `gofmt` on changed Go files.
|
||||
- Run `go build ./internal/exporter/...`, `go build ./internal/task/...`, and `go build ./...`.
|
||||
- Manually create a task and validate database rows plus downloaded file.
|
||||
|
||||
## Skeleton
|
||||
|
||||
```go
|
||||
package exporter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// XxxDataSource Xxx 导出数据源。
|
||||
type XxxDataSource struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewXxxDataSource 创建 Xxx 导出数据源。
|
||||
func NewXxxDataSource(db *gorm.DB) *XxxDataSource {
|
||||
return &XxxDataSource{db: db}
|
||||
}
|
||||
|
||||
// Scene 返回导出场景编码。
|
||||
func (s *XxxDataSource) Scene() string {
|
||||
return constants.ExportTaskSceneXxx
|
||||
}
|
||||
|
||||
// Count 统计 Xxx 导出行数。
|
||||
func (s *XxxDataSource) Count(ctx context.Context, params ExportParams) (int, error) {
|
||||
var total int64
|
||||
query := s.applyFilters(s.db.WithContext(ctx).Model(&model.Xxx{}), params)
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(total), nil
|
||||
}
|
||||
|
||||
// Headers 返回 Xxx 导出表头。
|
||||
func (s *XxxDataSource) Headers(ctx context.Context, params ExportParams) ([]string, error) {
|
||||
return []string{"ID", "名称", "状态", "店铺ID", "创建时间"}, nil
|
||||
}
|
||||
|
||||
// Fetch 按 offset/limit 查询 Xxx 导出数据。
|
||||
func (s *XxxDataSource) Fetch(ctx context.Context, params ExportParams, offset, limit int) ([][]string, error) {
|
||||
if limit <= 0 {
|
||||
return [][]string{}, nil
|
||||
}
|
||||
|
||||
var items []model.Xxx
|
||||
query := s.applyFilters(s.db.WithContext(ctx).Model(&model.Xxx{}), params).
|
||||
Order("id ASC").
|
||||
Limit(limit).
|
||||
Offset(offset)
|
||||
if err := query.Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows := make([][]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
rows = append(rows, []string{
|
||||
strconv.FormatUint(uint64(item.ID), 10),
|
||||
item.Name,
|
||||
strconv.Itoa(item.Status),
|
||||
formatOptionalUint(item.ShopID),
|
||||
item.CreatedAt.Format(exportTimeLayout),
|
||||
})
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (s *XxxDataSource) applyFilters(query *gorm.DB, params ExportParams) *gorm.DB {
|
||||
query = applyExportShopScope(query, params, "shop_id")
|
||||
|
||||
if status, ok := filterInt(params.Filters, "status"); ok {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
if shopID, ok := filterUint(params.Filters, "shop_id"); ok {
|
||||
query = query.Where("shop_id = ?", shopID)
|
||||
}
|
||||
if start, ok := filterTime(params.Filters, "created_at_start"); ok {
|
||||
query = query.Where("created_at >= ?", start)
|
||||
}
|
||||
if end, ok := filterTime(params.Filters, "created_at_end"); ok {
|
||||
query = query.Where("created_at <= ?", end)
|
||||
}
|
||||
return query
|
||||
}
|
||||
```
|
||||
|
||||
## JOIN Skeleton
|
||||
|
||||
Use this shape for multi-table exports:
|
||||
|
||||
```go
|
||||
type xxxExportRow struct {
|
||||
ID uint
|
||||
Name string
|
||||
Status int
|
||||
ShopID *uint
|
||||
ExtraName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (s *XxxDataSource) Fetch(ctx context.Context, params ExportParams, offset, limit int) ([][]string, error) {
|
||||
if limit <= 0 {
|
||||
return [][]string{}, nil
|
||||
}
|
||||
|
||||
var items []xxxExportRow
|
||||
query := s.applyFilters(s.db.WithContext(ctx).Table("tb_xxx AS x"), params, "x.").
|
||||
Select(`
|
||||
x.id,
|
||||
x.name,
|
||||
x.status,
|
||||
x.shop_id,
|
||||
COALESCE(e.name, '') AS extra_name,
|
||||
x.created_at
|
||||
`).
|
||||
Joins("LEFT JOIN tb_extra AS e ON e.xxx_id = x.id AND e.deleted_at IS NULL").
|
||||
Where("x.deleted_at IS NULL").
|
||||
Order("x.id ASC").
|
||||
Limit(limit).
|
||||
Offset(offset)
|
||||
if err := query.Scan(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows := make([][]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
rows = append(rows, []string{
|
||||
strconv.FormatUint(uint64(item.ID), 10),
|
||||
item.Name,
|
||||
strconv.Itoa(item.Status),
|
||||
formatOptionalUint(item.ShopID),
|
||||
item.ExtraName,
|
||||
item.CreatedAt.Format(exportTimeLayout),
|
||||
})
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (s *XxxDataSource) applyFilters(query *gorm.DB, params ExportParams, prefix string) *gorm.DB {
|
||||
query = applyExportShopScope(query, params, prefix+"shop_id")
|
||||
if status, ok := filterInt(params.Filters, "status"); ok {
|
||||
query = query.Where(prefix+"status = ?", status)
|
||||
}
|
||||
return query
|
||||
}
|
||||
```
|
||||
|
||||
If the JOIN multiplies rows, update `Count` to count the same exported row set. Do not count only the base table unless `Fetch` also returns one row per base record.
|
||||
|
||||
## Registry Patch
|
||||
|
||||
```go
|
||||
func NewDefaultRegistry(db *gorm.DB) *Registry {
|
||||
return NewRegistry(
|
||||
NewDeviceDataSource(db),
|
||||
NewIotCardDataSource(db),
|
||||
NewXxxDataSource(db),
|
||||
)
|
||||
}
|
||||
|
||||
func IsSupportedScene(scene string) bool {
|
||||
switch scene {
|
||||
case constants.ExportTaskSceneDevice,
|
||||
constants.ExportTaskSceneIotCard,
|
||||
constants.ExportTaskSceneXxx:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Manual API Smoke
|
||||
|
||||
```bash
|
||||
curl -X POST 'http://localhost:端口/api/admin/export-tasks' \
|
||||
-H 'Authorization: Bearer <token>' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"scene": "xxx",
|
||||
"format": "csv",
|
||||
"query": {
|
||||
"filters": {
|
||||
"status": 1
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
Check database:
|
||||
|
||||
```sql
|
||||
SELECT id, scene, format, status, total_rows, total_shards, query_json
|
||||
FROM tb_export_task
|
||||
WHERE id = <task_id>;
|
||||
|
||||
SELECT shard_no, status, shard_offset, shard_limit, row_count, file_key
|
||||
FROM tb_export_shard_task
|
||||
WHERE task_id = <task_id>
|
||||
ORDER BY shard_no;
|
||||
```
|
||||
@@ -1,7 +1,20 @@
|
||||
[[sources]]
|
||||
id = "main"
|
||||
description = "当前项目库"
|
||||
dsn = "postgresql://erp_pgsql:erp_2025@cxd.whcxd.cn:16159/junhong_cmp_test?sslmode=disable"
|
||||
|
||||
[[sources]]
|
||||
id = "legacy_mysql"
|
||||
description = "老系统 MySQL 库,仅用于 AI 查询和迁移脚本准备"
|
||||
type = "mysql"
|
||||
host = "120.79.89.216"
|
||||
port = 3306
|
||||
database = "kyhl"
|
||||
user = "root"
|
||||
password = "XiWaJ9Eu%go9-2>g!xGp"
|
||||
sslmode = "disable"
|
||||
lazy = true
|
||||
|
||||
[[tools]]
|
||||
name = "search_objects"
|
||||
source = "main"
|
||||
@@ -11,3 +24,13 @@ name = "execute_sql"
|
||||
source = "main"
|
||||
readonly = true # Only allow SELECT, SHOW, DESCRIBE, EXPLAIN
|
||||
max_rows = 1000 # Limit query results
|
||||
|
||||
[[tools]]
|
||||
name = "search_objects"
|
||||
source = "legacy_mysql"
|
||||
|
||||
[[tools]]
|
||||
name = "execute_sql"
|
||||
source = "legacy_mysql"
|
||||
readonly = true # Only allow SELECT, SHOW, DESCRIBE, EXPLAIN
|
||||
max_rows = 5000 # Limit query results for migration exploration
|
||||
|
||||
11
.env
Normal file
11
.env
Normal file
@@ -0,0 +1,11 @@
|
||||
MIGRATIONS_DIR=migrations
|
||||
DB_HOST=cxd.whcxd.cn
|
||||
DB_PORT=16159
|
||||
DB_USER=erp_pgsql
|
||||
DB_PASSWORD=erp_2025
|
||||
DB_NAME=junhong_cmp_test
|
||||
DB_SSLMODE=disable
|
||||
GOOGLE_GEMINI_BASE_URL="http://45.155.220.179:8317" # 根据实际填写你服务器的ip地址或者域名
|
||||
GEMINI_API_KEY="sk-VoNbvr6aGpjvZX64rvhrwowrZrCgtGuX9oxykIy8F1DBg"
|
||||
GOOGLE_GENAI_USE_GCA="true"
|
||||
GEMINI_MODEL="gemini-3-pro-preview" # 如果你有gemini3权限可以填: gemini-3-pro-preview
|
||||
93
.env.local
Normal file
93
.env.local
Normal file
@@ -0,0 +1,93 @@
|
||||
# ============================================================================
|
||||
# 君鸿卡管系统 - 本地开发环境变量
|
||||
# 生成时间: 2026-01-30 17:45:14
|
||||
# ============================================================================
|
||||
# 使用方法:
|
||||
# source .env.local && go run cmd/api/main.go
|
||||
# 或者:
|
||||
# ./scripts/run-local.sh
|
||||
# ============================================================================
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_DATABASE_HOST="cxd.whcxd.cn"
|
||||
export JUNHONG_DATABASE_PORT="16159"
|
||||
export JUNHONG_DATABASE_USER="erp_pgsql"
|
||||
export JUNHONG_DATABASE_PASSWORD="erp_2025"
|
||||
export JUNHONG_DATABASE_DBNAME="junhong_cmp_test"
|
||||
export JUNHONG_DATABASE_SSLMODE="disable"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_REDIS_ADDRESS="cxd.whcxd.cn"
|
||||
export JUNHONG_REDIS_PORT="16299"
|
||||
export JUNHONG_REDIS_PASSWORD="cpNbWtAaqgo1YJmbMp3h"
|
||||
export JUNHONG_REDIS_DB="6"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# JWT 配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_JWT_SECRET_KEY="dev-secret-key-for-testing-only-32chars!"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 客户端配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 是否强制 C 端用户绑定手机号(true: 强制,false: 不强制)
|
||||
export JUNHONG_CLIENT_REQUIRE_PHONE_BINDING="true"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 服务器配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_SERVER_ADDRESS=":3000"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 日志配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_LOGGING_LEVEL="debug"
|
||||
export JUNHONG_LOGGING_DEVELOPMENT="true"
|
||||
export JUNHONG_LOGGING_APP_LOG_FILENAME="logs/app.log"
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_FILENAME="logs/access.log"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Gateway 服务配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_GATEWAY_BASE_URL="https://open.whjhft.com/openapi"
|
||||
export JUNHONG_GATEWAY_APP_ID="LfjL0WjUqpwkItQ0"
|
||||
export JUNHONG_GATEWAY_APP_SECRET="K0DYuWzbRE6zg5bX"
|
||||
export JUNHONG_GATEWAY_TIMEOUT="30"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 对象存储配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_STORAGE_PROVIDER="s3"
|
||||
export JUNHONG_STORAGE_S3_ENDPOINT="http://obs-helf.cucloud.cn"
|
||||
export JUNHONG_STORAGE_S3_REGION="cn-langfang-2"
|
||||
export JUNHONG_STORAGE_S3_BUCKET="cmp"
|
||||
export JUNHONG_STORAGE_S3_ACCESS_KEY_ID="598F558CF6FF46E79D1CFC607852378C9523"
|
||||
export JUNHONG_STORAGE_S3_SECRET_ACCESS_KEY="8393425DCB2F48F1914FF39DCBC6C7B17325"
|
||||
export JUNHONG_STORAGE_S3_USE_SSL="false"
|
||||
export JUNHONG_STORAGE_S3_PATH_STYLE="true"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 迁移工具兼容配置(用于 scripts/migrate.sh)
|
||||
# ----------------------------------------------------------------------------
|
||||
export MIGRATIONS_DIR="migrations"
|
||||
export DB_HOST="cxd.whcxd.cn"
|
||||
export DB_PORT="16159"
|
||||
export DB_USER="erp_pgsql"
|
||||
export DB_PASSWORD="erp_2025"
|
||||
export DB_NAME="junhong_cmp_test"
|
||||
export DB_SSLMODE="disable"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 短信服务配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_SMS_GATEWAY_URL="https://gateway.sms.whjhft.com:8443"
|
||||
export JUNHONG_SMS_USERNAME="JH0001"
|
||||
export JUNHONG_SMS_PASSWORD="wwR8E4qnL6F0"
|
||||
export JUNHONG_SMS_SIGNATURE="【JHFTIOT】"
|
||||
|
||||
JUNHONG_QUEUE_CONCURRENCY=1000
|
||||
236
.env.prod
Normal file
236
.env.prod
Normal file
@@ -0,0 +1,236 @@
|
||||
# ==========================================================================
|
||||
# 君鸿卡管系统 - 本地开发环境变量
|
||||
# 生成时间: 2026-05-07 11:56:19
|
||||
# 配置依据: pkg/config/defaults/config.yaml + pkg/config/loader.go
|
||||
# ==========================================================================
|
||||
# 使用方法:
|
||||
# source .env.prod && go run cmd/api/main.go
|
||||
# 或者:
|
||||
# ./scripts/run-local.sh
|
||||
#
|
||||
# 说明:
|
||||
# - 未注释的 是本地启动常用或必填配置。
|
||||
# - 注释掉的 是当前有默认值、按需启用或当前主流程未使用的配置。
|
||||
# - 取消注释前请先阅读上方说明,避免覆盖嵌入配置默认值。
|
||||
# ==========================================================================
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库主机地址;应用启动必填。
|
||||
export JUNHONG_DATABASE_HOST=cxd.whcxd.cn
|
||||
# 数据库端口;默认 5432。
|
||||
export JUNHONG_DATABASE_PORT=16159
|
||||
# 数据库用户名;应用启动必填。
|
||||
export JUNHONG_DATABASE_USER=junhong_cmp
|
||||
# 数据库密码;应用启动必填,敏感信息请勿提交。
|
||||
export JUNHONG_DATABASE_PASSWORD=CtCom1zBzPQbpVNf3rCNxH
|
||||
# 数据库名称;应用启动必填。
|
||||
export JUNHONG_DATABASE_DBNAME=junhong_cmp_prod
|
||||
# 数据库 SSL 模式;本地通常使用 disable。
|
||||
export JUNHONG_DATABASE_SSLMODE=disable
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 主机地址;应用启动必填。
|
||||
export JUNHONG_REDIS_ADDRESS=192.168.1.22
|
||||
# Redis 端口;默认 6379。
|
||||
export JUNHONG_REDIS_PORT=6379
|
||||
# Redis 密码;无密码时留空。
|
||||
export JUNHONG_REDIS_PASSWORD=Bm500vXEyLg0RUzw7YcyPjbRifhz
|
||||
# Redis 数据库编号;默认 0。
|
||||
export JUNHONG_REDIS_DB=0
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# JWT 配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
# JWT 签名密钥;必须至少 32 字符,生产环境必须单独生成。
|
||||
export JUNHONG_JWT_SECRET_KEY=a0xzpGhR3zB54JAiEJtoKnjwgAGMLmRw
|
||||
# C 端 JWT Token 有效期;默认 24h,通常无需覆盖。
|
||||
export JUNHONG_JWT_TOKEN_DURATION=24h
|
||||
# B 端访问令牌 TTL;默认 24h。
|
||||
export JUNHONG_JWT_ACCESS_TOKEN_TTL=24h
|
||||
# B 端刷新令牌 TTL;默认 168h。
|
||||
export JUNHONG_JWT_REFRESH_TOKEN_TTL=168h
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 服务器配置
|
||||
# ----------------------------------------------------------------------------
|
||||
# 服务监听地址;本地默认 :3000。
|
||||
export JUNHONG_SERVER_ADDRESS=:3527
|
||||
# 读取请求超时时间;默认 30s,通常无需覆盖。
|
||||
export JUNHONG_SERVER_READ_TIMEOUT=30s
|
||||
# 写响应超时时间;默认 30s,通常无需覆盖。
|
||||
export JUNHONG_SERVER_WRITE_TIMEOUT=30s
|
||||
# 优雅关闭超时时间;默认 30s。
|
||||
export JUNHONG_SERVER_SHUTDOWN_TIMEOUT=30s
|
||||
# Fiber 预分叉模式;本地和 macOS 开发环境通常不要启用。
|
||||
# JUNHONG_SERVER_PREFORK=false
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 日志配置
|
||||
# ----------------------------------------------------------------------------
|
||||
# 日志级别;可选 debug/info/warn/error。
|
||||
export JUNHONG_LOGGING_LEVEL=debug
|
||||
# 本地开发模式日志;生产环境应使用 false。
|
||||
export JUNHONG_LOGGING_DEVELOPMENT=true
|
||||
# 应用日志文件路径;本地写入项目 logs 目录。
|
||||
export JUNHONG_LOGGING_APP_LOG_FILENAME=logs/app.log
|
||||
# 访问日志文件路径;本地写入项目 logs 目录。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_FILENAME=logs/access.log
|
||||
# 应用日志单文件最大大小(MB);默认 100。
|
||||
export JUNHONG_LOGGING_APP_LOG_MAX_SIZE=100
|
||||
# 应用日志最多保留的旧文件数;默认 3。
|
||||
export JUNHONG_LOGGING_APP_LOG_MAX_BACKUPS=15
|
||||
# 应用日志最多保留天数;默认 7。
|
||||
export JUNHONG_LOGGING_APP_LOG_MAX_AGE=14
|
||||
# 是否压缩应用日志轮转文件;默认 true。
|
||||
export JUNHONG_LOGGING_APP_LOG_COMPRESS=true
|
||||
# 访问日志单文件最大大小(MB);默认 100。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_MAX_SIZE=100
|
||||
# 访问日志最多保留的旧文件数;默认 3。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_MAX_BACKUPS=15
|
||||
# 访问日志最多保留天数;默认 7。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_MAX_AGE=14
|
||||
# 是否压缩访问日志轮转文件;默认 true。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_COMPRESS=true
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 客户端配置
|
||||
# ----------------------------------------------------------------------------
|
||||
# 是否强制 C 端用户绑定手机号;当前默认 true。
|
||||
export JUNHONG_CLIENT_REQUIRE_PHONE_BINDING=true
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库连接池配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库最大打开连接数;默认 25,本地通常不用改。
|
||||
export JUNHONG_DATABASE_MAX_OPEN_CONNS=25
|
||||
# 数据库最大空闲连接数;默认 10。
|
||||
export JUNHONG_DATABASE_MAX_IDLE_CONNS=10
|
||||
# 数据库连接最大生命周期;默认 5m。
|
||||
export JUNHONG_DATABASE_CONN_MAX_LIFETIME=5m
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 连接池配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 连接池大小;默认 10。
|
||||
export JUNHONG_REDIS_POOL_SIZE=20
|
||||
# Redis 最小空闲连接数;默认 5。
|
||||
export JUNHONG_REDIS_MIN_IDLE_CONNS=5
|
||||
# Redis 建连超时;默认 5s。
|
||||
export JUNHONG_REDIS_DIAL_TIMEOUT=5s
|
||||
# Redis 读取超时;默认 3s。
|
||||
export JUNHONG_REDIS_READ_TIMEOUT=3s
|
||||
# Redis 写入超时;默认 3s。
|
||||
export JUNHONG_REDIS_WRITE_TIMEOUT=3s
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 任务队列配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# Worker 并发数;默认 10。
|
||||
# JUNHONG_QUEUE_CONCURRENCY=10
|
||||
# 任务最大重试次数;默认 5。
|
||||
# JUNHONG_QUEUE_RETRY_MAX=5
|
||||
# 单个任务超时时间;默认 10m。
|
||||
# JUNHONG_QUEUE_TIMEOUT=10m
|
||||
# 队列权重 critical/default/low 当前由嵌入配置 queue.queues 管理,未绑定为环境变量。
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 限流中间件配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 是否启用全局限流;默认关闭。
|
||||
# JUNHONG_MIDDLEWARE_ENABLE_RATE_LIMITER=false
|
||||
# 限流窗口内最大请求数;默认 100。
|
||||
# JUNHONG_MIDDLEWARE_RATE_LIMITER_MAX=100
|
||||
# 限流时间窗口;默认 1m。
|
||||
# JUNHONG_MIDDLEWARE_RATE_LIMITER_EXPIRATION=1m
|
||||
# 限流存储后端;可选 memory 或 redis。
|
||||
# JUNHONG_MIDDLEWARE_RATE_LIMITER_STORAGE=memory
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 轮询配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 是否输出轮询详细日志;默认 false,排查上游数据时再开启。
|
||||
export JUNHONG_POLLING_VERBOSE_LOG=true
|
||||
# 是否启用 C 端实名自动触发;默认 true。
|
||||
# JUNHONG_POLLING_AUTO_TRIGGER_ENABLE_AUTO_TRIGGER=true
|
||||
# 自动触发使用的系统用户 ID;生产建议改成专用平台账号。
|
||||
export JUNHONG_POLLING_AUTO_TRIGGER_AUTO_TRIGGER_SYSTEM_USER_ID=1
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Worker 运行配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# Worker 角色;单实例默认 all,多实例可用 leader/consumer。
|
||||
# JUNHONG_WORKER_ROLE=all
|
||||
# Worker 实例名称;多实例部署时用于区分日志。
|
||||
# JUNHONG_WORKER_INSTANCE_NAME=''
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Gateway 服务配置
|
||||
# ----------------------------------------------------------------------------
|
||||
# Gateway API 基础 URL;已按本次输入覆盖嵌入默认值。
|
||||
export JUNHONG_GATEWAY_BASE_URL=https://open.whjhft.com/openapi
|
||||
# Gateway 应用 ID;敏感信息请勿提交。
|
||||
export JUNHONG_GATEWAY_APP_ID=LfjL0WjUqpwkItQ0
|
||||
# Gateway 应用密钥;敏感信息请勿提交。
|
||||
export JUNHONG_GATEWAY_APP_SECRET=K0DYuWzbRE6zg5bX
|
||||
# Gateway 请求超时时间(秒);有效范围 5-300。
|
||||
export JUNHONG_GATEWAY_TIMEOUT=30
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 短信服务配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 短信服务未配置时系统会跳过短信客户端初始化;需要短信验证码时再取消注释。
|
||||
# 短信网关地址;设置后 username/password/signature 也必须填写。
|
||||
export JUNHONG_SMS_GATEWAY_URL='https://gateway.sms.whjhft.com:8443'
|
||||
# 短信账号用户名。
|
||||
export JUNHONG_SMS_USERNAME='JH0001'
|
||||
# 短信账号密码;敏感信息请勿提交。
|
||||
export JUNHONG_SMS_PASSWORD='wwR8E4qnL6F0'
|
||||
# 短信签名,例如【君鸿】。
|
||||
export JUNHONG_SMS_SIGNATURE='【JHFTIOT】'
|
||||
# 短信请求超时时间;默认 10s。
|
||||
export JUNHONG_SMS_TIMEOUT=10s
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 对象存储配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 对象存储提供商;当前仅支持 s3 兼容服务。
|
||||
export JUNHONG_STORAGE_PROVIDER=s3
|
||||
# 临时文件目录;用于导入导出等临时文件。
|
||||
export JUNHONG_STORAGE_TEMP_DIR=/tmp/junhong-storage
|
||||
# S3 端点;配置后会初始化对象存储服务。
|
||||
export JUNHONG_STORAGE_S3_ENDPOINT=https://obs-helf.cucloud.cn
|
||||
# S3 区域。
|
||||
export JUNHONG_STORAGE_S3_REGION=cn-langfang-2
|
||||
# S3 存储桶名称。
|
||||
export JUNHONG_STORAGE_S3_BUCKET=cmp
|
||||
# S3 Access Key ID;敏感信息请勿提交。
|
||||
export JUNHONG_STORAGE_S3_ACCESS_KEY_ID=598F558CF6FF46E79D1CFC607852378C9523
|
||||
# S3 Secret Access Key;敏感信息请勿提交。
|
||||
export JUNHONG_STORAGE_S3_SECRET_ACCESS_KEY=8393425DCB2F48F1914FF39DCBC6C7B17325
|
||||
# 是否使用 SSL;本地兼容服务常用 false。
|
||||
export JUNHONG_STORAGE_S3_USE_SSL=false
|
||||
# 是否使用路径风格;兼容 S3 服务通常使用 true。
|
||||
export JUNHONG_STORAGE_S3_PATH_STYLE=true
|
||||
# 预签名上传 URL 有效期;默认 15m。
|
||||
export JUNHONG_STORAGE_PRESIGN_UPLOAD_EXPIRES=15m
|
||||
# 预签名下载 URL 有效期;默认 24h。
|
||||
export JUNHONG_STORAGE_PRESIGN_DOWNLOAD_EXPIRES=24h
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 默认超级管理员配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 不配置时会使用 pkg/constants 中的默认超管账号;生产环境建议在首次启动前覆盖。
|
||||
# 默认超级管理员用户名;留空则使用代码内置默认值 admin。
|
||||
export JUNHONG_DEFAULT_ADMIN_USERNAME='admin'
|
||||
# 默认超级管理员密码;留空则使用代码内置默认值 Admin@123456。
|
||||
export JUNHONG_DEFAULT_ADMIN_PASSWORD='Admin@123456'
|
||||
# 默认超级管理员手机号;留空则使用代码内置默认值 13800000000。
|
||||
# JUNHONG_DEFAULT_ADMIN_PHONE=''
|
||||
|
||||
export JUNHONG_MIDDLEWARE_CORS_ENABLED=true
|
||||
export JUNHONG_MIDDLEWARE_CORS_ALLOW_ORIGINS=https://cmp-admin.xm-iot.cn,https://cmp-agent.xm-iot.cn,https://cmp-c.xm-iot.cn
|
||||
export JUNHONG_MIDDLEWARE_CORS_ALLOW_CREDENTIALS=true
|
||||
40
.gitignore
vendored
40
.gitignore
vendored
@@ -26,8 +26,6 @@ vendor/
|
||||
.cache/
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Log files
|
||||
@@ -75,5 +73,39 @@ __debug_bin1621385388
|
||||
docs/admin-openapi.yaml
|
||||
/api
|
||||
/gendocs
|
||||
.env.local
|
||||
/worker
|
||||
/worker
|
||||
.opencode/skills/json-canvas
|
||||
.opencode/skills/obsidian-bases
|
||||
.gitignore
|
||||
.opencode/skills/obsidian-cli
|
||||
.opencode/skills/obsidian-markdown
|
||||
.opencode/skills/kb-sync
|
||||
.gitignore
|
||||
.opencode/skills/defuddle
|
||||
# CocoIndex Code (ccc)
|
||||
/.cocoindex_code/
|
||||
.omx/hud-config.json
|
||||
.omx/metrics.json
|
||||
.omx/setup-scope.json
|
||||
.omx/cache/codebase-map.json
|
||||
.omx/state/current-task-baseline.json
|
||||
.omx/state/notify-fallback-authority-owner.json
|
||||
.omx/state/notify-fallback-state.json
|
||||
.omx/state/notify-fallback.pid
|
||||
.omx/state/session.json
|
||||
.omx/state/subagent-tracking.json
|
||||
.omx/state/team-leader-nudge.json
|
||||
.omx/state/tmux-hook-state.json
|
||||
.omx/state/update-check.json
|
||||
.omx/state/sessions/omx-1777517355305-tzivrd/AGENTS.md
|
||||
.omx/state/sessions/omx-1777517355305-tzivrd/hud-state.json
|
||||
.omx/state/sessions/omx-1777517489966-oo3g37/AGENTS.md
|
||||
.omx/state/sessions/omx-1777517489966-oo3g37/hud-state.json
|
||||
.omx/state/sessions/omx-1777517489966-oo3g37/notify-hook-state.json
|
||||
.omx/state/tmux-extended-keys/private-tmp-tmux-501-default.json
|
||||
.aider*
|
||||
|
||||
# /teach skill 的个人学习工作区,不进入项目提交历史
|
||||
.claude/teach-workspace/
|
||||
scripts/batch_package_purchase/assets.example_购买结果_20260715_115804.csv
|
||||
scripts/batch_package_purchase/assets.example_购买结果_20260715_115814.csv
|
||||
|
||||
20
.mcp.json
20
.mcp.json
@@ -1,19 +1,15 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"postgres": {
|
||||
"command": "docker",
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"run",
|
||||
"-i",
|
||||
"--rm",
|
||||
"-e",
|
||||
"DATABASE_URI",
|
||||
"crystaldba/postgres-mcp",
|
||||
"--access-mode=restricted"
|
||||
],
|
||||
"env": {
|
||||
"DATABASE_URI": "postgresql://erp_pgsql:erp_2025@cxd.whcxd.cn:16159/junhong_cmp_test?sslmode=disable"
|
||||
}
|
||||
"-y",
|
||||
"@bytebase/dbhub@latest",
|
||||
"--transport",
|
||||
"stdio",
|
||||
"--config",
|
||||
".config/dbhub.toml"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
115
.opencode/package-lock.json
generated
Normal file
115
.opencode/package-lock.json
generated
Normal file
@@ -0,0 +1,115 @@
|
||||
{
|
||||
"name": ".opencode",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"dependencies": {
|
||||
"@opencode-ai/plugin": "1.3.17"
|
||||
}
|
||||
},
|
||||
"node_modules/@opencode-ai/plugin": {
|
||||
"version": "1.3.17",
|
||||
"resolved": "https://registry.npmjs.org/@opencode-ai/plugin/-/plugin-1.3.17.tgz",
|
||||
"integrity": "sha512-N5lckFtYvEu2R8K1um//MIOTHsJHniF2kHoPIWPCrxKG5Jpismt1ISGzIiU3aKI2ht/9VgcqKPC5oZFLdmpxPw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@opencode-ai/sdk": "1.3.17",
|
||||
"zod": "4.1.8"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentui/core": ">=0.1.96",
|
||||
"@opentui/solid": ">=0.1.96"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@opentui/core": {
|
||||
"optional": true
|
||||
},
|
||||
"@opentui/solid": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@opencode-ai/sdk": {
|
||||
"version": "1.3.17",
|
||||
"resolved": "https://registry.npmjs.org/@opencode-ai/sdk/-/sdk-1.3.17.tgz",
|
||||
"integrity": "sha512-2+MGgu7wynqTBwxezR01VAGhILXlpcHDY/pF7SWB87WOgLt3kD55HjKHNj6PWxyY8n575AZolR95VUC3gtwfmA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cross-spawn": "7.0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"path-key": "^3.1.0",
|
||||
"shebang-command": "^2.0.0",
|
||||
"which": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/path-key": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
||||
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shebang-command": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"shebang-regex": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shebang-regex": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
|
||||
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"isexe": "^2.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"node-which": "bin/node-which"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.1.8",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
139
.opencode/skills/comment-standards/SKILL.md
Normal file
139
.opencode/skills/comment-standards/SKILL.md
Normal file
@@ -0,0 +1,139 @@
|
||||
---
|
||||
name: comment-standards
|
||||
description: Go 注释规范。编写 Go 代码注释、文档注释时使用。包含包注释、结构体注释、接口注释、函数注释、内联注释的完整规范与示例。
|
||||
---
|
||||
|
||||
# Go 注释规范
|
||||
|
||||
**基本原则**:
|
||||
- **所有注释使用中文**
|
||||
- **导出符号必须有文档注释**(包、函数、方法、类型、接口、常量、变量)
|
||||
- **复杂逻辑必须有实现注释**(解释"为什么",而不是"做了什么")
|
||||
- **禁止废话注释**(不要用注释复述代码本身)
|
||||
- **修改代码时必须同步更新注释**
|
||||
|
||||
---
|
||||
|
||||
## 包注释
|
||||
|
||||
每个包的入口文件(通常是主文件或 `doc.go`)必须有包注释:
|
||||
|
||||
```go
|
||||
// Package account 提供账号管理的业务逻辑服务
|
||||
// 包含账号创建、修改、删除、权限分配等功能
|
||||
package account
|
||||
```
|
||||
|
||||
## 结构体注释
|
||||
|
||||
所有导出结构体必须有文档注释,说明该结构体代表什么:
|
||||
|
||||
```go
|
||||
// Service 账号业务服务
|
||||
// 负责账号的 CRUD、角色分配、密码管理等业务逻辑
|
||||
type Service struct {
|
||||
store *Store
|
||||
auditService AuditServiceInterface
|
||||
}
|
||||
```
|
||||
|
||||
## 接口注释
|
||||
|
||||
导出接口必须注释接口用途,每个方法必须说明契约:
|
||||
|
||||
```go
|
||||
// PermissionChecker 权限检查器接口
|
||||
// 用于查询用户的权限列表
|
||||
type PermissionChecker interface {
|
||||
// CheckPermission 检查用户是否拥有指定权限
|
||||
// userID: 用户ID
|
||||
// permCode: 权限编码(格式: module:action)
|
||||
// platform: 端口类型 (all/web/h5)
|
||||
CheckPermission(ctx context.Context, userID uint, permCode string, platform string) (bool, error)
|
||||
}
|
||||
```
|
||||
|
||||
## 函数和方法注释
|
||||
|
||||
**导出函数/方法**必须以函数名开头,说明功能:
|
||||
|
||||
```go
|
||||
// Create 创建账号
|
||||
// POST /api/admin/accounts
|
||||
func (h *AccountHandler) Create(c *fiber.Ctx) error {
|
||||
```
|
||||
|
||||
**复杂方法**(超过 30 行或包含复杂业务逻辑)必须额外说明实现思路:
|
||||
|
||||
```go
|
||||
// ActivateByRealname 首次实名激活套餐
|
||||
// 当用户完成实名认证后,自动激活处于"囤货待实名"状态的套餐:
|
||||
// 1. 查找该卡所有 status=3(待实名激活)的套餐
|
||||
// 2. 按创建时间排序,第一个主套餐立即激活(status=1)
|
||||
// 3. 其余主套餐进入排队状态(status=4)
|
||||
// 4. 加油包如果绑定了已激活的主套餐则一并激活
|
||||
func (s *UsageService) ActivateByRealname(ctx context.Context, cardID uint) error {
|
||||
```
|
||||
|
||||
**未导出函数/方法**:
|
||||
- 简单逻辑(< 15 行):可以不加注释
|
||||
- 复杂逻辑(≥ 15 行)或非显而易见的算法:必须加注释
|
||||
|
||||
```go
|
||||
// buildPermissionTree 递归构建权限树
|
||||
// 采用 map 索引 + 单次遍历算法,时间复杂度 O(n)
|
||||
func (s *Service) buildPermissionTree(permissions []*model.Permission) []*dto.PermissionTreeNode {
|
||||
```
|
||||
|
||||
## 常量和枚举注释
|
||||
|
||||
分组常量必须有组注释,每个值必须有行内注释:
|
||||
|
||||
```go
|
||||
// 用户类型常量
|
||||
const (
|
||||
UserTypeSuperAdmin = 1 // 超级管理员
|
||||
UserTypePlatform = 2 // 平台用户
|
||||
UserTypeAgent = 3 // 代理账号
|
||||
UserTypeEnterprise = 4 // 企业账号
|
||||
)
|
||||
```
|
||||
|
||||
## 内联注释规范
|
||||
|
||||
**必须添加内联注释的场景**:
|
||||
|
||||
| 场景 | 要求 |
|
||||
|------|------|
|
||||
| 复杂条件判断 | 解释判断的业务含义 |
|
||||
| 多步骤业务流程 | 用编号注释标明每一步 |
|
||||
| 非显而易见的设计决策 | 解释"为什么这样做"而不是"做了什么" |
|
||||
| 缓存/事务/并发处理 | 说明策略和原因 |
|
||||
| 临时方案/兼容逻辑 | 标注 TODO 或说明背景 |
|
||||
|
||||
**✅ 好的内联注释(解释为什么)**:
|
||||
|
||||
```go
|
||||
// 使用 Redis 分布式锁防止并发重复创建,锁超时 10 秒
|
||||
if !s.acquireLock(ctx, lockKey, 10*time.Second) {
|
||||
return errors.New(errors.CodeTooManyRequests, "操作过于频繁,请稍后重试")
|
||||
}
|
||||
|
||||
// 先冻结佣金再扣款,保证资金安全(失败时佣金自动解冻)
|
||||
if err := s.freezeCommission(ctx, tx, orderID); err != nil {
|
||||
return err
|
||||
}
|
||||
```
|
||||
|
||||
**❌ 废话注释(禁止)**:
|
||||
|
||||
```go
|
||||
// 获取用户ID ← 禁止:代码本身已经很清楚
|
||||
userID := middleware.GetUserIDFromContext(ctx)
|
||||
|
||||
// 创建账号 ← 禁止:变量名已说明意图
|
||||
account := &model.Account{}
|
||||
|
||||
// 返回错误 ← 禁止:return err 不需要注释
|
||||
return err
|
||||
```
|
||||
952
.opencode/skills/hurl-test/SKILL.md
Normal file
952
.opencode/skills/hurl-test/SKILL.md
Normal file
@@ -0,0 +1,952 @@
|
||||
---
|
||||
name: hurl-test
|
||||
description: Hurl 接口测试生成器。用户描述要测试的接口或业务流程,自动探索代码、确认需求、生成完整的 .hurl 测试文件(含 DTO 驱动的字段完整性断言)。触发词:测试、hurl、写测试、接口测试。
|
||||
---
|
||||
|
||||
# Hurl 接口测试生成器
|
||||
|
||||
**用户描述要测试什么,你来读代码、问确认、生成 .hurl 文件。**
|
||||
|
||||
适用于任何后端项目(Go / Python / Node / Java 等),不预设框架和目录结构。
|
||||
|
||||
---
|
||||
|
||||
## 触发条件
|
||||
|
||||
以下情况必须使用本 Skill:
|
||||
- 用户说"测试 XX 接口"、"写 hurl 测试"、"给 XX 加测试"
|
||||
- 用户说"测试 XX 流程"、"测试 XX 的业务逻辑"
|
||||
- 用户说"验证 XX 接口的字段"、"测试接口契约"
|
||||
- 用户提到 hurl、.hurl、接口测试、集成测试、冒烟测试
|
||||
|
||||
---
|
||||
|
||||
## 五阶段工作流(必须按顺序执行)
|
||||
|
||||
```
|
||||
Phase 1: 探索 → Phase 2: 确认 → Phase 3: 生成 → Phase 4: 验证 → Phase 5: 研判
|
||||
读代码搞清楚 展示给用户确认 输出 .hurl 文件 语法检查+试跑 分析失败/报告发现
|
||||
```
|
||||
|
||||
> **核心原则:测试是用来发现问题的,不是用来全部通过的。**
|
||||
> 断言基于代码定义(Handler + DTO)生成,与实际行为的差异是"发现",不是要修掉的"错误"。
|
||||
|
||||
---
|
||||
|
||||
### Phase 1: 探索(Explore)
|
||||
|
||||
**目标:读代码,搞清楚项目约定 + 涉及的接口 + 字段 + 依赖。要求准确,不求快。**
|
||||
|
||||
#### 真理源层级(必须遵守)
|
||||
|
||||
断言的字段名和类型基于以下优先级确定,**高优先级推翻低优先级**:
|
||||
|
||||
| 优先级 | 来源 | 说明 | 怎么找 |
|
||||
|-------|------|------|--------|
|
||||
| **1(最高)** | Handler 实际实现 | Handler 返回什么类型、调用哪个 response 方法、是否做了 model→DTO 转换 | 读 handler 函数体,看 `return response.Success(c, xxx)` 中 xxx 的类型 |
|
||||
| **2** | DTO / Response 结构体 | Handler 引用的 DTO 的 json tag、字段类型 | 读 DTO struct 定义 |
|
||||
| **3(最低)** | 路由注册的 Output 声明 | RouteSpec 中声明的 Output 类型,仅作为文档参考,可能过期 | 读路由注册代码 |
|
||||
|
||||
**关键规则**:
|
||||
- **不能只读 DTO 就生成断言**。必须追溯到 Handler 确认它确实用了这个 DTO
|
||||
- 如果 Handler 直接返回 GORM model 而非 DTO,断言用 model 的字段名(可能是大写 `ID` 而非小写 `id`)
|
||||
- 如果 Handler 用了 `response.SuccessWithPagination()`,分页字段以该函数的结构为准,而非 DTO 定义的分页结构
|
||||
- 当 Handler 实现与 DTO 定义不一致时,**以 Handler 为准生成断言,同时在 Phase 5 中将不一致标记为发现**
|
||||
|
||||
#### 1.1 项目画像(首次使用时必须执行,后续复用)
|
||||
|
||||
首次为项目生成 Hurl 测试时,先回答以下问题(通过读代码,不要猜):
|
||||
|
||||
| 问题 | 怎么找 |
|
||||
|------|--------|
|
||||
| **语言/框架** | 看 go.mod / package.json / requirements.txt / pom.xml |
|
||||
| **路由注册在哪** | 搜索 `router`、`app.Get`、`@GetMapping`、`@app.route` 等关键词 |
|
||||
| **请求/响应 schema 定义在哪** | 搜索 DTO / schema / serializer / model 目录,看 json tag 或装饰器 |
|
||||
| **统一响应格式是什么** | 找 response helper 文件(如 `response.go`、`response.py`),记录 JSON 结构 |
|
||||
| **认证方式是什么** | 找 auth middleware,确定是 Bearer Token / Cookie / API Key / Basic Auth |
|
||||
| **登录接口是什么** | 找登录 handler,记录路径、请求体、响应中 token 的位置 |
|
||||
| **分页格式是什么** | 找列表接口的响应结构,记录 items/total/page 等字段名 |
|
||||
| **已有 hurl 测试吗** | 搜索 `*.hurl` 文件,复用已有的约定 |
|
||||
|
||||
将画像结果**写入 `tests/hurl/.project-profile.md` 文件持久化保存**。
|
||||
|
||||
#### 画像持久化(关键机制)
|
||||
|
||||
**首次使用时**:完成 1.1 探索后,将画像写入 `tests/hurl/.project-profile.md`,格式如下:
|
||||
|
||||
```markdown
|
||||
# 项目画像(Hurl 测试自动生成用)
|
||||
<!-- 由 hurl-test skill 自动生成,请勿手动修改 -->
|
||||
<!-- 如需刷新,删除此文件后重新运行 skill -->
|
||||
|
||||
## 技术栈
|
||||
- 语言: Go 1.25
|
||||
- 框架: Fiber v2
|
||||
- ORM: GORM
|
||||
|
||||
## 路由定义位置
|
||||
- 路由注册入口: internal/routes/routes.go
|
||||
- 按模块拆分: internal/routes/{module}.go
|
||||
- 路由注册函数: Register(router, doc, basePath, method, path, handler, spec)
|
||||
|
||||
## Schema 定义位置
|
||||
- DTO 目录: internal/model/dto/
|
||||
- 命名规则: {module}_dto.go
|
||||
- 字段标签: json / validate / description
|
||||
|
||||
## 统一响应格式
|
||||
{code: int, msg: string, data: any, timestamp: string(RFC3339)}
|
||||
- 成功: code=0, msg="success"
|
||||
- 错误: code!=0
|
||||
|
||||
## 分页格式
|
||||
{items: [], total: int, page: int, size: int}
|
||||
- 包裹在 data 字段内: $.data.items / $.data.total
|
||||
|
||||
## 认证方式
|
||||
- 后台: POST /api/auth/admin-login → $.data.access_token → Authorization: Bearer {token}
|
||||
- C端: JWT → Authorization: Bearer {token}
|
||||
|
||||
## 默认测试账号
|
||||
- 用户名: admin
|
||||
- 密码: Admin@123456
|
||||
|
||||
## 服务端口
|
||||
- 默认: 3000
|
||||
```
|
||||
|
||||
**后续使用时**:检查 `tests/hurl/.project-profile.md` 是否存在:
|
||||
- **存在** → 直接读取,跳过 1.1 的探索步骤,节省时间
|
||||
- **不存在** → 执行 1.1 完整探索,然后生成此文件
|
||||
- **用户说"刷新画像"** → 删除旧文件,重新执行 1.1
|
||||
|
||||
#### 1.2 找接口定义
|
||||
|
||||
根据用户要测的模块,定位路由注册代码,提取:
|
||||
|
||||
- **HTTP 方法**(GET / POST / PUT / DELETE / PATCH)
|
||||
- **路由路径**(含路径参数格式,如 `/users/:id` 或 `/users/{id}`)
|
||||
- **接口说明**(注释、Summary、装饰器描述)
|
||||
- **是否需要认证**
|
||||
- **请求 schema 类型名**(Input / Request DTO)
|
||||
- **响应 schema 类型名**(Output / Response DTO)
|
||||
|
||||
#### 1.3 读 schema 定义(DTO / struct / class / type)
|
||||
|
||||
定位请求和响应的 schema 定义文件,提取每个字段的:
|
||||
|
||||
- **字段名**:JSON 序列化后的名称(json tag / @JsonProperty / serializer field)
|
||||
- **语言类型**:string / int / bool / 数组 / 嵌套对象 / 可空等
|
||||
- **是否必填**:validate tag / required 装饰器 / 非空标注
|
||||
- **是否可空**:指针类型 / Optional / nullable
|
||||
- **是否参与序列化**:`json:"-"` / @JsonIgnore / exclude
|
||||
- **是否 omitempty**:`json:",omitempty"` / 条件序列化
|
||||
- **字段描述**:description tag / docstring / 注释
|
||||
|
||||
#### 1.4 识别业务依赖
|
||||
|
||||
读 service / business logic 层,识别:
|
||||
|
||||
- 创建操作需要哪些前置数据(如创建订单需要先有商品和用户)
|
||||
- 是否有唯一性约束(如用户名不能重复)
|
||||
- 是否依赖外部服务(支付网关、短信、OAuth 等)
|
||||
- 业务流转逻辑(状态机、级联操作)
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: 确认(Clarify)
|
||||
|
||||
**目标:向用户展示发现的内容,确认模糊点。不要闷头生成。**
|
||||
|
||||
#### 2.1 必须展示的内容
|
||||
|
||||
```
|
||||
我梳理了相关代码,发现以下信息:
|
||||
|
||||
📋 涉及接口:
|
||||
- [方法] [路径] - [说明](认证: 是/否)
|
||||
- ...
|
||||
|
||||
📦 响应字段(基于 {SchemaName}):
|
||||
- [字段名]: [类型] - [说明]
|
||||
- ...(共 N 个字段,将全部生成断言)
|
||||
|
||||
🔗 依赖关系:
|
||||
- [创建 X 需要先创建 Y]
|
||||
- ...
|
||||
|
||||
⚠️ 特殊情况:
|
||||
- [涉及外部服务 / 文件上传 / 特殊认证等]
|
||||
```
|
||||
|
||||
#### 2.2 按需确认(只问有歧义的)
|
||||
|
||||
| 场景 | 要问的 |
|
||||
|------|--------|
|
||||
| 流程范围不明确 | "要测到哪一步?" |
|
||||
| 多种用户角色 | "用哪种身份测?" |
|
||||
| 是否测异常 | "需要包含异常 case 吗?(参数校验失败、权限不足等)" |
|
||||
| 是否测数据隔离 | "需要验证不同用户间数据不可见吗?" |
|
||||
| 涉及第三方 | "XX 部分怎么处理?绕过 / 模拟回调 / 跳过?" |
|
||||
| 前置数据来源 | "XX 依赖数据是通过 API 创建还是假设已存在?" |
|
||||
|
||||
**如果用户说"越完整越好"或"都要"→ 默认全部包含,不再追问。**
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: 生成(Generate)
|
||||
|
||||
**目标:生成完整的 .hurl 文件,字段断言基于 schema 代码,不能编造。**
|
||||
|
||||
#### 3.1 文件头注释
|
||||
|
||||
```hurl
|
||||
# ============================================================
|
||||
# 测试:{测试名称}
|
||||
# 生成时间:{日期}
|
||||
# 涉及模块:{module1, module2, ...}
|
||||
# 涉及接口:{N} 个
|
||||
# 断言数量:{N} 条
|
||||
# 前置条件:{服务运行 + 必要的前置条件}
|
||||
# ============================================================
|
||||
# 流程:
|
||||
# 1. {步骤描述}
|
||||
# 2. {步骤描述}
|
||||
# ...
|
||||
# ============================================================
|
||||
```
|
||||
|
||||
#### 3.2 请求生成规则
|
||||
|
||||
**认证**:
|
||||
|
||||
- 根据 Phase 1 画像中的登录接口和 token 位置生成
|
||||
- token 必须通过 `[Captures]` 捕获,后续请求引用
|
||||
- 如果是 Cookie 认证,用 `[Cookies]` 或 cookie capture
|
||||
|
||||
**CRUD 标准模式**:
|
||||
|
||||
| 操作 | 生成要求 |
|
||||
|------|---------|
|
||||
| **创建(POST)** | capture 返回的 ID;**所有**唯一约束字段用 `{{newUuid}}` 防冲突 |
|
||||
| **查询详情(GET)** | **逐字段断言**(类型 + 值,见 3.3) |
|
||||
| **查询列表(GET)** | 分页结构断言 + items[0] 逐字段断言 |
|
||||
| **修改(PUT/PATCH)** | 修改后**紧跟一个 GET 验证修改生效** |
|
||||
| **删除(DELETE)** | 删除后**紧跟一个 GET 验证已删除** |
|
||||
|
||||
#### 唯一值防冲突规范(强制执行)
|
||||
|
||||
**所有创建类请求(POST)中,凡是有唯一约束的字段,必须使用 `{{newUuid}}` 或包含 UUID 后缀**,确保测试可重复运行。
|
||||
|
||||
| 场景 | 正确做法 | 错误做法 |
|
||||
|------|---------|---------|
|
||||
| 编码/Code 字段 | `"code": "TEST-{{newUuid}}"` | `"code": "TEST-001"` |
|
||||
| 名称(有唯一约束) | `"name": "测试-{{newUuid}}"` | `"name": "测试角色"` |
|
||||
| 用户名 | `"username": "hurl_{{newUuid}}"` | `"username": "test_user"` |
|
||||
| 手机号 | `"phone": "189{{newUuid}}"` 取前11位,或放在 env 文件 | `"phone": "18899990001"` |
|
||||
| 邮箱 | `"email": "{{newUuid}}@test.com"` | `"email": "test@test.com"` |
|
||||
|
||||
**后续步骤需要引用的值(如登录用的 username/password)**:
|
||||
- 必须定义在 `env/dev.env` 中作为变量
|
||||
- 在创建请求和后续引用处都通过 `{{变量名}}` 引用,保持一致
|
||||
- env 文件中的值也应该带有测试标识前缀(如 `hurl_test_`),避免与真实数据冲突
|
||||
- **env 中有唯一约束的变量值每次运行前可能需要更新**(文档中注明)
|
||||
|
||||
**业务流程模式**:
|
||||
|
||||
- 按用户描述的流程顺序编排请求
|
||||
- 上一步的输出(ID、状态等)通过 `[Captures]` 传给下一步
|
||||
- 关键步骤加中间状态验证(如创建订单后验证状态为"待支付")
|
||||
|
||||
#### 3.3 schema 到断言的映射
|
||||
|
||||
读到 schema 字段后,按以下规则生成 jsonpath 断言:
|
||||
|
||||
**通用类型映射(所有语言)**:
|
||||
|
||||
| Schema 类型特征 | Hurl 断言 |
|
||||
|----------------|-----------|
|
||||
| 字符串(string / str / String) | `isString` |
|
||||
| 整数(int / integer / long / Int) | `isInteger` |
|
||||
| 浮点(float / double / decimal / Float) | `isNumber` |
|
||||
| 布尔(bool / boolean / Boolean) | `isBoolean` |
|
||||
| 数组 / 列表([] / List / Array) | `isList` |
|
||||
| 嵌套对象(struct / class / dict / object) | `isObject`,并递归检查子字段 |
|
||||
| 可空类型(指针 / Optional / nullable) | `exists`(不强制类型,因为可能是 null) |
|
||||
| 不参与序列化(json:"-" / @JsonIgnore / exclude=True) | **跳过,不生成断言** |
|
||||
| 条件序列化(omitempty / if not None) | `exists` 或不生成(取决于场景) |
|
||||
|
||||
**Go 特定映射**:
|
||||
|
||||
| Go 类型 | Hurl 断言 |
|
||||
|---------|-----------|
|
||||
| `string` | `isString` |
|
||||
| `int`, `int8/16/32/64`, `uint`, `uint8/16/32/64` | `isInteger` |
|
||||
| `float32`, `float64` | `isNumber` |
|
||||
| `bool` | `isBoolean` |
|
||||
| `[]T` | `isList` |
|
||||
| `*string`, `*int`, `*uint` 等指针 | `exists` |
|
||||
| `time.Time` | `isString`(通常序列化为字符串) |
|
||||
| `map[string]any` | `isObject` |
|
||||
|
||||
**Python 特定映射(Pydantic / Django / FastAPI)**:
|
||||
|
||||
| Python 类型 | Hurl 断言 |
|
||||
|------------|-----------|
|
||||
| `str` | `isString` |
|
||||
| `int` | `isInteger` |
|
||||
| `float`, `Decimal` | `isNumber` |
|
||||
| `bool` | `isBoolean` |
|
||||
| `list[T]`, `List[T]` | `isList` |
|
||||
| `Optional[T]`, `T | None` | `exists` |
|
||||
| `dict`, `Dict` | `isObject` |
|
||||
| `datetime`, `date` | `isString` |
|
||||
|
||||
**TypeScript/JavaScript 特定映射**:
|
||||
|
||||
| TS/JS 类型 | Hurl 断言 |
|
||||
|-----------|-----------|
|
||||
| `string` | `isString` |
|
||||
| `number`(整数上下文) | `isInteger` |
|
||||
| `number`(通用) | `isNumber` |
|
||||
| `boolean` | `isBoolean` |
|
||||
| `T[]`, `Array<T>` | `isList` |
|
||||
| `T \| null`, `T \| undefined` | `exists` |
|
||||
| `object`, `Record<>` | `isObject` |
|
||||
| `Date` | `isString` |
|
||||
|
||||
**Java 特定映射**:
|
||||
|
||||
| Java 类型 | Hurl 断言 |
|
||||
|----------|-----------|
|
||||
| `String` | `isString` |
|
||||
| `Integer`, `Long`, `int`, `long` | `isInteger` |
|
||||
| `Double`, `Float`, `BigDecimal` | `isNumber` |
|
||||
| `Boolean`, `boolean` | `isBoolean` |
|
||||
| `List<T>` | `isList` |
|
||||
| `@Nullable`, `Optional<T>` | `exists` |
|
||||
| `Map<K,V>` | `isObject` |
|
||||
| `LocalDateTime`, `Instant` | `isString` |
|
||||
|
||||
#### 3.4 统一响应格式断言
|
||||
|
||||
根据 Phase 1 画像中发现的统一响应格式,为**每个成功响应**添加格式断言。
|
||||
|
||||
示例:如果项目的统一格式是 `{code, msg, data, timestamp}`:
|
||||
|
||||
```hurl
|
||||
[Asserts]
|
||||
jsonpath "$.code" == 0
|
||||
jsonpath "$.msg" == "success"
|
||||
jsonpath "$.timestamp" isIsoDate
|
||||
```
|
||||
|
||||
示例:如果项目的格式是 `{status, message, result}`:
|
||||
|
||||
```hurl
|
||||
[Asserts]
|
||||
jsonpath "$.status" == "ok"
|
||||
jsonpath "$.message" isString
|
||||
```
|
||||
|
||||
示例:如果项目无统一包装,直接返回数据:
|
||||
|
||||
```hurl
|
||||
[Asserts]
|
||||
# 直接断言业务字段
|
||||
jsonpath "$.id" isInteger
|
||||
jsonpath "$.name" isString
|
||||
```
|
||||
|
||||
**不要假设响应格式,必须从代码中确认。**
|
||||
|
||||
#### 3.5 分页断言
|
||||
|
||||
根据 Phase 1 画像中发现的分页结构生成。
|
||||
|
||||
示例:如果是 `{items, total, page, size}` 格式:
|
||||
|
||||
```hurl
|
||||
jsonpath "$.data.items" isList
|
||||
jsonpath "$.data.total" isInteger
|
||||
jsonpath "$.data.total" >= 1
|
||||
jsonpath "$.data.page" isInteger
|
||||
jsonpath "$.data.size" isInteger
|
||||
# items 内元素逐字段断言
|
||||
jsonpath "$.data.items[0].{field}" {type_assert}
|
||||
```
|
||||
|
||||
示例:如果是 `{results, count, next, previous}` 格式(Django 风格):
|
||||
|
||||
```hurl
|
||||
jsonpath "$.results" isList
|
||||
jsonpath "$.count" isInteger
|
||||
jsonpath "$.count" >= 1
|
||||
# results 内元素逐字段断言
|
||||
jsonpath "$.results[0].{field}" {type_assert}
|
||||
```
|
||||
|
||||
**根据实际代码调整字段名,不硬编码。**
|
||||
|
||||
#### 3.6 异常 Case 模板
|
||||
|
||||
**参数校验失败**:
|
||||
|
||||
```hurl
|
||||
# ── 异常:参数校验失败 ──
|
||||
POST {{base_url}}/{path}
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
{
|
||||
"required_field": ""
|
||||
}
|
||||
HTTP {expected_error_status}
|
||||
[Asserts]
|
||||
# 断言错误响应格式(根据项目约定调整)
|
||||
```
|
||||
|
||||
> HTTP 状态码根据项目实际返回确定:有的项目错误也返回 200 + 业务错误码,有的返回 400/422。
|
||||
|
||||
**未认证访问**:
|
||||
|
||||
```hurl
|
||||
# ── 异常:未认证访问 ──
|
||||
GET {{base_url}}/{protected_path}
|
||||
HTTP {expected_unauth_status}
|
||||
```
|
||||
|
||||
**越权访问**(如果用户要求):
|
||||
|
||||
```hurl
|
||||
# ── 异常:用户 B 不能访问用户 A 的资源 ──
|
||||
GET {{base_url}}/{path}/{{user_a_resource_id}}
|
||||
Authorization: Bearer {{user_b_token}}
|
||||
HTTP {expected_forbidden_status}
|
||||
```
|
||||
|
||||
#### 3.7 特殊场景处理
|
||||
|
||||
| 场景 | 处理策略 |
|
||||
|------|---------|
|
||||
| **短信/邮件验证码** | 建议服务端加 test_mode 开关,固定验证码写入 env 文件;注释提醒用户 |
|
||||
| **第三方支付** | 优先用项目内部支付方式(如钱包支付);如需测回调,直接 POST 回调接口模拟 |
|
||||
| **OAuth 登录(微信/Google/GitHub)** | 建议服务端加 test_mode 支持直接传 openid/email;注释提醒用户 |
|
||||
| **文件上传** | 用 Hurl 的 `[Multipart]` 语法 + testdata 目录下的样本文件 |
|
||||
| **外部 API 依赖** | 只测参数校验和错误响应格式,不断言业务结果;注释说明依赖 |
|
||||
| **WebSocket** | Hurl 不支持,注释说明跳过 |
|
||||
| **异步任务结果** | 用 Hurl 的 `retry` + `retry-interval` 轮询直到状态变更 |
|
||||
|
||||
异步轮询示例:
|
||||
|
||||
```hurl
|
||||
# 等待异步任务完成(最多重试 10 次,间隔 500ms)
|
||||
GET {{base_url}}/{path}/{{task_id}}
|
||||
Authorization: Bearer {{token}}
|
||||
[Options]
|
||||
retry: 10
|
||||
retry-interval: 500ms
|
||||
HTTP 200
|
||||
[Asserts]
|
||||
jsonpath "$.data.status" == "completed"
|
||||
```
|
||||
|
||||
#### 3.8 文件输出
|
||||
|
||||
**目录结构**(首次使用时创建,如不存在):
|
||||
|
||||
```
|
||||
tests/hurl/
|
||||
├── env/
|
||||
│ └── dev.env # 环境变量
|
||||
├── testdata/ # 测试用的样本文件
|
||||
├── flows/ # 业务流程测试
|
||||
├── modules/ # 按模块的接口测试
|
||||
│ └── {module}/
|
||||
│ └── 01-crud.hurl
|
||||
├── negative/ # 异常/边界测试
|
||||
├── contract/ # 接口契约验证
|
||||
├── reports/ # Phase 5 发现报告(自动生成)
|
||||
│ └── findings-{name}-{date}.md
|
||||
└── Makefile # 快捷命令
|
||||
```
|
||||
|
||||
文件放置规则:
|
||||
|
||||
| 用户描述 | 输出路径 |
|
||||
|---------|---------|
|
||||
| 测试 XX 流程 / 业务流程 | `tests/hurl/flows/{flow-name}.hurl` |
|
||||
| 测试 XX 模块的 CRUD / 接口 | `tests/hurl/modules/{module}/01-crud.hurl` |
|
||||
| 测试异常/边界/权限 | `tests/hurl/negative/{name}.hurl` |
|
||||
| 测试接口契约/字段对齐 | `tests/hurl/contract/{name}.hurl` |
|
||||
|
||||
**如果项目已有 hurl 测试目录结构,沿用已有约定,不要另起炉灶。**
|
||||
|
||||
#### 3.9 env 和 Makefile
|
||||
|
||||
**env/dev.env**(首次创建时生成,内容基于 Phase 1 画像):
|
||||
|
||||
```properties
|
||||
# 服务地址
|
||||
base_url=http://localhost:{port}
|
||||
|
||||
# 认证信息(根据项目实际填写)
|
||||
admin_username={默认用户名}
|
||||
admin_password={默认密码}
|
||||
|
||||
# 测试模式变量(如果有特殊场景)
|
||||
# test_sms_code=888888
|
||||
# test_openid=test_openid_001
|
||||
```
|
||||
|
||||
**Makefile**(首次创建时生成):
|
||||
|
||||
```makefile
|
||||
SHELL := /bin/bash
|
||||
ENV ?= dev
|
||||
HURL_OPTS := --variables-file env/$(ENV).env --test
|
||||
|
||||
.PHONY: test test-flows test-modules test-negative report
|
||||
|
||||
test: ## 运行所有测试
|
||||
hurl $(HURL_OPTS) .
|
||||
|
||||
test-flows: ## 运行业务流程测试
|
||||
hurl $(HURL_OPTS) flows/
|
||||
|
||||
test-modules: ## 运行模块接口测试
|
||||
hurl $(HURL_OPTS) modules/
|
||||
|
||||
test-negative: ## 运行异常测试
|
||||
hurl $(HURL_OPTS) negative/
|
||||
|
||||
report: ## 生成 HTML 报告
|
||||
hurl $(HURL_OPTS) --report-html build/report/ .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Phase 4: 验证(Verify)
|
||||
|
||||
**目标:确保生成的 .hurl 文件语法正确、可运行。**
|
||||
|
||||
#### 4.1 语法自检
|
||||
|
||||
- [ ] 每个请求之间有空行分隔
|
||||
- [ ] `[Captures]` 和 `[Asserts]` 拼写正确(大小写敏感)
|
||||
- [ ] 所有 `{{变量}}` 引用都有来源(env 文件定义 或 上游 `[Captures]`)
|
||||
- [ ] JSON body 无尾逗号、格式正确
|
||||
- [ ] `HTTP {status}` 在请求之后、`[Captures]` / `[Asserts]` 之前
|
||||
- [ ] 请求和断言之间没有多余空行(`HTTP` 行必须紧跟请求)
|
||||
- [ ] 文件上传路径相对于 hurl 文件位置正确
|
||||
|
||||
#### 4.2 运行测试
|
||||
|
||||
```bash
|
||||
hurl --variables-file tests/hurl/env/dev.env --test tests/hurl/{生成的文件}
|
||||
```
|
||||
|
||||
- 服务在跑 → 执行,如有失败分析修正
|
||||
- 服务没跑 → 跳过,告知用户手动验证命令
|
||||
|
||||
---
|
||||
|
||||
### Phase 5: 研判(Triage)
|
||||
|
||||
**目标:分析测试失败原因,区分"测试自身问题"和"接口问题",生成发现报告。**
|
||||
|
||||
> **核心原则:不因实际返回与预期不符而盲目修改断言。差异是"发现",需要分类研判。**
|
||||
|
||||
#### 5.1 失败分类(A/B/C 三类)
|
||||
|
||||
每个断言失败必须归入以下三类之一:
|
||||
|
||||
| 类型 | 含义 | 判断标准 | 处置方式 |
|
||||
|------|------|---------|---------|
|
||||
| **A 类 — 测试自身错误** | JSON path 写错、请求参数遗漏、env 变量缺失、前置步骤失败导致 ID 为空 | 改正后 DTO/Handler 代码能对应上 | ✅ **自动修正测试**,不打扰用户 |
|
||||
| **B 类 — 代码一致性问题** | DTO 定义和 Handler 实际返回不一致(如 DTO 写 `json:"id"` 但 Handler 返回 `"ID"`;DTO 定义了分页结构但 Handler 用了另一种) | DTO 说的是 A,Handler 做的是 B,两个都是代码 | ⚠️ **以 Handler 为准修正断言** + **写入发现报告** |
|
||||
| **C 类 — 接口行为 Bug** | 接口行为不符合合理预期(如详情接口缺少列表接口有的字段;创建接口返回 500;同一个 DTO 在不同接口表现不一致) | Handler 的行为本身不合理,不是 DTO 过期的问题 | 🐛 **保留原始断言(测试会失败)** + **写入发现报告** |
|
||||
|
||||
#### 5.2 分类判断流程
|
||||
|
||||
```
|
||||
断言失败
|
||||
│
|
||||
├─ jsonpath 写错 / 变量未定义 / 前置步骤失败?
|
||||
│ → A 类:修正测试
|
||||
│
|
||||
├─ DTO 定义字段名 ≠ 实际返回字段名?(如 id vs ID, list vs items)
|
||||
│ │
|
||||
│ ├─ Handler 代码确实返回了不同的结构?
|
||||
│ │ → B 类:以 Handler 为准,报告不一致
|
||||
│ │
|
||||
│ └─ Handler 代码引用了 DTO 但行为不符?
|
||||
│ → C 类:接口 Bug
|
||||
│
|
||||
├─ 某个字段在接口 A 有、接口 B 没有?(如列表有但详情没有)
|
||||
│ → C 类:接口一致性 Bug
|
||||
│
|
||||
├─ 接口返回 5xx 错误?
|
||||
│ → C 类:服务端 Bug
|
||||
│
|
||||
└─ 业务逻辑不符预期?(如已传 packages 但响应中 packages 为空)
|
||||
→ C 类:业务逻辑 Bug
|
||||
```
|
||||
|
||||
#### 5.3 发现报告格式
|
||||
|
||||
报告输出到 **`tests/hurl/reports/findings-{测试文件名}-{日期}.md`**,格式如下:
|
||||
|
||||
```markdown
|
||||
# 🔍 Hurl 测试发现报告
|
||||
|
||||
- 测试文件:`flows/package-resource-full-flow.hurl`
|
||||
- 生成时间:2026-03-30
|
||||
- 总请求数:25
|
||||
- 通过:20
|
||||
- 失败:5(A类: 2, B类: 1, C类: 2)
|
||||
|
||||
---
|
||||
|
||||
## A 类(测试自身错误)— 已自动修正
|
||||
|
||||
### A-1: 角色名冲突导致创建失败
|
||||
- **位置**:第 2 步 POST /api/admin/roles
|
||||
- **原因**:角色名使用固定值,重复运行时 409 冲突
|
||||
- **修正**:角色名改为 `hurl测试角色-{{newUuid}}`
|
||||
|
||||
---
|
||||
|
||||
## B 类(代码一致性问题)— 已按 Handler 修正断言
|
||||
|
||||
### B-1: 角色接口返回原始 GORM 模型而非 DTO
|
||||
- **位置**:POST /api/admin/roles → 响应
|
||||
- **DTO 定义**:`RoleResponse` 有 `json:"id"`(小写)
|
||||
- **Handler 实际**:直接返回 `model.Role`,字段为 `ID`(大写 GORM 默认)
|
||||
- **影响**:前端按 API 文档对接会取不到 `id` 字段
|
||||
- **建议**:Handler 添加 model → DTO 转换
|
||||
|
||||
---
|
||||
|
||||
## C 类(接口行为 Bug)— 断言保留,测试会失败
|
||||
|
||||
### C-1: 套餐详情接口缺少 one_time_commission_amount
|
||||
- **位置**:GET /api/admin/packages/:id(代理视角)
|
||||
- **预期**:`PackageResponse` DTO 定义了 `one_time_commission_amount` 字段
|
||||
- **实际**:列表接口 GET /packages 返回该字段,详情接口不返回
|
||||
- **影响**:代理端查看单个套餐时看不到佣金信息
|
||||
- **建议**:Detail handler 增加佣金信息增强逻辑
|
||||
|
||||
### C-2: 批量分配对已授权店铺返回 500
|
||||
- **位置**:POST /api/admin/shop-package-batch-allocations
|
||||
- **预期**:对已有授权的店铺,应返回业务错误码(4xx),而非 500
|
||||
- **实际**:返回 `{code: 2001, msg: "内部服务器错误"}`
|
||||
- **影响**:前端无法区分是参数错误还是服务异常
|
||||
- **建议**:添加"已存在授权"的前置检查,返回明确的业务错误
|
||||
```
|
||||
|
||||
#### 5.4 研判完成后的交付物
|
||||
|
||||
| 交付物 | 说明 |
|
||||
|-------|------|
|
||||
| **修正后的 .hurl 文件** | A 类已自动修正;B 类按 Handler 实际修正;C 类**保留原始断言**(预期失败) |
|
||||
| **发现报告** | `tests/hurl/reports/findings-{name}-{date}.md` |
|
||||
| **终端摘要** | 向用户输出发现数量和关键 C 类问题摘要 |
|
||||
|
||||
#### 5.5 用户交互
|
||||
|
||||
研判完成后,向用户展示摘要并询问:
|
||||
|
||||
```
|
||||
## 研判结果
|
||||
|
||||
- A 类(测试错误):N 个,已自动修正
|
||||
- B 类(一致性问题):N 个,已按实际修正并记录
|
||||
- C 类(接口 Bug):N 个,断言保留(测试会失败直到代码修复)
|
||||
|
||||
### C 类发现摘要:
|
||||
1. [C-1] 套餐详情缺少 one_time_commission_amount
|
||||
2. [C-2] 批量分配对已授权店铺返回 500
|
||||
|
||||
详细报告已写入: tests/hurl/reports/findings-xxx.md
|
||||
|
||||
是否需要对某个 C 类发现调整处置?(如确认为已知行为,改为 B 类)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 红线规则
|
||||
|
||||
| 规则 | 说明 |
|
||||
|------|------|
|
||||
| **不跳过 Phase 1** | 必须读代码确认接口路径和字段,不能凭记忆或猜测 |
|
||||
| **不跳过 Phase 2** | 必须向用户展示发现的接口和字段,确认后再生成 |
|
||||
| **不编造字段** | 所有断言的字段名必须来自实际 schema 代码 |
|
||||
| **不编造路径** | 所有接口路径必须来自实际路由代码 |
|
||||
| **不遗漏字段** | schema 中每个参与序列化的字段都必须有对应断言 |
|
||||
| **不硬编码 ID** | 所有依赖的 ID 通过 `[Captures]` 从上游请求获取 |
|
||||
| **不假设响应格式** | 统一响应结构必须从代码中确认,不同项目格式不同 |
|
||||
| **唯一值防冲突** | 创建类请求的**所有**唯一约束字段必须使用 `{{newUuid}}`(详见 3.2 规范) |
|
||||
| **自给自足** | 每个 .hurl 文件自己创建测试数据,不依赖外部数据准备 |
|
||||
| **不为通过而改断言** | 断言失败时走 Phase 5 研判流程,C 类 Bug 必须保留断言并写入发现报告 |
|
||||
| **Handler 追溯** | 断言字段名必须追溯到 Handler 实际返回的类型,不能只看 DTO 定义(详见 Phase 1 真理源层级) |
|
||||
|
||||
---
|
||||
|
||||
## AI 助手检查清单
|
||||
|
||||
### 生成阶段自检(Phase 3 完成后)
|
||||
|
||||
1. ✅ 文件头注释包含流程描述和前置条件
|
||||
2. ✅ 认证步骤正确 capture 了 token / cookie
|
||||
3. ✅ 所有依赖数据通过 API 链式创建(自给自足)
|
||||
4. ✅ 每个成功响应断言了项目的统一响应格式
|
||||
5. ✅ 查询详情接口**逐字段断言**(类型 + 值,基于 Handler 实际返回)
|
||||
6. ✅ 分页接口断言了分页结构 + 第一条记录的字段
|
||||
7. ✅ 修改操作后紧跟 GET 验证修改生效
|
||||
8. ✅ 删除操作后紧跟 GET 验证已删除
|
||||
9. ✅ **所有**创建请求的唯一约束字段使用了 `{{newUuid}}`
|
||||
10. ✅ `{{变量}}` 引用无悬空(都有 env 或 capture 来源)
|
||||
11. ✅ 文件放在了正确的目录位置
|
||||
12. ✅ 特殊场景有明确的处理策略和注释提醒
|
||||
13. ✅ 断言字段名已追溯到 Handler 实际返回类型(非仅依赖 DTO)
|
||||
|
||||
### 研判阶段自检(Phase 5 完成后)
|
||||
|
||||
14. ✅ 每个断言失败都已分类(A/B/C)
|
||||
15. ✅ A 类错误已自动修正
|
||||
16. ✅ B 类不一致已按 Handler 修正断言,并写入发现报告
|
||||
17. ✅ C 类 Bug 保留了原始断言(测试预期失败),并写入发现报告
|
||||
18. ✅ 发现报告已输出到 `tests/hurl/reports/findings-{name}-{date}.md`
|
||||
19. ✅ 向用户展示了研判结果摘要
|
||||
|
||||
---
|
||||
|
||||
## 附录:Hurl 语法速查
|
||||
|
||||
**生成 .hurl 文件时必须参照本速查,不可凭记忆编造语法。**
|
||||
|
||||
### 文件结构
|
||||
|
||||
一个 .hurl 文件由多个 entry 组成,每个 entry = 请求 + 可选响应:
|
||||
|
||||
```
|
||||
请求1
|
||||
响应1(可选)
|
||||
|
||||
请求2
|
||||
响应2(可选)
|
||||
```
|
||||
|
||||
entry 之间用空行分隔。
|
||||
|
||||
### 请求格式
|
||||
|
||||
```hurl
|
||||
METHOD URL
|
||||
Header1: value1
|
||||
Header2: value2
|
||||
[Options]
|
||||
key: value
|
||||
[Query]
|
||||
param1: value1
|
||||
[Form]
|
||||
field1: value1
|
||||
[Multipart]
|
||||
file1: file,path/to/file;
|
||||
[BasicAuth]
|
||||
username: password
|
||||
[Cookies]
|
||||
name: value
|
||||
BODY(JSON / XML / multiline string / file)
|
||||
```
|
||||
|
||||
**规则**:
|
||||
- Method + URL 是第一行,必须
|
||||
- Headers 紧跟 URL 之后(无 section 标记)
|
||||
- Sections(`[Query]`、`[Form]`、`[Options]` 等)顺序任意
|
||||
- Body 必须在最后
|
||||
- JSON body 直接写 `{ }` 即可,自动设置 Content-Type: application/json
|
||||
|
||||
### 响应格式
|
||||
|
||||
```hurl
|
||||
HTTP {status_code}
|
||||
Header1: expected_value1
|
||||
[Captures]
|
||||
var_name: jsonpath "$.path"
|
||||
[Asserts]
|
||||
jsonpath "$.field" == "value"
|
||||
```
|
||||
|
||||
**规则**:
|
||||
- `HTTP {status}` 紧跟请求之后(中间不能有空行)
|
||||
- `HTTP *` 表示不检查状态码
|
||||
- Headers 检查紧跟 HTTP 行之后
|
||||
- `[Captures]` 和 `[Asserts]` 顺序任意
|
||||
|
||||
### 变量和模板
|
||||
|
||||
```hurl
|
||||
# 引用变量(从 env 文件、命令行或上游 capture 获取)
|
||||
GET {{base_url}}/api/users/{{user_id}}
|
||||
|
||||
# 内置函数
|
||||
POST {{base_url}}/api/users
|
||||
{
|
||||
"email": "{{newUuid}}@test.com",
|
||||
"created_at": "{{newDate}}"
|
||||
}
|
||||
```
|
||||
|
||||
可用函数:
|
||||
- `{{newUuid}}` — 生成 UUID v4
|
||||
- `{{newDate}}` — 生成 RFC 3339 UTC 时间戳
|
||||
|
||||
### Capture 语法
|
||||
|
||||
```hurl
|
||||
[Captures]
|
||||
# JSONPath
|
||||
token: jsonpath "$.data.access_token"
|
||||
user_id: jsonpath "$.data.id"
|
||||
first_item: jsonpath "$.items[0].name"
|
||||
|
||||
# Header
|
||||
location: header "Location"
|
||||
|
||||
# Cookie
|
||||
session: cookie "SESSIONID"
|
||||
|
||||
# Body(整个响应体作为字符串)
|
||||
full_body: body
|
||||
|
||||
# Status code
|
||||
code: status
|
||||
|
||||
# 正则表达式
|
||||
csrf: regex "name=\"csrf\" value=\"([^\"]+)\""
|
||||
|
||||
# 响应时间(毫秒)
|
||||
response_time: duration
|
||||
```
|
||||
|
||||
### Assert 语法
|
||||
|
||||
```hurl
|
||||
[Asserts]
|
||||
# ── 状态码 ──
|
||||
status == 200
|
||||
status >= 200
|
||||
status < 300
|
||||
|
||||
# ── JSONPath 断言 ──
|
||||
jsonpath "$.name" == "Alice" # 等于
|
||||
jsonpath "$.name" != "Bob" # 不等于
|
||||
jsonpath "$.age" > 18 # 大于
|
||||
jsonpath "$.age" >= 18 # 大于等于
|
||||
jsonpath "$.count" < 100 # 小于
|
||||
jsonpath "$.items" count == 5 # 集合长度
|
||||
jsonpath "$.name" startsWith "Al" # 前缀
|
||||
jsonpath "$.name" endsWith "ce" # 后缀
|
||||
jsonpath "$.name" contains "lic" # 包含
|
||||
jsonpath "$.date" matches /\\d{4}-\\d{2}-\\d{2}/ # 正则
|
||||
|
||||
# ── 类型断言 ──
|
||||
jsonpath "$.name" isString
|
||||
jsonpath "$.age" isInteger
|
||||
jsonpath "$.score" isFloat
|
||||
jsonpath "$.count" isNumber # 整数或浮点
|
||||
jsonpath "$.active" isBoolean
|
||||
jsonpath "$.items" isList
|
||||
jsonpath "$.meta" isObject
|
||||
jsonpath "$.id" isUuid
|
||||
jsonpath "$.created_at" isIsoDate # RFC 3339 格式
|
||||
jsonpath "$.field" isEmpty # 空集合
|
||||
|
||||
# ── 存在性 ──
|
||||
jsonpath "$.field" exists
|
||||
jsonpath "$.field" not exists
|
||||
|
||||
# ── 否定 ──
|
||||
jsonpath "$.name" not contains "Bob"
|
||||
jsonpath "$.status" not == "deleted"
|
||||
|
||||
# ── Header 断言 ──
|
||||
header "Content-Type" contains "application/json"
|
||||
header "X-Request-Id" exists
|
||||
|
||||
# ── 性能 ──
|
||||
duration < 1000 # 响应时间(毫秒)
|
||||
|
||||
# ── Body 断言 ──
|
||||
body contains "Hello"
|
||||
bytes count == 1024
|
||||
```
|
||||
|
||||
### Options(逐请求配置)
|
||||
|
||||
```hurl
|
||||
GET {{base_url}}/api/task/{{task_id}}
|
||||
[Options]
|
||||
retry: 10 # 最大重试次数(-1 = 无限)
|
||||
retry-interval: 500ms # 重试间隔
|
||||
delay: 2s # 请求前等待
|
||||
location: true # 跟随重定向
|
||||
insecure: true # 允许不安全 SSL
|
||||
verbose: true # 输出详细日志
|
||||
very-verbose: true # 输出更详细日志
|
||||
skip: true # 跳过此请求
|
||||
variable: key=value # 定义变量
|
||||
HTTP 200
|
||||
```
|
||||
|
||||
### Multipart 文件上传
|
||||
|
||||
```hurl
|
||||
POST {{base_url}}/api/upload
|
||||
[Multipart]
|
||||
file: file,testdata/sample.xlsx;
|
||||
field1: value1
|
||||
# 指定 Content-Type
|
||||
file2: file,testdata/data.bin; application/octet-stream
|
||||
```
|
||||
|
||||
### 运行命令
|
||||
|
||||
```bash
|
||||
# 运行单个文件
|
||||
hurl --test file.hurl
|
||||
|
||||
# 带变量文件
|
||||
hurl --variables-file env/dev.env --test file.hurl
|
||||
|
||||
# 运行目录下所有 .hurl
|
||||
hurl --test tests/hurl/
|
||||
|
||||
# 生成 HTML 报告
|
||||
hurl --test --report-html build/report/ tests/hurl/
|
||||
|
||||
# 生成 JUnit 报告(CI 用)
|
||||
hurl --test --report-junit build/report.xml tests/hurl/
|
||||
|
||||
# 并行执行(--test 默认并行,同文件内串行)
|
||||
hurl --test --jobs 4 tests/hurl/
|
||||
|
||||
# 指定单个变量
|
||||
hurl --variable base_url=http://localhost:3000 --test file.hurl
|
||||
|
||||
# 失败后继续执行
|
||||
hurl --test --continue-on-error tests/hurl/
|
||||
```
|
||||
|
||||
### 常见错误
|
||||
|
||||
| 错误 | 原因 | 修正 |
|
||||
|------|------|------|
|
||||
| `HTTP 200` 和请求之间有空行 | 空行会被当作 entry 分隔符 | 删除空行,HTTP 行紧跟请求 |
|
||||
| JSON body 有尾逗号 | Hurl 严格解析 JSON | 删除最后一个逗号 |
|
||||
| `jsonpath` 写成 `json_path` 或 `JsonPath` | 关键字大小写敏感 | 必须小写 `jsonpath` |
|
||||
| `[Captures]` 写成 `[Capture]` | 必须是复数 | `[Captures]`、`[Asserts]`、`[Options]` |
|
||||
| 变量 `{{ var }}` 有空格 | 允许,但建议统一 | `{{var}}` 或 `{{ var }}` 都可以 |
|
||||
| `isIsoDate` 用在非 RFC 3339 格式 | 只认 `YYYY-MM-DDTHH:mm:ss` 格式 | 如果是其他格式用 `matches` |
|
||||
| `file,path;` 路径含 `..` | Hurl 禁止相对父目录 | 用 `--file-root` 或调整路径 |
|
||||
97
.opencode/skills/openspec-api-contract/SKILL.md
Normal file
97
.opencode/skills/openspec-api-contract/SKILL.md
Normal file
@@ -0,0 +1,97 @@
|
||||
---
|
||||
name: openspec-api-contract
|
||||
description: OpenSpec API 契约规范。创建涉及接口的 OpenSpec 提案时使用。探索阶段提供业务与契约引导清单,提案文档要求 API 契约设计、错误码与完成标准等必填章节。
|
||||
---
|
||||
|
||||
# OpenSpec API 契约规范
|
||||
|
||||
**适用场景**:创建涉及 API/接口的 OpenSpec 提案时,探索和提案两个阶段均须遵守本规范。
|
||||
|
||||
---
|
||||
|
||||
## 一、探索阶段引导清单
|
||||
|
||||
在 `openspec-explore` 阶段,当内容涉及接口时,讨论必须覆盖以下所有维度。
|
||||
|
||||
### 业务与契约确认
|
||||
|
||||
**输入与输出**
|
||||
- 请求方是谁?用户类型(SuperAdmin/Platform/Agent/Enterprise/Personal)?
|
||||
- 输入参数:必填/选填字段、格式约束、参数来源(路径/查询/Body)?
|
||||
- 输出结构:哪些字段必须返回?是否需要分页?
|
||||
|
||||
**业务规则**
|
||||
- 核心业务规则与边界条件?
|
||||
- 是否涉及状态流转?状态机的完整定义?
|
||||
- 依赖外部服务时,外部异常的降级行为?
|
||||
|
||||
**权限与资源所有权**
|
||||
- 哪些用户类型可以访问?
|
||||
- 是否涉及跨用户/跨店铺/跨企业的资源访问?(需三层越权防护)
|
||||
- 资源所有权校验方式:`CanManageShop` / `CanManageEnterprise` / 自有资源?
|
||||
|
||||
**幂等性**
|
||||
- 操作类型:查询(天然幂等)/ 创建 / 更新 / 删除?
|
||||
- 写操作幂等策略:状态条件更新 / Redis 业务键防重 + 分布式锁 / 乐观锁(version)?
|
||||
- 异步任务是否需要任务锁?
|
||||
|
||||
**数据模型变更**
|
||||
- 是否需要新建表、修改现有表或数据回填?
|
||||
- 迁移策略:上线顺序、兼容旧数据的方式?
|
||||
- 是否影响 GORM Callback 自动数据权限过滤?
|
||||
|
||||
**错误码与异常语义**
|
||||
- 预期错误场景及对应错误码?
|
||||
- 错误响应是否泄露敏感信息?(参数校验失败统一返回 `CodeInvalidParam`)
|
||||
|
||||
---
|
||||
|
||||
## 二、提案文档必填章节
|
||||
|
||||
在 `openspec-propose` 生成的提案(`proposal.md` / `design.md`)中,涉及接口时以下内容**不可缺失**。
|
||||
|
||||
### API 契约设计
|
||||
|
||||
**接口定义**
|
||||
|
||||
| 项 | 内容 |
|
||||
|---|---|
|
||||
| Endpoint | `METHOD /api/{scope}/{resource}[/:id]` |
|
||||
| 请求参数 | 字段名、类型、必填/选填、说明 |
|
||||
| 响应结构 | `data` 字段的完整结构定义 |
|
||||
| 鉴权要求 | 允许的用户类型 |
|
||||
| 资源所有权 | 所有权校验方式 |
|
||||
|
||||
**列表接口额外要求**
|
||||
- 分页:`page` + `page_size`(默认 20,最大 100)
|
||||
- 排序:默认排序字段与方向
|
||||
- 过滤:支持的过滤条件列表
|
||||
|
||||
**错误码清单**
|
||||
|
||||
| 场景 | 错误码 | 说明 |
|
||||
|---|---|---|
|
||||
| 参数校验失败 | `CodeInvalidParam` | 统一返回,不泄露细节 |
|
||||
| 资源不存在/越权 | `CodeForbidden` | 不区分两者,防止信息泄露 |
|
||||
| (业务错误场景...) | (对应错误码) | (说明) |
|
||||
|
||||
### 完成标准
|
||||
|
||||
**最小验证步骤**(按顺序列出可操作的验证步骤)
|
||||
|
||||
1. (例:调用创建接口,验证返回 `code=0`)
|
||||
2. (例:查询接口确认数据存在且字段正确)
|
||||
3. (例:PostgreSQL MCP 查询确认数据库记录符合预期)
|
||||
|
||||
**影响范围说明**
|
||||
- 新增/修改的表:
|
||||
- 影响的现有接口:
|
||||
- 影响的权限与数据过滤范围:
|
||||
|
||||
---
|
||||
|
||||
## 约束(必须遵守)
|
||||
|
||||
- **优先复用现有架构与库**:不引入新依赖,错误码优先复用已有定义
|
||||
- **不做顺手重构**:提案范围严格限定在目标功能;发现可优化点,记录到 backlog 但不执行
|
||||
- **数据库设计**:禁止外键约束,禁止 GORM 关联标签,关联通过 ID 字段手动维护
|
||||
@@ -1,265 +0,0 @@
|
||||
---
|
||||
name: systematic-debugging
|
||||
description: 遇到任何 bug、异常行为、报错时必须使用。在提出任何修复方案之前,强制执行根因分析流程。适用于 API 报错、数据异常、业务逻辑错误、性能问题等所有技术问题。
|
||||
license: MIT
|
||||
metadata:
|
||||
author: junhong
|
||||
version: "1.0"
|
||||
source: "adapted from obra/superpowers systematic-debugging"
|
||||
---
|
||||
|
||||
# 系统化调试方法论
|
||||
|
||||
## 铁律
|
||||
|
||||
```
|
||||
没有找到根因,禁止提出任何修复方案。
|
||||
```
|
||||
|
||||
改之前先搞懂为什么坏了。猜测不是调试,验证假设才是。
|
||||
|
||||
---
|
||||
|
||||
## 什么时候用
|
||||
|
||||
**所有技术问题都用这个流程**:
|
||||
- API 接口报错(4xx / 5xx)
|
||||
- 业务数据异常(金额不对、状态流转错误)
|
||||
- 性能问题(接口慢、数据库慢查询)
|
||||
- 异步任务失败(Asynq 任务报错/卡住)
|
||||
- 构建失败、启动失败
|
||||
|
||||
**尤其是以下场景**:
|
||||
- 时间紧迫(越急越不能瞎猜)
|
||||
- "很简单的问题"(简单问题也有根因)
|
||||
- 已经试了一次修复但没解决
|
||||
- 不完全理解为什么出问题
|
||||
|
||||
---
|
||||
|
||||
## 四阶段流程
|
||||
|
||||
必须按顺序完成每个阶段,不可跳过。
|
||||
|
||||
### 阶段一:根因调查
|
||||
|
||||
**这是最重要的阶段,占整个调试时间的 60%。没完成本阶段,禁止进入阶段二。**
|
||||
|
||||
#### 1. 仔细阅读错误信息
|
||||
|
||||
- 完整阅读 stack trace,不要跳过
|
||||
- 注意行号、文件路径、错误码
|
||||
- 很多时候答案就在错误信息里
|
||||
- 检查 `logs/app.log` 和 `logs/access.log` 中的上下文
|
||||
|
||||
#### 2. 稳定复现
|
||||
|
||||
- 能稳定触发吗?精确的请求参数是什么?
|
||||
- 用 curl 或 Postman 复现,记录完整的请求和响应
|
||||
- 不能复现 → 收集更多数据(检查日志、Redis 状态、数据库记录),**不要瞎猜**
|
||||
|
||||
#### 3. 检查最近改动
|
||||
|
||||
- `git diff` / `git log --oneline -10` 看最近改了什么
|
||||
- 新加了什么依赖?改了什么配置?改了什么 SQL?
|
||||
- 对比改动前后的行为差异
|
||||
|
||||
#### 4. 逐层诊断(针对本项目架构)
|
||||
|
||||
本项目有明确的分层架构,问题一定出在某一层的边界:
|
||||
|
||||
```
|
||||
请求 → Fiber Middleware → Handler → Service → Store → PostgreSQL/Redis
|
||||
↑ ↑ ↑ ↑ ↑
|
||||
认证/限流 参数解析 业务逻辑 SQL/缓存 数据本身
|
||||
```
|
||||
|
||||
**在每个层边界确认数据是否正确**:
|
||||
|
||||
```go
|
||||
// Handler 层 — 请求进来的参数对不对?
|
||||
logger.Info("Handler 收到请求",
|
||||
zap.Any("params", req),
|
||||
zap.String("request_id", requestID),
|
||||
)
|
||||
|
||||
// Service 层 — 传给业务逻辑的数据对不对?
|
||||
logger.Info("Service 开始处理",
|
||||
zap.Uint("user_id", userID),
|
||||
zap.Any("input", input),
|
||||
)
|
||||
|
||||
// Store 层 — SQL 查询/写入的数据对不对?
|
||||
// 开启 GORM Debug 模式查看实际 SQL
|
||||
db.Debug().Where(...).Find(&result)
|
||||
|
||||
// Redis 层 — 缓存的数据对不对?
|
||||
// 用 redis-cli 直接检查 key 的值
|
||||
// GET auth:token:{token}
|
||||
// GET sim:status:{iccid}
|
||||
```
|
||||
|
||||
**跑一次 → 看日志 → 找到断裂的那一层 → 再深入该层排查。**
|
||||
|
||||
#### 5. 追踪数据流
|
||||
|
||||
如果错误深藏在调用链中:
|
||||
- 坏数据从哪来的?
|
||||
- 谁调用了这个函数,传了什么参数?
|
||||
- 一直往上追,直到找到数据变坏的源头
|
||||
- **修源头,不修症状**
|
||||
|
||||
---
|
||||
|
||||
### 阶段二:模式分析
|
||||
|
||||
**找到参照物,对比差异。**
|
||||
|
||||
#### 1. 找能用的参照
|
||||
|
||||
项目里有没有类似的、能正常工作的代码?
|
||||
|
||||
| 如果问题在... | 参照物在... |
|
||||
|-------------|-----------|
|
||||
| Handler 参数解析 | 其他 Handler 的相同模式 |
|
||||
| Service 业务逻辑 | 同模块其他方法的实现 |
|
||||
| Store SQL 查询 | 同 Store 文件中类似的查询 |
|
||||
| Redis 操作 | `pkg/constants/redis.go` 中的 Key 定义 |
|
||||
| 异步任务 | `internal/task/` 中其他任务处理器 |
|
||||
| GORM Callback | `pkg/database/` 中的 callback 实现 |
|
||||
|
||||
#### 2. 逐行对比
|
||||
|
||||
完整阅读参考代码,不要跳读。列出每一处差异。
|
||||
|
||||
#### 3. 不要假设"这个不重要"
|
||||
|
||||
小差异经常是 bug 的根因:
|
||||
- 字段标签 `gorm:"column:xxx"` 拼写不对
|
||||
- `errors.New()` 用了错误的错误码
|
||||
- Redis Key 函数参数传反了
|
||||
- Context 里的 UserID 没取到(中间件没配)
|
||||
|
||||
---
|
||||
|
||||
### 阶段三:假设和验证
|
||||
|
||||
**科学方法:一次只验证一个假设。**
|
||||
|
||||
#### 1. 形成单一假设
|
||||
|
||||
明确写下:
|
||||
|
||||
> "我认为根因是 X,因为 Y。验证方法是 Z。"
|
||||
|
||||
#### 2. 最小化验证
|
||||
|
||||
- 只改一个地方
|
||||
- 一次只验证一个变量
|
||||
- 不要同时修多处
|
||||
|
||||
#### 3. 验证结果
|
||||
|
||||
- 假设成立 → 进入阶段四
|
||||
- 假设不成立 → 回到阶段一,用新信息重新分析
|
||||
- **绝对不能在失败的修复上再叠加修复**
|
||||
|
||||
#### 4. 三次失败 → 停下来
|
||||
|
||||
如果连续 3 次假设都不成立:
|
||||
|
||||
**这不是 bug,是架构问题。**
|
||||
|
||||
- 停止一切修复尝试
|
||||
- 整理已知信息
|
||||
- 向用户说明情况,讨论是否需要重构
|
||||
- 不要再试第 4 次
|
||||
|
||||
---
|
||||
|
||||
### 阶段四:实施修复
|
||||
|
||||
**确认根因后,一次性修好。**
|
||||
|
||||
#### 1. 修根因,不修症状
|
||||
|
||||
```
|
||||
❌ 症状修复:在 Handler 里加个 if 把坏数据过滤掉
|
||||
✅ 根因修复:修 Service 层生成坏数据的逻辑
|
||||
```
|
||||
|
||||
#### 2. 一次只改一个地方
|
||||
|
||||
- 不搞"顺手优化"
|
||||
- 不在修 bug 的同时重构代码
|
||||
- 修完 bug 就停
|
||||
|
||||
#### 3. 验证修复
|
||||
|
||||
- `go build ./...` 编译通过
|
||||
- `lsp_diagnostics` 无新增错误
|
||||
- 用原来复现 bug 的请求再跑一次,确认修好了
|
||||
- 用 PostgreSQL MCP 工具检查数据库中的数据状态
|
||||
|
||||
#### 4. 清理诊断代码
|
||||
|
||||
- 删除阶段一加的临时诊断日志(除非它们本身就该保留)
|
||||
- 确保没有 `db.Debug()` 残留在代码里
|
||||
|
||||
---
|
||||
|
||||
## 本项目常见调试场景速查
|
||||
|
||||
| 场景 | 首先检查 |
|
||||
|------|---------|
|
||||
| API 返回 401 | `logs/access.log` 中该请求的 token → Redis 中 `auth:token:{token}` 是否存在 |
|
||||
| API 返回 403 | 用户类型是什么 → GORM Callback 自动过滤的条件对不对 → `middleware.CanManageShop()` 的参数 |
|
||||
| 数据查不到 | GORM 数据权限过滤有没有生效 → `shop_id` / `enterprise_id` 是否正确 → 是否需要 `SkipDataPermission` |
|
||||
| 金额/余额不对 | 乐观锁 version 字段 → `RowsAffected` 是否为 0 → 并发场景下的锁竞争 |
|
||||
| 状态流转错误 | `WHERE status = expected` 条件更新 → 状态机是否有遗漏的路径 |
|
||||
| 异步任务不执行 | Asynq Dashboard → `RedisTaskLockKey` 有没有残留 → Worker 日志 |
|
||||
| 异步任务重复执行 | `RedisTaskLockKey` 的 TTL → 任务幂等性检查 |
|
||||
| 分佣计算错误 | 佣金类型(差价/一次性) → 套餐级别的佣金率 → 设备级防重复分佣 |
|
||||
| 套餐激活异常 | 卡状态 → 实名状态 → 主套餐排队逻辑 → 加油包绑定关系 |
|
||||
| Redis 缓存不一致 | Key 的 TTL → 缓存更新时机 → 是否有手动 `Del` 清除 |
|
||||
| 微信支付回调失败 | 签名验证 → 幂等性处理 → 回调 URL 是否可达 |
|
||||
| GORM 查询慢 | `db.Debug()` 看实际 SQL → 是否 N+1 → 是否缺少索引 |
|
||||
|
||||
---
|
||||
|
||||
## 红线规则
|
||||
|
||||
如果你发现自己在想以下任何一条,**立刻停下来,回到阶段一**:
|
||||
|
||||
| 想法 | 为什么是错的 |
|
||||
|------|------------|
|
||||
| "先快速修一下,回头再查" | 快速修 = 猜测。猜测 = 浪费时间。 |
|
||||
| "试试改这个看看行不行" | 一次只验证一个假设,不是随机改。 |
|
||||
| "大概是 X 的问题,我直接改了" | "大概"不是根因。先验证再改。 |
|
||||
| "这个很简单,不用走流程" | 简单问题走流程只需要 5 分钟。不走流程可能浪费 2 小时。 |
|
||||
| "我不完全理解但这应该行" | 不理解 = 没找到根因。回阶段一。 |
|
||||
| "再试一次"(已经失败 2 次) | 3 次失败 = 架构问题。停下来讨论。 |
|
||||
| "同时改这几个地方应该能修好" | 改多处 = 无法确认哪个是根因。一次只改一处。 |
|
||||
|
||||
---
|
||||
|
||||
## 常见借口和真相
|
||||
|
||||
| 借口 | 真相 |
|
||||
|------|------|
|
||||
| "问题很简单,不需要走流程" | 简单问题也有根因。走流程对简单问题只花 5 分钟。 |
|
||||
| "太紧急了,没时间分析" | 系统化调试比乱猜快 3-5 倍。越急越要走流程。 |
|
||||
| "先改了验证一下" | 这叫猜测,不叫验证。先确认根因再改。 |
|
||||
| "我看到问题了,直接修" | 看到症状 ≠ 理解根因。症状修复是技术债。 |
|
||||
| "改了好几个地方,反正能用了" | 不知道哪个改动修的,下次还会出问题。 |
|
||||
|
||||
---
|
||||
|
||||
## 快速参考
|
||||
|
||||
| 阶段 | 核心动作 | 完成标准 |
|
||||
|------|---------|---------|
|
||||
| **一、根因调查** | 读错误日志、复现、检查改动、逐层诊断、追踪数据流 | 能说清楚"因为 X 所以 Y" |
|
||||
| **二、模式分析** | 找参照代码、逐行对比、列出差异 | 知道正确的应该长什么样 |
|
||||
| **三、假设验证** | 写下假设、最小改动、单变量验证 | 假设被证实或推翻 |
|
||||
| **四、实施修复** | 修根因、编译检查、请求验证、清理诊断代码 | bug 消失,无新增问题 |
|
||||
126
.scratch/customer-binding-architecture/PRD.md
Normal file
126
.scratch/customer-binding-architecture/PRD.md
Normal file
@@ -0,0 +1,126 @@
|
||||
Status: ready-for-agent
|
||||
|
||||
# PRD:客户绑定体系重构与资产归属验证统一
|
||||
|
||||
## Problem Statement
|
||||
|
||||
C 端用户在使用没有虚拟号的 IoT 卡时,整个业务流程完全失效:登录后无法实名认证、无法购买套餐、无法操作设备。根本原因是系统的客户绑定机制依赖虚拟号(`virtual_no`)作为唯一标识,而虚拟号在 IoT 卡上是可选字段,线上有 12,000+ 张无虚拟号的卡且确认会流向 C 端用户。
|
||||
|
||||
与此同时,换货流程在旧卡有虚拟号、新卡无虚拟号时会被错误拦截,即使旧卡实际上没有任何客户绑定记录,换货依然报错"新资产无法承接客户绑定"。
|
||||
|
||||
从设计层面看,`tb_personal_customer_iccid` 表(按 ICCID 绑定)早已建好,Store 层也实现完整,但从未被任何 Service 或 Handler 接入。同时,"判断某张卡/设备是否属于某个客户"这个核心安全规则,散落在 6 个文件中以 4 种不同方式实现,部分实现缺少对已禁用绑定记录的过滤,存在安全缺口。
|
||||
|
||||
## Solution
|
||||
|
||||
建立统一的 **CustomerBinding 模块**,封装客户与资产之间的绑定创建和归属验证逻辑,屏蔽"有虚拟号走 `tb_personal_customer_device` / 无虚拟号走 `tb_personal_customer_iccid`"的路由细节。所有调用方只需传入资产信息,不感知底层用了哪张表。
|
||||
|
||||
在此基础上,修复换货服务中校验与执行逻辑混淆的 bug,并将资产解析和 IoT 卡状态字段整理为后续阶段任务。
|
||||
|
||||
## User Stories
|
||||
|
||||
### C 端用户(无虚拟号的卡)
|
||||
|
||||
1. 作为一个持有无虚拟号 IoT 卡的 C 端用户,我想在首次登录时成功绑定我的卡,以便后续能正常使用所有 C 端功能。
|
||||
2. 作为一个持有无虚拟号 IoT 卡的 C 端用户,我想在绑定卡后能正常提交实名认证,以便激活卡的完整功能。
|
||||
3. 作为一个持有无虚拟号 IoT 卡的 C 端用户,我想购买流量套餐,以便为我的卡充值续费。
|
||||
4. 作为一个持有无虚拟号 IoT 卡的 C 端用户,我想在换货后仍能访问新卡并正常操作,以便换货不影响我的使用体验。
|
||||
|
||||
### C 端用户(有虚拟号的卡)
|
||||
|
||||
5. 作为一个持有有虚拟号 IoT 卡的 C 端用户,我的所有现有功能不受本次改动影响,以便升级对我透明无感知。
|
||||
6. 作为一个持有有虚拟号 IoT 卡的 C 端用户,当我的绑定关系被禁用后,我不能通过该绑定关系访问资产,以便系统安全边界得到保障。
|
||||
|
||||
### 后台运营人员(换货)
|
||||
|
||||
7. 作为后台运营人员,我想将一张有虚拟号的旧卡换货为一张无虚拟号的新卡,并且换货能正常完成,以便不再因无虚拟号而被系统错误拦截。
|
||||
8. 作为后台运营人员,当旧卡有客户绑定记录、新卡无虚拟号时,我希望系统在换货完成后自动将客户绑定迁移到新卡的 ICCID,以便客户换货后仍能访问新卡。
|
||||
9. 作为后台运营人员,当旧卡没有任何客户绑定记录时,无论旧卡是否有虚拟号,换货都应该正常完成,以便换货流程不被无意义的条件拦截。
|
||||
|
||||
### 系统(数据一致性)
|
||||
|
||||
10. 作为系统,当客户首次绑定一张无虚拟号的卡时,应正确将该卡的 `asset_status` 从在库更新为已销售,以便轮询系统能感知到该卡有真实用户在使用。
|
||||
11. 作为系统,当客户的绑定关系被禁用(`status=0`)后,归属验证应拒绝该客户访问对应资产,以便被撤销的绑定不再赋予访问权限。
|
||||
|
||||
## Implementation Decisions
|
||||
|
||||
### 1. 新增 CustomerBinding 模块
|
||||
|
||||
在 `internal/service/` 下建立 `customer_binding` 包,对外暴露两个核心接口:
|
||||
|
||||
- `Bind(ctx, tx, customerID, assetType, assetID)` — 创建或更新客户与资产的绑定关系;对于卡资产,有虚拟号写 `tb_personal_customer_device`,无虚拟号写 `tb_personal_customer_iccid`
|
||||
- `OwnsAsset(ctx, customerID, assetType, assetID) bool` — 验证客户是否持有该资产的有效绑定(`status=1`);按资产类型路由到对应绑定表查询
|
||||
- `Migrate(ctx, tx, oldAsset, newAsset)` — 换货时迁移绑定关系;处理四种组合(有→有、有→无、无→有、无→无)
|
||||
|
||||
`OwnsAsset` 内部统一强制 `status=1` 过滤,解决当前部分实现缺少此过滤的安全缺口。
|
||||
|
||||
### 2. 绑定路由规则(卡资产)
|
||||
|
||||
| 旧卡 | 新卡 | Migrate 行为 |
|
||||
|------|------|-------------|
|
||||
| 有虚拟号,有 pcd 绑定 | 有虚拟号 | 更新 pcd 记录的 virtual_no |
|
||||
| 有虚拟号,有 pcd 绑定 | 无虚拟号 | 禁用旧 pcd 记录 + 创建 pci ICCID 绑定 |
|
||||
| 有虚拟号,无绑定 | 无虚拟号 | 跳过(无需迁移) |
|
||||
| 无虚拟号 | 任意 | 迁移 pci 记录(若存在)到新卡 ICCID |
|
||||
|
||||
### 3. 接入 CustomerBinding 的调用点
|
||||
|
||||
以下调用点需要替换为 CustomerBinding 模块:
|
||||
|
||||
- `client_auth/service.go: bindAsset()` — 使用 `CustomerBinding.Bind()`
|
||||
- `client_auth/service.go: resolveAssetBindingKey()` — 废弃,逻辑内聚到 CustomerBinding
|
||||
- `handler/app/client_realname.go: ExistsByCustomerAndDevice()` — 替换为 `CustomerBinding.OwnsAsset()`
|
||||
- `handler/app/client_device.go: ExistsByCustomerAndDevice()` — 替换为 `CustomerBinding.OwnsAsset()`
|
||||
- `handler/app/client_wallet.go: isCustomerOwnAsset()` — 替换为 `CustomerBinding.OwnsAsset()`
|
||||
- `handler/app/client_asset.go: isCustomerOwnAsset()` — 替换为 `CustomerBinding.OwnsAsset()`
|
||||
- `service/client_order/service.go: checkAssetOwnership()` — 替换为 `CustomerBinding.OwnsAsset()`
|
||||
- `service/exchange/service.go: switchCustomerBindingWithTx()` — 替换为 `CustomerBinding.Migrate()`
|
||||
|
||||
### 4. 修复 switchCustomerBindingWithTx 的校验混淆
|
||||
|
||||
当前 `switchCustomerBindingWithTx`(执行函数)在执行阶段重复做了 `ensureNewAssetBindingAvailableWithTx`(校验函数)的判断,且条件更严(不查实际记录数,只看 key 是否为空)。
|
||||
|
||||
修复方式:将 `switchCustomerBindingWithTx` 改为调用 `CustomerBinding.Migrate()`,移除函数内的 `newKey==""` 拦截逻辑。`ensureNewAssetBindingAvailableWithTx` 同步更新:当 `newKey==""` 时,不再拦截,因为 `Migrate()` 已能正确处理此情形。
|
||||
|
||||
### 5. asset_status 首销标记修复
|
||||
|
||||
`bindAsset` 中通过 `firstEverBind`(查 `virtual_no=""` 的记录数)来判断是否首次绑定并触发 `markAssetAsSold()`。无虚拟号的卡因为 key 为空,导致此逻辑失效,`asset_status` 永远停在在库。
|
||||
|
||||
修复方式:在 `CustomerBinding.Bind()` 内,对 IoT 卡分别按各自绑定表查询首绑状态,再触发 `markAssetAsSold()`。
|
||||
|
||||
### 6. 不引入新的数据库表或字段
|
||||
|
||||
`tb_personal_customer_iccid` 表和 `PersonalCustomerICCIDStore` 已经存在且完整,本次只是接入,不需要迁移或 schema 变更。
|
||||
|
||||
### 7. 现有 personal_customer_device 数据不迁移
|
||||
|
||||
有虚拟号的卡现有绑定数据保持不变,继续走 `tb_personal_customer_device` 路径。只有无虚拟号的卡新登录时才写 `tb_personal_customer_iccid`。
|
||||
|
||||
## Testing Decisions
|
||||
|
||||
本项目禁止自动化测试,使用 PostgreSQL MCP 和 Postman/curl 手动验证。
|
||||
|
||||
**验证重点场景:**
|
||||
|
||||
1. **无虚拟号卡首次登录**:用无虚拟号卡的 ICCID 登录后,`tb_personal_customer_iccid` 应出现绑定记录,`tb_iot_card.asset_status` 应变为 2(已销售)
|
||||
2. **无虚拟号卡归属验证**:登录后调用实名认证接口,应返回成功而非"无权限"
|
||||
3. **无虚拟号卡购买套餐**:购买套餐接口应正常通过归属验证
|
||||
4. **有虚拟号换无虚拟号(旧卡有绑定)**:换货完成后,`tb_personal_customer_device` 旧记录 status 应为 0,`tb_personal_customer_iccid` 应出现新卡 ICCID 的绑定记录
|
||||
5. **有虚拟号换无虚拟号(旧卡无绑定)**:换货应正常完成,无报错,不写入任何绑定记录
|
||||
6. **有虚拟号换有虚拟号(回归)**:现有流程不受影响,pcd 表记录的 virtual_no 正确更新到新卡
|
||||
7. **禁用绑定后归属验证**:将某条 pcd 或 pci 记录 status 设为 0,对应客户调用归属验证应返回无权限
|
||||
8. **有虚拟号卡回归(全流程)**:确认有虚拟号卡的登录、实名、购买套餐流程无任何变化
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- **IoT 卡状态字段整理**(`status` / `asset_status` / `activation_status` 语义重叠问题):影响面广,单独规划
|
||||
- **资产解析函数统一**(12 个 resolve 变体合并):不影响当前 bug,单独规划
|
||||
- **`tb_personal_customer_iccid` 换货迁移的历史数据回填**:历史上无虚拟号卡的用户无绑定记录,不做回填,用户需重新登录
|
||||
- **`tb_personal_customer_device` 中 `virtual_no=""` 的历史垃圾数据清理**:需先确认实际数量(SQL 查询),作为独立数据修复任务
|
||||
|
||||
## Further Notes
|
||||
|
||||
- 线上有 12,000+ 张无虚拟号的 IoT 卡,这是合法业务数据,不是数据质量问题
|
||||
- `tb_personal_customer_iccid` 的 Store 已有完整的 CRUD 实现(Create、ExistsByCustomerAndICCID、GetByCustomerID、CreateOrUpdateLastUsed 等),无需重写
|
||||
- 换货 bug 的直接触发路径:`completeExchangeWithTx → switchCustomerBindingWithTx`,在执行阶段因 `newKey==""` 报错,即使旧卡实际无任何客户绑定记录
|
||||
- 建议在上线前执行:`SELECT COUNT(*) FROM tb_personal_customer_device WHERE (virtual_no IS NULL OR virtual_no = '') AND deleted_at IS NULL` 确认是否有历史脏数据需要清理
|
||||
- **临时线上补丁(知悉)**:2026-06-18 已将线上 12,000+ 张无虚拟号的卡手动补充了虚拟号作为应急措施,以保障线上可用性。数据回滚由业务方自行处理,不在本次实现范围内。
|
||||
@@ -0,0 +1,50 @@
|
||||
Status: done
|
||||
|
||||
# CustomerBinding 模块骨架 + 有虚拟号路径替换(纯重构)
|
||||
|
||||
## What to build
|
||||
|
||||
建立 `internal/service/customer_binding` 包,对外暴露 `Bind()` 和 `OwnsAsset()` 两个接口,将现有有虚拟号路径的逻辑迁入。同时将代码库中 6 处归属验证调用点统一替换为新接口。
|
||||
|
||||
**本切片是纯重构,不改变任何现有行为。**
|
||||
|
||||
### Bind(ctx, tx, customerID, assetType, assetID)
|
||||
|
||||
封装创建客户与资产绑定记录的逻辑,当前只实现有虚拟号路径:
|
||||
- IoT 卡有虚拟号 → 写 `tb_personal_customer_device`(与现在 `bindAsset` 行为一致)
|
||||
- 设备 → 写 `tb_personal_customer_device`(设备必然有虚拟号)
|
||||
- 首次绑定时触发 `markAssetAsSold()`(firstEverBind 逻辑保持不变)
|
||||
|
||||
### OwnsAsset(ctx, customerID, assetType, assetID) bool
|
||||
|
||||
封装归属验证逻辑,当前只实现有虚拟号路径:
|
||||
- 查 `tb_personal_customer_device WHERE virtual_no = ? AND status = 1`
|
||||
- 内部统一强制 `status = 1` 过滤(修复现有部分实现缺少此过滤的安全缺口)
|
||||
|
||||
### 替换 6 处调用点
|
||||
|
||||
以下调用点替换为 `CustomerBinding` 的方法:
|
||||
|
||||
| 调用点 | 替换目标 |
|
||||
|--------|---------|
|
||||
| `client_auth/service.go: bindAsset()` | `CustomerBinding.Bind()` |
|
||||
| `handler/app/client_realname.go:92` | `CustomerBinding.OwnsAsset()` |
|
||||
| `handler/app/client_device.go:82` | `CustomerBinding.OwnsAsset()` |
|
||||
| `handler/app/client_wallet.go: isCustomerOwnAsset()` | `CustomerBinding.OwnsAsset()` |
|
||||
| `handler/app/client_asset.go: isCustomerOwnAsset()` | `CustomerBinding.OwnsAsset()` |
|
||||
| `service/client_order/service.go: checkAssetOwnership()` | `CustomerBinding.OwnsAsset()` |
|
||||
|
||||
exchange service 的 `customerOwnsAsset()` 在切片 3 中处理。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `internal/service/customer_binding` 包存在,对外暴露 `Bind` 和 `OwnsAsset`
|
||||
- [ ] 有虚拟号的 IoT 卡登录后,`tb_personal_customer_device` 正常写入绑定记录(与现在一致)
|
||||
- [ ] 设备登录后,`tb_personal_customer_device` 正常写入绑定记录(与现在一致)
|
||||
- [ ] 被禁用(status=0)的绑定记录不能通过 `OwnsAsset` 验证(修复安全缺口)
|
||||
- [ ] 6 处调用点全部替换完毕,原有私有方法(resolveAssetBindingKey、isCustomerOwnAsset 等)可删除
|
||||
- [ ] 有虚拟号卡的实名认证、购买套餐、设备操作全链路与现在行为一致
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - 可立即开始
|
||||
@@ -0,0 +1,52 @@
|
||||
Status: done
|
||||
|
||||
# 无虚拟号单卡 C 端完整链路
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/customer-binding-architecture/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
扩展 `CustomerBinding` 模块,使无虚拟号的独立 IoT 卡(单卡)能够完整走通 C 端业务流程:登录绑定、实名认证、购买套餐。
|
||||
|
||||
**仅影响 IoT 卡(单卡)。设备资产必然有虚拟号,不在本切片处理范围内。**
|
||||
|
||||
### 扩展 Bind()
|
||||
|
||||
当资产为 IoT 卡且 `virtual_no` 为空时:
|
||||
- 写 `tb_personal_customer_iccid`(按 ICCID 绑定),而非 `tb_personal_customer_device`
|
||||
- `PersonalCustomerICCIDStore` 已有完整实现,直接注入使用
|
||||
|
||||
当资产为 IoT 卡且 `virtual_no` 不为空时:行为与切片 1 一致,不变。
|
||||
|
||||
### 修复 firstEverBind + markAssetAsSold
|
||||
|
||||
当前 `firstEverBind` 通过查 `tb_personal_customer_device WHERE virtual_no = ""` 来判断是否首次绑定,对无虚拟号的卡完全失效(所有无虚拟号的卡共用同一个空 key)。
|
||||
|
||||
修复方式:在 `Bind()` 内,按路径分别判断首绑:
|
||||
- 有虚拟号路径:查 `tb_personal_customer_device WHERE virtual_no = ?`
|
||||
- 无虚拟号路径:查 `tb_personal_customer_iccid WHERE iccid = ?`
|
||||
|
||||
首次绑定后正常触发 `markAssetAsSold()`,将卡的 `asset_status` 从在库(1)更新为已销售(2)。
|
||||
|
||||
### 扩展 OwnsAsset()
|
||||
|
||||
当资产为 IoT 卡时:
|
||||
- 若卡有 `virtual_no`:查 `tb_personal_customer_device`(与切片 1 一致)
|
||||
- 若卡无 `virtual_no`:查 `tb_personal_customer_iccid WHERE iccid = ? AND status = 1`
|
||||
|
||||
当资产为设备时:行为不变,只查 `tb_personal_customer_device`。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 无虚拟号的单卡 C 端登录后,`tb_personal_customer_iccid` 中出现对应的绑定记录
|
||||
- [ ] 无虚拟号单卡首次登录后,`tb_iot_card.asset_status` 变为 2(已销售)
|
||||
- [ ] 无虚拟号单卡登录后,实名认证接口返回成功(不报"无权限")
|
||||
- [ ] 无虚拟号单卡登录后,购买套餐接口归属验证通过
|
||||
- [ ] 有虚拟号卡的全部行为与切片 1 完成后保持一致(无回归)
|
||||
- [ ] 设备资产的全部行为不受影响
|
||||
|
||||
## Blocked by
|
||||
|
||||
`.scratch/customer-binding-architecture/issues/01-customer-binding-module-refactor.md`
|
||||
@@ -0,0 +1,45 @@
|
||||
Status: done
|
||||
|
||||
# 换货绑定迁移修复
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/customer-binding-architecture/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在 `CustomerBinding` 模块上实现 `Migrate(ctx, tx, oldAsset, newAsset)` 方法,替换换货服务中现有的 `switchCustomerBindingWithTx` 和 `ensureNewAssetBindingAvailableWithTx` 逻辑,修复有虚拟号旧卡换无虚拟号新卡时被误拦截的 bug。
|
||||
|
||||
### Migrate(ctx, tx, oldAsset, newAsset)
|
||||
|
||||
处理四种虚拟号组合,仅涉及 IoT 卡(设备必然有虚拟号,只有有→有一种情形):
|
||||
|
||||
| 旧卡 | 新卡 | 行为 |
|
||||
|------|------|------|
|
||||
| 有虚拟号,pcd 有绑定 | 有虚拟号 | 更新 pcd 记录的 virtual_no 为新卡虚拟号 |
|
||||
| 有虚拟号,pcd 有绑定 | 无虚拟号 | 禁用旧 pcd 记录(status=0)+ 创建新 pci ICCID 绑定 |
|
||||
| 有虚拟号,pcd 无绑定 | 无虚拟号 | 跳过,无需迁移 |
|
||||
| 无虚拟号,pci 有绑定 | 任意 | 迁移 pci 记录到新卡 ICCID(或新卡虚拟号路径) |
|
||||
| 任意 | 任意(无绑定) | 跳过 |
|
||||
|
||||
### 修复换货服务
|
||||
|
||||
- `switchCustomerBindingWithTx` 替换为调用 `CustomerBinding.Migrate()`,移除函数内 `newKey == ""` 的误拦截逻辑
|
||||
- `ensureNewAssetBindingAvailableWithTx` 更新:当新卡无虚拟号时,不再拦截换货,因为 `Migrate()` 已能正确处理此情形(无绑定时跳过,有绑定时迁移到 pci)
|
||||
|
||||
### 根本 bug 说明
|
||||
|
||||
原 `switchCustomerBindingWithTx` 在执行阶段做了 `if newKey == "" { return error }` 的检查,但没有先确认旧资产是否实际存在绑定记录。旧卡有虚拟号但无任何客户绑定时,也会被误拦截报错"新资产无法承接客户绑定"。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 旧卡有虚拟号 + 有客户绑定,换货为有虚拟号新卡:pcd 记录的 virtual_no 正确更新为新卡虚拟号
|
||||
- [ ] 旧卡有虚拟号 + 有客户绑定,换货为无虚拟号新卡:旧 pcd 记录 status 变为 0,pci 表出现新卡 ICCID 的绑定记录
|
||||
- [ ] 旧卡有虚拟号 + 无客户绑定,换货为无虚拟号新卡:换货正常完成,不报错,不写入任何绑定记录
|
||||
- [ ] 旧卡无虚拟号,换货为任意新卡:换货正常完成
|
||||
- [ ] 有虚拟号换有虚拟号(原有场景):行为与修复前一致,无回归
|
||||
- [ ] 换货完成后,客户通过新卡(无论有无虚拟号)能正常通过归属验证
|
||||
|
||||
## Blocked by
|
||||
|
||||
`.scratch/customer-binding-architecture/issues/02-no-virtual-no-card-cend-flow.md`
|
||||
143
.scratch/enterprise-auth-and-asset-enhancements/PRD.md
Normal file
143
.scratch/enterprise-auth-and-asset-enhancements/PRD.md
Normal file
@@ -0,0 +1,143 @@
|
||||
Status: ready-for-agent
|
||||
|
||||
# PRD:企业授权增强 & 资产列表扩展
|
||||
|
||||
## Problem Statement
|
||||
|
||||
平台运营人员在管理企业授权和查看资产状态时面临以下痛点:
|
||||
|
||||
1. **企业维度检索缺失**:卡列表和设备列表无法按企业维度过滤,也无法在列表中直接看到某张卡/设备被授权给了哪个企业,需要跨页面跳转查询。
|
||||
2. **企业授权操作繁琐**:授权和收回接口只接受精确 ICCID/虚拟号列表,但前端列表有分页,量大时需一个个选,无法按批次号、号段等条件一次性批量操作。
|
||||
3. **换货历史不可见**:经历过换货的旧卡/设备,在列表和详情中没有任何标记,运营无法判断当前资产是否为"换货遗留"状态或曾经历过换货后被重新激活(转新)的资产。
|
||||
4. **主钱包流水和退款列表检索维度不足**:无法直接通过资产标识(ICCID 或虚拟号)快速定位某个资产相关的流水和退款记录。
|
||||
5. **卡网络状态过滤缺失**:standalone 卡列表无法按网络状态(开机/停机)过滤,批量运维操作不便。
|
||||
|
||||
## Solution
|
||||
|
||||
对六个业务场景进行针对性扩展:
|
||||
|
||||
1. 在 standalone 卡列表和设备列表中新增企业维度过滤及企业信息返回字段
|
||||
2. 将企业授权/收回接口升级为支持 list/range/filter 三(两)模式选资产
|
||||
3. 在 standalone 卡列表和设备列表响应中暴露换货业务状态和资产世代编号
|
||||
4. 主钱包流水列表新增资产标识精确检索
|
||||
5. 退款列表新增资产标识精确检索
|
||||
6. standalone 卡列表新增网络状态过滤
|
||||
|
||||
同时修复卡企业授权表的数据一致性问题(补唯一约束,与设备授权保持一致)。
|
||||
|
||||
## User Stories
|
||||
|
||||
1. 作为平台运营,我希望在 standalone 卡列表中输入企业 ID 进行过滤,以便快速找到已授权给该企业的所有卡
|
||||
2. 作为平台运营,我希望在 standalone 卡列表中使用"是否授权企业"开关过滤,以便快速区分已授权和未授权的卡库存
|
||||
3. 作为平台运营,我希望在 standalone 卡列表中直接看到每张卡被授权给哪个企业(企业ID和名称),以便不用跳转到企业详情页
|
||||
4. 作为平台运营,我希望在设备列表中输入企业 ID 进行过滤,以便快速找到已授权给该企业的所有设备
|
||||
5. 作为平台运营,我希望在设备列表中使用"是否授权企业"开关过滤,以便区分已授权和未授权的设备
|
||||
6. 作为平台运营,我希望在设备列表中直接看到每台设备被授权给哪个企业,以便快速掌握设备归属
|
||||
7. 作为平台运营,我希望在授权卡给企业时能通过 ICCID 号段范围一次性选取,以便高效授权大批量卡
|
||||
8. 作为平台运营,我希望在授权卡给企业时能通过批次号、运营商等筛选条件选取,以便按业务维度批量授权
|
||||
9. 作为平台运营,我希望在收回企业卡授权时同样支持 list/range/filter 三种模式,以便与授权操作保持一致的操作体验
|
||||
10. 作为平台运营,我希望在授权设备给企业时能通过虚拟号模糊搜索和批次号筛选一次性选取,以便批量操作设备
|
||||
11. 作为平台运营,我希望在收回企业设备授权时支持 list/filter 两种模式,以便批量收回
|
||||
12. 作为平台运营,我希望在 standalone 卡列表中看到每张卡的业务状态(`asset_status`),以便识别已换货但尚未转新的"死档"卡
|
||||
13. 作为平台运营,我希望在 standalone 卡列表中看到每张卡的世代编号(`generation`),以便识别曾换货后转新重入库的卡
|
||||
14. 作为平台运营,我希望在设备列表中看到每台设备的业务状态和世代编号,以便同样掌握设备的换货历史
|
||||
15. 作为平台运营,我希望在主钱包流水列表中输入 ICCID 或虚拟号精确检索,以便快速定位某资产的所有充值/扣款记录
|
||||
16. 作为平台运营,我希望在退款列表中输入 ICCID 或虚拟号精确检索,以便快速找到某资产相关的所有退款申请
|
||||
17. 作为平台运营,我希望在 standalone 卡列表中按网络状态(开机/停机)过滤,以便批量处理特定网络状态的卡
|
||||
|
||||
## Implementation Decisions
|
||||
|
||||
### 数据一致性修复(前置)
|
||||
|
||||
- **卡企业授权唯一约束**:在 `tb_enterprise_card_authorization` 表上补充部分唯一索引,约束同一张卡在同一时间只能有一条有效授权记录(`WHERE revoked_at IS NULL AND deleted_at IS NULL`),与设备授权表的 `uq_active_device_auth` 约束保持一致
|
||||
- **service 层校验补充**:卡授权 service 在执行授权前,需增加"卡是否已授权给其他企业"的校验,目前只校验同一企业重复授权
|
||||
|
||||
### 需求1:standalone 卡列表 + 设备列表企业字段
|
||||
|
||||
**Request 新增过滤条件**(`ListStandaloneIotCardRequest` 和 `ListDeviceRequest`):
|
||||
- `authorized_enterprise_id *uint`:按企业ID过滤,只匹配当前有效授权(`revoked_at IS NULL`)
|
||||
- `is_authorized_to_enterprise *bool`:true=已授权给某企业,false=未授权任何企业
|
||||
|
||||
**Response 新增字段**(`StandaloneIotCardResponse` 和 `DeviceResponse`):
|
||||
- `authorized_enterprise_id *uint`:未授权时为 null
|
||||
- `authorized_enterprise_name string`:未授权时为空字符串
|
||||
|
||||
Store 层需通过 JOIN 或子查询 `tb_enterprise_card_authorization` / `tb_enterprise_device_authorization` 表获取企业ID,再批量查企业名称
|
||||
|
||||
### 需求2:企业授权/收回接口升级为多模式
|
||||
|
||||
参照 `AllocateStandaloneCardsRequest` / `RecallStandaloneCardsRequest` 的 `selection_type` 三模式设计:
|
||||
|
||||
**allocate-cards / recall-cards**(三模式:list / range / filter):
|
||||
- `list`:`ICCIDs []string`,精确 ICCID 列表
|
||||
- `range`:`ICCIDStart string` + `ICCIDEnd string`,号段范围
|
||||
- `filter`:筛选条件
|
||||
- allocate-cards filter 字段:`ICCID`(模糊)、`BatchNo`、`CarrierID`、`ShopID`/`ShopIDs`
|
||||
- recall-cards filter 字段:`ICCID`(模糊)、`BatchNo`、`CarrierID`
|
||||
|
||||
**allocate-devices / recall-devices**(两模式:list / filter,不支持 range):
|
||||
- `list`:`DeviceNos []string`,设备虚拟号列表
|
||||
- `filter`:筛选条件
|
||||
- allocate-devices filter 字段:`VirtualNo`(模糊)、`BatchNo`、`ShopID`
|
||||
- recall-devices filter 字段:`VirtualNo`(模糊)、`BatchNo`
|
||||
|
||||
原有接口的请求结构需要破坏性变更(DTO 重构),需与前端联调确认过渡方案
|
||||
|
||||
### 需求3:换货状态字段
|
||||
|
||||
**`StandaloneIotCardResponse` 和 `DeviceResponse` 新增字段**:
|
||||
- `asset_status int`:业务状态(1=在库, 2=已销售, 3=已换货, 4=已停用)
|
||||
- `asset_status_name string`:对应中文名称
|
||||
- `generation int`:资产世代编号(初始值1,每次换货+转新后+1)
|
||||
|
||||
语义约定:
|
||||
- `asset_status = 3`:该资产已换货且尚未执行"旧资产转新",是永久性死档标记
|
||||
- `generation > 1`:该资产历史上曾执行过换货+转新,目前仍在流通
|
||||
|
||||
### 需求4:主钱包流水资产标识检索
|
||||
|
||||
`MainWalletTransactionListRequest` 新增:
|
||||
- `AssetIdentifier string`:精确匹配 `asset_identifier` 快照字段(ICCID 或虚拟号),空字符串时不过滤
|
||||
|
||||
### 需求5:退款列表资产标识检索
|
||||
|
||||
`RefundListRequest` 新增:
|
||||
- `AssetIdentifier string`:精确匹配 `asset_identifier` 快照字段(ICCID 或虚拟号),空字符串时不过滤
|
||||
|
||||
### 需求6:standalone 卡列表网络状态过滤
|
||||
|
||||
`ListStandaloneIotCardRequest` 新增:
|
||||
- `NetworkStatus *int`:网络状态过滤(0=停机, 1=开机),不传则不过滤
|
||||
|
||||
Store 层 `applyStandaloneFilters` 函数中补充 `network_status = ?` 条件
|
||||
|
||||
## Testing Decisions
|
||||
|
||||
本项目禁止自动化测试,验证方式为:
|
||||
|
||||
- **数据库验证**:通过 PostgreSQL MCP 工具验证授权表唯一约束是否生效、字段值是否正确写入
|
||||
- **接口验证**:通过 curl/Postman 对各接口进行手动联调,重点覆盖以下场景:
|
||||
- 企业 ID 过滤:确认只返回有效授权(revoked_at IS NULL)的卡/设备
|
||||
- 是否授权企业过滤:true/false 结果集互补且无交集
|
||||
- 授权时尝试将同一张卡授权给第二个企业,确认被拒绝
|
||||
- allocate-cards 三种 selection_type 均能正确选取目标卡
|
||||
- allocate-devices 两种 selection_type 均能正确选取目标设备
|
||||
- asset_status=3 的卡在列表中可见且字段正确
|
||||
- generation 字段在换货+转新后正确递增
|
||||
- 主钱包流水 asset_identifier 精确匹配不漏不多
|
||||
- 退款 asset_identifier 精确匹配不漏不多
|
||||
- 网络状态过滤 0/1 结果集互补
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- 企业卡/设备授权列表接口本身的改造(本次只改授权/收回操作接口)
|
||||
- `AllocateCardsPreviewReq`(预览接口)是否同步升级为多模式(待后续评估)
|
||||
- standalone 卡列表和设备列表的导出功能是否同步支持新增过滤条件
|
||||
- 换货历史的完整时间线展示(仅暴露字段,不新增详情接口)
|
||||
- `generation` 字段的过滤能力(暂只返回,不支持作为检索条件)
|
||||
|
||||
## Further Notes
|
||||
|
||||
- 需求1 的企业名称需要 N+1 防护:通过授权查询批量拿到 enterprise_id 后,用 IN 一次性查企业名称,不能逐条查
|
||||
- 需求2 的 filter 模式对于 allocate-cards 场景,卡的范围天然受操作者权限约束(代理用户只能授权自己店铺的卡),Store 层已有 `middleware.ApplyShopFilter` 处理,filter 模式需要同样受此约束
|
||||
- 卡唯一约束迁移执行前,需确认现有数据中是否存在一张卡同时有多条 `revoked_at IS NULL` 的记录,若有需先清理
|
||||
@@ -0,0 +1,28 @@
|
||||
Status: ready-for-human
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/enterprise-auth-and-asset-enhancements/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
修复卡企业授权的数据一致性问题,使其与设备授权保持一致:一张卡在同一时间只能授权给一个企业。
|
||||
|
||||
分两步:
|
||||
|
||||
**第一步:数据库迁移**
|
||||
在 `tb_enterprise_card_authorization` 表上新增部分唯一索引,约束同一张卡不能同时存在两条有效授权记录(`revoked_at IS NULL AND deleted_at IS NULL`)。迁移执行前需先查询是否存在脏数据(同一 card_id 有多条 revoked_at IS NULL 的记录),若有需在迁移脚本中先行清理。
|
||||
|
||||
**第二步:service 层校验补充**
|
||||
卡授权 service(`BatchAuthorize`)在执行授权前,增加"目标卡是否已授权给其他企业"的校验。目前代码只跳过已授权给同一企业的卡,不阻止授权给第二个企业。新逻辑:若目标卡已存在有效授权(`revoked_at IS NULL`)且授权对象不是当前企业,则将该卡加入失败列表并给出明确错误原因(如"卡已授权给其他企业,请先收回")。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] `tb_enterprise_card_authorization` 表存在部分唯一索引,约束 `(card_id) WHERE revoked_at IS NULL AND deleted_at IS NULL`
|
||||
- [x] 尝试将同一张卡授权给第二个企业时,接口返回失败,错误信息明确说明"已授权给其他企业"
|
||||
- [x] 已撤回(revoked_at 有值)的历史记录不受唯一约束影响,可正常查询
|
||||
- [x] 同一张卡授权给同一企业时仍返回"已授权给该企业"的原有错误,行为不变
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,22 @@
|
||||
Status: ready-for-human
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/enterprise-auth-and-asset-enhancements/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在 `/api/admin/iot-cards/standalone` 接口的查询条件中新增网络状态过滤。
|
||||
|
||||
Request DTO 新增可选字段 `network_status *int`(0=停机,1=开机),不传时不过滤。Store 层 `applyStandaloneFilters` 函数补充对应的 `network_status = ?` WHERE 条件。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] 传入 `network_status=0` 时只返回停机的卡
|
||||
- [x] 传入 `network_status=1` 时只返回开机的卡
|
||||
- [x] 不传 `network_status` 时返回全部(与改动前行为一致)
|
||||
- [x] 网络状态过滤可与现有其他过滤条件(ICCID、运营商等)叠加使用
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,34 @@
|
||||
Status: ready-for-human
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/enterprise-auth-and-asset-enhancements/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在 standalone 卡列表响应和设备列表响应中暴露换货相关字段,使运营人员能直接在列表中识别资产的换货历史。
|
||||
|
||||
**`StandaloneIotCardResponse` 新增三个字段:**
|
||||
- `asset_status int`:业务状态(1=在库, 2=已销售, 3=已换货, 4=已停用)
|
||||
- `asset_status_name string`:对应中文名称
|
||||
- `generation int`:资产世代编号(初始值1,每次换货+旧资产转新后 +1)
|
||||
|
||||
**`DeviceResponse` 同步新增相同三个字段。**
|
||||
|
||||
语义约定(写入注释和 description):
|
||||
- `asset_status = 3`:该资产已换货且尚未执行"旧资产转新",不再流通
|
||||
- `generation > 1`:该资产历史上曾执行过换货后转新,目前仍在使用
|
||||
|
||||
Service 层组装响应时直接从 Model 取值,`asset_status_name` 通过 constants 中的方法转换。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] `/api/admin/iot-cards/standalone` 响应中每条记录包含 `asset_status`、`asset_status_name`、`generation` 三个字段
|
||||
- [x] `/api/admin/devices` 响应中每条记录包含相同三个字段
|
||||
- [x] 已换货未转新的卡/设备返回 `asset_status=3`、`asset_status_name="已换货"`
|
||||
- [x] 经过换货转新重入库的卡/设备返回 `generation=2`(或更高)且 `asset_status=1`
|
||||
- [x] 普通未经历换货的资产返回 `generation=1`
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,23 @@
|
||||
Status: ready-for-human
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/enterprise-auth-and-asset-enhancements/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在 `/api/admin/shops/{shop_id}/main-wallet/transactions` 接口的查询条件中新增资产标识精确检索。
|
||||
|
||||
`MainWalletTransactionListRequest` 新增可选字段 `asset_identifier string`,非空时对 `asset_identifier` 列做精确匹配(`= ?`,不做模糊匹配)。`asset_identifier` 字段存储的是下单时资产的标识符快照(ICCID 或虚拟号),空字符串时不过滤。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] 传入有效的 ICCID 时只返回该卡相关的主钱包流水
|
||||
- [x] 传入有效的设备虚拟号时只返回该设备相关的主钱包流水
|
||||
- [x] 传入不存在的标识符时返回空列表(total=0),不报错
|
||||
- [x] 不传 `asset_identifier` 时行为与改动前完全一致
|
||||
- [x] 可与 `transaction_type`、`start_date`、`end_date` 等现有条件叠加使用
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,23 @@
|
||||
Status: ready-for-human
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/enterprise-auth-and-asset-enhancements/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在 `/api/admin/refunds` 接口的查询条件中新增资产标识精确检索。
|
||||
|
||||
`RefundListRequest` 新增可选字段 `asset_identifier string`,非空时对退款记录的 `asset_identifier` 列做精确匹配(`= ?`)。该字段存储的是下单时资产的标识符快照(ICCID 或虚拟号),空字符串时不过滤。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] 传入有效的 ICCID 时只返回该卡相关的退款申请
|
||||
- [x] 传入有效的设备虚拟号时只返回该设备相关的退款申请
|
||||
- [x] 传入不存在的标识符时返回空列表(total=0),不报错
|
||||
- [x] 不传 `asset_identifier` 时行为与改动前完全一致
|
||||
- [x] 可与 `status`、`order_id`、`shop_id` 等现有条件叠加使用
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,33 @@
|
||||
Status: ready-for-human
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/enterprise-auth-and-asset-enhancements/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在 `/api/admin/iot-cards/standalone` 接口中新增企业维度过滤条件,并在响应中返回当前有效授权的企业信息。
|
||||
|
||||
**Request 新增过滤条件(`ListStandaloneIotCardRequest`):**
|
||||
- `authorized_enterprise_id *uint`:按企业ID过滤,只匹配 `tb_enterprise_card_authorization` 中 `revoked_at IS NULL` 的有效授权
|
||||
- `is_authorized_to_enterprise *bool`:true=只返回当前已授权给某企业的卡,false=只返回未授权任何企业的卡
|
||||
|
||||
**Response 新增字段(`StandaloneIotCardResponse`):**
|
||||
- `authorized_enterprise_id *uint`:当前有效授权的企业ID,未授权时为 null
|
||||
- `authorized_enterprise_name string`:对应企业名称,未授权时为空字符串
|
||||
|
||||
Store 层在 `applyStandaloneFilters` 中增加对 `authorized_enterprise_id` 和 `is_authorized_to_enterprise` 的处理,通过子查询 `tb_enterprise_card_authorization`(`revoked_at IS NULL AND deleted_at IS NULL`)实现过滤。响应组装时批量查询企业名称(IN 查询),不逐条查询。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] 传入 `authorized_enterprise_id` 时只返回当前有效授权给该企业的卡
|
||||
- [x] 传入 `is_authorized_to_enterprise=true` 时只返回已授权给某企业的卡
|
||||
- [x] 传入 `is_authorized_to_enterprise=false` 时只返回未授权任何企业的卡
|
||||
- [x] 已撤回的历史授权不影响过滤结果(已撤回视为未授权)
|
||||
- [x] 响应中每张卡包含 `authorized_enterprise_id` 和 `authorized_enterprise_name`,未授权卡对应字段为 null/空字符串
|
||||
- [x] 企业名称通过批量查询获取,不触发 N+1 查询
|
||||
- [x] 新增过滤条件可与现有条件(ICCID、运营商、店铺等)叠加使用
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/01-card-enterprise-auth-unique-constraint.md`
|
||||
@@ -0,0 +1,32 @@
|
||||
Status: ready-for-human
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/enterprise-auth-and-asset-enhancements/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在 `/api/admin/devices` 接口中新增企业维度过滤条件,并在响应中返回当前有效授权的企业信息。
|
||||
|
||||
**Request 新增过滤条件(`ListDeviceRequest`):**
|
||||
- `authorized_enterprise_id *uint`:按企业ID过滤,只匹配 `tb_enterprise_device_authorization` 中 `revoked_at IS NULL` 的有效授权
|
||||
- `is_authorized_to_enterprise *bool`:true=只返回当前已授权给某企业的设备,false=只返回未授权任何企业的设备
|
||||
|
||||
**Response 新增字段(`DeviceResponse`):**
|
||||
- `authorized_enterprise_id *uint`:当前有效授权的企业ID,未授权时为 null
|
||||
- `authorized_enterprise_name string`:对应企业名称,未授权时为空字符串
|
||||
|
||||
Store 层通过子查询或 JOIN `tb_enterprise_device_authorization` 实现过滤。响应组装时批量查询企业名称(IN 查询),不逐条查询。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] 传入 `authorized_enterprise_id` 时只返回当前有效授权给该企业的设备
|
||||
- [x] 传入 `is_authorized_to_enterprise=true` 时只返回已授权给某企业的设备
|
||||
- [x] 传入 `is_authorized_to_enterprise=false` 时只返回未授权任何企业的设备
|
||||
- [x] 已撤回的历史授权不影响过滤结果(已撤回视为未授权)
|
||||
- [x] 响应中每台设备包含 `authorized_enterprise_id` 和 `authorized_enterprise_name`,未授权设备对应字段为 null/空字符串
|
||||
- [x] 企业名称通过批量查询获取,不触发 N+1 查询
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,42 @@
|
||||
Status: ready-for-human
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/enterprise-auth-and-asset-enhancements/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
将企业卡授权和收回接口升级为支持 list/range/filter 三种模式批量选取卡,替代原来只接受精确 ICCID 列表的方式。
|
||||
|
||||
**涉及接口:**
|
||||
- `POST /api/admin/enterprises/{id}/allocate-cards`
|
||||
- `POST /api/admin/enterprises/{id}/recall-cards`
|
||||
|
||||
**`AllocateCardsReq` 重构为:**
|
||||
- `selection_type string`(必填,`list`、`range` 或 `filter`)
|
||||
- list 模式:`iccids []string`(ICCID 列表,最多1000个)
|
||||
- range 模式:`iccid_start string` + `iccid_end string`(号段范围)
|
||||
- filter 模式过滤字段:`iccid string`(模糊)、`batch_no string`、`carrier_id *uint`、`shop_id *uint`、`shop_ids []uint`
|
||||
- `remark string`(备注,所有模式均可选)
|
||||
|
||||
**`RecallCardsReq` 重构为:**
|
||||
- `selection_type string`(必填,`list`、`range` 或 `filter`)
|
||||
- list 模式:`iccids []string`
|
||||
- range 模式:`iccid_start string` + `iccid_end string`
|
||||
- filter 模式过滤字段:`iccid string`(模糊)、`batch_no string`、`carrier_id *uint`
|
||||
|
||||
filter 和 range 模式下,allocate 操作的候选卡集受操作者权限约束(代理用户只能授权自己店铺的卡),与 `applyStandaloneFilters` 中的 `ApplyShopFilter` 逻辑保持一致。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] `allocate-cards` 接口接受 `selection_type=list` + `iccids`,行为与改动前一致
|
||||
- [x] `allocate-cards` 接口接受 `selection_type=range` + 号段,批量授权号段内所有匹配的卡
|
||||
- [x] `allocate-cards` 接口接受 `selection_type=filter` + 过滤条件,批量授权所有匹配的卡
|
||||
- [x] `recall-cards` 接口同样支持三种模式,分别正确收回对应卡的企业授权
|
||||
- [x] filter/range 模式下代理用户只能操作自己店铺的卡,超出范围的卡进入失败列表
|
||||
- [x] 任何模式下尝试授权"已授权给其他企业"的卡,该卡进入失败列表并附带原因
|
||||
- [x] 响应中 `success_count`、`fail_count`、`failed_items` 准确反映实际执行结果
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/01-card-enterprise-auth-unique-constraint.md`
|
||||
@@ -0,0 +1,38 @@
|
||||
Status: ready-for-human
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/enterprise-auth-and-asset-enhancements/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
将企业设备授权和收回接口升级为支持 list/filter 两种模式批量选取设备,替代原来只接受精确设备号列表的方式。
|
||||
|
||||
**涉及接口:**
|
||||
- `POST /api/admin/enterprises/{id}/allocate-devices`
|
||||
- `POST /api/admin/enterprises/{id}/recall-devices`
|
||||
|
||||
**`AllocateDevicesReq` 重构为:**
|
||||
- `selection_type string`(必填,`list` 或 `filter`)
|
||||
- list 模式:`device_nos []string`(设备虚拟号列表)
|
||||
- filter 模式过滤字段:`virtual_no string`(模糊)、`batch_no string`、`shop_id *uint`
|
||||
|
||||
**`RecallDevicesReq` 重构为:**
|
||||
- `selection_type string`(必填,`list` 或 `filter`)
|
||||
- list 模式:`device_nos []string`
|
||||
- filter 模式过滤字段:`virtual_no string`(模糊)、`batch_no string`
|
||||
|
||||
filter 模式下,allocate 操作的候选设备集受操作者权限约束(代理用户只能授权自己店铺的设备)。filter 模式命中的设备数量无硬性上限,但单次事务处理建议分批,超大批次需记录日志。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] `allocate-devices` 接口接受 `selection_type=list` + `device_nos` 列表,行为与改动前一致
|
||||
- [x] `allocate-devices` 接口接受 `selection_type=filter` + 过滤条件,批量授权所有匹配设备
|
||||
- [x] `recall-devices` 接口接受 `selection_type=list` + `device_nos` 列表,行为与改动前一致
|
||||
- [x] `recall-devices` 接口接受 `selection_type=filter` + 过滤条件,批量收回所有匹配设备
|
||||
- [x] filter 模式下代理用户只能操作自己店铺的设备,超出范围的设备进入失败列表
|
||||
- [x] 响应中 `success_count`、`fail_count`、`failed_items` 准确反映实际执行结果
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
124
.scratch/iot-risk-import-voucher-remark/PRD.md
Normal file
124
.scratch/iot-risk-import-voucher-remark/PRD.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# PRD:IoT 卡风险状态限制 / 导入任务操作人与批量失效 / 凭证多图 / 预充值备注
|
||||
|
||||
Status: ready-for-agent
|
||||
|
||||
---
|
||||
|
||||
## Problem Statement
|
||||
|
||||
运营团队在日常工作中遇到四个独立痛点:
|
||||
|
||||
1. **风险停机/已销户卡无法有效拦截**:运营商侧将某些卡置为"风险停机"或"已销户"状态后,系统仍允许对这些卡发起复机操作,且轮询系统仍持续轮询这些卡,浪费资源并可能产生错误数据。
|
||||
|
||||
2. **导入任务无操作人信息**:IoT 卡导入任务和设备导入任务的列表中没有"操作人"字段,无法追溯是谁发起的批量操作。同时缺少批量失效订单套餐的操作入口,运营只能逐条手动处理。
|
||||
|
||||
3. **凭证只能上传一张**:后台创建订单和发起退款时,只允许上传一张凭证图片,无法满足多张凭证的业务场景(如多笔转账记录、多页合同等)。
|
||||
|
||||
4. **代理预充值缺少备注字段**:代理预充值操作无法附加运营备注,导致事后无法追溯充值的业务原因。
|
||||
|
||||
---
|
||||
|
||||
## Solution
|
||||
|
||||
1. 在复机接口和轮询系统中增加对 `gateway_extend` 字段的检查,当独立卡处于"风险停机"或"已销户"状态时,拒绝复机并停止轮询。
|
||||
|
||||
2. 在所有导入任务中快照操作人姓名;新增"批量失效订单套餐"导入任务,支持通过 CSV 批量将订单下的套餐置为失效状态。
|
||||
|
||||
3. 将订单、退款、代理预充值的凭证字段改为支持最多5张的 jsonb 数组存储。
|
||||
|
||||
4. 在代理预充值记录上新增 `remark` 备注字段,供运营创建时填写,并在列表/详情接口中返回。
|
||||
|
||||
---
|
||||
|
||||
## User Stories
|
||||
|
||||
1. 作为运营人员,当我尝试对"风险停机"状态的独立卡发起复机时,我希望系统拒绝并提示原因,以免产生无效操作。
|
||||
2. 作为运营人员,当我尝试对"已销户"状态的独立卡发起复机时,我希望系统拒绝并提示原因,以免对已注销的卡发起无意义请求。
|
||||
3. 作为运营人员,我希望"风险停机"和"已销户"的独立卡不再参与系统轮询,以免浪费轮询资源并产生噪音数据。
|
||||
4. 作为运营人员,当轮询系统检测到某张独立卡的网关状态变为"风险停机"或"已销户"时,我希望系统自动将该卡的轮询关闭,而不需要手动干预。
|
||||
5. 作为运营人员,我希望在 IoT 卡导入任务列表中看到"操作人"姓名,以便追溯每次批量导入是谁发起的。
|
||||
6. 作为运营人员,我希望在设备导入任务列表中看到"操作人"姓名,以便追溯每次批量导入是谁发起的。
|
||||
7. 作为运营人员,我希望通过上传 CSV 文件批量将一批订单的套餐置为失效,以便快速处理异常订单。
|
||||
8. 作为运营人员,我希望在创建批量失效任务时能填写备注和上传凭证(最多5张),以便记录操作原因。
|
||||
9. 作为运营人员,我希望批量失效任务完成后能看到成功数、失败数,以及失败原因(如订单号不存在),以便核查处理结果。
|
||||
10. 作为运营人员,我希望批量失效套餐只影响套餐记录本身,不触发退款和其他业务流程,让轮询系统自行根据套餐状态处理停机。
|
||||
11. 作为运营人员,我希望在创建后台订单时可以上传最多5张凭证,以便完整记录线下付款证明。
|
||||
12. 作为运营人员,我希望在发起退款申请时可以上传最多5张凭证,以便完整记录退款证明材料。
|
||||
13. 作为运营人员,我希望在代理预充值列表中看到备注内容,以便了解每笔预充值的业务背景。
|
||||
14. 作为运营人员,我希望在创建代理预充值订单时填写备注,以便记录本次充值的原因或说明。
|
||||
15. 作为开放 API 调用方,当我通过 Open API 对"风险停机"或"已销户"的独立卡调用复机接口时,我希望收到明确的错误响应。
|
||||
|
||||
---
|
||||
|
||||
## Implementation Decisions
|
||||
|
||||
### 需求一:风险停机/已销户卡限制
|
||||
|
||||
- **判断字段**:`tb_iot_card.gateway_extend` 原文值 = `"风险停机"` 或 `"已销户"`。新增两个常量 `GatewayCardExtendRiskStop`、`GatewayCardExtendCancelled`。
|
||||
- **判断范围**:仅 `is_standalone = true` 的独立卡(未绑定设备的卡)。绑定设备的卡不受此限制。
|
||||
- **复机拦截**:在 `ManualStartCard`(后台管理员入口)和 `ResumeCard`(Open API 入口)两个函数中,调用网关前先读取 DB 中已落库的 `gateway_extend`,若命中则返回业务错误,不实时查询网关。
|
||||
- **轮询停止**:轮询状态处理器(`PollingCardStatusHandler`)在将新的 `gateway_extend` 写入 DB 后,检查若命中风险状态且 `is_standalone=true`,则调用现有的 `UpdatePollingStatus(false)` 将 `enable_polling` 写为 `false`,并跳过 `requeueCard`,终止该卡的轮询循环。
|
||||
- **错误码**:复机被拒绝时返回业务错误,提示信息明确说明原因("风险停机"/"已销户")。
|
||||
|
||||
### 需求二:导入任务操作人与批量失效
|
||||
|
||||
**操作人快照:**
|
||||
- `tb_iot_card_import_task` 和 `tb_device_import_task` 表各新增 `creator_name varchar` 字段。
|
||||
- 新的批量失效任务表同样包含此字段。
|
||||
- 创建任务时从当前登录用户快照姓名写入,旧数据留空(不回填)。
|
||||
- 列表响应 DTO 新增 `creator_name` 字段。
|
||||
|
||||
**批量失效订单套餐任务:**
|
||||
- 新建模型、Store、Service、Handler,参照现有 IoT 卡导入任务的结构(CSV 上传 → 异步任务处理)。
|
||||
- CSV 格式:单列 `order_no`(无表头行约定沿用现有导入任务的处理方式)。
|
||||
- 创建接口额外支持:`remark`(字符串备注)和最多5张凭证(jsonb 存储)。
|
||||
- 处理逻辑:按行读取 `order_no` → 查询 `Order` → 找到 `PackageUsage WHERE order_id = ? AND status NOT IN (3, 4)` → 批量更新 `status = 4`(已失效)。
|
||||
- 订单不存在:记为失败(fail),继续处理后续行。
|
||||
- 订单存在但旗下套餐全部已是终态(status 3 或 4):记为成功(success)。
|
||||
- 不触发退款,不直接操作 IoT 卡停机,由轮询系统根据套餐状态自行评估。
|
||||
- 任务表命名:`tb_order_package_invalidate_task`。
|
||||
|
||||
### 需求三:凭证多图改造
|
||||
|
||||
- `tb_order.payment_voucher_key`(varchar 500)→ `jsonb`,存储 `[]string`,最多5个元素。
|
||||
- `tb_refund.refund_voucher_key`(varchar 500)→ `jsonb`,存储 `[]string`,最多5个元素。
|
||||
- `tb_agent_recharge_record.payment_voucher_key`(varchar 500)→ `jsonb`,存储 `[]string`,最多5个元素。
|
||||
- **数据迁移**(同一 Migration 语句):非空旧值 `"some_key"` → `["some_key"]`;空字符串 → `[]`。生产环境由运营手动执行 Migration。
|
||||
- 所有涉及凭证的请求 DTO 字段由 `string` 改为 `[]string`,validate 标签限制 `max=5`,每项 `max=500`。
|
||||
- 所有涉及凭证的响应 DTO 字段改为 `[]string`。
|
||||
- 不限制文件类型(上传 URL 获取接口层面不变,仅存储 key 列表)。
|
||||
|
||||
### 需求四:代理预充值备注
|
||||
|
||||
- `tb_agent_recharge_record` 新增 `remark text` 字段(可为空)。
|
||||
- `CreateAgentRechargeRequest` 新增 `remark` 字段(`omitempty`,无最大长度强限制,建议 1000 字符内)。
|
||||
- `AgentRechargeResponse` 新增 `remark` 字段(列表和详情接口均返回)。
|
||||
- 创建后不可修改,无需新增修改接口。
|
||||
|
||||
---
|
||||
|
||||
## Testing Decisions
|
||||
|
||||
本项目禁止自动化测试。验证方式:
|
||||
|
||||
- **PostgreSQL MCP**:核查 `tb_iot_card.enable_polling` 在风险状态卡被轮询后是否正确置为 `false`;核查 `tb_package_usage.status` 在批量失效任务执行后是否按预期更新;核查 jsonb 字段迁移结果。
|
||||
- **curl / Postman**:对风险停机卡调用复机接口,验证返回正确错误码;上传多张凭证创建订单,验证存储和返回正确;创建代理预充值时附带备注,验证列表返回。
|
||||
|
||||
---
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- 已绑定设备的卡(`is_standalone=false`)不受"风险停机/已销户"限制约束。
|
||||
- 批量失效订单套餐不触发退款流程。
|
||||
- 批量失效不直接调用网关停机,依赖轮询系统自行评估。
|
||||
- 历史导入任务的 `creator_name` 不回填。
|
||||
- 凭证文件类型校验(文件类型限制不在本次范围内)。
|
||||
- 代理预充值备注创建后不可修改(无修改接口)。
|
||||
|
||||
---
|
||||
|
||||
## Further Notes
|
||||
|
||||
- 凭证字段改为 jsonb 后,前端需同步更新上传组件支持多选;本 PRD 只覆盖后端改造。
|
||||
- 批量失效任务的凭证和备注字段,与代理预充值备注字段、以及需求三的多凭证设计保持一致的数据形态,便于后续统一处理。
|
||||
- "风险停机"和"已销户"的 `gateway_extend` 原文值来自上游网关,若上游修改返回值需同步更新常量。
|
||||
@@ -0,0 +1,28 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
新增两个 gateway_extend 常量(`GatewayCardExtendRiskStop = "风险停机"`、`GatewayCardExtendCancelled = "已销户"`),然后在后台复机入口(`ManualStartCard`)和 Open API 复机入口(`ResumeCard`)中增加前置拦截:
|
||||
|
||||
- 仅对 `is_standalone = true` 的独立卡生效
|
||||
- 读取 DB 中已落库的 `gateway_extend` 字段(不实时查网关)
|
||||
- 若命中 `"风险停机"` 或 `"已销户"`,立即返回业务错误,不再继续调用网关
|
||||
- 错误提示需明确说明被拒绝的原因(如"该卡已被运营商风险停机,不允许复机")
|
||||
|
||||
无 Schema 变更,不需要 Migration。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `pkg/constants/iot.go` 新增 `GatewayCardExtendRiskStop`、`GatewayCardExtendCancelled` 两个常量
|
||||
- [ ] 后台 `ManualStartCard` 在调用网关前检查独立卡 `gateway_extend`,命中风险值时返回业务错误
|
||||
- [ ] Open API `ResumeCard` 在调用网关前检查独立卡 `gateway_extend`,命中风险值时返回业务错误
|
||||
- [ ] 已绑定设备的卡(`is_standalone = false`)不受此限制,复机正常进行
|
||||
- [ ] 返回的错误信息能区分"风险停机"和"已销户"两种情况
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,28 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在 `PollingCardStatusHandler` 中,当轮询查询网关后将新的 `gateway_extend` 写入 DB,若新值命中风险常量(`GatewayCardExtendRiskStop` 或 `GatewayCardExtendCancelled`)且该卡 `is_standalone = true`,则:
|
||||
|
||||
1. 调用现有的 `UpdatePollingStatus(false)` 将 `enable_polling` 写为 `false`
|
||||
2. 跳过末尾的 `requeueCard`,终止该卡的轮询循环
|
||||
|
||||
检查时机:在 `UpdateFields` 写入 `gateway_extend` 成功之后,`requeueCard` 调用之前。
|
||||
|
||||
不需要 Schema 变更,不需要 Migration。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 轮询处理器在写入 `gateway_extend` 后检查风险状态
|
||||
- [ ] 独立卡(`is_standalone=true`)命中风险值时调用 `UpdatePollingStatus(false)`,`tb_iot_card.enable_polling` 被置为 `false`
|
||||
- [ ] 该卡不再入队(不调用 `requeueCard`),轮询循环终止
|
||||
- [ ] 已绑定设备的卡(`is_standalone=false`)命中风险值时不触发此逻辑,轮询正常继续
|
||||
- [ ] 可通过 PostgreSQL MCP 验证:风险状态卡处理后 `enable_polling = false`
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/01-risk-resume-block.md`(依赖 `GatewayCardExtendRiskStop`、`GatewayCardExtendCancelled` 常量)
|
||||
@@ -0,0 +1,30 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在现有两个导入任务表中新增操作人快照字段,并在列表接口返回:
|
||||
|
||||
- `tb_iot_card_import_task` 新增 `creator_name varchar(100)` 字段
|
||||
- `tb_device_import_task` 新增 `creator_name varchar(100)` 字段
|
||||
- 创建任务时从当前登录用户快照姓名写入(不可为 null,旧数据留空字符串)
|
||||
- IoT 卡导入任务列表响应 DTO 新增 `creator_name` 字段
|
||||
- 设备导入任务列表响应 DTO 新增 `creator_name` 字段
|
||||
|
||||
历史数据不回填,旧记录 `creator_name` 为空字符串。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Migration 为两个现有任务表各添加 `creator_name varchar(100) not null default ''` 字段
|
||||
- [ ] IoT 卡导入任务创建时写入当前用户姓名快照
|
||||
- [ ] 设备导入任务创建时写入当前用户姓名快照
|
||||
- [ ] IoT 卡导入任务列表接口返回 `creator_name` 字段
|
||||
- [ ] 设备导入任务列表接口返回 `creator_name` 字段
|
||||
- [ ] 旧记录 `creator_name` 为空字符串,不报错
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,43 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
新增"批量失效订单套餐"导入任务,完整实现 Model → Store → Service → Handler → Route → Worker 全链路,参照现有 IoT 卡导入任务的结构。
|
||||
|
||||
**数据模型**(新建 `tb_order_package_invalidate_task`):
|
||||
- 参照 `tb_iot_card_import_task` 的基础字段(任务编号、状态、计数、失败/跳过明细、文件存储 key、时间戳等)
|
||||
- 额外字段:`creator_name varchar(100)`、`remark text`、`voucher_keys jsonb`(存储 `[]string`,最多5个元素)
|
||||
|
||||
**上传接口**(创建任务):
|
||||
- 接受 CSV 文件(单列 `order_no`)
|
||||
- 额外参数:`remark`(字符串,可选)和 `voucher_keys`(`[]string`,最多5个,可选)
|
||||
- 写入 `creator_name` 快照
|
||||
|
||||
**Worker 处理逻辑**:
|
||||
- 逐行读取 `order_no`
|
||||
- 按 `order_no` 查询 `tb_order` 获取 `order_id`;找不到则记为失败,继续处理
|
||||
- 查询 `tb_package_usage WHERE order_id = ? AND status NOT IN (3, 4)`,批量更新 `status = 4`(已失效)
|
||||
- 订单存在但套餐全部已是终态(status 3 或 4):记为成功
|
||||
- 不触发退款,不调用网关,不直接停机
|
||||
|
||||
**列表/详情接口**:参照现有导入任务接口结构。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Migration 创建 `tb_order_package_invalidate_task` 表,包含所有必要字段
|
||||
- [ ] 创建任务接口:接受 CSV + remark + voucher_keys(最多5个),写入 creator_name 快照
|
||||
- [ ] Worker 按行处理:`order_no` 不存在 → 失败并记录原因,继续下一行
|
||||
- [ ] Worker 按行处理:订单存在且有可失效套餐 → 批量更新 `status=4` → 记为成功
|
||||
- [ ] Worker 按行处理:订单存在但套餐全为终态 → 记为成功
|
||||
- [ ] 处理过程中不调用退款接口、不操作网关
|
||||
- [ ] 列表接口返回 `creator_name`、`remark`、任务状态和计数
|
||||
- [ ] 详情接口返回失败明细(含 order_no 和原因)
|
||||
- [ ] 已在路由和文档生成器中注册
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,36 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
一次 Migration 完成三个现有表的凭证字段类型变更,并同时新增代理预充值备注字段:
|
||||
|
||||
**字段类型变更**(varchar(500) → jsonb):
|
||||
- `tb_order.payment_voucher_key`
|
||||
- `tb_refund.refund_voucher_key`
|
||||
- `tb_agent_recharge_record.payment_voucher_key`
|
||||
|
||||
**数据转换规则**(在同一 Migration 的 USING 子句中完成):
|
||||
- 非空旧值 `"some_key"` → `["some_key"]`
|
||||
- 空字符串 `""` → `[]`
|
||||
- NULL → `[]`
|
||||
|
||||
**新增字段**:
|
||||
- `tb_agent_recharge_record.remark text`(可为空,默认 null)
|
||||
|
||||
生产环境由运营手动执行,Migration 文件需包含完整的 UP 和 DOWN 语句。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Migration UP:三个凭证字段成功从 varchar 转为 jsonb,历史单值数据转换为单元素数组
|
||||
- [ ] Migration UP:空字符串/NULL 转换为空数组 `[]`
|
||||
- [ ] Migration UP:`tb_agent_recharge_record` 新增 `remark text` 字段
|
||||
- [ ] Migration DOWN:可回滚(jsonb → varchar,取数组第一个元素;remark 字段删除)
|
||||
- [ ] 迁移后可用 PostgreSQL MCP 验证数据格式正确
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -0,0 +1,27 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
将后台创建订单接口的凭证字段从单个字符串改为最多5个字符串的列表:
|
||||
|
||||
- `CreateAdminOrderRequest.payment_voucher_key`:`string` → `[]string`,validate 限制 `max=5`,每项 `max=500`
|
||||
- `OrderResponse.payment_voucher_key`(以及所有订单相关响应 DTO):`string` → `[]string`
|
||||
- Order Model 的 `PaymentVoucherKey` 字段类型改为适配 jsonb 的 `pq.StringArray` 或自定义 JSON 类型
|
||||
- Order Service 中读写 `payment_voucher_key` 的逻辑同步更新
|
||||
|
||||
Schema 变更已由 `issues/05-voucher-multi-migration.md` 完成。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 后台创建订单接口接受 `payment_voucher_key []string`(0-5个元素),offline 支付时至少需要1个
|
||||
- [ ] 订单列表/详情接口返回 `payment_voucher_key []string`
|
||||
- [ ] 传入超过5个凭证 key 时返回参数校验错误
|
||||
- [ ] 现有无凭证的订单(wallet 支付)返回空数组,不报错
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/05-voucher-multi-migration.md`
|
||||
@@ -0,0 +1,29 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
将退款申请接口的凭证字段从单个字符串改为最多5个字符串的列表:
|
||||
|
||||
- `CreateRefundRequest.refund_voucher_key`:`string` → `[]string`,validate 限制 `max=5`,每项 `max=500`,required(至少1个)
|
||||
- `ResubmitRefundRequest.refund_voucher_key`:`*string` → `*[]string`(重新提交时可选替换)
|
||||
- `RefundResponse.refund_voucher_key`(以及所有退款相关响应 DTO):`string` → `[]string`
|
||||
- Refund Model 的 `RefundVoucherKey` 字段类型改为适配 jsonb 的类型
|
||||
- Refund Service 中读写 `refund_voucher_key` 的逻辑同步更新
|
||||
|
||||
Schema 变更已由 `issues/05-voucher-multi-migration.md` 完成。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 创建退款申请接口接受 `refund_voucher_key []string`(1-5个元素,必填)
|
||||
- [ ] 重新提交退款接口的 `refund_voucher_key` 可选,传入时替换全部凭证
|
||||
- [ ] 退款列表/详情接口返回 `refund_voucher_key []string`
|
||||
- [ ] 传入超过5个凭证 key 时返回参数校验错误
|
||||
- [ ] 传入空数组时返回参数校验错误(至少需要1个)
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/05-voucher-multi-migration.md`
|
||||
@@ -0,0 +1,35 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
同时完成代理预充值的凭证多图改造和备注字段接入:
|
||||
|
||||
**凭证多图**:
|
||||
- `CreateAgentRechargeRequest.payment_voucher_key`:`string` → `[]string`,validate 限制 `max=5`,每项 `max=500`(offline 支付时至少1个,微信支付时忽略)
|
||||
- `AgentRechargeResponse.payment_voucher_key`:`string` → `[]string`
|
||||
- `AgentRechargeRecord.PaymentVoucherKey` Model 字段类型改为适配 jsonb 的类型
|
||||
|
||||
**备注字段**:
|
||||
- `CreateAgentRechargeRequest` 新增 `remark string`(可选,建议不超过1000字符)
|
||||
- `AgentRechargeResponse` 新增 `remark string`(列表和详情接口均返回)
|
||||
- `AgentRechargeRecord.Remark` 在创建时写入,后续不可修改
|
||||
|
||||
AgentRecharge Service 中读写相关字段的逻辑同步更新。
|
||||
|
||||
Schema 变更(payment_voucher_key 类型 + remark 字段)已由 `issues/05-voucher-multi-migration.md` 完成。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 创建代理预充值接口接受 `payment_voucher_key []string`(offline 时至少1个)和可选 `remark`
|
||||
- [ ] 代理预充值列表/详情接口返回 `payment_voucher_key []string` 和 `remark`
|
||||
- [ ] 传入超过5个凭证 key 时返回参数校验错误
|
||||
- [ ] 不新增 remark 修改接口,创建后备注字段只读
|
||||
- [ ] 微信支付创建预充值时可不传凭证(与现有逻辑一致)
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/05-voucher-multi-migration.md`
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"active_plan": "/Users/break/csxjProject/junhong_cmp_fiber/.sisyphus/plans/add-gateway-admin-api.md",
|
||||
"started_at": "2026-02-02T09:24:48.582Z",
|
||||
"session_ids": [
|
||||
"ses_3e254bedbffeBTwWDP2VQqDr7q"
|
||||
],
|
||||
"plan_name": "add-gateway-admin-api"
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# 架构决策记录
|
||||
|
||||
## goroutine context 设计(已确认)
|
||||
- 必须使用 `context.WithTimeout(context.Background(), 3*time.Second)` 创建独立 context
|
||||
- 禁止复用 `c.UserContext()`(Fiber 请求 context 在 handler 返回后立即失效)
|
||||
- goroutine 只接受标量参数(uint、string),不捕获 *fiber.Ctx 或任何指针
|
||||
|
||||
## 系统用户身份(已确认)
|
||||
- 使用 `UserTypePlatform` 而非 `UserTypeSuperAdmin`
|
||||
- Platform 用户仍受 500次/天日限制约束
|
||||
- SuperAdmin 不受日限制约束(不符合要求)
|
||||
|
||||
## 配置结构体命名(已确认)
|
||||
- 新增 `PollingAutoTriggerConfig` 结构体
|
||||
- Config 中字段名:`PollingAutoTrigger PollingAutoTriggerConfig`
|
||||
- YAML key: `polling_auto_trigger`
|
||||
- 环境变量前缀:`JUNHONG_POLLING_AUTO_TRIGGER_`
|
||||
|
||||
## 配置验证(已确认)
|
||||
- 不在 Validate() 中添加校验
|
||||
- 零值(false/0)是合法默认值
|
||||
|
||||
## 原子提交策略(已确认)
|
||||
- Commit 1: config 文件
|
||||
- Commit 2: service bug fix + redis 注释
|
||||
- Commit 3: handler 集成(此时全量 build 暂时报错)
|
||||
- Commit 4: DI 接线(修复全量 build)
|
||||
@@ -0,0 +1,22 @@
|
||||
# 已知问题和注意事项
|
||||
|
||||
## assetService.ResolvedAsset 类型名已确认(重要修正)
|
||||
- 计划中写的 `assetService.ResolvedAsset` 是错误的
|
||||
- 实际类型:`*dto.AssetResolveResponse`(在 `internal/model/dto/asset_dto.go` 定义)
|
||||
- `h.assetService.Resolve()` 返回 `(*dto.AssetResolveResponse, error)`
|
||||
- 字段:`.AssetType` (string), `.AssetID` (uint), `.VirtualNo` (string)
|
||||
- `resolveTargetCard` 函数签名应为:
|
||||
`func (h *ClientRealnameHandler) resolveTargetCard(c *fiber.Ctx, asset *dto.AssetResolveResponse, iccid string) (*model.IotCard, error)`
|
||||
|
||||
## import 别名冲突
|
||||
- client_realname.go 已导入 `internal/middleware` (for GetCustomerID)
|
||||
- 需要额外导入 `pkg/middleware` (for SetUserContext) 时需使用别名
|
||||
- 建议: `pkgMiddleware "github.com/break/junhong_cmp_fiber/pkg/middleware"`
|
||||
|
||||
## processBatchTrigger 中也有 TTL Bug
|
||||
- 不仅 TriggerSingle (行72),processBatchTrigger (行192) 也有相同 Bug
|
||||
- 两处都需修复,不能漏
|
||||
|
||||
## 功能开关检查逻辑
|
||||
- `config.Get().PollingAutoTrigger.EnableAutoTrigger` 为 false 时跳过 goroutine 启动
|
||||
- 零值(false/0)是合法默认值,不需要在 Validate() 中校验
|
||||
@@ -0,0 +1,37 @@
|
||||
# 项目约定和模式
|
||||
|
||||
## 模块路径
|
||||
- 项目模块路径:`github.com/break/junhong_cmp_fiber`
|
||||
|
||||
## 关键包路径(区分 pkg vs internal)
|
||||
- `pkg/middleware` - 包含 `SetUserContext`, `UserContextInfo`, `GetUserTypeFromContext`
|
||||
- `internal/middleware` - 包含 `GetCustomerID(c *fiber.Ctx)` (C端个人客户认证)
|
||||
- `internal/service/polling` - ManualTriggerService 所在包
|
||||
- `pkg/constants` - UserTypePlatform, TaskTypePollingRealname 等常量
|
||||
|
||||
## 重要发现
|
||||
- `SetUserContext` 在 `pkg/middleware` 包,不在 `internal/middleware`
|
||||
- `UserContextInfo` 字段:UserID(uint), UserType(int), ShopID(uint), EnterpriseID(uint), CustomerID(uint)
|
||||
- `GetCustomerID(c *fiber.Ctx)` 在 `internal/middleware/personal_auth.go`,返回 (uint, bool)
|
||||
- manual_trigger_service.go 当前 469 行,进行重构
|
||||
|
||||
## 当前待修复 Bug
|
||||
- `todayCount >= 100` 在 3 处(行58, 129, 238)需改为 `>= 500`
|
||||
- `time.Hour` TTL 在 2 处(行72, 192)需改为 `24*time.Hour`
|
||||
- `RedisPollingManualDedupeKey` 注释写的"1小时"需改为"24小时"
|
||||
|
||||
## client_realname.go 重构要点
|
||||
- 当前 `GetRealnameLink` 函数 127 行,加新代码会超 100 行限制
|
||||
- 需提取 `resolveTargetCard(c *fiber.Ctx, asset, iccid)` - 资产类型 switch
|
||||
- 需提取 `buildRealnameResponse(ctx, card, carrier)` - 运营商 URL 调度
|
||||
- 注意:`findCardInDeviceBindings` 和 `findFirstBoundCard` 已存在,可从 resolveTargetCard 调用
|
||||
- goroutine 传标量值(uint, string),不能捕获 `c *fiber.Ctx`
|
||||
|
||||
## 依赖注入
|
||||
- `handlers.go` 第 66 行:`ClientRealname: app.NewClientRealnameHandler(...)` 需加第8个参数
|
||||
- `docs.go` 和 `gendocs/main.go` 各有一处 `NewClientRealnameHandler(nil*7)` 需改为 8个nil
|
||||
- `svc.PollingManualTrigger` 已在 services.go:210 初始化,可直接使用
|
||||
|
||||
## Commit 3 后临时编译失败
|
||||
- Task 4 修改构造函数后、Task 5 接线前,全量编译报错是预期行为
|
||||
- 只做文件级 LSP 检查,不跑全量 build
|
||||
15
.sisyphus/notepads/tech-debt-cleanup/decisions.md
Normal file
15
.sisyphus/notepads/tech-debt-cleanup/decisions.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# tech-debt-cleanup 决策记录
|
||||
|
||||
## [2026-04-14] 初始化
|
||||
|
||||
### 任务执行顺序策略
|
||||
1. **优先执行独立任务(并行)**:Task 2 (API docs)、Task 3 (polling constants)、Task 4 (deprecated cleanup)、Task 7 (unused constants)、Task 8 (empty files)
|
||||
2. **Task 1(支付配置)**:需要先确认 pkg/payment/ 现有结构
|
||||
3. **Task 5(Model 字段)**:代码变更可与其他任务并行,DB 迁移执行需 DB 环境
|
||||
4. **Task 6(DTO _name)**:分模块逐批,每批独立验证
|
||||
5. **Task 0(DB迁移合并)**:需要 DB 环境,最后执行
|
||||
|
||||
### 支付配置动态加载架构
|
||||
- 新建 `pkg/payment/loader.go`,定义 `PaymentConfigLoader` 接口
|
||||
- Redis 缓存 TTL 1h,key: `payment:config:{configID}`
|
||||
- 权限检查:仅用户主动操作时校验;支付回调场景验证商户号一致性
|
||||
5
.sisyphus/notepads/tech-debt-cleanup/issues.md
Normal file
5
.sisyphus/notepads/tech-debt-cleanup/issues.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# tech-debt-cleanup 问题记录
|
||||
|
||||
## [2026-04-14] 初始化
|
||||
|
||||
暂无已知问题。执行过程中发现的问题将记录于此。
|
||||
229
.sisyphus/notepads/tech-debt-cleanup/learnings.md
Normal file
229
.sisyphus/notepads/tech-debt-cleanup/learnings.md
Normal file
@@ -0,0 +1,229 @@
|
||||
# tech-debt-cleanup 学习记录
|
||||
|
||||
## [2026-04-14] 初始化
|
||||
|
||||
### 项目规范关键点
|
||||
- 所有注释必须使用中文
|
||||
- Redis Key 必须通过函数生成(格式:`Redis{Module}{Purpose}Key(params...)`)
|
||||
- 错误码必须定义在 `pkg/errors/codes.go`
|
||||
- 常量定义在 `pkg/constants/`
|
||||
- 架构:Handler → Service → Store → Model
|
||||
- 禁止使用外键约束
|
||||
- 禁止 Go 测试文件(*_test.go)
|
||||
|
||||
### 关键文件路径
|
||||
- 支付服务: `internal/service/order/service.go`, `internal/service/recharge/service.go`
|
||||
- 轮询服务: `internal/service/polling/manual_trigger_service.go`, `alert_service.go`
|
||||
- 轮询 Handler: `internal/handler/admin/polling_manual_trigger.go`
|
||||
- 轮询 Store: `internal/store/postgres/polling_manual_trigger_store.go`
|
||||
- 文档生成: `cmd/api/docs.go`, `cmd/gendocs/main.go`
|
||||
- Redis Key: `pkg/constants/redis.go`
|
||||
- 支付包: `pkg/payment/`
|
||||
- 废弃 DTO: `internal/model/dto/enterprise_card_authorization_dto.go`
|
||||
- 废弃任务: `internal/task/sync.go`
|
||||
- 空文件: `internal/routes/recharge.go`
|
||||
- Model: `internal/model/iot_card.go`, `internal/model/device.go`
|
||||
|
||||
## [2026-04-14] Task 3: 轮询状态常量提取
|
||||
|
||||
### 发现和注意点
|
||||
|
||||
1. **alert_service.go 的 "pending" 只有 1 处**:`NotificationStatus: "pending"` 在 `triggerAlert()` 函数中,其他字符串如 `"sent"`、`"partial"`、`"failed"` 是通知发送状态(非轮询触发日志状态),不在替换范围内。
|
||||
|
||||
2. **Store 层 SQL 字符串处理**:`polling_manual_trigger_store.go` 中 `GetRunning` 函数原本使用 SQL 字面量 `status IN ('pending', 'processing')`,改为 GORM 参数化查询 `status IN (?, ?)` 并传入常量,既消除硬编码又提升安全性。
|
||||
|
||||
3. **Store 层需要新增 import**:`polling_manual_trigger_store.go` 原本未导入 `constants` 包,添加时注意 Go import 分组规范(stdlib / 第三方 / 内部包)。
|
||||
|
||||
4. **constants 包在 handler 文件已存在**:`polling_manual_trigger.go` 已导入 `pkg/constants`,无需额外修改 import。
|
||||
|
||||
5. **manual_trigger_service.go 共 6 处替换**:3 处 `"processing"`(triggerLog 创建)、2 处 `"completed"`(UpdateStatus 调用)、1 处同时含 `"pending"` + `"processing"` + `"cancelled"` 的 CancelTrigger 状态检查。
|
||||
|
||||
## [2026-04-14] Task 4: 废弃代码清理
|
||||
|
||||
### 废弃别名实际引用情况
|
||||
扫描 `internal/` 和 `pkg/` 后,真正使用废弃别名的只有 3 处(其他文件早已用新常量):
|
||||
- `shop_commission/service.go:645` → `TransactionTypeWithdrawal` 替换为 `AgentTransactionTypeWithdrawal`
|
||||
- `recharge/service.go:91,94,417,418` → `RechargeMinAmount/RechargeMaxAmount` 替换为 `AssetRechargeMinAmount/AssetRechargeMaxAmount`(资产钱包充值场景,最小1元/最大100000元)
|
||||
|
||||
### CheckAndStopCard 无法删除
|
||||
`stop_resume_service.go` 中的 `CheckAndStopCard` 在接口 `StopResumeServiceInterface`(`usage_service.go:20`)中声明,并在 `package_activation_handler.go`(327、347行)和 `usage_service.go`(230、255行)中活跃调用。任务描述要求"确认无调用后再删除",此方法有调用,故跳过删除。
|
||||
|
||||
### grep 验证注意事项
|
||||
- `SyncHandler` 的 grep 命中了 `CommissionStatsSyncHandler`(合法),不是废弃的 DataSync handler。
|
||||
- `CardWallet` 出现在 `data_scope.go:82` 的注释字符串里(非代码引用),不需要修改。
|
||||
|
||||
### 删除的代码统计
|
||||
- `sync.go` 整个文件(166行)
|
||||
- `handler.go` 3行(syncHandler var + HandleFunc + logger.Info)
|
||||
- `constants.go` 1行(TaskTypeDataSync)
|
||||
- `wallet.go` 86行(149-234行废弃别名块)
|
||||
- `enterprise_card_authorization_dto.go` 22行(DeviceBundle、DeviceBundleCard、AllocatedDevice)
|
||||
- `order/service.go` 约243行(CreateLegacy 方法)
|
||||
|
||||
## [2026-04-14] Task 7+8: 常量清理和空文件删除
|
||||
|
||||
### 执行内容
|
||||
|
||||
**Task 7.1:删除 CodeExceedLimit 错误码**
|
||||
- 删除常量定义:`CodeExceedLimit = 1055` (line 68)
|
||||
- 删除 allErrorCodes 列表条目 (line 227)
|
||||
- 删除 errorMessages 映射条目 (line 359)
|
||||
- 验证:grep 确认代码库中无任何引用
|
||||
|
||||
**Task 7.2:为预留常量添加 [预留] 注释**
|
||||
- LadderType 系列(激活量、提货量、充值量):添加 `[预留] 用于分佣阶梯功能,待产品规划`
|
||||
- ApprovalType/ApprovalStatus 系列(审批类型/状态):添加 `[预留] 用于审批流程功能,待产品规划`
|
||||
- MerchantType 系列(支付宝、微信、银行卡):添加 `[预留] 用于未来商户管理功能,待产品规划`
|
||||
- ReplacementStatus 系列(换卡申请状态):添加 `[预留] 用于换卡申请功能,待产品规划`
|
||||
- ReplacementReason 系列(换货原因):添加 `[预留] 用于换卡原因管理功能,待产品规划`
|
||||
|
||||
**Task 8.1:删除空文件**
|
||||
- 删除 `internal/routes/recharge.go`(仅包含 `package routes`)
|
||||
|
||||
**Task 8.2:删除 postgres.go 的 AutoMigrate 注释块**
|
||||
- 删除 lines 90-95 的注释掉的 AutoMigrate 代码块
|
||||
|
||||
**Task 8.3:更新 client_order/service.go 注释**
|
||||
- 在 line 140 的实名认证检查注释前添加:`// [待确认] 业务是否需要实名认证检查?参见 tech-debt-cleanup 提案`
|
||||
|
||||
### 验证结果
|
||||
- ✅ `go build ./cmd/api ./cmd/worker` 通过
|
||||
- ✅ `go vet ./pkg/errors/ ./pkg/constants/ ./pkg/database/` 无报告
|
||||
- ✅ `grep -r "CodeExceedLimit"` 无结果(完全删除)
|
||||
- ✅ 所有预留常量已添加 [预留] 标记和产品规划说明
|
||||
|
||||
## [2026-04-14] Task 2: API 文档生成器补全
|
||||
|
||||
### 发现
|
||||
|
||||
- `BuildDocHandlers()` 缺少 3 个 Handler:`ClientAuth`、`AdminAuth`、`AssetLifecycle`,它们在 `bootstrap/types.go` 中有定义,但从未加入文档生成器
|
||||
- `AdminAuth` 在 `docs.go` 和 `gendocs/main.go` 中**完全未被设置**(连手动覆写都没有),这意味着 Admin Auth 相关路由一直缺失于 OpenAPI 文档
|
||||
- `docs.go` 和 `gendocs/main.go` 的手动覆写列表(9 行 `handlers.Xxx = ...`)中,大多数 handler 其实已经在 `BuildDocHandlers()` 中了,属于纯冗余
|
||||
|
||||
### 操作
|
||||
|
||||
1. `pkg/openapi/handlers.go`:按 types.go 字段顺序插入 `ClientAuth`(PersonalCustomer 后)、`AdminAuth`(ShopRole 后)、`AssetLifecycle`(Asset 后)
|
||||
2. `cmd/api/docs.go`:删除所有手动覆写行(9 行)+ 移除 `admin` 和 `apphandler` import
|
||||
3. `cmd/gendocs/main.go`:同上
|
||||
|
||||
### 注意点
|
||||
|
||||
- `admin.NewAuthHandler` 需要 2 个 nil 参数(authService + validator)
|
||||
- `app.NewClientAuthHandler` 需要 2 个 nil 参数(service + logger)
|
||||
- `admin.NewAssetLifecycleHandler` 只需 1 个 nil 参数(service 接口)
|
||||
- 清理完 import 后 `go build` + `go vet` 均通过,无报错
|
||||
|
||||
## [2026-04-14] Task 5: Model 废弃字段清理
|
||||
|
||||
### 引用情况(超出预期的额外文件)
|
||||
|
||||
计划中列出的文件之外,还发现了额外引用:
|
||||
- `internal/service/device/service.go` line 576-577:`DeviceResponse` 构建中有引用(计划中未提及)
|
||||
- `internal/service/recharge/service.go` line 31:`ForceRechargeRequirement` struct 有 `FirstCommissionPaid` 字段
|
||||
- `internal/service/recharge/service.go` line 458:`result.FirstCommissionPaid = firstCommissionPaid` 赋值
|
||||
|
||||
### 关键判断:recharge/service.go 的 firstCommissionPaid 变量
|
||||
|
||||
`checkForceRechargeRequirement` 中的 `firstCommissionPaid` 变量**不是废弃字段**:
|
||||
- 它读自 `card.IsFirstRechargeTriggeredBySeries(*seriesID)` 和 `device.IsFirstRechargeTriggeredBySeries(*seriesID)`(均是新 BySeries 方法)
|
||||
- 该变量用于 `if firstCommissionPaid {` 的业务判断(已发放则跳过强充检查)
|
||||
- 正确做法:只删 `ForceRechargeRequirement.FirstCommissionPaid` 字段 + `result.FirstCommissionPaid = firstCommissionPaid` 赋值,保留变量声明和 if 判断
|
||||
|
||||
### 迁移文件
|
||||
- 新建 `migrations/000116_remove_legacy_commission_fields.up.sql`
|
||||
- 新建 `migrations/000116_remove_legacy_commission_fields.down.sql`
|
||||
|
||||
### 验证结果
|
||||
- ✅ `go build ./cmd/api ./cmd/worker` 通过,无任何错误
|
||||
|
||||
## [2026-04-14] Task 1: 支付配置动态加载
|
||||
|
||||
### 实现架构决策
|
||||
|
||||
#### 1. PaymentConfigLoader 位置
|
||||
- 新建 `pkg/payment/loader.go`(包名 `payment`)
|
||||
- `pkg/` 下可以 import `internal/` 包(项目中已有先例:`pkg/wechat/config.go` import `internal/model`)
|
||||
|
||||
#### 2. 缓存策略
|
||||
- 不缓存 Payment 实例(含连接/状态,不可序列化)
|
||||
- 缓存 **WechatConfig JSON 数据**(key: `payment:config:{id}`,TTL: 1 小时)
|
||||
- 每次从缓存数据构建 Payment 实例(轻量操作,无 I/O)
|
||||
|
||||
#### 3. v2 适配器模式
|
||||
- `PaymentV2Service` 未实现完整 `PaymentServiceInterface`(缺少 H5/查单/关单/HandlePaymentNotify)
|
||||
- 通过 `v2PaymentAdapter` 包装,补全缺失方法(返回"不支持"错误)
|
||||
- **不修改** `payment_v2.go` 原文件
|
||||
|
||||
#### 4. `appID` 来源
|
||||
- `NewPaymentAppFromConfig` / `NewPaymentV2ServiceFromConfig` 均需要 `appID` 参数
|
||||
- 使用 `wechatConfig.OaAppID`(公众号 AppID)
|
||||
|
||||
#### 5. wechatCache 共享
|
||||
- loader 在构造时通过 `wechat.NewRedisCache(rdb)` 创建一次,所有 LoadConfig 调用复用
|
||||
- v3 Payment 实例构建需要此 cache(用于 PowerWeChat SDK 内部 token 缓存)
|
||||
|
||||
#### 6. worker_services.go 也需更新
|
||||
- `internal/bootstrap/worker_services.go` 里有另一处 `orderSvc.New` 调用(超时取消专用)
|
||||
- 需额外传 `nil` 占位
|
||||
|
||||
### 关键文件变更
|
||||
| 文件 | 变更内容 |
|
||||
|------|---------|
|
||||
| `pkg/constants/redis.go` | +`RedisPaymentConfigKey` |
|
||||
| `pkg/payment/loader.go` | 新建:接口 + 实现 + v2 适配器 |
|
||||
| `internal/service/order/service.go` | +`paymentLoader` 字段/参数,替换 2 处 TODO |
|
||||
| `internal/service/recharge/service.go` | +`paymentLoader` 字段/参数,更新 1 处 TODO 注释 |
|
||||
| `internal/bootstrap/services.go` | 创建 loader 实例,传入 Order/Recharge 构造函数 |
|
||||
| `internal/bootstrap/worker_services.go` | `orderSvc.New` 补传 `nil` |
|
||||
|
||||
### 验证结果
|
||||
- ✅ `go build ./cmd/api ./cmd/worker` 通过,无任何错误
|
||||
- ✅ `go vet` 无报告
|
||||
|
||||
## [2026-04-14] Task 6: DTO _name 字段补全
|
||||
|
||||
### 概述
|
||||
为所有 Response DTO 中的 `int` 类型状态字段补全对应 `string` 类型 `_name` 字段,并在 Service 层赋值。
|
||||
|
||||
### 常量映射函数(新增)
|
||||
|
||||
**`pkg/constants/constants.go`:**
|
||||
- `GetStatusName(status int) string` — 通用 0=禁用/1=启用
|
||||
- `GetShelfStatusName(status int) string` — 1=上架/2=下架
|
||||
- `GetExchangeStatusName(status int) string` — 换货单状态
|
||||
|
||||
**`pkg/constants/iot.go`:**
|
||||
- `GetIotCardStatusName` — 1=在库, 2=已分销, 3=已激活, 4=已停用
|
||||
- `GetActivationStatusName` — 0=未激活, 1=已激活
|
||||
- `GetRealNameStatusName` — 0=未实名, 1=已实名
|
||||
- `GetNetworkStatusName` — 0=停机, 1=开机
|
||||
- `GetCommissionRecordStatusName` — 1=已冻结/2=解冻中/3=已发放/4=已失效/99=待人工修正
|
||||
- `GetOrderPaymentStatusName` — 1=待支付/2=已支付/3=已取消/4=已退款
|
||||
- `GetOrderCommissionStatusName` — 1=待计算/2=已计算
|
||||
- `GetRefundStatusName` — 1=待审批/2=已通过/3=已拒绝/4=已退回
|
||||
|
||||
### 模块处理情况
|
||||
|
||||
| 模块 | DTO 改动 | Service 赋值位置 | 备注 |
|
||||
|------|---------|-----------------|------|
|
||||
| Account | `AccountResponse` + `status_name` | `toAccountResponse()` | constants 已导入 |
|
||||
| Shop | `ShopResponse` + `status_name` | Create/Update/ListShopResponses(3处)| constants 已导入 |
|
||||
| IotCard | `StandaloneIotCardResponse` + 4个 `_name` 字段 | `toStandaloneResponse()` | status/activation/realname/network |
|
||||
| Order | `OrderResponse` + `commission_status_name` | `buildOrderResponse()` | payment_status 已有 `_text` 字段 |
|
||||
| Package | `PackageResponse` + `status_name`/`shelf_status_name` | `toResponse()` 末尾(agent 覆盖后赋值) | my_package.go 也同步更新(不涉及 service)|
|
||||
| Refund | `RefundResponse` + `status_name` | `buildRefundResponse()` | constants 已导入 |
|
||||
| Device | `DeviceCardBindingResponse` + `status_name` | `device/binding.go` | 新增 constants import |
|
||||
| Asset | `AssetResolveResponse` + `status_name` | `buildDeviceResolveResponse` + `buildCardResolveResponse` | constants 已导入 |
|
||||
| Commission | `CommissionRecordResponse` + `status_name` | 未找到 service 调用(DTO 未被使用,ShopCommissionRecordItem 已有 status_name)| 仅 DTO 更新;同时修正了 description 错误 |
|
||||
| Client Asset | `AssetInfoResponse` + 4个 `_name` 字段 | handler `client_asset.go`(直接赋值)| constants 已导入 |
|
||||
| Client Order | `ClientOrderInfo/ListItem/DetailResponse` + `payment_status_name`; `ClientRechargeInfo` + `status_name` | `client_order/service.go` | 增加 `clientRechargeStatusName` 辅助函数 |
|
||||
| MyPackage | `MyPackageResponse/DetailResponse` + `status_name`/`shelf_status_name`; `MySeriesAllocationResponse` + `status_name` | 未找到 service 调用,仅 DTO 更新 | |
|
||||
|
||||
### 关键发现
|
||||
1. `CommissionRecordResponse.status` description 原先错误(写的 "1:已入账" 但常量是 "1:已冻结"),已修正为正确值
|
||||
2. `ClientRechargeInfo.Status` 使用的是 `rechargeStatusToClientStatus()` 转换后的值(0/1/2),与 RechargeStatus* 常量不同
|
||||
3. 部分 DTO(MyPackage、CommissionRecord)未被 service 层引用,仅更新 DTO 定义
|
||||
4. `DeviceResponse` 和 `ImportTaskResponse` 已经有 `status_name` 和 `status_text` 字段,无需修改
|
||||
|
||||
### 验证结果
|
||||
- ✅ `go build ./cmd/api ./cmd/worker` 通过,无任何错误
|
||||
691
.sisyphus/plans/realname-trigger-priority-enhancement.md
Normal file
691
.sisyphus/plans/realname-trigger-priority-enhancement.md
Normal file
@@ -0,0 +1,691 @@
|
||||
# realname-trigger-priority-enhancement 执行计划
|
||||
|
||||
## TL;DR
|
||||
|
||||
> **快速摘要**:修复手动触发去重TTL不对齐、日限制过低两个Bug,并在C端实名链接接口中异步触发优先级检查,减少用户等待时间。
|
||||
>
|
||||
> **交付物**:
|
||||
> - `pkg/config/` 新增 PollingAutoTriggerConfig 配置结构
|
||||
> - `internal/service/polling/manual_trigger_service.go` 修复3处日限制(100→500)、2处TTL(1h→24h)、提取权限检查公共函数、增强错误日志
|
||||
> - `internal/handler/app/client_realname.go` 新增异步触发逻辑(含2个辅助方法提取)
|
||||
> - `internal/bootstrap/handlers.go`、`cmd/api/docs.go`、`cmd/gendocs/main.go` 依赖注入接线
|
||||
> - `pkg/constants/redis.go` 注释同步更新
|
||||
>
|
||||
> **预计工作量**:60-90 分钟
|
||||
> **关键路径**:配置 → ManualTriggerService修复 → Handler集成 → 依赖注入接线 → 手动验证
|
||||
|
||||
---
|
||||
|
||||
## 上下文
|
||||
|
||||
### 原始需求
|
||||
|
||||
用户在C端主动获取实名跳转链接后,需等待轮询系统定时检查(30秒-5分钟间隔)才能检测到实名状态变化。同时手动触发功能存在两个Bug:去重key TTL(1小时)与日限制周期(24小时)不对齐,以及日限制次数(100次)过低导致正常使用受限。
|
||||
|
||||
### 代码库现状(已验证)
|
||||
|
||||
| 项目 | 状态 |
|
||||
|------|------|
|
||||
| `constants.TaskTypePollingRealname` | ✅ 已存在:`"polling:realname"`(constants.go:55) |
|
||||
| `svc.PollingManualTrigger` in bootstrap | ✅ 已初始化(services.go:210) |
|
||||
| 日限制 `>= 100` 位置 | **3处**:manual_trigger_service.go:58, 129, 238 |
|
||||
| `Expire(..., time.Hour)` 位置 | **2处**:manual_trigger_service.go:72(TriggerSingle)和 :192(processBatchTrigger) |
|
||||
| `NewClientRealnameHandler` 当前参数数 | 7个 → 改后8个 |
|
||||
| docs.go / gendocs/main.go 调用处 | 各1处,7个nil → 8个nil |
|
||||
| `GetRealnameLink` 当前行数 | **127行**(已超100行限制,需提取辅助方法) |
|
||||
| 系统用户 | 暂用 SuperAdmin ID=1,使用 UserTypePlatform 身份 |
|
||||
|
||||
### 关键设计决策
|
||||
|
||||
1. **goroutine 异步触发**:使用 `context.WithTimeout(context.Background(), 3s)` 独立 context,**禁止**复用 `c.UserContext()`(Fiber 请求 context 在 handler 返回后失效)
|
||||
2. **系统用户身份**:`UserTypePlatform`(非 UserTypeSuperAdmin),既绕过卡归属权限检查,又仍受500次/天限制约束
|
||||
3. **goroutine 参数**:只传标量值(uint、string),**绝对不捕获 `c *fiber.Ctx` 或任何指针**
|
||||
4. **GetRealnameLink 行数**:当前127行已超限,需在 Task 4 中额外提取两个 helper(已批准)
|
||||
5. **processBatchTrigger TTL**:两处都修(已确认)
|
||||
6. **Commit 3 临时编译失败**:Task 4 修改构造函数后、Task 5 接线前,全量编译会报错,只做文件级 LSP 检查
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 — 现状分析
|
||||
|
||||
### Task 1.1 — LSP 基线诊断
|
||||
|
||||
**操作**:对以下两个文件运行 `lsp_diagnostics`:
|
||||
- `internal/handler/app/client_realname.go`
|
||||
- `internal/service/polling/manual_trigger_service.go`
|
||||
|
||||
**目的**:建立干净基线,区分预存问题与本次引入的问题
|
||||
|
||||
**验收**:记录所有预存 warning,确认无预存 error
|
||||
|
||||
---
|
||||
|
||||
### Task 1.2 — 依赖关系确认
|
||||
|
||||
**操作**:
|
||||
- 确认 `handler/app → service/polling` 无循环依赖(polling service 不导入 handler 包)
|
||||
- 确认 `internal/bootstrap/handlers.go` 已有 `pollingSvcPkg` import alias
|
||||
|
||||
**验收**:无循环依赖,`svc.PollingManualTrigger` 在 bootstrap 中可访问
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — 配置管理
|
||||
|
||||
### Task 2.1 — 新增配置结构体和字段
|
||||
|
||||
**文件**:`pkg/config/config.go`
|
||||
|
||||
新增结构体(放在其他 Config 结构体附近):
|
||||
```go
|
||||
// PollingAutoTriggerConfig 轮询自动触发配置
|
||||
type PollingAutoTriggerConfig struct {
|
||||
// EnableAutoTrigger 是否启用C端实名自动触发
|
||||
// 环境变量:JUNHONG_POLLING_AUTO_TRIGGER_ENABLE_AUTO_TRIGGER
|
||||
EnableAutoTrigger bool `mapstructure:"enable_auto_trigger"`
|
||||
// AutoTriggerSystemUserID 自动触发使用的系统用户ID(暂用 SuperAdmin ID=1)
|
||||
// 环境变量:JUNHONG_POLLING_AUTO_TRIGGER_AUTO_TRIGGER_SYSTEM_USER_ID
|
||||
AutoTriggerSystemUserID int `mapstructure:"auto_trigger_system_user_id"`
|
||||
}
|
||||
```
|
||||
|
||||
在 `Config` struct 中添加字段(位置:Gateway 字段之后):
|
||||
```go
|
||||
PollingAutoTrigger PollingAutoTriggerConfig `mapstructure:"polling_auto_trigger"`
|
||||
```
|
||||
|
||||
**陷阱**:不要在 `Validate()` 中添加校验——零值(false/0)是合法默认值
|
||||
|
||||
**验收**:结构体定义正确,mapstructure tag 与 yaml key 对应
|
||||
|
||||
---
|
||||
|
||||
### Task 2.2 — 更新默认配置 YAML
|
||||
|
||||
**文件**:`pkg/config/defaults/config.yaml`
|
||||
|
||||
在文件末尾添加(保留尾部换行):
|
||||
```yaml
|
||||
# 轮询自动触发配置
|
||||
polling_auto_trigger:
|
||||
enable_auto_trigger: true
|
||||
auto_trigger_system_user_id: 1 # 暂用 SuperAdmin,生产环境建议创建专用平台账号并更新此值
|
||||
```
|
||||
|
||||
对应环境变量:
|
||||
- `JUNHONG_POLLING_AUTO_TRIGGER_ENABLE_AUTO_TRIGGER`
|
||||
- `JUNHONG_POLLING_AUTO_TRIGGER_AUTO_TRIGGER_SYSTEM_USER_ID`
|
||||
|
||||
**验收**:config.Get().PollingAutoTrigger.EnableAutoTrigger 默认为 true
|
||||
|
||||
---
|
||||
|
||||
### Task 2.3 — LSP 检查配置
|
||||
|
||||
**操作**:`lsp_diagnostics` 对 `pkg/config/config.go`
|
||||
|
||||
**验收**:0 error
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — 手动触发服务 Bug 修复
|
||||
|
||||
### Task 3.1 — 日限制 100 → 500(3处)
|
||||
|
||||
**文件**:`internal/service/polling/manual_trigger_service.go`
|
||||
|
||||
| 行号 | 修改内容 |
|
||||
|------|---------|
|
||||
| 58 | `todayCount >= 100` → `todayCount >= 500`,同步更新行内注释 `// 每日最多触发100次` → `// 每日最多触发500次` |
|
||||
| 129 | `todayCount >= 100` → `todayCount >= 500`,补充注释 `// 每日最多触发500次` |
|
||||
| 238 | `todayCount >= 100` → `todayCount >= 500`,补充注释 `// 每日最多触发500次` |
|
||||
|
||||
**验收**:`grep -n "100" manual_trigger_service.go` 无日限制相关残留
|
||||
|
||||
---
|
||||
|
||||
### Task 3.2 — 去重 TTL 1h → 24h(2处)
|
||||
|
||||
**文件**:`internal/service/polling/manual_trigger_service.go`
|
||||
|
||||
| 行号 | 修改内容 |
|
||||
|------|---------|
|
||||
| 71-72 | 注释改为 `// 设置去重 key 过期时间(24小时,与日限制周期对齐)`;`time.Hour` → `24*time.Hour` |
|
||||
| 191-192 | 同上(processBatchTrigger 中,存在相同 Bug,一并修复) |
|
||||
|
||||
**验收**:`grep -n "time.Hour" manual_trigger_service.go` 无残留
|
||||
|
||||
---
|
||||
|
||||
### Task 3.3 — 同步 Redis 常量注释
|
||||
|
||||
**文件**:`pkg/constants/redis.go`
|
||||
|
||||
找到 `RedisPollingManualDedupeKey` 函数注释,将:
|
||||
```
|
||||
// 过期时间:1小时
|
||||
```
|
||||
改为:
|
||||
```
|
||||
// 过期时间:24小时(与日限制周期对齐)
|
||||
```
|
||||
|
||||
**验收**:注释与实际 TTL 一致
|
||||
|
||||
---
|
||||
|
||||
### Task 3.4 — 提取公共权限检查函数
|
||||
|
||||
**文件**:`internal/service/polling/manual_trigger_service.go`
|
||||
|
||||
从 `canManageCard`、`canManageCards`、`applyShopPermissionFilter` 三处提取重复的用户类型检查,新增私有方法:
|
||||
|
||||
```go
|
||||
// checkUserTypePermission 检查用户类型是否有手动触发权限
|
||||
// 返回 skip=true 表示超级管理员/平台用户直接放行
|
||||
// 返回 err!=nil 表示企业账号无权限
|
||||
// 返回 skip=false, err=nil 表示代理账号需继续细粒度检查
|
||||
func (s *ManualTriggerService) checkUserTypePermission(ctx context.Context) (skip bool, err error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType == constants.UserTypeSuperAdmin || userType == constants.UserTypePlatform {
|
||||
return true, nil
|
||||
}
|
||||
if userType == constants.UserTypeEnterprise {
|
||||
return false, errors.New(errors.CodeForbidden, "企业账号无权限手动触发轮询")
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
```
|
||||
|
||||
三个调用方改为:
|
||||
```go
|
||||
skip, err := s.checkUserTypePermission(ctx)
|
||||
if err != nil || skip {
|
||||
return err // canManageCard 签名
|
||||
}
|
||||
```
|
||||
|
||||
**陷阱**:`applyShopPermissionFilter` 中超管分支有 filter 对象逻辑,只提取类型检查部分,不删除 filter 修改逻辑
|
||||
|
||||
**验收**:三个函数各减少约5行重复代码,行为不变
|
||||
|
||||
---
|
||||
|
||||
### Task 3.5 — 改进 TriggerSingle 错误日志
|
||||
|
||||
**文件**:`internal/service/polling/manual_trigger_service.go`
|
||||
|
||||
在 `TriggerSingle` 每条 `return err` 路径前补充结构化日志,字段要求:
|
||||
|
||||
| 错误场景 | 必须包含字段 |
|
||||
|---------|------------|
|
||||
| 查询今日触发次数失败 | `triggered_by`、`task_type`、`error` |
|
||||
| Redis去重操作失败 | `card_id`、`task_type`、`error` |
|
||||
| 创建触发日志失败 | `card_id`、`triggered_by`、`error` |
|
||||
| 写入队列失败 | `card_id`、`task_type`、`error` |
|
||||
|
||||
**验收**:每条 return err 路径有对应日志,级别为 Error
|
||||
|
||||
---
|
||||
|
||||
### Task 3.6 — LSP 检查
|
||||
|
||||
**操作**:`lsp_diagnostics` 对 `internal/service/polling/manual_trigger_service.go`
|
||||
|
||||
**验收**:0 error,0 新增 warning
|
||||
|
||||
---
|
||||
|
||||
### Task 3.7 — 手动验证去重 + 限制
|
||||
|
||||
**操作**(通过 Redis CLI 或 PostgreSQL MCP):
|
||||
|
||||
```bash
|
||||
# 1. 触发某张卡,验证 TTL 为 24小时
|
||||
redis-cli TTL polling:manual:dedupe:polling:realname
|
||||
# 期望:≈ 86400
|
||||
|
||||
# 2. 再次触发同一张卡,验证被拒绝
|
||||
# 期望返回:"该卡已在手动触发队列中"
|
||||
|
||||
# 3. 删除 dedupe key 后重新触发,验证成功
|
||||
redis-cli DEL polling:manual:dedupe:polling:realname
|
||||
```
|
||||
|
||||
```sql
|
||||
-- 验证今日触发次数计数正确
|
||||
SELECT COUNT(*) as today_count
|
||||
FROM tb_polling_manual_trigger_log
|
||||
WHERE DATE(triggered_at) = CURRENT_DATE;
|
||||
```
|
||||
|
||||
**验收**:TTL ≈ 86400,重复触发被拒绝,DB 计数正确
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Handler 集成
|
||||
|
||||
### Task 4.1 — 结构体新增字段
|
||||
|
||||
**文件**:`internal/handler/app/client_realname.go`
|
||||
|
||||
添加 import(注意区分 `internal/service/polling` 与 `internal/polling` 是不同包):
|
||||
```go
|
||||
pollingSvc "github.com/xxx/junhong_cmp_fiber/internal/service/polling"
|
||||
```
|
||||
|
||||
在 `ClientRealnameHandler` 结构体新增字段:
|
||||
```go
|
||||
manualTriggerSvc *pollingSvc.ManualTriggerService // 手动触发服务(可为nil,nil时跳过自动触发)
|
||||
```
|
||||
|
||||
**验收**:结构体字段添加正确,import 路径正确
|
||||
|
||||
---
|
||||
|
||||
### Task 4.2 — 修改构造函数(第8个参数)
|
||||
|
||||
**文件**:`internal/handler/app/client_realname.go`
|
||||
|
||||
在 `NewClientRealnameHandler` 末尾新增参数:
|
||||
```go
|
||||
func NewClientRealnameHandler(
|
||||
// ...现有7个参数保持不变...
|
||||
manualTriggerSvc *pollingSvc.ManualTriggerService, // 可为nil
|
||||
) *ClientRealnameHandler {
|
||||
return &ClientRealnameHandler{
|
||||
// ...现有字段初始化...
|
||||
manualTriggerSvc: manualTriggerSvc,
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**陷阱**:修改后 `docs.go`、`gendocs/main.go`、`bootstrap/handlers.go` 会出现编译错误(构造函数参数不一致),待 Task 5 修复。此阶段**只做文件级** LSP 检查,不跑全量 build
|
||||
|
||||
**验收**:`client_realname.go` 本身 LSP 0 error
|
||||
|
||||
---
|
||||
|
||||
### Task 4.3 — 提取辅助方法(解决 GetRealnameLink 行数超限问题)
|
||||
|
||||
**文件**:`internal/handler/app/client_realname.go`
|
||||
|
||||
**背景**:当前 `GetRealnameLink` 127行,加 goroutine 代码约133行,违反 ≤100行规范。需提取两个私有方法。
|
||||
|
||||
**提取1:`resolveTargetCard`**(资产类型 switch 分支,约26行):
|
||||
```go
|
||||
// resolveTargetCard 根据资产类型和ICCID定位目标卡
|
||||
// 支持三条路径:直接卡资产、设备+指定ICCID、设备取第一张绑定卡
|
||||
func (h *ClientRealnameHandler) resolveTargetCard(c *fiber.Ctx, asset *assetService.ResolvedAsset, iccid string) (*model.IotCard, error) {
|
||||
switch {
|
||||
case asset.AssetType == "card":
|
||||
// ...
|
||||
case asset.AssetType == "device" && iccid != "":
|
||||
// ...
|
||||
case asset.AssetType == "device":
|
||||
// ...
|
||||
default:
|
||||
return nil, errors.New(errors.CodeInvalidParam, "不支持的资产类型")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**提取2:`buildRealnameResponse`**(运营商 URL 调度,约32行):
|
||||
```go
|
||||
// buildRealnameResponse 根据运营商实名链接类型构建响应
|
||||
func (h *ClientRealnameHandler) buildRealnameResponse(ctx context.Context, card *model.IotCard, carrier *model.Carrier) (*dto.RealnimeLinkResponse, error) {
|
||||
// switch carrier.RealnameLinkType { ... }
|
||||
}
|
||||
```
|
||||
|
||||
提取后 `GetRealnameLink` ≈70行,加 goroutine 后 ≈76行 ✅
|
||||
|
||||
**陷阱**:
|
||||
- `resolveTargetCard` 需要 `c *fiber.Ctx`(子函数调用需要 Fiber context)
|
||||
- `buildRealnameResponse` 用 `ctx context.Context`(只调 gatewayClient)
|
||||
- 确认 `assetService.ResolvedAsset` 的实际类型名称(读文件确认后再写)
|
||||
|
||||
**验收**:`GetRealnameLink` 函数体 ≤100行,两个新方法编译正常,逻辑不变
|
||||
|
||||
---
|
||||
|
||||
### Task 4.4 — 添加异步触发调用
|
||||
|
||||
**文件**:`internal/handler/app/client_realname.go`
|
||||
|
||||
添加 import:`"github.com/xxx/junhong_cmp_fiber/pkg/config"`
|
||||
|
||||
在 `GetRealnameLink` 中,成功构建响应之后、`response.Success(c, resp)` 之前插入:
|
||||
```go
|
||||
// 异步触发实名检查,提升检测优先级;失败不影响主流程
|
||||
if h.manualTriggerSvc != nil && config.Get().PollingAutoTrigger.EnableAutoTrigger {
|
||||
systemUserID := uint(config.Get().PollingAutoTrigger.AutoTriggerSystemUserID)
|
||||
go h.triggerRealnameCheck(targetCard.ID, customerID, targetCard.ICCID, systemUserID)
|
||||
}
|
||||
```
|
||||
|
||||
**强制约束**:goroutine 只传标量值(uint、string),**绝对不捕获 `c *fiber.Ctx` 或任何指针类型**
|
||||
|
||||
**验收**:goroutine 启动代码不捕获 Fiber context 相关变量
|
||||
|
||||
---
|
||||
|
||||
### Task 4.5 — 实现 triggerRealnameCheck 私有方法
|
||||
|
||||
**文件**:`internal/handler/app/client_realname.go`
|
||||
|
||||
添加 imports:`"context"`、`"time"`、`"github.com/xxx/junhong_cmp_fiber/pkg/middleware"`
|
||||
|
||||
```go
|
||||
// triggerRealnameCheck 异步触发单卡实名检查
|
||||
// 在独立 goroutine 中调用,使用独立 context 避免 Fiber 请求 context 失效问题
|
||||
// 参数全部为值类型,不捕获请求相关指针
|
||||
func (h *ClientRealnameHandler) triggerRealnameCheck(cardID, customerID uint, iccid string, systemUserID uint) {
|
||||
// 必须使用独立 context,禁止复用 Fiber 请求 context(请求返回后即失效)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 使用平台用户身份构建 context,绕过卡归属权限检查
|
||||
// 注意:使用 UserTypePlatform 而非 UserTypeSuperAdmin,SuperAdmin 不受日限制约束
|
||||
sysCtx := middleware.SetUserContext(ctx, &middleware.UserContextInfo{
|
||||
UserID: systemUserID,
|
||||
UserType: constants.UserTypePlatform,
|
||||
})
|
||||
|
||||
err := h.manualTriggerSvc.TriggerSingle(sysCtx, cardID, constants.TaskTypePollingRealname, systemUserID)
|
||||
if err != nil {
|
||||
h.logger.Warn("自动触发实名检查失败",
|
||||
zap.Uint("customer_id", customerID),
|
||||
zap.String("iccid", iccid),
|
||||
zap.Uint("card_id", cardID),
|
||||
zap.Error(err))
|
||||
return
|
||||
}
|
||||
h.logger.Info("自动触发实名检查成功",
|
||||
zap.Uint("customer_id", customerID),
|
||||
zap.String("iccid", iccid),
|
||||
zap.Uint("card_id", cardID))
|
||||
}
|
||||
```
|
||||
|
||||
**验收**:方法 ≤30行,使用 `context.Background()`,context 注入 UserTypePlatform,日志字段完整
|
||||
|
||||
---
|
||||
|
||||
### Task 4.6 — 日志字段核查
|
||||
|
||||
**检查清单**:
|
||||
- [x] WARN 路径包含:`customer_id`、`iccid`、`card_id`、`error`
|
||||
- [x] INFO 路径包含:`customer_id`、`iccid`、`card_id`
|
||||
- [x] 无 nil panic 风险(err 已检查)
|
||||
- [x] goroutine 无 panic 风险(manualTriggerSvc 已在调用前检查非 nil)
|
||||
|
||||
**验收**:所有字段齐全,无潜在 panic
|
||||
|
||||
---
|
||||
|
||||
### Task 4.7 — LSP 检查 Handler 文件
|
||||
|
||||
**操作**:`lsp_diagnostics` 对 `internal/handler/app/client_realname.go`
|
||||
|
||||
**注意**:此时 `bootstrap/handlers.go`、`docs.go`、`gendocs/main.go` 仍有编译错误(待 Task 5),只关注 `client_realname.go` 自身
|
||||
|
||||
**验收**:`client_realname.go` 自身 0 error
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — 依赖注入接线
|
||||
|
||||
### Task 5.1 — 更新 bootstrap/handlers.go
|
||||
|
||||
**文件**:`internal/bootstrap/handlers.go`
|
||||
|
||||
找到 `ClientRealname` 初始化行,在末尾补充 `svc.PollingManualTrigger` 参数:
|
||||
|
||||
```go
|
||||
// 修改前(7个参数)
|
||||
ClientRealname: app.NewClientRealnameHandler(
|
||||
svc.Asset, personalCustomerDeviceStore, iotCardStore,
|
||||
deviceSimBindingStore, carrierStore, deps.GatewayClient, deps.Logger,
|
||||
),
|
||||
|
||||
// 修改后(8个参数)
|
||||
ClientRealname: app.NewClientRealnameHandler(
|
||||
svc.Asset, personalCustomerDeviceStore, iotCardStore,
|
||||
deviceSimBindingStore, carrierStore, deps.GatewayClient, deps.Logger,
|
||||
svc.PollingManualTrigger,
|
||||
),
|
||||
```
|
||||
|
||||
**验收**:`svc.PollingManualTrigger` 类型匹配(已在 services.go:210 初始化)
|
||||
|
||||
---
|
||||
|
||||
### Task 5.2 — 确认 ManualTriggerService 初始化(只读)
|
||||
|
||||
**操作**:确认 `internal/bootstrap/services.go:210` 已有:
|
||||
```go
|
||||
PollingManualTrigger: pollingSvc.NewManualTriggerService(...)
|
||||
```
|
||||
|
||||
**无需变更**,仅确认
|
||||
|
||||
**验收**:`svc.PollingManualTrigger` 非 nil
|
||||
|
||||
---
|
||||
|
||||
### Task 5.3 — 更新 docs.go 和 gendocs/main.go
|
||||
|
||||
**文件**:`cmd/api/docs.go` 和 `cmd/gendocs/main.go`
|
||||
|
||||
两处均将 `NewClientRealnameHandler` 调用从 7个nil 改为 8个nil:
|
||||
|
||||
```go
|
||||
// 修改前
|
||||
handlers.ClientRealname = apphandler.NewClientRealnameHandler(nil, nil, nil, nil, nil, nil, nil)
|
||||
|
||||
// 修改后
|
||||
handlers.ClientRealname = apphandler.NewClientRealnameHandler(nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
```
|
||||
|
||||
**验收**:两个文件均编译通过
|
||||
|
||||
---
|
||||
|
||||
### Task 5.4 — LSP 检查依赖注入相关文件
|
||||
|
||||
**操作**:`lsp_diagnostics` 对以下3个文件:
|
||||
- `internal/bootstrap/handlers.go`
|
||||
- `cmd/api/docs.go`
|
||||
- `cmd/gendocs/main.go`
|
||||
|
||||
**验收**:全部 0 error
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — 手动验证
|
||||
|
||||
### Task 6.1 — 接口调用验证 goroutine 启动
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer <token>" \
|
||||
"http://localhost:3000/api/c/v1/realname/link?identifier=<iccid>"
|
||||
```
|
||||
|
||||
**查看 app.log** 确认出现:
|
||||
```json
|
||||
{"level":"info","msg":"自动触发实名检查成功","customer_id":...,"iccid":"...","card_id":...}
|
||||
```
|
||||
|
||||
**验收**:响应正常返回实名链接,日志在响应后3秒内出现
|
||||
|
||||
---
|
||||
|
||||
### Task 6.2 — DB 验证触发记录
|
||||
|
||||
```sql
|
||||
SELECT triggered_by, task_type, total_count, status, created_at
|
||||
FROM tb_polling_manual_trigger_log
|
||||
WHERE triggered_by = 1
|
||||
ORDER BY id DESC LIMIT 5;
|
||||
```
|
||||
|
||||
**期望**:`triggered_by = 1`(SuperAdmin),`task_type = 'polling:realname'`,`total_count = 1`
|
||||
|
||||
**验收**:记录存在且字段正确
|
||||
|
||||
---
|
||||
|
||||
### Task 6.3 — Redis 队列验证
|
||||
|
||||
```bash
|
||||
redis-cli LRANGE polling:manual:polling:realname 0 -1
|
||||
```
|
||||
|
||||
**期望**:卡 ID 存在于队列中
|
||||
|
||||
**验收**:队列条目可见
|
||||
|
||||
---
|
||||
|
||||
### Task 6.4 — 日限制计数验证
|
||||
|
||||
```sql
|
||||
SELECT COUNT(*) as today_count
|
||||
FROM tb_polling_manual_trigger_log
|
||||
WHERE triggered_by = 1
|
||||
AND DATE(triggered_at) = CURRENT_DATE;
|
||||
```
|
||||
|
||||
**期望**:计数正确,未超过500
|
||||
|
||||
**验收**:计数准确
|
||||
|
||||
---
|
||||
|
||||
### Task 6.5 — Redis 去重 TTL 验证
|
||||
|
||||
```bash
|
||||
redis-cli TTL polling:manual:dedupe:polling:realname
|
||||
```
|
||||
|
||||
**期望**:≈ 86400(24小时)
|
||||
|
||||
**验收**:TTL 约等于 86400
|
||||
|
||||
---
|
||||
|
||||
### Task 6.6 — 功能开关验证
|
||||
|
||||
设置 `JUNHONG_POLLING_AUTO_TRIGGER_ENABLE_AUTO_TRIGGER=false` 后重启服务,调用接口:
|
||||
|
||||
**期望**:正常返回实名链接,app.log 无自动触发相关日志,DB 无新增触发记录,无 panic
|
||||
|
||||
**验收**:功能开关有效,主流程不受影响
|
||||
|
||||
---
|
||||
|
||||
## Phase 6 — 最终验收
|
||||
|
||||
### Task 7.1 — 全文件 LSP 最终扫描
|
||||
|
||||
对所有修改过的文件运行 `lsp_diagnostics`:
|
||||
- `internal/handler/app/client_realname.go`
|
||||
- `internal/service/polling/manual_trigger_service.go`
|
||||
- `internal/bootstrap/handlers.go`
|
||||
- `pkg/constants/redis.go`
|
||||
- `pkg/config/config.go`
|
||||
- `cmd/api/docs.go`
|
||||
- `cmd/gendocs/main.go`
|
||||
|
||||
**验收**:全部 0 error,0 新增 warning
|
||||
|
||||
---
|
||||
|
||||
### Task 7.2 — 环境变量文档记录
|
||||
|
||||
确认以下环境变量已在部署文档中记录:
|
||||
|
||||
| 环境变量 | 默认值 | 说明 |
|
||||
|---------|-------|------|
|
||||
| `JUNHONG_POLLING_AUTO_TRIGGER_ENABLE_AUTO_TRIGGER` | `true` | 自动触发开关,可临时关闭 |
|
||||
| `JUNHONG_POLLING_AUTO_TRIGGER_AUTO_TRIGGER_SYSTEM_USER_ID` | `1` | 暂用 SuperAdmin。**生产环境建议创建专用平台账号(user_type=Platform)并更新此值** |
|
||||
|
||||
**验收**:文档中有上述两个环境变量的说明
|
||||
|
||||
---
|
||||
|
||||
### Task 7.3 — GetRealnameLink 行数确认
|
||||
|
||||
统计 `GetRealnameLink` 函数体行数(从 `func` 到最后一个 `}`):
|
||||
|
||||
**验收**:≤ 100 行
|
||||
|
||||
---
|
||||
|
||||
## 原子提交策略
|
||||
|
||||
| 提交顺序 | 涵盖文件 | Commit Message |
|
||||
|---------|---------|---------------|
|
||||
| Commit 1 | `pkg/config/config.go`、`pkg/config/defaults/config.yaml` | `feat: 新增轮询自动触发配置(EnableAutoTrigger、AutoTriggerSystemUserID)` |
|
||||
| Commit 2 | `internal/service/polling/manual_trigger_service.go`、`pkg/constants/redis.go` | `fix: 修复手动触发去重TTL和日限制次数,优化权限检查和错误日志` |
|
||||
| Commit 3 | `internal/handler/app/client_realname.go` | `feat: ClientRealnameHandler 集成异步触发实名检查` |
|
||||
| Commit 4 | `internal/bootstrap/handlers.go`、`cmd/api/docs.go`、`cmd/gendocs/main.go` | `feat: 更新依赖注入,传入 ManualTriggerService` |
|
||||
|
||||
> ⚠️ Commit 3 之后、Commit 4 完成之前,全量编译会报错(构造函数参数不一致)。只做文件级 LSP 检查,不跑全量 build。
|
||||
|
||||
---
|
||||
|
||||
## 风险清单
|
||||
|
||||
| 风险 | 级别 | 对策 |
|
||||
|------|------|------|
|
||||
| goroutine 捕获 `c *fiber.Ctx` 导致 use-after-free | **致命** | `triggerRealnameCheck` 只接受标量参数(uint、string) |
|
||||
| GetRealnameLink 超 100 行 | 高 | Task 4.3 提取两个 helper(已批准) |
|
||||
| processBatchTrigger TTL 漏修 | 中 | Task 3.2 明确修复两处(已确认) |
|
||||
| SuperAdmin(ID=1) 与其他系统进程共享日限额 | 低 | 生产环境创建专用账号后更新配置 |
|
||||
| Commit 3 后临时全量编译失败 | 预期行为 | 文件级 LSP 即可,Task 5 完成后全量恢复 |
|
||||
| `assetService.ResolvedAsset` 实际类型名称不确定 | 低 | Task 4.3 执行前先读文件确认类型名 |
|
||||
|
||||
---
|
||||
|
||||
## 提案 tasks.md 更新规则
|
||||
|
||||
**文件**:`openspec/changes/realname-trigger-priority-enhancement/tasks.md`
|
||||
|
||||
每完成一个 Phase 后,必须将对应条目从 `- [ ]` 改为 `- [x]`。对应关系如下:
|
||||
|
||||
| 本计划 Phase/Task | 提案 tasks.md 条目 |
|
||||
|-----------------|------------------|
|
||||
| Task 1.1 完成 | `1.1 使用 lsp_diagnostics 检查...` |
|
||||
| Task 1.2 完成 | `1.2 分析现有 ClientRealnameHandler...` |
|
||||
| Task 2.1 完成 | `2.1 在 pkg/config/ 中新增...` |
|
||||
| Task 2.2 完成 | `2.2 更新 pkg/config/defaults/config.yaml...` |
|
||||
| Task 2.3 完成 | `2.3 运行 lsp_diagnostics 检查配置...` |
|
||||
| Task 3.1 完成 | `3.1 ...三处将 todayCount >= 100 改为...` |
|
||||
| Task 3.2 完成 | `3.2 ...将 s.redis.Expire(ctx, dedupeKey, time.Hour) 改为...` |
|
||||
| Task 3.3 完成 | `3.3 同步更新 pkg/constants/redis.go...` |
|
||||
| Task 3.4 完成 | `3.4 优化 canManageCard 和 canManageCards...` |
|
||||
| Task 3.5 完成 | `3.5 改进 TriggerSingle 的错误日志...` |
|
||||
| Task 3.6 完成 | `3.6 运行 lsp_diagnostics 检查 ManualTriggerService...` |
|
||||
| Task 3.7 完成 | `3.7 使用 PostgreSQL MCP 和 Redis CLI 手动验证...` |
|
||||
| Task 4.1–4.2 完成 | `4.1 在 ClientRealnameHandler 结构体中新增...` + `4.2 修改 NewClientRealnameHandler...` |
|
||||
| Task 4.3 完成(提取 helper) | — (本计划新增步骤,提案无对应条目) |
|
||||
| Task 4.4–4.5 完成 | `4.3 在 GetRealnameLink 成功返回...` + `4.4 goroutine 内部必须使用...` + `4.5 goroutine 内部构造系统用户 context...` |
|
||||
| Task 4.6 完成 | `4.6 goroutine 执行失败时记录 WARN 日志...` |
|
||||
| Task 4.7 完成 | `4.7 运行 lsp_diagnostics 检查 ClientRealnameHandler...` |
|
||||
| Task 5.1 完成 | `5.1 在 internal/bootstrap/handlers.go 中更新...` |
|
||||
| Task 5.2 完成 | `5.2 确认 ManualTriggerService 在 bootstrap/services.go 中已初始化...` |
|
||||
| Task 5.3 完成 | `5.3 更新 cmd/api/docs.go 和 cmd/gendocs/main.go...` |
|
||||
| Task 5.4 完成 | `5.4 运行 lsp_diagnostics 检查 bootstrap 和 docs.go...` |
|
||||
| Task 6.1 完成 | `6.1 使用 curl 调用...` |
|
||||
| Task 6.2 完成 | `6.2 通过 PostgreSQL MCP 查询 tb_polling_manual_trigger_log...` |
|
||||
| Task 6.3 完成 | `6.3 通过 Redis CLI 检查 polling:manual:realname 队列...` |
|
||||
| Task 6.4 完成 | `6.4 使用 PostgreSQL MCP 查询今日触发次数...` |
|
||||
| Task 6.5 完成 | `6.5 使用 Redis CLI 确认 dedup key TTL 为 24 小时...` |
|
||||
| Task 6.6 完成 | `6.6 模拟 manualTriggerSvc 不可用场景...` |
|
||||
| Task 7.1 完成 | `7.1 运行 lsp_diagnostics 对所有修改过的文件...` |
|
||||
| Task 7.2 完成 | `7.2 确认环境变量...已在部署文档中记录` |
|
||||
| Task 7.3 完成 | `7.3 确认 GetRealnameLink handler 函数长度不超过 100 行` |
|
||||
|
||||
**更新方式**:直接编辑 `tasks.md`,将对应行的 `- [ ]` 替换为 `- [x]`。每个 Phase 执行完毕后集中更新该 Phase 所有条目,不要跨 Phase 提前勾选。
|
||||
108
.sisyphus/plans/tech-debt-cleanup.md
Normal file
108
.sisyphus/plans/tech-debt-cleanup.md
Normal file
@@ -0,0 +1,108 @@
|
||||
# tech-debt-cleanup 执行计划
|
||||
|
||||
## TL;DR
|
||||
|
||||
> **快速摘要**:清理项目技术债务:API 文档补全(18.75% → 100%)、支付配置动态化、轮询常量提取、废弃代码清理、Model 字段清理、DTO _name 字段补全、数据库迁移基线合并。
|
||||
>
|
||||
> **提案文件**:`openspec/changes/tech-debt-cleanup/`
|
||||
|
||||
---
|
||||
|
||||
## TODOs
|
||||
|
||||
### Task 1: 支付配置动态加载(pkg/payment + service层)
|
||||
|
||||
- [x] 1.1 在 `pkg/constants/redis.go` 中新增 `RedisPaymentConfigKey(configID uint) string` 函数
|
||||
- [x] 1.2 确认 `pkg/payment/` 包中现有支付接口定义
|
||||
- [x] 1.3 创建 `pkg/payment/loader.go`,定义 `PaymentConfigLoader` 接口和实现(Redis 缓存 TTL 1h)
|
||||
- [x] 1.4 修改 `internal/service/order/service.go`,注入 paymentLoader,替换两处 TODO
|
||||
- [x] 1.5 修改 `internal/service/recharge/service.go`,注入 paymentLoader,替换 TODO
|
||||
- [x] 1.7 运行 `go build ./cmd/api ./cmd/worker` 确认编译,`go vet` 静态分析
|
||||
|
||||
### Task 2: API 文档生成器补全(docs.go + gendocs)
|
||||
|
||||
- [x] 2.1 修改 `cmd/api/docs.go`,注册所有 48 个 Handler(含 39 个缺失 Handler)
|
||||
- [x] 2.2 修改 `cmd/gendocs/main.go`,同步注册所有 48 个 Handler
|
||||
- [x] 2.3 运行 `go run cmd/gendocs/main.go` 生成 OpenAPI 文档,验证覆盖率
|
||||
- [x] 2.4 人工核查生成文档接口数量与路由注册数量一致
|
||||
|
||||
### Task 3: 轮询状态常量提取(pkg/constants + handler/service/store)
|
||||
|
||||
- [x] 3.1 在 `pkg/constants/polling.go` 中新增轮询手动触发日志状态常量(4 个)
|
||||
- [x] 3.2 修改 `internal/handler/admin/polling_manual_trigger.go`,替换硬编码字符串为常量
|
||||
- [x] 3.3 修改 `internal/service/polling/manual_trigger_service.go`,替换硬编码字符串
|
||||
- [x] 3.4 修改 `internal/store/postgres/polling_manual_trigger_store.go`,替换硬编码字符串
|
||||
- [x] 3.5 修改 `internal/service/polling/alert_service.go`,替换 NotificationStatus 中的硬编码
|
||||
- [x] 3.6 运行 grep 确认无剩余硬编码,`go vet` 静态分析
|
||||
|
||||
### Task 4: 废弃代码清理(sync.go + wallet.go + DTO + 方法)
|
||||
|
||||
- [x] 4.1 删除 `internal/task/sync.go`,清理 queue/handler.go 注册和 constants.go 中的 TaskTypeDataSync
|
||||
- [x] 4.2 全局搜索 wallet.go 中 15 个废弃别名的引用情况
|
||||
- [x] 4.3 替换所有有引用的废弃别名为新常量
|
||||
- [x] 4.4 删除 `pkg/constants/wallet.go` 中所有 Deprecated 别名定义(15 个)
|
||||
- [x] 4.5 删除 `internal/model/dto/enterprise_card_authorization_dto.go` 中的 3 个废弃 DTO 类型
|
||||
- [x] 4.6 删除 `internal/service/order/service.go` 中的 `CreateLegacy()` 方法
|
||||
- [x] 4.7 [跳过] `CheckAndStopCard()` 仍在 StopResumeServiceInterface 接口中且被活跃调用,不是废弃代码
|
||||
- [x] 4.8 运行 `go build ./cmd/api ./cmd/worker` 和 `go vet` 确认编译无误
|
||||
|
||||
### Task 5: Model 废弃字段删除与数据库迁移
|
||||
|
||||
- [x] 5.1 从 `internal/model/iot_card.go` 中删除 `FirstCommissionPaid` 和 `AccumulatedRecharge` 字段
|
||||
- [x] 5.2 从 `internal/model/device.go` 中删除 `FirstCommissionPaid` 和 `AccumulatedRecharge` 字段
|
||||
- [x] 5.3 创建 `migrations/000116_remove_legacy_commission_fields.up.sql`(DROP COLUMN)
|
||||
- [x] 5.4 创建 `migrations/000116_remove_legacy_commission_fields.down.sql`(ADD COLUMN 回滚)
|
||||
- [x] 5.5 在测试环境执行迁移,通过 PostgreSQL MCP 确认字段已删除(字段不存在于 DB)
|
||||
- [x] 5.6 运行 `go build ./cmd/api ./cmd/worker` 确认编译通过
|
||||
|
||||
### Task 6: DTO _name 字段补全(分模块逐批)
|
||||
|
||||
- [x] 6.1 遍历 `internal/model/dto/` 统计所有 int 状态字段缺少 _name 字段的清单
|
||||
- [x] 6.2 **Account 模块**:补全 DTO _name 字段 + 常量映射函数 + Service 层赋值
|
||||
- [x] 6.3 **Asset 模块**:补全 DTO _name 字段 + 常量映射函数 + Service 层赋值
|
||||
- [x] 6.4 **Order 模块**:补全 DTO _name 字段 + 常量映射函数 + Service 层赋值
|
||||
- [x] 6.5 **Commission 模块**:补全 DTO _name 字段 + 常量映射函数 + Service 层赋值
|
||||
- [x] 6.6 **IotCard / Device 模块**:补全 DTO _name 字段 + 常量映射函数 + Service 层赋值
|
||||
- [x] 6.7 **剩余模块**(Recharge、Wallet、Package、Shop 等):批量补全
|
||||
- [x] 6.8 全量编译与静态分析(`go build + go vet`)
|
||||
- [x] 6.9 代码审查确认 _name 字段存在于 account/order/iot_card 等关键 DTO,Service 层赋值逻辑已实现(运行时验证需服务启动)
|
||||
|
||||
### Task 7: 未使用常量和错误码清理
|
||||
|
||||
- [x] 7.1 删除 `pkg/errors/codes.go` 中的 `CodeExceedLimit` 常量和对应错误消息映射
|
||||
- [x] 7.2 为 `pkg/constants/iot.go` 中约 22 个未引用的预留常量添加用途注释
|
||||
- [x] 7.3 运行 `go build` 和 `go vet` 确认清理无破坏
|
||||
|
||||
### Task 8: 删除空文件和注释代码
|
||||
|
||||
- [x] 8.1 删除 `internal/routes/recharge.go` 空文件
|
||||
- [x] 8.2 删除 `pkg/database/postgres.go` 中的 AutoMigrate 注释块(行 90-95)
|
||||
- [x] 8.3 保留 `internal/service/client_order/service.go` 中的实名认证检查注释,添加待确认标记
|
||||
|
||||
### Task 9: 全量编译验证
|
||||
|
||||
- [x] 9.1 运行 `go mod tidy` 确认依赖无变化
|
||||
- [x] 9.2 运行 `go build ./cmd/api` 和 `go build ./cmd/worker` 确认编译通过
|
||||
- [x] 9.3 运行 `go vet ./...` 进行静态分析
|
||||
- [x] 9.4 运行 `gofmt -l ./internal ./pkg` 检查代码格式(修复了2个预存文件)
|
||||
|
||||
### Task 0: 数据库迁移文件合并为生产基线(需 DB 环境)
|
||||
|
||||
- [x] 0.1 确认当前数据库 schema 完整可用(PostgreSQL MCP 验证 66 张表存在)
|
||||
- [x] 0.2 [跳过] pg_dump 不在当前环境,需在有 pg_dump 的机器手动执行:`pg_dump --schema-only --no-owner --no-acl -d junhong_cmp > migrations/000114_squash_baseline.up.sql`
|
||||
- [x] 0.3 [跳过] 依赖 0.2,完成 0.2 后手动编写 DROP TABLE 语句
|
||||
- [x] 0.4 创建 `migrations/000115_init_data.up.sql`(合并轮询配置初始数据 + purchase_role 回填)
|
||||
- [x] 0.5 创建 `migrations/000115_init_data.down.sql`(回滚初始数据)
|
||||
- [x] 0.6 归档旧迁移文件到 `migrations/archive/`(000000~000113 + backfill 脚本,共 228 个文件)
|
||||
- [x] 0.7 编写测试环境重置脚本 `scripts/reset_db.sh`
|
||||
- [ ] 0.8 [阻塞] 在全新数据库上验证 migrate up 完整链路(依赖 0.2)
|
||||
- [ ] 0.9 [阻塞] 重置测试环境数据库,切换到新基线(需团队协调)
|
||||
|
||||
---
|
||||
|
||||
## Final Verification Wave
|
||||
|
||||
- [x] F1 全量编译通过:`go build ./cmd/api ./cmd/worker` 无错误
|
||||
- [x] F2 静态分析通过:`go vet ./...` 无报告,`gofmt -l` 无格式问题(修复2个预存文件)
|
||||
- [x] F3 API 文档覆盖率 100%:`go run cmd/gendocs/main.go` 生成文档包含 190 个 API 路径
|
||||
- [x] F4 核心功能验证:代码审查通过(支付动态加载、轮询常量、_name字段已实现)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user