630 Commits

Author SHA1 Message Date
d022cc8788 迭代方案确认 2026-07-17 16:39:41 +08:00
bcf3e31db6 迭代计划准备 2026-07-16 15:08:07 +08:00
c4f430ccb3 迭代计划准备 2026-07-16 15:07:59 +08:00
1a9db9328e 批量购买 2026-07-15 12:00:05 +08:00
2e130b98f5 临时备份一次 2026-07-13 12:01:18 +09:00
5cdcdad534 Create 业务需求.md 2026-07-11 15:10:24 +08:00
d2e08dbbec skill提交
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m22s
2026-07-11 15:32:56 +09:00
026d4908d8 删除
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 53s
2026-07-11 12:28:38 +09:00
31232ea899 优化迁移脚本速度
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 53s
2026-07-10 13:10:00 +09:00
b38df737e1 先短暂去除限制,上传迁移脚本
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m51s
2026-07-09 18:23:29 +09:00
346156ee9b 卡只允许支付宝支付,设备只允许微信支付,钱包充值也遵循这个规则
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m53s
2026-07-03 10:26:48 +09:00
0d79130e07 入参
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m46s
2026-07-02 17:02:13 +09:00
b3fb8c7a82 资产详情新增两个字段
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-07-02 16:49:50 +09:00
44fb21eb6a 修复导入重试的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m53s
2026-07-02 15:13:22 +09:00
8f738ffbe8 导入的问题修复
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m51s
2026-07-02 13:04:36 +09:00
6db152bb2f chore: 安装 ponytail lazy senior dev 规则 2026-07-01 12:26:19 +09:00
fc6af43baa 修复:溢出流量应优先记到主套餐而非加油包
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m47s
主套餐和加油包同时 Depleted 时,recordOverflowToDepletedPackage
原先取 id 最大的套餐,可能取到加油包,语义不对。

改为优先查 master_usage_id IS NULL(主套餐),找不到时
再回退取任意 Depleted 套餐。
2026-07-01 12:06:19 +09:00
52bdbbae25 修复:套餐耗尽后流量详单断档问题
问题:套餐 status=Depleted 后,queryActivePackages 查不到套餐,
DeductDataUsage 直接 return CodeNoAvailablePackage,导致上游
仍有真实流量时,tb_package_usage_daily_record 不再写入,详单断档。

修复:无 Active 套餐时,找最近一条 Depleted 套餐,将溢出流量
累加到 data_usage_mb 并写入当日 daily_record,保持详单连续性。
status 不变,不重复触发停机。
2026-07-01 12:03:39 +09:00
76f657c986 1. 套餐过期前再主动同步一次流量
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m55s
2. 生效套餐逻辑错误的问题
2026-06-30 15:54:55 +09:00
a2793f7bec 需要改造的地方 2026-06-29 18:17:06 +09:00
b5b7f9a41e 迁移
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m53s
2026-06-29 12:29:31 +09:00
b930662817 从乐观锁变成悲观锁 2026-06-29 12:29:21 +09:00
ab9da7bb33 修复
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m33s
2026-06-26 13:11:39 +09:00
781e82441d 环境变量
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 39s
2026-06-26 11:59:28 +08:00
f4b6a55b27 驳回
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 7m17s
2026-06-26 12:12:15 +09:00
8cf921f11c 驳回接口
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m55s
2026-06-25 17:10:24 +09:00
c5871b59a1 修复开放接口 wallet/package-orders 支持 IMEI 下单
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m48s
2026-06-23 11:46:02 +09:00
c0b9604515 完成
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-06-23 11:05:58 +09:00
5c2ef97c24 相关问题优化以及新功能开发
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m57s
迁移 155- 157
2026-06-22 17:21:13 +09:00
2885b503b3 一次重构修复 2026-06-22 12:15:40 +09:00
062f5a436f Merge branch 'main' of https://git.boss160.cn/csxj2026/junhong_cmp_fiber
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m17s
2026-06-22 11:10:58 +08:00
ba435dd6a6 关于绑定的问题
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-06-22 12:08:41 +09:00
3f21f7a7d6 让超时时间设置成60秒 2026-06-21 17:06:40 +08:00
5f960daf78 修改过期时间跟修改流量
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m10s
2026-06-18 15:53:43 +09:00
3b7b856e48 企业授权增强与资产列表扩展
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m9s
- 企业卡授权唯一约束:新增 DB 迁移(000154),卡级部分唯一索引防止同一张卡被多个企业同时持有,Service 层新增跨企业冲突检测
- 单卡列表新增 network_status 过滤参数
- 单卡/设备列表新增 asset_status、asset_status_name、generation 响应字段
- 单卡/设备列表新增企业维度过滤(authorized_enterprise_id、is_authorized_to_enterprise)及响应中企业授权信息(批量加载,无 N+1)
- 主钱包流水/退款列表新增 asset_identifier 精确过滤参数
- 企业卡授权/收回接口升级为三模式(list/range/filter),企业设备授权/收回升级为双模式(list/filter)
- 升级 sonic v1.14.2 → v1.15.2 以兼容 Go 1.26

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 16:23:03 +09:00
cf36f1447f 尝试某个skills
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m24s
2026-06-16 18:58:55 +09:00
Break
1f634eb465 init
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m3s
2026-06-16 15:15:50 +08:00
Break
84ab3bad99 order导出
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 3m11s
2026-06-16 09:38:20 +08:00
Break
6c8594633a 设备导出
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m33s
2026-06-15 17:29:36 +08:00
Break
064961471b 设备导出
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 10m42s
2026-06-15 16:43:50 +08:00
Break
e37aad9e1d 修复导出数据不全的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m41s
2026-06-15 15:55:32 +08:00
Break
7ec84fbc0f 导出系统
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m50s
2026-06-15 15:28:29 +08:00
Break
2f0b24ce88 迁移脚本的修复 2026-06-15 10:53:47 +08:00
Break
e56649e5be 还有例子
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 53s
2026-06-12 18:10:37 +08:00
Break
1c492fe8db 更新一版 2026-06-12 18:10:22 +08:00
Break
e139f5e227 管理员也可以
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m42s
2026-06-12 17:58:25 +08:00
Break
016e7bee79 修改过期时间,以及修改套餐已用量
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-06-12 10:41:24 +08:00
Break
c437593a8c 修复错误购买报错的问题,修复接口返回虚流量启动错误的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m48s
2026-06-11 14:51:26 +08:00
Break
134021c91e 修复错误的停止
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m51s
2026-06-11 10:01:35 +08:00
Break
5c779cb6e0 不允许购买第二个主套餐
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m50s
2026-06-10 15:24:26 +08:00
Break
32c9859b38 监控 2026-06-10 01:15:26 +08:00
Break
283e3e3eb3 迁移脚本的一些修复 2026-06-09 11:29:40 +08:00
Break
6a70713b30 加分布式锁
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m0s
2026-06-09 10:54:13 +08:00
Break
4ccbf13197 开放接口已用完流量查询错误的问题 2026-06-08 10:10:10 +08:00
Break
0ae8148689 审批金额
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m13s
2026-06-06 14:55:48 +08:00
Break
9a802c04e5 审计日志修复
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m20s
2026-06-05 17:22:05 +08:00
Break
4d419a1966 校验bug 2026-06-05 16:59:27 +08:00
Break
fe2041bcf5 机卡分离复机判断
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m13s
2026-06-05 14:20:58 +08:00
Break
6ac19d6565 支撑单卡
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m16s
2026-06-04 14:29:20 +08:00
Break
cce27975a1 设备关键词查询
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m7s
2026-06-04 10:34:58 +08:00
Break
d86ac46761 关键词查询
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-06-04 10:34:14 +08:00
Break
420f3d83f9 应当允许卡就算没有销售也能换货
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-06-04 10:26:47 +08:00
Break
27fba9160c 提案
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 56s
2026-06-04 09:39:20 +08:00
Break
5089a71764 返回错误原因
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m25s
2026-06-03 17:52:51 +08:00
Break
5f57429fb0 直接换货流程
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m28s
2026-06-03 16:55:32 +08:00
Break
46ede81aef 修复佣金错误计算的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m15s
2026-06-03 10:25:49 +08:00
Break
36e68e6672 提案 2026-06-02 16:56:18 +08:00
Break
a6cd550b94 1
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m18s
2026-06-02 16:56:09 +08:00
Break
c6e65fde9b 开放接口 2026-06-02 16:56:01 +08:00
Break
1b47fb8f32 佣金计算问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m23s
2026-06-02 16:19:42 +08:00
Break
c5126c583b 修复以前的老数据
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m51s
2026-06-01 11:49:24 +08:00
Break
918b9b4f25 退款也应该记录快照 2026-06-01 11:45:31 +08:00
Break
944526d9ef 修复订单金额落库不对的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m17s
2026-06-01 11:21:29 +08:00
Break
6c8352491c 修复
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 53s
2026-05-29 15:08:25 +08:00
Break
1ee554daec 钱包流水新增资产信息
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m59s
2026-05-29 10:52:12 +08:00
Break
34a7cf0f3c 修复一些问题 2026-05-29 10:30:19 +08:00
Break
6a3fffc46c 错误的套餐购买限制
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m48s
2026-05-29 09:44:48 +08:00
Break
872769e69e 迁移脚本的一些问题修复 2026-05-28 17:22:52 +08:00
Break
1550ef3cb1 修复超额流量不记录的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m18s
2026-05-28 15:19:54 +08:00
Break
58863e8ec5 数据迁移脚本
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 54s
2026-05-27 11:10:56 +08:00
Break
0d96a94e5f 关于上游流量同步覆盖修复,以及新增redis同步迁移
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m25s
2026-05-27 10:59:19 +08:00
Break
cf689beceb 修复问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m9s
2026-05-26 18:06:51 +08:00
Break
f4d92f99a2 新增退款凭证
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m41s
2026-05-26 17:16:11 +08:00
Break
e131d6ba77 imei
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 21m51s
2026-05-26 16:55:35 +08:00
Break
bcbc290bad 卡新增imei字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m10s
2026-05-26 16:30:12 +08:00
4c1e4f428a 一次补偿
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m2s
2026-05-25 14:40:34 +08:00
20b5d70af9 1. 清理预充值SQL
2. 查日志的脚本
2026-05-25 14:30:09 +08:00
226474b434 轮训有问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m7s
2026-05-22 16:21:46 +08:00
860f589b9a 错误提示有问题 2026-05-22 15:54:54 +08:00
2adbc87a52 Merge commit 'a03ba5d39645948f1c48ca0cfccc74c6edd1ccbf'
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m14s
2026-05-22 14:20:21 +08:00
6e564d1d1a Merge commit '599289a94ee0b8f36a09711122303a5bfacb265a' 2026-05-22 14:20:21 +08:00
3d28e29eaa Merge commit '58bdb2f18e5dd4eef84467961a1b55f3434b9ee5' 2026-05-22 14:20:20 +08:00
0948494b1c task: 修复支付宝C端入口构建失败
移除不存在的 alipay.CalcExpireAt 调用,改为按 cfg.AliPayExpireMinutes(默认 30 分钟)
内联计算 expireAt;将所有 BuildWapPayURL 调用从 5 参数改为 4 参数(移除 returnURL)。
修复范围:getOrBuildAlipayPaymentLink、createAlipayForceRechargeOrder、createAlipayRecharge。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 14:18:21 +08:00
599289a94e task: 修复支付宝C端入口构建失败
移除不存在的 alipay.CalcExpireAt 调用,改为按 cfg.AliPayExpireMinutes(默认 30 分钟)
内联计算 expireAt;将所有 BuildWapPayURL 调用从 5 参数改为 4 参数(移除 returnURL)。
修复范围:getOrBuildAlipayPaymentLink、createAlipayForceRechargeOrder、createAlipayRecharge。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 14:13:46 +08:00
b988f99a95 task: 完成支付宝回调安全(验签、多维度校验、业务分发) 2026-05-22 14:07:20 +08:00
56adc30409 task: 完成支付宝C端入口
新增支付宝支付方式支持:
- DTO:ClientPaymentLink、ClientPayOrderRequest/Response 增加 alipay;ClientCreateOrderRequest 增加 payment_method;ClientCreateOrderResponse 增加 payment_link;ClientCreateRechargeRequest 允许 alipay,app_type 改为微信必填;ClientRechargeResponse PayConfig 改为可选指针,增加 payment_link
- Service(client_order):PayOrder 新增 alipay 分支(不需要 app_type/OpenID,复用或新建 pending payment,生成 WAP URL);CreateOrder 强充路径按 payment_method 分支,alipay 不需要 app_type/OpenID;幂等命中时支付宝强充返回同一充值单对应的 payment_link;新增 getOrBuildAlipayPaymentLink(过期 payment 自动续建);新增 createAlipayForceRechargeOrder(事务创建充值单+支付单,WAP URL 生成失败则标记 failed)
- Handler(client_wallet):CreateRecharge 移除微信唯一限制,按 payment_method 分发到 createWechatRecharge / createAlipayRecharge;alipay 分支事务内创建充值单+支付单,然后生成 WAP URL,失败标记 payment failed
- 依赖 worker-1 共享 API:pkg/alipay.BuildWapPayURL/CalcExpireAt、Payment.ExpireAt、WechatConfig.AliReturnURL/AliPayExpireMinutes、PaymentStore.FindLatestPendingByOrderAndMethod;本 worktree 暂不能独立构建,待 leader 集成

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 14:07:20 +08:00
53e95751b1 task: 完成支付宝共享基础(迁移/WechatConfig/PaymentStore/pkg/alipay) 2026-05-22 14:07:20 +08:00
58bdb2f18e task: 完成支付宝共享基础(迁移/WechatConfig/PaymentStore/pkg/alipay) 2026-05-22 12:09:55 +08:00
a03ba5d396 task: 完成支付宝回调安全(验签、多维度校验、业务分发) 2026-05-22 12:09:50 +08:00
2768deb0b6 设备新增搜索条件
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m8s
2026-05-20 10:27:30 +08:00
e2301d5f3b chore(集成验证): gofmt 修复 DTO 格式并重新生成 OpenAPI 文档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m3s
- 修复 ListStandaloneIotCardRequest 和 ListDeviceRequest 字段对齐格式
- 重新生成 docs/admin-openapi.yaml,两个列表接口均新增 has_active_package 参数
- go build ./cmd/api、go build ./cmd/worker 均通过验证

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 12:15:06 +08:00
9f5c5c3680 feat(卡列表): 新增 has_active_package 查询条件筛选生效中套餐
- DTO ListStandaloneIotCardRequest 增加 HasActivePackage *bool 字段,
  query/json 名 has_active_package,description 中文
- Service ListStandalone 将 HasActivePackage 映射为 filters["has_active_package"]
- Store applyStandaloneFilters 新增 EXISTS/NOT EXISTS 子查询,
  使用 constants.PackageUsageStatusActive,限制 master_usage_id IS NULL
  且 deleted_at IS NULL,所有查询路径(默认/两阶段/并行)均复用此函数

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 12:15:06 +08:00
5e7e68cce7 feat(设备列表): 新增 has_active_package 查询条件
- DTO ListDeviceRequest 增加 HasActivePackage *bool 字段(query/json: has_active_package)
- Service List 方法将 HasActivePackage 透传至 filters["has_active_package"]
- Store applyDeviceFilters 新增 applyHasActivePackageFilter:
  true  → EXISTS 子查询(生效中主套餐)
  false → NOT EXISTS 子查询
  均限制 master_usage_id IS NULL、deleted_at IS NULL,状态使用 constants.PackageUsageStatusActive

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 12:15:06 +08:00
ca939ff617 暂存一下 2026-05-19 11:57:02 +08:00
8de9c59b1c 查询
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m13s
2026-05-19 11:32:41 +08:00
631c5392b6 1
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m56s
2026-05-18 10:47:10 +08:00
af5a21ed1e 新增三个同步时间字段 2026-05-18 10:47:07 +08:00
480d4c4583 1
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m59s
2026-05-18 10:34:04 +08:00
ed071918ed 钱包订单退款时应当正确退回,充值时允许最低充值1分
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m7s
2026-05-18 09:51:59 +08:00
d597a25c69 机卡分离复机接口
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m1s
2026-05-14 09:50:48 +08:00
81aa3c2b11 新增字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m15s
2026-05-13 17:50:21 +08:00
a5388446d3 新增字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m7s
2026-05-12 14:10:48 +08:00
8f3a68a673 新增上游的停机原因
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m5s
2026-05-12 11:13:04 +08:00
95fc0b0a1b 修复一些问题,主要是生效套餐
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m16s
2026-05-12 10:32:38 +08:00
b7369a9c71 修复并发,暂时的,不够完整,后续还是需要重新设计,这个太乱了,傻逼AI
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m22s
2026-05-11 17:19:40 +08:00
05a5694a5f 修复bug
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m5s
2026-05-11 16:45:37 +08:00
1350a9ed79 批量
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m53s
2026-05-11 14:54:23 +08:00
93200a9074 开放接口完成
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m57s
2026-05-11 14:26:10 +08:00
02d522564f 删除hurl 2026-05-11 12:00:02 +08:00
b6d21b81e3 文档生成 2026-05-11 11:59:36 +08:00
98ff88d5c3 开放接口,修复上游同步不对的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m55s
2026-05-11 11:20:48 +08:00
a9eaf1d697 修复缓存没有更新的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m13s
2026-05-11 10:38:52 +08:00
97851c2595 修正代理主钱包余额快照口径
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m0s
代理主钱包扣款流水必须记录扣款前后的真实余额,避免资金概况与流水展示出现双重扣减错觉。

Constraint: 项目禁止自动化测试,使用构建和数据库对账验证。

Rejected: 在资金汇总接口按历史充值总量或流水末条余额展示 | 资金概况口径应来自主钱包剩余余额。

Confidence: high

Scope-risk: narrow

Directive: 修改代理钱包扣款链路时必须同时维护余额字段与流水快照一致性。

Tested: go build ./...;migrate up 已执行到 141;只读 SQL 对账确认主钱包余额、成功流水累计、最新流水余额一致且 mismatch_tx_count=0。

Not-tested: 未新增自动化测试(项目规范禁止)。
2026-05-11 10:22:48 +08:00
ebaf112c80 新增排查自己的逻辑
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m53s
2026-05-09 15:22:29 +08:00
09cf0be86e 联级,多选
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m52s
2026-05-09 15:06:27 +08:00
6a6672d0e4 允许代理看
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 10m11s
2026-05-09 11:03:32 +08:00
0b86720534 chore: add placeholder file
Co-authored-by: aider (openai/gpt-5.5) <aider@aider.chat>
2026-05-09 10:35:22 +08:00
a93acc0784 有效天数问题,充值单回调问题 2026-05-08 11:46:34 +08:00
7c85a8cf29 修复支付以及订单相关的问题
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 1s
2026-05-08 10:15:03 +08:00
348cb4e670 修复绑定的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m55s
2026-05-07 18:18:11 +08:00
e77bb0d09b 跨域
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m57s
2026-05-07 17:16:54 +08:00
73a3a04204 跨域
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m59s
2026-05-07 16:28:23 +08:00
573e887ca5 灰度脚本 2026-05-07 11:28:42 +08:00
29d3d48dbe 黑魔法
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m48s
2026-05-06 16:59:10 +08:00
d42fe2b0ca 补上参数
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m53s
2026-05-06 16:44:14 +08:00
eb74dd7849 补回是否启用虚流量
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m58s
2026-05-06 16:07:59 +08:00
3a2e3f2571 浅浅升级一下
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m8s
2026-05-06 14:41:14 +08:00
b0bd37ec12 尝试优化一下
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m0s
2026-05-06 10:21:38 +08:00
001f8caf35 修复当前卡不对的问题 2026-05-06 10:19:21 +08:00
21b73a750d c端当前套餐开始时间过期时间,以及excel导入字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m55s
2026-05-06 09:57:58 +08:00
ee7bfb81f0 修复解绑卡没有iccid的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m56s
2026-05-06 09:44:15 +08:00
b4a9e0c1c9 归档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m52s
2026-04-30 15:59:40 +08:00
948243b13d 修改 2026-04-30 15:49:40 +08:00
5425e2ce19 保留提案基线以便团队 worktree 按契约执行
Constraint: omx team 默认使用独立 worktree,要求 leader 工作区干净
Rejected: git stash 提案文件 | 会让 worker 无法读取当前提案契约
Confidence: high
Scope-risk: narrow
Directive: 后续实现必须继续严格按 tasks.md 顺序推进,不得擅自跳步
Tested: git status 仅剩未跟踪的 .omx 上下文文件
Not-tested: 未验证提案内容本身的实现正确性
2026-04-30 15:11:32 +08:00
70fb7dadef 归档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m53s
2026-04-30 11:58:33 +08:00
8a3c45c577 设备导入卡槽不对的问题 2026-04-30 11:56:09 +08:00
9238eeb56e 更新提案 2026-04-30 11:18:13 +08:00
9674e0d0d9 文档更新 2026-04-30 10:54:29 +08:00
248ed55f4e 获取当前生效的appid
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m46s
2026-04-30 10:52:33 +08:00
66e12e9629 订单相关以及佣金相关修复
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m57s
2026-04-30 09:52:39 +08:00
4f4e42f27e 应当返回真流量
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m1s
2026-04-29 16:19:15 +08:00
6b3b33b2f0 废除激活时间
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m57s
2026-04-29 12:04:23 +08:00
74c7b27327 切卡模式更新
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m58s
2026-04-29 10:18:15 +08:00
37b4483183 赠送套餐逻辑
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m55s
2026-04-28 17:40:06 +08:00
516a7f5bdf 优化后台创建订单的代理套餐下架提示
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m59s
2026-04-28 14:27:29 +08:00
fe4c545308 修正数据
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m55s
2026-04-27 18:10:08 +08:00
bb33232b1b 日志记录不全
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m48s
2026-04-27 15:32:17 +08:00
c3ae7fcfbc 修复设备WiFi上游请求参数
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m40s
2026-04-27 15:19:23 +08:00
66cec7515a 更新
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m18s
2026-04-27 14:52:17 +08:00
cb75b5668b 操作日志
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m10s
2026-04-27 12:16:38 +08:00
95104100c9 修复企业授权报错的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m57s
2026-04-27 10:30:10 +08:00
02ccf57aa3 平台应当要可以用代理的钱包支付
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m6s
2026-04-27 10:01:38 +08:00
60debb7505 统一导出任务
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m4s
2026-04-27 09:47:03 +08:00
531de3c760 已退回后的还是可以继续提交
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m49s
2026-04-27 09:29:54 +08:00
a887f91686 修复卡轮训的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 10m14s
2026-04-26 12:41:16 +08:00
7efcea2b54 修复错误报错
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m0s
2026-04-24 17:53:22 +08:00
85bef83752 跨级
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m7s
2026-04-24 16:33:13 +08:00
bc344f892c 新增日志输出
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m33s
2026-04-24 11:25:13 +08:00
41db5b56af 上级店铺名称
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-04-24 11:20:41 +08:00
15cd26c81a 强制手机绑定
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m1s
2026-04-24 10:26:32 +08:00
3f2cf31543 校验修复以及查询修复
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m55s
2026-04-24 09:41:51 +08:00
ba73913a41 当前卡的逻辑变更
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m53s
2026-04-24 09:25:44 +08:00
a44c88005d 手动实名
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m24s
2026-04-23 17:35:38 +08:00
f177c26016 快照订单号以及退款订单号
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m27s
2026-04-23 17:14:10 +08:00
4bde09837a 激活时间
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m35s
2026-04-23 17:02:11 +08:00
c250a47651 卡不激活的问题 2026-04-23 16:58:16 +08:00
a7f2c4480a 同步更新订单状态,校验退款金额小于等于订单实付金额
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m16s
2026-04-23 15:40:59 +08:00
37e113bbf4 新增查询字段
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-04-23 15:33:15 +08:00
5442dcbeda 时间支持
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m4s
2026-04-23 14:20:02 +08:00
b9fc828567 订单总价和订单明细单价在代购/成本价场景会不一致,已改为同一套价格来源并支持多套餐求和
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m24s
2026-04-23 12:11:48 +08:00
327c72ca74 修复查询问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m28s
2026-04-23 11:48:59 +08:00
32f03cd2c1 新增退款时应当快照当时的资产
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-04-23 11:43:15 +08:00
8d2e8faa84 修复退款bug
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m43s
2026-04-23 11:30:46 +08:00
1f1f31a7cb 退款列表快照订单号
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m30s
2026-04-23 10:59:34 +08:00
52d883d8a0 修复店铺名不存在的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m29s
2026-04-23 10:21:23 +08:00
6b1fbf4a92 修复金额的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m30s
2026-04-23 10:09:23 +08:00
10a35625a5 新增状态筛选条件,同时修复价格未正常写入的情况
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m35s
2026-04-23 09:57:39 +08:00
a207c51bfb 修复设备套餐流量不同步的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m32s
2026-04-22 18:04:53 +08:00
6eb6d381f7 日志
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m32s
2026-04-22 16:58:04 +08:00
e27758cce3 修复新卡导入时没有正确填写停机原因的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m45s
2026-04-22 16:41:33 +08:00
7137ed087f 修复序列化的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m29s
2026-04-22 15:24:39 +08:00
a9690a49db 提交
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m33s
2026-04-22 15:06:01 +08:00
0f58886454 增加日志,提交流程图
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m42s
2026-04-22 14:49:09 +08:00
9f8173e124 灰度上线流程图准备 2026-04-21 16:42:47 +08:00
1d930cc82d 运营商名称问题TODO
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m29s
2026-04-21 11:27:19 +08:00
1b21d4dafa 新增运营商名称模糊搜索 2026-04-21 11:24:47 +08:00
e573a82120 设备卡列表没有正确返回网络状态以及实名认证策略的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m34s
2026-04-21 11:11:03 +08:00
e049080f6c 分裂iccid长度
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m47s
2026-04-21 10:55:12 +08:00
9942bbc74e docs: 更新实名认证策略 DTO description 默认值说明
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m35s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-20 15:39:47 +08:00
fc9f819787 feat: 修改实名认证策略默认值为先充值后实名(after_order)
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-20 15:39:01 +08:00
33a4d25ca9 chore: 新增数据库迁移,将实名认证策略默认值改为 after_order
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-20 15:29:25 +08:00
e9862a67ba fix: 修复资产卡列表未返回 realname_policy 字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m10s
buildDeviceResolveResponse 和 GetRealtimeStatus 中构建 BoundCardInfo 时
均遗漏了 RealnamePolicy 字段赋值,导致 resolve 和 realtime-status
两个接口的设备卡列表不返回实名认证策略。字段在 Model 和 DTO 中均
已定义,Service 层补充赋值即可。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-20 14:43:09 +08:00
868f5a8ef3 fix: 修复轮询停机连坐、实名逆转防抖及carrier_stopped原因写入缺失三个逻辑缺陷
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m37s
2026-04-20 11:24:56 +08:00
fd795d8742 feat: 新增设备切卡模式接口 SetSwitchMode
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m32s
2026-04-18 16:22:30 +08:00
2b3a9cb33f feat: 新增套餐使用记录实付金额快照字段 paid_amount
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m19s
- 新增迁移 000129:tb_package_usage 添加 paid_amount BIGINT 字段,存量数据通过 JOIN tb_order 回填
- PackageUsage Model 新增 PaidAmount *int64 字段
- 4 个写入点(order service 主套餐/加油包、auto_purchase 主套餐/加油包)赋值 order.ActualPaidAmount
- AssetPackageResponse DTO 新增 paid_amount 字段
- GetCurrentPackage / GetPackages 填充 paid_amount,接口直接返回购买价格无需 JOIN 订单表
2026-04-18 10:19:21 +08:00
4b8784d5e7 docs: 更新 OpenAPI 文档,新增批量下载 URL 接口文档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m15s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-18 10:08:53 +08:00
2413c2fe14 feat: 新增批量获取文件下载预签名 URL 接口
新增 POST /api/admin/storage/batch-download-urls,支持一次传入最多 50 个 file_key,返回对应预签名下载 URL 映射。解决列表页批量展示图片需多次请求的问题。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-18 10:08:45 +08:00
e52671eaed 归档提案 2026-04-18 09:35:27 +08:00
716e9f5971 chore: 更新 fix-realname-activation-logic OpenSpec 任务清单
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m15s
标记全部 13 个任务为已完成

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-18 09:30:56 +08:00
28ac58ea18 feat: PollingRealnameHandler 新增设备级套餐实名激活联动
- 结构体新增 deviceSimBindingStore 字段,构造函数参数列表末尾追加
- 新增 triggerDeviceRealnameActivation:卡首次实名(0→1)时查询所属设备,
  若有绑定则提交 carrier_type=device 的 TaskTypePackageFirstActivation 任务
- 独立卡(无绑定设备)静默跳过,任务提交失败仅记录 Warn 日志不阻断流程
- registerPollingHandlers 传入 h.workerResult.Stores.DeviceSimBinding
- 修复「购买后某张卡实名」场景下设备级套餐永不激活的缺陷

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-18 09:30:50 +08:00
8e61cb1a54 fix: 购买时检查载体实名状态,已实名跳过 pending 直接激活
- iot_card 载体:扩展查询字段同时读取 real_name_status,已实名则保持 Active 不切换 pending
- device 载体:通过 GORM 子查询统计绑定卡中已实名数量,count>0 则直接激活
- 查询出错时保守默认 false,不阻断购买流程
- 修复「先实名后购买」场景下套餐永久 pending 及购买后不自动复机的双重缺陷

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-18 09:30:40 +08:00
4aab0bcbf2 提案以及归档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m39s
2026-04-18 09:10:29 +08:00
6caf0f6141 feat: 新增全局操作密码功能,将线下充值验证从登录密码改为统一操作密码
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- 新增 RedisSystemOperationPasswordKey 常量函数(pkg/constants/redis.go)
- 新增 operation_password Service(Set/IsSet/Verify,bcrypt 哈希存 Redis)
- 新增 SuperAdminHandler 及两个接口:
  - POST /api/admin/super-admin/operation-password(设置/重置,仅超级管理员)
  - GET /api/admin/super-admin/operation-password/status(查询是否已设置)
- AgentRecharge.OfflinePay 操作密码验证从"查当前用户登录密码"改为"全局操作密码 Verify"
- Bootstrap/路由/文档生成器同步注册
2026-04-18 09:06:33 +08:00
6e15e1b853 docs: 更新 OpenAPI 文档及提案任务清单,新增 payment_voucher_key 字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m26s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 18:29:42 +08:00
ad30f5d41b feat: 代理充值支持线下支付凭证上传与存储
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 18:29:06 +08:00
b538e45bd9 feat: 新增数据库迁移,为 tb_agent_recharge_record 添加 payment_voucher_key 列
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 18:28:38 +08:00
1033d7666b 修复主账号问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m6s
2026-04-17 18:07:29 +08:00
0d2baabcf1 chore: 更新 asset-realname-policy 提案任务清单,勾选全部已完成项
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m24s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:33:52 +08:00
9d8e3926ff docs: 更新 OpenAPI 文档,新增 realname-mode 更新接口文档
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:33:07 +08:00
c5ed040359 feat: 后台管理新增 UpdateRealnameMode 接口并注册路由 PATCH /api/admin/assets/:identifier/realname-mode
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:32:18 +08:00
363e0efb34 feat: C 端充值、购买、实名链接接口接入实名策略拦截(before_order/after_order)
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:31:21 +08:00
1363797378 feat: 导入 Service 和 Worker 传递 realname_policy 写入资产记录
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:31:01 +08:00
71498883b5 feat: iot_card/device Service 新增 UpdateRealnamePolicy 方法(含幂等检查)
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:30:13 +08:00
1d75a4c31a feat: asset Service 新增 GetEffectiveRealnamePolicy 策略判断及 HasValidRechargeOrPaidOrder 检查逻辑
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:29:32 +08:00
89eec1406a feat: iot_card/device Store 新增 UpdateRealnamePolicy 方法
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:28:58 +08:00
9a625f51ef feat: C 端查询及设备导入接口 DTO 新增 realname_policy 字段
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:28:20 +08:00
2d6456c4a3 feat: 后台管理查询接口 DTO 新增 realname_policy 字段
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:27:10 +08:00
9bd1d60e85 feat: 四个 Model 新增 realname_policy 字段(含 gorm 标签和中文注释)
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:26:20 +08:00
908c5fa1de feat: 新增 RealnamePolicy 常量枚举及 CodeRealnameNotAvailable 错误码
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 17:25:02 +08:00
505b30aa8f feat: 实现资产实名认证策略功能 (asset-realname-policy)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m44s
- 新增 realname_policy 字段到 tb_iot_card、tb_device、tb_iot_card_import_task、tb_device_import_task 四张表
- 策略枚举:none(无需实名)、before_order(先实名后充值/购买)、after_order(先充值/购买后实名)
- C端充值拦截:before_order 策略下未实名用户禁止充值
- C端订单拦截:before_order 策略下未实名用户禁止购买套餐
- C端实名链接拦截:after_order 策略下无充值/订单用户禁止实名认证
- Admin API:PATCH /api/admin/assets/:identifier/realname-mode
- 新增错误码 CodeRealnameNotAvailable=1189
2026-04-17 17:03:41 +08:00
e0a37f4a11 fix: verify-asset 接口增加卡绑定设备校验
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m29s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 14:49:11 +08:00
4c284c422c fix: 移除 IoT 卡导入 ICCID 长度限制
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m29s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 12:04:44 +08:00
44e4f03957 docs: 补充微信 JSSDK 配置接口 OpenAPI 文档
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-17 12:04:35 +08:00
0a2961ecd6 fix: 支付回调补写 actual_paid_amount 字段,从支付平台回调中提取实付金额
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m48s
- HandlePaymentCallback 新增 actualPaidAmount int64 参数,Updates 写入 actual_paid_amount
- 微信 V2 回调从 TotalFee 字符串解析分值;V3 直接使用 TotalAmount
- 支付宝回调优先取 buyer_pay_amount(实付),回退 total_amount,元转分使用 math.Round
- 富友回调从 OrderAmt 字符串解析分值
- dispatchWechatCallback 同步增加 paidAmount 参数透传
2026-04-17 11:12:35 +08:00
fa554c3930 feat: 注册 C 端微信 JSSDK 配置接口路由及文档生成
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m35s
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-16 18:38:43 +08:00
1125701329 feat: 新增 C 端微信 JSSDK 签名配置接口 Handler
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-16 18:38:20 +08:00
ed1facc1b8 feat: 公众号服务新增 GetJSSDKConfig 方法及 JSSDK 配置 DTO
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-16 18:37:59 +08:00
0cba6fd6d5 fix: 修复轮询缓存竞态导致流量增量重复计全量的问题
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
getCardWithCache 在缓存 miss 时将 writeCardToCache 由异步协程改为同步调用。
原实现中协程可能在 updateCardCache 之后才被调度执行,将
last_gateway_reading_mb 覆盖回 DB 旧值(0),导致下次轮询
increment = gatewayFlowMB - 0 = 全量,触发套餐流量重复扣减。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-16 18:33:46 +08:00
94f20ce8c7 配置
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m12s
2026-04-16 17:50:49 +08:00
aef20d2ab1 fix: 修复禁用所有轮询配置重启后再启用无法工作的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m23s
- 新增 RedisPollingConfigChangedChannel 常量,用于跨进程配置变更通知
- ConfigService 注入 Redis,Create/Delete/UpdateStatus 后发布 Pub/Sub 事件
- PollingConfigManager 新增 WatchChanges() 方法,收到通知立即刷新内存缓存
- PollingInitializer 新增 Restart() 方法,支持初始化完成后安全重启(CAS 防并发)
- Worker 订阅配置变更事件,configs 从空变为非空时触发 Initializer.Restart()

根因:启动时所有配置禁用导致分片队列为空,Initializer 是一次性的,
之后启用配置只更新 DB 但不重建队列,调度器无卡可处理
2026-04-16 17:32:43 +08:00
0ec16d4afa fix: 实名轮询防止上游接口故障时误降级已实名状态
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m34s
Gateway 返回 data=null 时 sonic 解析为零值结构体(ICCID="" RealStatus=false),
导致已实名卡被误判为未实名并触发停机。

通过检查响应中 ICCID 是否回填来判断数据有效性:
- ICCID 为空:视为上游接口故障,重新入队,不更新实名状态
- ICCID 有值:响应有效,正常处理(含合法的未实名降级)
2026-04-16 16:48:14 +08:00
7e4c61e6e9 docs: 新增枚举状态字段规范及 Code Review 检查清单
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m28s
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-16 15:58:28 +08:00
2d0b4e9bc0 fix: 充值订单列表按当前登录资产过滤,修复越权查看其他资产数据的漏洞
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-16 15:56:43 +08:00
520b126ecf feat: JWT Claims 新增资产字段,登录 token 携带当前资产上下文
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-16 15:55:41 +08:00
5d9be1d7e4 fix: 修正轮询配置多匹配逻辑,支持同卡匹配多个配置并按 priority 合并 interval
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m27s
核心变更:
- MatchConfig 改为 MatchConfigs,返回所有匹配配置
- MergedTaskIntervals 按 task type 合并各配置,选取最高优先级(非 nil 且最小 priority 值)
- hasAnyEnabledInterval 过滤所有 interval 均为 NULL 的配置
- calcInitialDelay 重构为纯函数,接收 interval 参数
- 移除 getEnabledTaskTypes 和 getIntervalByTaskType(被 MergedTaskIntervals 替代)
- scheduler.go 新增心跳 key + 顶层 panic recovery + Init 完成守卫
- initializer.go 批量失败日志升级为 Error,逐条检查 Pipeline 命令错误
- 数据迁移:禁用 id=29 的轮询配置(所有 interval 均为 NULL)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 14:27:47 +08:00
5065d925ad fix: 修正套餐激活和时间字段nullable问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m33s
核心变更:
1. Model层时间字段改为*time.Time并设为nullable
   - PackageUsage.ActivatedAt/ExpiresAt
   - PersonalCustomerDevice/ICCID/Phone.LastUsedAt/VerifiedAt

2. 数据库迁移:
   - activated_at/expires_at列移除NOT NULL约束
   - 清洗零值记录(status=0且activated_at<'2000-01-01')

3. 新增ActivateSpecificPackage方法:精准激活指定套餐,
   修复HandlePackageQueueActivation从"查找过期包"改为直接激活payload指定套餐

4. 新增孤儿套餐恢复扫描:Worker启动或每次套餐检查时,
   自动发现并恢复无status=1主套餐的孤儿载体

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 11:14:39 +08:00
97d6319b64 fix: 修正 HasValidByCarrier 有效套餐定义,仅 status=Active 才算有效
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m43s
修复Bug:原代码将 Pending(0) 也算作有效套餐,导致待生效套餐的卡
不会被触发停机指令。现改为仅生效中(Active)才算有效套餐。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 18:14:50 +08:00
0a27a78d97 fix: 修正强充订单状态映射错误,0-based DB 常量正确映射为 1-based 客户端状态
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 48s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 14:58:37 +08:00
fc995187df 输出日志
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 49s
2026-04-15 14:11:42 +08:00
8bf1282378 归档: add-polling-card-status-with-verbose-log,同步主规范
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m24s
change 目录归档至 openspec/changes/archive/2026-04-15-add-polling-card-status-with-verbose-log/
新建主规范 openspec/specs/polling-card-status-task/spec.md(6个需求)
追加 verbose log 需求至 openspec/specs/polling-task-handlers/spec.md(4个新需求)
protect handler 规范更新字段名:network_status → network_status_at_check + action_taken

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:23:05 +08:00
854330a4b4 docs: 更新 OpenAPI 文档,新增卡状态检查间隔字段
PollingConfig 请求/响应结构中添加 card_status_check_interval 字段说明

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:22:55 +08:00
e40ad462e1 feat: 注册卡状态轮询 Worker Handler
registerPollingHandlers 创建并注册 PollingCardStatusHandler
日志更新为 realname/carddata/package/protect/card_status

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:22:49 +08:00
647d78309d feat: 将卡状态任务类型接入队列管理、生命周期和初始化器
queue_manager.go: allTaskTypes 追加 TaskTypePollingCardStatus,注释更正为5个队列
lifecycle_service.go: getEnabledTaskTypes 和 calcInitialDelay 新增 card_status 条件
initializer.go: initBatch 新增 CardStatusCheckInterval 块,以 LastCardStatusCheckAt 为基准写入分片队列

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:22:42 +08:00
c7f486ae09 feat: 新增 PollingCardStatusHandler 及工具函数卡状态支持
polling_cardstatus_handler.go: 新文件,实现卡开停机状态轮询
  - Gateway QueryCardStatus → 停机/0,其他/1
  - 状态变化时写 DB + 更新缓存 + 触发 EvaluateAndAct
  - verbose log 位于 gateway 块内
polling_utils.go: getIntervalByTaskType 新增 TaskTypePollingCardStatus case

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:22:34 +08:00
71559547b6 feat: 为四种现有轮询 Handler 添加 verbose log 输出
realname: verbose log 移入 gateway 块内,避免 gateway=nil 时输出零值
carddata: 添加 && h.gateway != nil 门卫,确保仅 gateway 查询成功时输出
package: verbose log 在 freshCard 加载后、EvaluateAndAct 之前输出
protect: 引入 actionTaken 变量,字段名 network_status → network_status_at_check,新增 action_taken

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:22:25 +08:00
6292443f69 feat: PollingBase 新增 verboseLog 支持,Worker 传入配置
polling_base.go: PollingBase.verboseLog bool 字段,NewPollingBase 新增参数
main.go: cfg.Polling.VerboseLog 作为第6个参数传入 NewPollingBase

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:22:16 +08:00
97c196b7c6 feat: PollingConfig DTO 和 Service 支持卡状态检查间隔
dto: 新增 CardStatusCheckInterval 字段(validate min=30,description 含枚举说明)
config_service.go: 创建/更新/响应映射均支持 CardStatusCheckInterval

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:22:09 +08:00
cb328f3ec2 feat: PollingConfig 和 IotCard 模型新增卡状态检查字段
polling.go: CardStatusCheckInterval *int(card_status_check_interval)
iot_card.go: LastCardStatusCheckAt *time.Time(last_card_status_check_at)

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:22:01 +08:00
9992e82a3c feat: 新增卡状态轮询任务类型常量及 verbose_log 配置
constants.go: 新增 TaskTypePollingCardStatus = "polling:card_status"
config.go: 新增 PollingConfig struct 含 VerboseLog bool
config.yaml: polling.verbose_log 默认 false

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:21:43 +08:00
e2003eb9e3 feat: 新增卡状态检查轮询数据库迁移
tb_polling_config 新增 card_status_check_interval INT NULL
tb_iot_card 新增 last_card_status_check_at TIMESTAMPTZ NULL
含 IF NOT EXISTS 保证幂等,含完整回滚文件

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 12:21:21 +08:00
71048e31d4 更换新的上游域名
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m15s
2026-04-15 11:21:14 +08:00
4a1e44f9e1 提案
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-04-15 11:17:23 +08:00
dd408fcdca 日志输出 2026-04-15 11:17:09 +08:00
516bb92a16 refactor: 删除 enterprise_device service 中无路由接入的死代码方法
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
ListDevicesForEnterprise、GetDeviceDetail、SuspendCard、ResumeCard、validateCardOperation 均无对应路由和 Handler 调用,且 SuspendCard/ResumeCard 仅修改本地 DB 未调 Gateway,存在错误实现风险。统一使用 iot_card stop_resume_service 处理停复机。

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 11:16:36 +08:00
023a4309eb fix: 修正 realtime-status 路由文档描述,补充说明设备类型会实时调 Gateway
原描述误写为不调网关,实际 GetRealtimeStatus 对设备类型会调用 SyncDeviceInfo 接口。

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-15 11:16:01 +08:00
b972a776d9 重构充值订单模块:用 tb_recharge_order + tb_payment 替换 tb_asset_recharge_record
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m32s
- 新增 RechargeOrder 和 Payment 模型及对应 Store
- 新增 ClientRechargeOrderHandler 提供充值订单列表/详情接口
- 修改 client_wallet.go 使用新表读写充值数据
- 修改 callback/payment.go 将 CRCH 订单路由到 rechargeOrderService
- 修改 client_order/service.go 的强充流程使用新表
- 修改 auto_purchase.go 从 tb_recharge_order 读取 linked_package_ids
- 修改 order/service.go 的 WalletPay 使用 tb_payment 记录
- 修改 wechat_config_store.go 从 tb_recharge_order 统计待支付充值数
- 移除 AssetRechargeStore 和 AssetRechargeRecord 的注册引用
- 修复文档生成器缺失 ClientRechargeOrder handler
- 状态枚举改为 0-based: Pending=0, Paid=1, Closed=2, Refunded=3
2026-04-15 11:00:32 +08:00
d26010b29d 重构用的提案,现在不敢跑
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 49s
2026-04-14 17:38:36 +08:00
8706247436 fix: 资产解析接口 BoundCardInfo 添加运营商字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m18s
2026-04-14 17:10:28 +08:00
8154a61453 fix: 移除 standaloneListColumns 中已废弃的分佣字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m51s
迁移 000116 已从 tb_iot_card 删除 first_commission_paid 和 accumulated_recharge
两列,但 standaloneListColumns 未同步清理,导致 SELECT 查询报列不存在错误。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-14 12:40:04 +08:00
d9de704d73 归档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 49s
2026-04-14 12:14:29 +08:00
4ea4a1e53f docs: 更新 tech-debt-cleanup tasks.md 实际完成状态 2026-04-14 11:59:28 +08:00
041856dc8c docs: 新增迁移说明文档,reset_db.sh 添加 000114 基线检查
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m13s
2026-04-14 11:56:50 +08:00
7cdb66cbe4 refactor: 统一状态名称映射为公共函数,清理废弃换卡/商户类型常量和模型 2026-04-14 11:51:58 +08:00
5410181e77 修复:C端资产信息接口 lan_ip 字段无值时不返回的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m17s
去掉 DeviceRealtimeInfo.LANIP 的 omitempty 标签,
确保 device_realtime.lan_ip 始终出现在响应中(无值时返回 null)
2026-04-14 11:49:17 +08:00
548ec0cd6b feat: 补全 _name 字段公共映射函数,修正实名认证注释 2026-04-14 11:44:23 +08:00
5e9e41db21 feat: 归档旧迁移文件,创建初始化数据迁移和重置脚本 2026-04-14 11:24:35 +08:00
c35542f911 feat: 补全客户端订单和资产 DTO _name 字段,修复代码格式 2026-04-14 11:19:57 +08:00
42c5ec912f feat: 技术债务清理(支付配置动态化、API文档补全、轮询常量提取、废弃代码清理)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m13s
2026-04-14 11:11:15 +08:00
c0b64c9e30 fix: 登录时将主手机号写入 JWT,修复 bound_phone 返回空的问题
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-04-14 11:09:42 +08:00
37706bc7ce feat: 资产信息接口返回当前登录用户绑定手机号
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m30s
2026-04-14 10:08:42 +08:00
7308afe801 归档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m18s
2026-04-13 15:03:02 +08:00
c1456f3c54 docs: 补充轮询自动触发环境变量说明 2026-04-13 14:57:00 +08:00
640ea8ec99 feat: 更新依赖注入,传入 ManualTriggerService 2026-04-13 14:52:50 +08:00
8569873690 feat: ClientRealnameHandler 集成异步触发实名检查 2026-04-13 14:51:42 +08:00
5196472d7e fix: 修复手动触发去重TTL和日限制次数,优化权限检查和错误日志 2026-04-13 14:50:14 +08:00
814a2956b3 feat: 新增轮询自动触发配置(EnableAutoTrigger、AutoTriggerSystemUserID) 2026-04-13 14:48:12 +08:00
4879d9bf07 fix: 修复公众号登录初始化失败(PowerWeChat 日志写入权限)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m29s
NewOfficialAccountAppFromConfig 未设置 Log.Stdout=true,PowerWeChat SDK
默认尝试在工作目录创建 wechat/info.log 文件,容器环境无写权限导致
NewOfficialAccount 返回 permission denied,触发 1181 配置不可用错误。

支付配置已有此修复(NewPaymentAppFromConfig),公众号配置漏掉了。

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-13 14:39:54 +08:00
8d8d426e2e feat: verify-asset 接口返回当前生效的公众号和小程序 AppID
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m51s
2026-04-11 17:22:21 +08:00
246ae5e123 docs: 新增 status-convention 主规范
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m20s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-11 12:21:07 +08:00
7e613a0d2b 归档: fix-status-convention-comments
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-11 12:21:02 +08:00
510a5bfb21 chore: 删除未使用的僵尸状态常量 DevCapabilityStatusEnabled/Disabled
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-11 12:20:56 +08:00
decb7a10ec fix: 使用专用常量 ShelfStatusOn 替代 StatusEnabled 赋值 ShelfStatus
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-11 12:20:49 +08:00
5588c7c762 fix: 修正 DTO status 字段 description 和 validate 标签
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-11 12:20:43 +08:00
eebc7194d8 fix: 修正 model status 字段 GORM comment 为 0=禁用 1=启用
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-11 12:20:31 +08:00
e945a672ed fix: 修正套餐系列状态注释格式
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m19s
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-11 12:00:01 +08:00
41d3667df2 feat: 设备卡列表新增运营商类型字段
在 DeviceCardItem DTO 和 GetDeviceCards Handler 中补充 carrier_type 字段,解决设备视角卡列表缺少运营商类型的问题

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-11 11:59:54 +08:00
8f66ca7bcb 文档提交
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m14s
2026-04-11 11:27:43 +08:00
e9ff14df0e 规范: 新增枚举与状态字段规范并修复代理充值状态描述错误
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- 新增 docs/enum-status-standards.md:完整的枚举/状态规范,涵盖 int vs string 选择、起始值约定、description 格式统一、constants 唯一真相来源、Response DTO 必须提供 status_name
- 更新 dto-standards SKILL.md:加入枚举规范要点,AI 写 DTO 时自动触发
- 更新 AGENTS.md:常量管理章节和 Code Review 检查清单各加入枚举检查项
- 修复 agent_recharge_dto.go:description 从错误的 3 个状态改为正确的 5 个状态(原 3:已取消 实为 3:已完成)
- 修复 agent_recharge service:toResponse 补充 StatusName 中文字段,防止前端映射出错
2026-04-11 11:25:58 +08:00
c807b99a91 fix: 修复佣金明细列表多表 JOIN 时 shop_id 字段歧义问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m24s
ListByShopID 使用 tb_commission_record.shop_id 限定表名,
避免与 JOIN 的 tb_order/tb_iot_card/tb_device 表中同名字段冲突,
解决 SQLSTATE 42702 ambiguous column reference 错误。

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-11 11:06:13 +08:00
677d6239ce fix: 统一佣金状态常量并修复佣金明细关联查询
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m33s
- 删除 model/commission.go 中与 constants 包冲突的旧常量(值=1/2)
- 所有服务层改用 constants.CommissionStatusReleased(值=3)写入和查询
- 数据库迁移:status 1→3(已发放),2→4(已失效)
- 修复佣金明细列表接口,通过 JOIN 关联返回 order_no、iccid、virtual_no、order_created_at
- 新增 seller_shop_id / seller_shop_name 销售来源字段
- 统计接口过滤条件从精确匹配改为排除无效(NOT IN 4,99)
- 更新 OpenAPI 文档及 commission-record-query spec
2026-04-11 10:42:37 +08:00
d0989c66bb 暂且不需要实名
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m19s
2026-04-10 18:31:40 +08:00
67f3286e09 fix: 修复店铺资金摘要接口username和phone字段为空的bug
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m17s
问题原因:GetPrimaryAccountsByShopIDs 在 Store 层重复应用了数据权限过滤,
导致当前用户无权限访问的店铺账号被错误过滤,accountMap 为 nil,
最终返回的 username 和 phone 为空字符串。

解决方案:移除 Store 层的 ApplyShopFilter 权限过滤,
因为调用方(Service 层)已经保证了 shopIDs 的合法性。
2026-04-10 17:21:27 +08:00
a8b52f8ae1 fix: 设备详情 RealNameStatus 取当前使用卡而非聚合最小值
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-04-10 17:15:40 +08:00
5496cb58aa feat: 订单创建时快照买家手机号/昵称和套餐类型
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
新增字段:
- tb_order: buyer_phone, buyer_nickname(个人客户下单时快照)
- tb_order_item: package_type(套餐类型快照)

后台订单列表支持按 buyer_phone 精确过滤查询。

OpenSpec: order-buyer-snapshot
2026-04-10 17:12:56 +08:00
3cb16804a4 fix: 设备资产详情返回 enable_polling 字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m19s
2026-04-10 15:54:47 +08:00
2a7ac3f86e fix: 修复轮询系统缓存不一致和可观测性问题
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- OnCardStatusChanged/Enabled/Disabled 添加 InvalidateCardCache,
  解决 Refresh API 更新 DB 后 polling 缓存仍为旧值的 bug
- AssetResolveResponse 的 enable_polling/network_status 去掉
  omitempty,解决 false/0 时字段从响应中消失的问题
- Scheduler/Initializer/PackageHandler 增加 INFO 级别日志,
  可通过日志判断轮询是否工作、处理了哪些卡
2026-04-10 15:52:38 +08:00
ef8ec025bd feat: 资产套餐接口返回是否开启虚流量字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m26s
current-package 和 packages 两个接口的响应中新增
enable_virtual_data 字段,表示该套餐是否启用虚流量

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 14:33:05 +08:00
23e12d8a73 fix: 卡导入 Excel 解析移除虚拟号强制校验
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m19s
虚拟号(virtual_no)为可选字段,解析时不应强制要求填写。
与 processBatch 中的处理逻辑保持一致。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 11:58:39 +08:00
4a18aac6ce fix: 资产验证支持虚拟号(virtual_no)查询
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m27s
resolveAsset 查询 IoT 卡时仅匹配 iccid,导致用户输入
虚拟号时返回"资产不存在"(1180)。将查询条件扩展为
iccid OR virtual_no,与设备查询逻辑保持一致。

顺带将 jwt.ParseWithClaims 回调的 interface{} 替换为 any。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 11:42:23 +08:00
51fa027eb8 归档 2026-04-09 17:47:06 +08:00
afc6d7fc76 docs: 归档 excel-import-refactor,同步更新主 specs
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 50s
- 将变更目录移至 archive/2026-04-09-excel-import-refactor
- device-import spec:更新为固定列位置读取(IMEI 调整至第5列),新增 MaxSimSlots 范围校验说明
- iot-card-import-task spec:更新为固定列位置读取,新增"导入批次支持卡业务类型"需求

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 17:37:44 +08:00
cd807e58e3 feat: Excel 导入按列位置读取,IoT 卡导入支持卡业务类型
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m28s
- 重写 parseCardRows:移除列名识别,固定跳过第1行表头,按 col0=ICCID、
  col1=MSISDN、col2=VirtualNo 取值,VirtualNo 升级为必填字段
- 重写 ParseDeviceExcel:移除 buildDeviceColumnIndex,IMEI 调整至第5列
  新增 MaxSimSlots 范围校验 [1,4],整行为空时不计入 total
- 删除 findCardColumns 和 buildDeviceColumnIndex 两个冗余函数
- ImportIotCardRequest 新增 card_category 字段(normal/industry,默认 normal)
- IotCardImportTask model 新增 card_category 字段
- 迁移 000111:tb_iot_card_import_task 新增 card_category 列
- CreateImportTask 将 req.CardCategory 写入任务,空串兜底 normal
- processBatch 改用 task.CardCategory 替代写死的 CardCategoryNormal
- ImportTaskResponse 新增 card_category 字段返回

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 17:16:31 +08:00
ff7e749bf2 归档 2026-04-09 14:53:48 +08:00
0627ffec42 feat: 代理商资金可见性重构(agent-fund-visibility)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m10s
- 将 GET /shops/commission-summary 重命名为 GET /shops/fund-summary,
  响应新增 main_balance、main_frozen_balance 两个预充值钱包字段
- 新增 GET /shops/:id/main-wallet/transactions 预充值钱包流水接口
- 将佣金统计、每日统计、发起提现从 /my/ 路径迁移至 /shops/:id/ 路径:
  GET /shops/:id/commission-stats
  GET /shops/:id/commission-daily-stats
  POST /shops/:id/withdrawal-requests
- 删除 MyCommissionService、MyCommissionHandler 及全部 /my/ 路由
- 补齐 ListShopWithdrawalRequests、ListShopCommissionRecords 的
  CanManageShop 越权校验(安全修复)
- 提现接口增加严格权限:仅代理账号本人可为自己店铺发起提现

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:40:39 +08:00
1d6535b81b fix: 修复移除账号角色接口路由参数名错误
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
RemoveRole handler 中使用 c.Params("id") 取账号 ID,
但路由注册的参数名为 account_id,导致解析失败报"无效的账号 ID"。
修正为 c.Params("account_id")。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:38:01 +08:00
0f6fd42aff fix: 禁用角色时检查是否已分配给账号或店铺
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
角色禁用前新增分配情况检查,若角色已分配给账号或店铺则拒绝禁用操作,
需先移除相关分配后才能禁用,与删除角色的防护逻辑保持一致。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:35:55 +08:00
c1cec0aede fix: 修复C端订单差价佣金计算错误及自动购包订单系列ID缺失问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m11s
- C端普通订单(createPackageOrder)创建时未设置 SellerCostPrice,
  导致底层店铺得到整个零售价作为差价佣金,上级代理链无法获得任何佣金。
  修复:在 createPackageOrder 中查询卖家成本价并写入订单字段。

- purchase_validation 新增 GetCostPrice 方法,供 C 端订单查询代理渠道成本价。

- auto_purchase 自动购包订单未设置 SeriesID 和 SellerCostPrice,
  导致差价佣金计算被整体跳过。修复:在 ProcessTask 中从卡/设备获取
  SeriesID,从套餐分配记录获取 SellerCostPrice,传入 buildOrderAndItems。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:35:13 +08:00
6dfc5c0301 feat: 资产解析接口新增实名时间字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m5s
- AssetResolveResponse 新增 real_name_at 字段:card 类型取 first_realname_at,device 类型取绑定卡中最小的实名时间
- BoundCardInfo 新增 real_name_at 字段:各卡自己的 first_realname_at
- RefreshCardDataFromGateway 手动刷新路径补写实名时间:检测到 0→1 变化时同步写入 first_realname_at
- 同步更新 asset-resolve 规格文档

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 12:12:28 +08:00
fce35e8a2d fix: 修复角色分配权限并发竞态导致唯一约束冲突报错
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m4s
- Store 层 Create 方法对唯一约束冲突幂等处理,消除并发写入报错
- Service 层预批量加载角色已有权限集合(1次查询),替换逐条 Exists 查询(N次查询),同时降低竞态窗口

💘 Generated with Crush

Assisted-by: Claude Sonnet 4.6 via Crush <crush@charm.land>
2026-04-09 11:58:52 +08:00
81ba84cf05 feat: 新增店铺联级查询接口
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m3s
- 新增 GET /api/admin/shops/cascade 接口,支持按店铺名模糊查询和上级ID过滤
- Store 层新增 ListForCascade(支持数据权限过滤)和 GetParentIDsWithChildren 方法
- Service 层新增 ListCascade,批量判断 has_children 避免 N+1 查询
- 返回格式:[{id, shop_name, has_children}]

💘 Generated with Crush

Assisted-by: Claude Sonnet 4.6 via Crush <crush@charm.land>
2026-04-09 11:43:37 +08:00
384a54164b feat: 新增批量移除角色权限接口
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- 新增 DELETE /api/admin/roles/:role_id/permissions 接口
- Store 层新增 BatchDelete 方法,单次 SQL 批量软删除
- Service 层新增 BatchRemovePermissions 方法
- Handler 层新增 BatchRemovePermissions 处理函数
- DTO 新增 BatchRemovePermissionsRequest/Params
- 修复 openapi generator 对 DELETE 方法 requestBody 不生成的问题
- RouteSpec 新增 Body 字段,支持显式指定 JSON 请求体

💘 Generated with Crush

Assisted-by: Claude Sonnet 4.6 via Crush <crush@charm.land>
2026-04-09 11:41:58 +08:00
a7dfe858c7 feat: 创建代理账号时自动分配店铺默认角色
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m22s
💘 Generated with Crush

Assisted-by: Claude Sonnet 4.6 via Crush <crush@charm.land>
2026-04-09 11:06:31 +08:00
e9df1e7ded feat: IoT卡新增绑定设备虚拟号快照字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m28s
- tb_iot_card 新增 device_virtual_no 字段,存储绑定设备的虚拟号快照
- 列表/详情接口响应新增 device_virtual_no 字段
- 列表接口 is_standalone 改为可选参数(不传返回全部卡)
- 移除列表接口 virtual_no 查询参数
- 绑卡/解绑时同步更新 device_virtual_no 快照
- 设备导入时批量写入 device_virtual_no 快照
- 归档 feat-iot-card-device-virtual-no 变更提案

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 10:50:46 +08:00
cc56e27c01 feat: 后台线下支付订单强制上传支付凭证
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m15s
在后台创建订单接口中新增 payment_voucher_key 字段,线下支付方式
下该字段为必填,存储对象存储 file_key,便于后续追溯与审计。

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 16:45:06 +08:00
78d6aded9b fix: 修复IoT卡导入时未写入carrier_type和carrier_name字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m21s
processBatch 构建 IotCard 时只写了 CarrierID,遗漏了 CarrierType 和 CarrierName,
导致导入后所有卡的运营商名称和运营商类型为空,影响 /api/admin/iot-cards/standalone
和 /api/admin/assets/resolve/{identifier} 接口返回结果

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-08 11:56:57 +08:00
14a8ea5a2c fix: 单卡导入虚拟号改为可选,非空时保证全局唯一
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m26s
2026-04-08 10:45:23 +08:00
38ef73fd7f docs: 补充资产标识符标准化接口文档更新 2026-04-08 10:45:13 +08:00
303bffbe84 文档生成不正确的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m52s
2026-04-07 18:19:47 +08:00
80c6f6c756 feat: 资产标识符标准化、资产历史订单查询及导入虚拟号强制验证
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m21s
主要变更:
- 新增 AssetIdentifier 模型及 Store,统一管理资产标识符(ICCID/IMEI/SN 等)
- 新增迁移:asset_identifier 表、order 表新增 asset_identifier 字段、iot_card.virtual_no NOT NULL 约束
- 资产 Handler/Service/Route 全面重构,支持标识符路由查询与解析
- 新增资产历史订单查询接口,支持跨设备/卡/钱包维度的订单聚合
- 设备与物联卡导入任务强制校验虚拟号,缺失时直接拒绝
- Excel 工具函数优化,前端导入指引文档同步更新
- 归档三个 OpenSpec 提案:asset-identifier-standardization、asset-historical-orders、import-mandatory-virtual-no
- 更新 OpenAPI 文档及相关 DTO

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-07 17:39:36 +08:00
7e489a19fb fix: 角色删除前校验分配情况,禁止删除使用中的角色
角色被删除后,其关联的账号-角色记录未清理,导致 CountByAccountID
统计到孤儿记录,使被分配该角色的账号无法重新分配新角色。

修复方案:删除角色前检查 tb_account_role 和 tb_shop_role,
若仍有账号或店铺持有该角色则返回 1028 错误,强制管理员显式
解除所有分配后再删除,保证数据一致性与审计完整性。
2026-04-07 17:23:49 +08:00
434a8b0349 feat: 轮询系统重构(分片队列 + 停复机统一 + Handler 拆分)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m46s
【核心变更】

1. 停复机逻辑统一(StopResumeService)
   - 新增 EvaluateAndAct 统一入口,封装三条件停复机判断
   - 停机条件:无套餐(no_package) / 流量耗尽(traffic_exhausted) / 未实名(not_realname)
   - 复机条件:stop_reason 合规 + 有套餐且未耗尽 + 已实名或行业卡
   - 修复设备套餐 Bug:hasValidPackage 按 device_id 查套餐,而非仅 iot_card_id
   - 设备维度停复机加幂等锁(Redis SetNX,TTL 30s),防止多卡并发重复调 Gateway

2. Redis 分片队列(PollingQueueManager)
   - 新建 queue_manager.go,封装所有轮询 Redis 操作
   - 16 分片 Sorted Set,Key 格式:polling:shard:{shardID}:queue:{taskType}
   - Lua 脚本原子出队(ZRANGEBYSCORE + 分批 ZREM),消除竞态窗口
   - 新增背压检测:队列深度超 50 万时 Scheduler 跳过该分片
   - RemoveFromAllQueues 覆盖 4 种任务类型(含 protect)

3. Handler 拆分(polling_handler.go 1360行 → 5个专注文件)
   - polling_base.go:共享基类(并发控制/卡缓存/重入队)
   - polling_realname_handler.go:实名采集,实名 0→1 时立即触发复机
   - polling_carddata_handler.go:流量采集,保留跨月边界检测逻辑
   - polling_package_handler.go:套餐采集,委托 EvaluateAndAct 决策
   - polling_protect_handler.go:保护期一致性检查,保护期内强制修正

4. 配置管理(PollingConfigManager)
   - 新建 config_manager.go,从 scheduler.go 提取配置职责
   - 内存缓存 + 5 分钟定时刷新,刷新失败保留原缓存
   - 修复 getCardCondition:停机卡返回 suspended,不再错配 activated 配置

5. 渐进式初始化(CardInitializer)
   - 新建 initializer.go,分批加载(每批 10 万),批次间 sleep 500ms
   - 过滤 enable_polling=false 的卡,初始化完成前 Scheduler 不出队

6. 卡生命周期服务(PollingLifecycleService)
   - 新建 lifecycle_service.go,替代已删除的 callbacks.go 和 api_callback.go
   - OnCardCreated/OnCardEnabled/OnCardStatusChanged 入队前检查 enable_polling

7. Scheduler 精简(1000+行 → 227行)
   - 保留纯调度循环:scheduleLoop + processShardSchedule + enqueueBatch
   - 保留每 10 秒触发套餐过期检测和流量重置
   - 移除所有 DB 操作、配置加载、卡初始化逻辑

8. 轮询管控 API(enable_polling)
   - 新增 PUT /api/admin/assets/:id/polling-status 接口
   - 支持对设备/卡维度开关轮询,关闭后从所有分片队列移除

9. 数据库迁移
   - 000103:tb_device 新增 enable_polling 字段(boolean, NOT NULL, DEFAULT true)
   - 000104:新增 suspended 轮询配置,为 activated 配置补全 protect_check_interval

【文件统计】
- 新增:19 个文件(handler × 5、polling 组件 × 4、迁移 × 3 等)
- 修改:20 个文件(bootstrap 注入、store 接口、monitoring 适配分片等)
- 删除:3 个文件(polling_handler.go、callbacks.go、api_callback.go)

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-07 12:27:04 +08:00
10fcc0b3c9 fix: 修复强充场景幂等 key 在微信支付失败时未被清除的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m20s
将 markClientPurchaseCreated 移至 CreateJSAPIPayment 成功之后调用,
确保支付失败时 defer 能可靠地删除幂等 key,避免用户无法重新下单。

原顺序:创建充值单 → markClientPurchaseCreated → CreateJSAPIPayment
修复后:创建充值单 → CreateJSAPIPayment → markClientPurchaseCreated → *created=true

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-07 09:55:06 +08:00
c0c32c62f4 fix: 修复代理充值 Handler 缺少参数验证导致 check constraint 违反的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m18s
payment_method 字段传入中文值「线下转账」时,因 AgentRechargeHandler
未注入 validator 而跳过 oneof 验证,直接写入 DB 触发
chk_agent_recharge_method 约束报错。

- AgentRechargeHandler 注入 validator,Create 方法补加 Struct 验证
- bootstrap/handlers.go 传入 validate 实例
- openapi/handlers.go 补 nil 占位保持编译通过
2026-04-03 09:17:15 +08:00
a8a91fe04e fix: 修复 RealtimeStatus 查询后未回写 DB 导致 Resolve 接口在线状态不同步的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m12s
2026-04-02 15:14:04 +08:00
8980e6d999 fix: 补全三处轮询覆盖缺口
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m11s
问题一:protect 轮询任务从未被调度器初始化入队
PollingConfig 新增 protect_check_interval 字段(NULL=不参与),
调度器 initCardsBatch/initCardPolling/requeueCard 补全 protect 队列
初始化逻辑,IotCard 新增 last_protect_check_at 记录上次检查时间。
迁移文件:000102_add_polling_protect_fields

问题二:设备套餐流量耗尽时绑定卡未被停机
UsageService.checkAndTriggerSuspension 新增 carrier_type=device 分支,
通过 DeviceSimBindingStore.ListByDeviceID 查询绑定卡,对每张卡异步
触发 CheckAndStopCard,同步注入 Bootstrap 依赖。

问题三:主套餐过期后不立即停机,依赖下次轮询兜底
PackageActivationHandler.processExpiredPackage 在 updateCarrierSuspended
Status 后,若载体无后续生效套餐,立即异步调用 CheckAndStopCard(iot_card
类型直接触发,device 类型遍历绑定卡),消除停机延迟窗口。

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-02 14:36:24 +08:00
322ded0012 fix: 修复未启用一次性佣金的系列无法创建授权的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m18s
2026-04-02 14:27:09 +08:00
ecfa417c15 设备调用问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m12s
2026-04-02 11:05:21 +08:00
4770e053ee fix: 修复轮询检测到首次实名时未记录 first_realname_at 的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m13s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-02 10:52:58 +08:00
138f08ddd7 fix: 修复平台账号无法访问我的佣金记录和提现记录接口的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m18s
2026-04-02 10:14:44 +08:00
950c0bfb8f fix: 修复已激活在线卡无有效套餐时未被轮询停机的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m3s
- 新增 activated 轮询配置覆盖已实名+在线的卡(此前仅 real_name 配置)
- HandleCarddataCheck 添加独立停机/复机检查(不依赖流量增量)
- shouldStopCard 对齐 hasAvailablePackage 逻辑,检查待生效+生效中套餐
- 新增复机安全网:流量耗尽停机的卡检测到有效套餐后自动复机
- 卡缓存补充 stop_reason 字段支持复机判断
2026-03-31 20:51:42 +08:00
724967b8b8 fix: 修复日志文件 level 字段包含 ANSI 颜色转义码导致乱码
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m5s
2026-03-31 20:05:12 +08:00
1c6f8ed07b fix: 修复停复机操作未同步轮询卡缓存导致卡无法实际停机的问题
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
多处修改 network_status 的代码只更新了 DB 而未失效轮询缓存(polling:card:{id}),
导致轮询系统持续读取旧缓存值,跳过 Gateway 停机调用。

修复方式:DB 更新后立即 Del 轮询缓存 key,下次轮询自动从 DB 重建。

涉及文件:
- StopResumeService: CheckAndStopCard/resumeSingleCard/ManualStopCard/ManualStartCard
- iot_card/Service: RefreshCardDataFromGateway(通过 OnCardStatusChanged 回调)
- device/Service: StopDevice/StartDevice
2026-03-31 19:59:35 +08:00
58eb047433 fix: 修复手动刷新资产时流量直接覆盖为运营商原始读数的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m6s
RefreshCardDataFromGateway 原先直接将网关返回的累计读数写入
current_month_usage_mb,导致本月已用流量从 312MB 跳变为 29GB。

修复内容:
- 流量计算改为增量逻辑(与轮询 calculateFlowUpdates 一致)
- 补充更新 last_gateway_reading_mb 基准,防止后续轮询增量异常
- 补充跨月检测和运营商重置日窗口判断
- 通过 DataDeductor 回调触发套餐流量扣减(手动刷新也能更新套餐)
2026-03-31 19:50:17 +08:00
045aa4fa3a fix: 修复微信/富友支付回调配置加载错误
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m5s
- WechatPayCallback 移除对永远为 nil 的单例 wechatPayment 的依赖,
  改为动态按 payment_config_id 加载创建订单时所用的精确配置
- PaymentV2Service 新增 VerifyCallback()(v2 XML 验签)和 PeekOrderNo()(不验签预解析)
- FuiouPayCallback 由 GetActiveConfig 改为 GetConfigForCallback,
  通过 ParseNotify 预解析订单号后精确加载配置,防止切换配置后旧订单验签失败
- wechat_config.Service 注入 assetRechargeStore/agentRechargeStore,
  新增 GetConfigForCallback():按订单号前缀查 payment_config_id,
  GetByIDUnscoped 加载配置(含已停用/软删除记录),找不到则回退激活配置
- 修复微信 v2 回调响应格式:从 JSON 改为 XML,避免微信持续重试
2026-03-31 19:17:45 +08:00
69ee754c19 feat: 补全网关停复机调用的关键日志(调用前/成功后均输出 INFO)
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-03-31 19:15:45 +08:00
9d50424edc fix: 修复 access.log response_body 乱码(compress 中间件须在 logger 之前注册)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m7s
2026-03-31 19:06:14 +08:00
302664404b fix: 修复流量轮询 cache 未同步 last_gateway_reading_mb 导致假增量触发停机死循环
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-03-31 19:00:26 +08:00
619f029a5a fix: 修复佣金计算任务载荷二次序列化导致 base64 编码错误
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m11s
问题:EnqueueTask 内部调用 sonic.Marshal,传入 []byte 时会将字节数组
base64 编码为 JSON 字符串,Handler 反序列化时类型不匹配(CommissionCalculationPayload vs string)

根因:order/service.go 的 enqueueCommissionCalculation 预先 Marshal 得到 []byte
后传给 EnqueueTask,导致载荷被二次序列化

修复:直接传入 map,由 EnqueueTask 统一序列化一次

规范同步:
- pkg/queue/client.go 函数注释明确禁止传 []byte
- AGENTS.md 新增「异步任务载荷规范」防止重现
2026-03-31 18:48:17 +08:00
31e147495c fix: 修复提现冻结逻辑错误导致数据库约束违反
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- 余额检查从 wallet.Balance 改为 wallet.GetAvailableBalance(),
  防止 frozen_balance 已有值时误判为余额充足
- 冻结余额时只增加 frozen_balance,不再同时减少 balance,
  与系统其他冻结操作保持一致(balance = 总额,frozen 为其子集)
- 修复后 SQL 不再触发 chk_agent_wallet_frozen_balance 约束
2026-03-31 18:41:07 +08:00
ad095d73f3 docs: 同步能力规范 — 新增购买/重置后复机 spec,更新停复机和排队激活规范
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m8s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:12:52 +08:00
8b5cd50576 chore: 归档 fix-stop-resume-lifecycle-engine 变更提案
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:12:44 +08:00
8227ab2f20 fix: Bootstrap 注入复机回调至 orderService 和 resetService
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:12:32 +08:00
6457ffa6f9 fix: 支付回调激活套餐后异步触发停机卡自动复机
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:12:24 +08:00
8d69858413 fix: 套餐激活和流量重置后注入并调用复机回调
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:12:16 +08:00
49e8ebed60 fix: 过期套餐检测扩展覆盖 Depleted 状态(status IN (1,2))
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:12:04 +08:00
bb5a5ec6ef fix: stopCards 停机时补充写入 stop_reason 和 stopped_at 字段
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:11:48 +08:00
cf602ab5be fix: ResumeCardIfStopped 扩展 — 支持 device 类型、实名检查、并发锁
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:11:38 +08:00
d7ade821f4 fix: 移除 carrier 表 billing_day 字段(模型 + 数据库迁移)
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:11:29 +08:00
7f42d198eb fix: 新增 StopReasonProtectPeriod 常量和 RedisCardResumeLockKey 函数
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-31 18:11:01 +08:00
ebc3e78ba9 修复gateway权限问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m48s
2026-03-31 15:59:54 +08:00
00cae60fe1 chore: 删除卡价格验证 hurl 测试文件
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m14s
2026-03-31 15:26:09 +08:00
67e0840695 fix: 修复钱包充值不支持 wechat_v2 支付渠道导致 1046 报错
当前激活的微信支付配置 provider_type = wechat_v2,但 CreateRecharge
硬编码使用 V3(PowerWeChat)路径,导致初始化失败。

新增 createJSAPIPayOrder 方法,根据 provider_type 路由到对应通道:
- wechat_v2 → NewPaymentV2ServiceFromConfig
- wechat(默认)→ NewPaymentAppFromConfig(V3)

与 client_order.Service.newPaymentProvider 保持相同的路由逻辑。
2026-03-31 15:26:03 +08:00
bc2dbcb416 fix: 修复 V2 微信支付参数全为空字符串的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m17s
extractPaymentResult 只处理 map[string]any,而 V2 自建实现返回
map[string]string,类型断言静默失败导致所有字段为空字符串。
增加对 map[string]string 的处理分支,兼容 V1 和 V2 两种支付渠道。
2026-03-31 14:59:43 +08:00
dc4f3cb7ba feat: C端订单支付拆分 — 创建订单与发起支付分离
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m10s
- CreateOrder 改造:普通下单只建单(无支付参数),强充场景保持原有微信支付一步完成
- 新增 POST /orders/:id/pay 统一支付入口,支持 wallet(钱包)和 wechat(微信 JSAPI)
- 移除 POST /orders/:id/wallet-pay,合并至统一支付接口
- app_type 改为可选字段(强充场景必传,普通下单无需传)
- CreateOrderResponse.pay_config 改为 omitempty(普通下单不返回支付参数)
2026-03-31 12:43:34 +08:00
121462c00f feat: 给 PackageUsage 添加 package_name 快照字段,修复企业卡列表 carrier_name/package_name 为空问题
- 迁移 000099:tb_package_usage 新增 package_name 列,回填历史数据
- PackageUsage model 添加 PackageName 字段(与 DataResetCycle 保持一致的快照设计)
- 4 处 PackageUsage 创建点补充 PackageName 快照(order/service.go + auto_purchase.go)
- EnterpriseCard ListCards:carrier_name 直接取 card.CarrierName,package_name 通过
  DISTINCT ON 批量查当前生效主套餐,单次查询覆盖整页,无 N+1
2026-03-31 12:43:07 +08:00
5b283285a2 fix: 修复微信支付容器内 mkdir 权限错误,新增 wechat_v2 支付渠道
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m11s
- NewPaymentAppFromConfig 加 Log.Stdout=true,禁止 PowerWeChat SDK 在容器
  工作目录创建 wechat/ 日志文件夹(Permission denied 根因)
- 新增 ProviderTypeWechatV2 = wechat_v2 常量,与 wechat(v3) 独立区分
- 新增 PaymentV2Service:直连统一下单 v2 接口,XML + MD5 签名
- newPaymentProvider 按 ProviderType 分支路由到对应版本
2026-03-31 12:12:13 +08:00
4e65cf95d1 fix: 修复企业端用户所有接口返回403的问题 — AdminAuth中间件白名单遗漏Enterprise类型
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m15s
2026-03-31 10:41:31 +08:00
2b408230a6 skill
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m0s
2026-03-31 10:00:01 +08:00
48ad0844ae fix: gendocs panic — config.Get() nil 守卫防止未初始化时访问 Logging.Development
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
2026-03-31 09:56:25 +08:00
2ef8b8a705 fix: 修复分页字段/角色DTO/套餐详情/批量分配Bug,新增C端测试登录接口和Hurl价格验证测试
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- 修复B-2:27个分页DTO字段名统一(list→items, page_size→size,删除total_pages)
- 修复B-1:角色接口统一返回DTO(id小写,消除GORM大写字段名)
- 修复C-1:套餐详情接口(GET /packages/:id)补充代理佣金字段
- 修复C-2:批量分配已存在记录由500改为静默跳过
- 修复C-3:创建系列授权响应在事务提交后构建,packages数组不再为空
- 新增C端开发测试登录接口(POST /api/c/v1/auth/dev-login,仅logging.development=true时生效)
- 新增Hurl测试:card-price-verification-flow.hurl(导入卡→分配→C端价格验证)
- 新增测试Excel数据文件和dev.env测试变量
2026-03-31 09:54:08 +08:00
33e7f99fdc fix: 修复数据清理预览接口 panic 及路由文档路径翻倍问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m12s
1. CountOldRecords 改用 GORM .Scan() 替代 .Row().Scan(),避免查询不存在的表时 nil pointer panic
2. polling_cleanup 路由注册的 basePath 参数去掉多余拼接,修复生成的 OpenAPI 文档路径翻倍
2026-03-30 15:09:14 +08:00
06ee422e34 fix: 富友验签失败 — 补全3.3接口所有非reserved字段(空值字段也必须参与签名)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m7s
2026-03-30 13:48:45 +08:00
30d6743310 fix: 富友验签错误 — 签名原文必须包含空值字段(与富友文档签名实例一致)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m9s
2026-03-30 13:21:04 +08:00
a97462dd69 fix: 支付失败时幂等标记未清理导致用户无法重试 — *created=true移到支付成功后
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m9s
2026-03-30 13:06:45 +08:00
d56b841443 fix: 富友回调应答XMLName缺失 + term_ip自动探测服务器IP替代硬编码
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m8s
2026-03-30 12:46:50 +08:00
8296742cce fix: 富友预下单补充必填字段 txn_begin_ts(交易起始时间)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m6s
2026-03-30 12:23:50 +08:00
0c82ae2b73 fix: 修复富友预下单报文格式错(1014) — XML根元素、小程序tradeType、termIP三处问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m27s
2026-03-30 11:57:46 +08:00
f339fb1987 fix: 资产钱包自动创建机制 — 修复C端购买时钱包不存在报错
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m8s
- client_order: 新增 getOrCreateWallet 兜底,钱包不存在时自动创建
- device_import: 设备导入事务内同步创建设备钱包
- iot_card_import: IoT卡批量导入后批量创建卡钱包
- queue/handler: 传递 AssetWalletStore 给两个导入 handler
- migration 000098: 为存量IoT卡和设备补建资产钱包
2026-03-30 11:37:41 +08:00
40809d11c5 修复
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m54s
2026-03-30 10:20:16 +08:00
50dbc52432 fix: C端资产详情设备补充已连接数(client_number)字段
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
Gateway sync-info 返回的 client_number 字段未在整条数据链路中传递,
导致 C 端资产详情的设备实时状态缺少已连接客户端数。

修改范围:
- Gateway 模型 SyncDeviceInfoResp 新增 ClientNumber
- B 端 DTO DeviceGatewayInfo 新增 ClientNumber
- C 端 DTO DeviceRealtimeInfo 新增 ClientNumber
- 两层映射函数同步补充字段传递
2026-03-30 10:18:30 +08:00
cebcada950 refactor: 流量系统重构 — 增量累加算法 + 日粒度缓冲 + 旧详单清理
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m16s
核心改造:
- 增量算法:流量计算从覆盖式改为增量累加(gateway - lastReading),支持上游运营商重置检测
- 日流量缓冲:insertDataUsageRecord 改为 Redis INCRBYFLOAT,每日凌晨落盘到 tb_card_daily_usage
- 运营商:新增 data_reset_day 字段(联通=27,其余=1)
- IoT卡:新增 last_gateway_reading_mb 字段存储上次网关读数
- 查询层:新建 TrafficQueryService 合并 Redis(今日)+ DB(历史)数据源
- 清理:删除 DataUsageRecord model/store,移除 polling_handler 旧引用

迁移:000094-000097(carrier字段、iot_card字段、数据初始化、日流量表)
2026-03-30 09:59:30 +08:00
f5dd2ce4ab fix: Gateway 响应类型兼容 — 新增 FlexBool/FlexInt 处理设备返回的字符串类型字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m4s
部分设备厂商(如华为)的 Gateway 响应中 bool/int 字段返回为字符串(wifi_enabled: "1"、battery_level: "30"),
导致 sonic 严格类型检查反序列化失败,整个设备实时数据丢失。

- 新增 FlexBool 类型:兼容 true/false、"1"/"0"、"true"/"false"
- 新增 FlexInt 类型:兼容 30、"30"、null
- SyncDeviceInfoResp 所有 bool/int 字段改用 Flex 类型
- 更新 B 端和 C 端 DTO 映射函数的类型转换
2026-03-28 18:24:17 +08:00
02b10f87cf feat: 新增退款管理模块 — 完整的退款审批流程、佣金回扣和资产重置
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m8s
新增退款申请全生命周期管理:创建/列表/详情/审批通过/拒绝/退回/重新提交
审批通过后异步执行佣金全额回扣(扣减各代理佣金钱包)和资产重置(套餐失效+停机+世代重置)
新增 tb_refund_request 表(迁移 000093)、RefundRequest Model、8 个 DTO
新增 Store/Service/Handler/路由注册,仅平台用户可访问
2026-03-28 17:57:52 +08:00
5e64c64ce3 修复
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m5s
2026-03-28 17:12:29 +08:00
a2fd1dfd62 fix: 佣金修正接口 DTO 补充 path 参数声明,修复 OpenAPI 生成 panic
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m59s
2026-03-28 17:01:06 +08:00
623a622298 feat: 业务逻辑补全 — 佣金待审记录、C端订单重构、支付抽象、富友支付、卡设备状态联动
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
F-1: 佣金链断裂时创建 status=99 零额待审记录,新增修正接口 POST /commission-records/:id/resolve
F-4: C端订单查询从 Handler 迁移至 Service 层,移除 SkipPermissionCtx
J-1: 富友支付 JSAPI/MiniApp 预下单实现,回调补全签名验证
J-2: 平台钱包代购支持(buyerType 为空时使用资产所属代理钱包)
J-3: 套餐激活后自动更新卡/设备 status=3,最后套餐过期后更新 status=4
支付抽象: 引入 PaymentProvider 接口 + 微信/富友适配器,CreateOrder 支持多支付渠道
修复: 设备/IoT卡响应 DTO 移除 omitempty,空值字段返回 null 而非省略
2026-03-28 16:57:39 +08:00
65e461eff7 fix: 代码质量清理 — 统一C端支付枚举、修复静默错误、注入Worker回调、移除废弃同步代码
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m6s
- C端订单支付状态直接使用管理端统一枚举(1/2/3/4),移除冗余映射函数
- 资产查询绑定卡/套餐查询失败时记录Warn日志而非静默忽略
- Worker bootstrap注入停复机回调(流量耗尽停机、套餐激活复机)
- 删除废弃的SIM状态同步服务和任务处理器
- 新增开发环境数据清理脚本(full/soft/table三种模式)
2026-03-28 15:27:59 +08:00
e81d3a58ad docs(04): capture phase context
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m6s
2026-03-28 14:24:25 +08:00
da8aedc96b docs(phase-03.1): evolve PROJECT.md after phase completion 2026-03-28 13:42:29 +08:00
9995dcd0a3 docs(phase-03.1): complete phase execution 2026-03-28 13:41:26 +08:00
f0f21e52f1 docs: 重新生成 OpenAPI 文档,补全 Phase 03.1 新增字段 2026-03-28 13:32:48 +08:00
a8becf55ff chore: 更新 STATE.md 记录 Phase 03.1 完成 2026-03-28 13:24:39 +08:00
f9da1a937f docs(03.1-01): 完成 Phase 03.1 Plan 01 执行总结
- 创建 03.1-01-SUMMARY.md:记录 3 个任务完成情况、6 个文件修改、SwitchMode 类型偏差修复
- 更新 STATE.md:追加执行日志、补充 B/C 端独立 DTO 结构决策
2026-03-28 13:23:43 +08:00
a202b2da8a feat(03.1-01): 建立设备实时 Gateway 调用链路,替换 mock 数据
- GetRealtimeStatus() device case 新增 Gateway sync-info 实时调用(IMEI/SN 优先,gatewayClient nil 安全)
- 新增 mapSyncRespToDeviceGatewayInfo() 将 SyncDeviceInfoResp 映射为 B 端 DeviceGatewayInfo DTO
- 新增 strPtr() 辅助函数(空字符串→nil,防止 JSON 出现大量空字符串字段)
- client_asset.go 删除 buildMockDeviceRealtime(),改为调用 assetService.GetRealtimeStatus() 获取真实数据
- 新增 mapDeviceGatewayInfoToClientInfo() 将 B 端 DeviceGatewayInfo 映射为 C 端 DeviceRealtimeInfo
- Gateway 调用失败时 DeviceRealtime 返回 null,不阻断主流程
2026-03-28 13:21:02 +08:00
3b54850f1b feat(03.1-01): 修复静态 DTO 映射缺口
- toDeviceResponse() 补全 5 个 DB 缓存字段(OnlineStatus/LastOnlineTime/SoftwareVersion/SwitchMode/LastGatewaySyncAt)
- ListBindings() 补全 IsCurrent 字段映射
- buildDeviceResolveResponse() 补全 isCurrentMap + BoundCardInfo.IsCurrent + 5 个 DB 缓存字段
- GetRealtimeStatus() device case 补全 isCurrentMap + BoundCardInfo.IsCurrent
2026-03-28 13:19:09 +08:00
00dba42a63 feat(03.1-01): 补全 Gateway SyncDeviceInfoResp 缺失字段及 B 端 DeviceGatewayInfo DTO
- SyncDeviceInfoResp 新增 Rsrp/Rsrq/Sinr/WifiPassword/IPAddress/WANIP/LANIP/MaxClients/ConnectTime/Status/IMSI/ULStats/DLStats/LimitSpeed/SyncInterval 共 15 个字段
- asset_dto.go 新增 DeviceGatewayInfo B 端实时状态结构体(49 字段,全部含 description tag)
- AssetRealtimeStatusResponse 新增 DeviceRealtime *DeviceGatewayInfo 字段
- AssetResolveResponse 新增 5 个设备 DB 缓存字段(online_status/last_online_time/software_version/switch_mode/last_gateway_sync_at)
2026-03-28 13:17:52 +08:00
3450c20236 docs(03.1): 创建 Phase 03.1 计划(设备读取链路修复 + DTO 映射补全) 2026-03-28 13:12:42 +08:00
debe8f6edc docs(03.1): 补充 D-12 AssetResolveResponse 5字段扩展决策 2026-03-28 13:04:35 +08:00
d0ef3bb712 修复错误的状态码 2026-03-28 12:54:04 +08:00
8826d95516 docs(state): record phase 03.1 context session 2026-03-28 12:38:15 +08:00
8af5d1a045 docs(03.1): capture phase context 2026-03-28 12:38:02 +08:00
ff62ea457a docs(phase-03): evolve PROJECT.md after phase completion 2026-03-28 11:45:58 +08:00
71b948f22b docs(phase-03): complete phase execution 2026-03-28 11:45:22 +08:00
129a38f942 docs(03-02): 完成设备体系 sync-info 接入计划(DEVICE-04)
- 新增 03-02-SUMMARY.md,记录 updateDeviceFromSyncInfo 实现细节
- STATE.md:Phase 3 完成标记,追加 DEVICE-04 决策,Next Action 更新为 Phase 4
- ROADMAP.md:Phase 3 进度更新为 Complete(2/2 plans)
- REQUIREMENTS.md:DEVICE-04 标记完成
2026-03-28 11:40:04 +08:00
15dbf8dc66 feat(03-02): Asset Service 接入 Gateway sync-info(DEVICE-04)
- Service 结构体新增 gatewayClient 字段,New() 追加 gatewayClient 参数
- Refresh device 分支在绑定卡刷新后调用 SyncDeviceInfo,nil guard + Warn 日志不阻断主流程
- 新增 updateDeviceFromSyncInfo 私有函数:更新 5 个 device 字段 + 调用 UpdateIsCurrentByDeviceID
- bootstrap/services.go asset.New() 调用追加 deps.GatewayClient
- go build ./... 零新增编译错误
2026-03-28 11:38:14 +08:00
ba1886c314 feat(03-02): DeviceSimBindingStore 新增 UpdateIsCurrentByDeviceID 方法
- 事务两步原子更新:先全部清空 is_current=false,再按 ICCID 设 true
- 通过子查询定位 iot_card_id,避免跨表 JOIN 更新
- currentIccid 为空时仅清空,不做第二步设置
2026-03-28 11:36:40 +08:00
8819c94322 docs(03-01): 完成设备体系数据基础层计划
- 创建 03-01-SUMMARY.md
- 更新 STATE.md(进度推进至 Plan 2)
- 更新 ROADMAP.md(Phase 3 进行中)
- 标记 REQUIREMENTS.md(DEVICE-01/02/03 完成)
2026-03-28 11:34:38 +08:00
825def88a4 feat(03-01): Gateway SyncDeviceInfo 方法 + DTO 字段扩展
- gateway/models.go:新增 SyncDeviceInfoReq / SyncDeviceInfoResp 结构定义
- gateway/device.go:新增 SyncDeviceInfo() 方法,POST /device/sync-info
- device_dto.go:DeviceResponse 新增 5 个 sync-info 同步字段;DeviceCardBindingResponse 新增 is_current
- asset_dto.go:BoundCardInfo 新增 is_current 字段
2026-03-28 11:33:01 +08:00
42b884aaf8 feat(03-01): DB 迁移扩展设备字段 + 更新模型
- 新增迁移 000090:tb_device 扩展 5 个 Gateway sync-info 字段(online_status / last_online_time / software_version / switch_mode / last_gateway_sync_at)
- 新增迁移 000091:tb_device_sim_binding 新增 is_current 字段(当前使用卡标识)
- 更新 Device 模型新增对应 5 个字段
- 更新 DeviceSimBinding 模型新增 IsCurrent 字段
2026-03-28 11:31:16 +08:00
8a4c6f3cee docs(03-device-system): 创建 Phase 3 设备体系完善计划(2个Plan) 2026-03-28 11:24:31 +08:00
ce6aa62fd6 docs(03): capture phase context 2026-03-28 11:16:02 +08:00
4ff5dcf55e docs(roadmap): 修复 Phase 2 状态标记 — 勾选复选框、更新 Progress 表格
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m9s
2026-03-28 10:56:21 +08:00
d3eaac0eb0 docs(state): 修复 STATE.md 状态混乱 — 同步至 Phase 2 完成后实际状态 2026-03-28 10:54:53 +08:00
8ace759200 docs(phase-02): evolve PROJECT.md after phase completion — B/C/G/H 方案全部标记 Validated 2026-03-28 10:53:37 +08:00
5432fb0513 docs(phase-02): 完成 Phase 2 执行 PERM/FIN/REALNAME/POLL 14项修复 2026-03-28 10:52:47 +08:00
e1ec024904 docs(02-01): 完成 PERM+FIN+POLL 9项修复计划 PERM-01/02 FIN-01/02/03 POLL-01/02/03/04 2026-03-28 10:46:10 +08:00
754bbcdf3b fix(fin): 同步更新 openapi handlers 中 CommissionWithdrawalHandler 签名
- NewCommissionWithdrawalHandler 新增了 validator 参数,同步更新文档生成器调用处
2026-03-28 10:43:32 +08:00
47aa5f8d25 fix(poll): Series 删除前检查关联套餐 POLL-04
- package_store.go 新增 CountBySeriesID 方法,统计指定系列下的活跃套餐数量
- package_series/service.go Service 注入 packageStore 字段,Delete 前调用 CountBySeriesID 检查
- bootstrap/services.go 更新 PackageSeries 服务初始化,传入 PackageStore
2026-03-28 10:42:58 +08:00
facc766993 docs(02-02): 完成实名激活架构重构计划 REALNAME-01~05
- 新增 02-02-SUMMARY.md
- 更新 STATE.md 进度(plan 2/2)
- 更新 ROADMAP.md 进度
- 标记 REALNAME-01~05 需求完成
2026-03-28 10:42:04 +08:00
8553a46143 fix(poll): GetPackages 接口新增分页 POLL-03
- 新增 AssetPackagesResult DTO(含 total/page/page_size/items 字段)
- GetPackages 签名新增 page/pageSize 参数,默认 page=1、pageSize=50、最大 100
- admin/asset.go:Packages 从 Query 参数读取 page/page_size 传入 Service
- client_asset.go 调用处同步更新,使用默认分页参数
2026-03-28 10:41:20 +08:00
4be473c248 fix(realname): 移除 auto_purchase.go 中废弃的 EnableRealnameActivation 引用
- C 端充值触发的自动购包不需要等实名(前置检查已完成)
- 删除对已废弃 EnableRealnameActivation 字段的引用
2026-03-28 10:40:08 +08:00
8a531237c3 fix(poll): gatewayClient=nil 时停复机返回错误而非成功 POLL-02
- stopCardWithRetry: gatewayClient==nil 时返回业务错误而非 nil(静默跳过会假装停机成功)
- resumeCardWithRetry: 同上修复
2026-03-28 10:39:47 +08:00
922a3d0b49 fix(poll): polling:protect 接入调度器 POLL-01
- processSchedule 中新增 TaskTypePollingProtect 的 processManualQueue 和 processTimedQueue 调用
- 保护期一致性检查任务现在会被定期调度处理
2026-03-28 10:39:18 +08:00
60b43bb29e fix(realname): ActivateByRealname 按 ExpiryBase 选择计时基准 REALNAME-04
- from_purchase:用 PackageUsage.CreatedAt(购买时刻)作为激活时间起点
- from_activation(默认):用实名被触发的当前时刻作为激活时间起点
2026-03-28 10:39:00 +08:00
bdac4ab7b2 fix(fin): 激活配置并发行锁保护 FIN-03
- commission_withdrawal_setting/service.go: 激活事务内首步加 FOR UPDATE 行锁,防止并发时出现多条 is_active=true
- wechat_config_store.go: ActivateInTx 激活前同样加行锁保护
2026-03-28 10:38:53 +08:00
0ebb3d75f3 fix(realname): C 端实名检查改为按卡类型判断 REALNAME-03
- 删除 packagesNeedRealname 函数(依赖已废弃的 EnableRealnameActivation)
- 改为按 assetInfo.CardCategory==normal 判断是否需要实名
- 行业卡(industry)绕过实名检查,普通卡(normal)需要实名
2026-03-28 10:38:44 +08:00
7dd55630dc fix(realname): activateMainPackage 三维决策重构 REALNAME-02
- 替换 EnableRealnameActivation 布尔判断为三维决策逻辑
- 行业卡(card_category=industry)永远直接激活
- C 端购买(BuyerTypePersonal)前置实名检查已完成,直接激活
- 后台囤货按 ExpiryBase 决定:from_activation 等实名,from_purchase 立即激活
2026-03-28 10:38:24 +08:00
9ee2f0b466 fix(fin): 提现拒绝补 remark 必填校验 FIN-02
- CommissionWithdrawalHandler 新增 validator 字段
- RejectWithdrawal 在 BodyParser 后补充 validator.Struct 参数验证,确保 remark 必填
2026-03-28 10:37:54 +08:00
244a2742c1 fix(realname): DTO 更新 expiry_base 替换 enable_realname_activation REALNAME-05
- package_dto.go: CreatePackageRequest/UpdatePackageRequest/PackageResponse 三处替换
- service.go: 同步更新 DTO 映射逻辑使用 ExpiryBase
2026-03-28 10:37:51 +08:00
8f62496250 fix(fin): 补全提现审批人字段 FIN-01
- Approve updates map 补充 approved_by 和 approved_at 字段,确保审批人信息正确填充
2026-03-28 10:36:33 +08:00
344850fe1d fix(realname): DB 迁移 + Model + Store 清理 REALNAME-01
- 新增迁移 000089: 移除 enable_realname_activation,添加 expiry_base 字段
- package.go: 删除 EnableRealnameActivation 字段,新增 ExpiryBase 字段
- package_store.go: 移除两步写入特殊处理,改为直接一步 Create
2026-03-28 10:36:31 +08:00
2a92ab64af fix(perm): 修复企业账号资产权限边界 PERM-01/02
- PERM-01: 删除 Resolve 接口对企业账号的错误拦截(企业账号应可查询资产)
- PERM-02: 在 Refresh 接口开头新增企业账号拦截(企业账号只读,不允许主动触发运营商刷新)
2026-03-28 10:36:17 +08:00
62eb43a1cf docs(02-perm-fin-realname-poll): 创建 Phase 2 执行计划(2 个 Plan) 2026-03-28 10:29:50 +08:00
84aca2fd63 docs(02): capture phase context 2026-03-28 10:11:04 +08:00
c083596ef6 docs(phase-01): evolve PROJECT.md after phase completion — move CRITICAL-01~08 to Validated
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m18s
2026-03-28 09:49:15 +08:00
fb14c51fc2 docs(phase-01): complete phase execution — verification passed, all CRITICAL-01~08 satisfied 2026-03-28 09:47:54 +08:00
dbeed92ed9 docs(01-03): 完成充值回调自动购包链路修复 Plan 执行总结
- 创建 01-03-SUMMARY.md(CRITICAL-04 + CRITICAL-05 修复记录)
- 更新 STATE.md(Plan 计数推进至 4/5,progress 100%)
- 更新 ROADMAP.md(Phase 1 进度更新)
- 标记 CRITICAL-04、CRITICAL-05 需求已完成
2026-03-27 23:33:47 +08:00
030425be33 feat(01-03): AutoPurchaseHandler 注入 asynqClient,触发佣金并注册处理器(CRITICAL-04/05)
- AutoPurchaseHandler struct 新增 asynqClient *asynq.Client 字段
- NewAutoPurchaseHandler() 新增 asynqClient 参数
- ProcessTask 事务成功后入队 TaskTypeCommission(事务外,防止一致性问题)
- pkg/queue/handler.go 新增 registerAutoPurchaseHandler() 方法
- RegisterHandlers() 调用 registerAutoPurchaseHandler()
2026-03-27 23:31:49 +08:00
0ed804c4b3 docs(01-02): 完成 PollingHandler 注入 asynq.Client 修复断链计划摘要 2026-03-27 23:30:47 +08:00
20b4b6d6bf fix(01-02): 修复实名激活任务断链,为 PollingHandler 注入 asynq.Client
- PollingHandler struct 新增 asynqClient *asynq.Client 字段
- NewPollingHandler 构造函数新增 asynqClient 参数(redis 之后,gatewayClient 之前)
- triggerFirstRealnameActivation 改用 asynqClient.EnqueueContext,删除 RPush 降级方案
- 删除 _ = task 废弃代码
- registerPollingHandlers 传入 h.asynqClient 参数
2026-03-27 23:29:12 +08:00
9a4d87a0d4 feat(01-03): 充值回调触发自动购包任务入队(CRITICAL-04)
- recharge.Service struct 新增 queueClient *queue.Client 字段
- recharge.New() 新增 queueClient 参数
- HandlePaymentCallback 事务成功后,LinkedPackageIDs 非空时入队 TaskTypeAutoPurchaseAfterRecharge
- bootstrap/services.go 的 recharge.New() 传入 deps.QueueClient
2026-03-27 23:29:05 +08:00
0df992c98a docs(01-04): 完成 sellerCostPrice CRITICAL-06 修正计划摘要 2026-03-27 23:25:48 +08:00
f74b7da25f fix(01-04): 修正场景5代理代购下级的sellerCostPrice赋值
- 三处代理代购下级分支(wallet场景子场景2.2)均将 sellerCostPrice = buyerCostPrice 改为 sellerCostPrice = operatorCostPrice
- buyerCostPrice 是下级成本价,operatorCostPrice 是操作方(代理自己)的成本价
- 使用 buyerCostPrice 会导致佣金差额为 0,所有上级代理无法获得应有佣金
- 修复涉及三个函数(普通下单/后台下单/H5下单),行号分别约在 264/551/813
2026-03-27 23:24:16 +08:00
6de830fcc4 docs(01-01): 完成实名状态常量统一计划执行总结
- 创建 01-01-SUMMARY.md(CRITICAL-01 + CRITICAL-02 完成)
- STATE.md: 更新进度至 Plan 3/5,记录执行指标
- ROADMAP.md: 更新 Phase 1 计划进度(2/5 完成)
- REQUIREMENTS.md: 标记 CRITICAL-01、CRITICAL-02 已完成
2026-03-27 22:58:05 +08:00
da50a35a62 fix(01-01): 修复 C 端实名校验使用常量(CRITICAL-02)
- client_order/service.go: 实名校验 assetInfo.RealNameStatus != 1 改为常量比较
- client_realname.go: 实名状态检查 == 1 改为 constants.RealNameStatusVerified
- go build ./... 编译通过,无遗留硬编码 != 1 / == 1 的实名判断
2026-03-27 22:54:50 +08:00
1fd0072f69 fix(01-01): 统一实名状态常量(CRITICAL-01 核心)
- polling_handler.go: parseRealnameStatus 不再返回硬编码 2,改为 constants.RealNameStatusVerified(=1)
- polling_handler.go: isFirstRealname 判断改用常量比较,不再使用 == 2
- polling_handler.go: HandleProtectConsistencyCheck 注释更正为 real_name_status=1
- iot_card.go: RealNameStatus gorm comment 统一为 0-未实名 1-已实名(去除行业卡说明)
- asset_dto.go: RealNameStatus description 更正为 0未实名 1已实名(去除错误的 1实名中 2已实名)
- scheduler.go: getCardCondition 改用常量替代硬编码 0/1/2 判断
- iot_card/service.go: parseGatewayRealnameStatus 注释更正,返回值改为常量
2026-03-27 22:53:30 +08:00
bfcea1c18f docs(01-05): 完成 Plan 05 执行摘要,更新 STATE/ROADMAP/REQUIREMENTS
- 创建 01-05-SUMMARY.md(CRITICAL-07 + CRITICAL-08 修复记录)
- STATE.md 进度推进至 plan 2/5(20%)
- ROADMAP.md 更新 Phase 1 进度(1/5 SUMMARY 已完成)
- REQUIREMENTS.md 标记 CRITICAL-07、CRITICAL-08 为完成
2026-03-27 22:52:27 +08:00
db166807c7 fix(01-05): 提现冻结并发校验缺失(CRITICAL-08)
- 冻结余额改为 result := tx...Updates(),分离结果对象
- 检查 result.Error 处理数据库错误
- 检查 result.RowsAffected == 0 防止并发余额不足时仍创建提现单
- RowsAffected == 0 时返回 errors.New(CodeInsufficientBalance, ...)
2026-03-27 22:50:18 +08:00
809cb2b8a8 fix(01-05): 设备导入补充 IMEI 字段(CRITICAL-07)
- DeviceRow struct 新增 IMEI string 字段
- buildDeviceColumnIndex 支持 imei/设备imei/imei号 列名映射
- ParseDeviceExcel 解析数据行时填充 row.IMEI
- device_import.go processBatch 创建 model.Device 时赋值 IMEI: row.IMEI
2026-03-27 22:49:40 +08:00
f48f11beb4 docs(01-p0): 创建 Phase 1 P0 紧急修复执行计划(5 个 Plan,涵盖 CRITICAL-01~08) 2026-03-27 22:35:28 +08:00
5862018e7c docs(01): capture phase context 2026-03-27 21:52:09 +08:00
dc9bf0c9b7 docs: create roadmap (6 phases) 2026-03-27 20:18:06 +08:00
7f2e978288 docs: define v1 requirements 2026-03-27 19:07:58 +08:00
3078bc71c8 docs: add research findings 2026-03-27 19:04:17 +08:00
cf59380784 docs: initialize project 2026-03-27 18:50:18 +08:00
876151ec1c 修复
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m22s
2026-03-23 09:49:30 +08:00
c10b70757f fix: 资产信息接口 device_realtime 字段返回固定假数据,避免前端因 nil 报错
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m58s
Gateway 同步接口尚未对接,临时为设备类型资产返回 mock 数据,
后续对接后搜索 buildMockDeviceRealtime 替换为真实数据
2026-03-21 14:42:48 +08:00
4d1e714366 fix: 补齐迁移 000076 遗漏的列名重命名(card_wallet_id → asset_wallet_id)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m52s
迁移 000076 只将表名从 card_wallet 改为 asset_wallet,但遗漏了表内
card_wallet_id 列的重命名,导致 Model 中 column:asset_wallet_id 与数据库
实际列名不匹配,所有涉及该字段的 INSERT/SELECT 均报错 2002。

影响范围:
- tb_asset_recharge_record.card_wallet_id → asset_wallet_id
- tb_asset_wallet_transaction.card_wallet_id → asset_wallet_id
2026-03-21 14:30:29 +08:00
d2b765327c 完整的字段返回
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m52s
2026-03-21 13:41:44 +08:00
7dfcf41b41 fix: 修复卡类型资产绑定键错误导致归属校验永远失败
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m48s
resolveAssetBindingKey 对卡类型错误地返回 card.ICCID 作为绑定键,
但归属校验 isCustomerOwnAsset 使用 card.VirtualNo 比对,二者不一致
导致所有卡资产的 C 端接口返回 403 无权限。

修复:卡类型绑定键改为 card.VirtualNo,与设计文档一致。
附带数据迁移修正已有的错误绑定记录。
2026-03-21 11:33:57 +08:00
ed334b946b refactor: 清理重构遗留的死代码
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- personal_customer.Service: 删除已迁移到 client_auth 的死方法
  (GetProfile/SendVerificationCode/VerifyCode),移除多余的
  verificationService/jwtManager 依赖
- 删除 internal/service/customer/ 整个目录(零引用的早期残留)
2026-03-21 11:33:06 +08:00
95b2334658 feat: 资产套餐历史接口新增 package_type 和 status 筛选条件
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m10s
GET /api/c/v1/asset/package-history 支持可选参数:
- package_type: formal(正式套餐) / addon(加油包)
- status: 0(待生效) / 1(生效中) / 2(已用完) / 3(已过期) / 4(已失效)
不传则返回全部,保持向后兼容。
2026-03-21 11:01:21 +08:00
da66e673fe feat: 接入短信服务,修复 SMS 客户端 API 路径
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- cmd/api/main.go: 新增 initSMS() 初始化短信客户端并注入 verificationService
- pkg/sms/client.go: 修复 API 路径缺少 /sms 前缀(/api/... → /sms/api/...)
- docker-compose.prod.yml: 添加线上短信服务环境变量
2026-03-21 10:51:43 +08:00
284f6c15c7 fix: 修复个人客户设备绑定查询使用已废弃的 device_no 列名
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m4s
数据库列已重命名为 virtual_no,但 Store 层 3 处原始 SQL 仍使用旧列名 device_no,
导致小程序登录时查询客户资产绑定关系报 column device_no does not exist。
2026-03-20 18:20:24 +08:00
55918a0b88 fix: 修复 C 端公开路由被认证中间件拦截的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m51s
Fiber 的 Group.Use() 在路由表中注册全局 USE 处理器,不区分 Group 对象。
原代码先调用 authProtectedGroup.Use() 再注册公开路由,导致 verify-asset、
wechat-login、miniapp-login、send-code 四个无需认证的接口被拦截返回 1004。

修复方式:公开路由直接注册在 router 上且在任何 Use() 之前,
利用 Fiber 按注册顺序匹配的机制确保公开路由优先命中。
2026-03-20 18:01:12 +08:00
d2494798aa fix: 修正停复机接口错误码,网关失败不再返回模糊的内部服务器错误
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m13s
- 单卡停复机:网关错误从 CodeInternalError(2001) 改为 CodeGatewayError(1110),前端可看到具体失败原因
- 单卡停复机:DB 更新裸返 GORM error 改为 CodeDatabaseError(2002) 包装
- 设备复机:全部卡失败时错误码从 CodeInternalError 改为 CodeGatewayError
2026-03-19 18:37:03 +08:00
b9733c4913 fix: 修正零售价架构错误 + 清理旧微信配置 + 归档提案 + 前端接口文档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m12s
1. 修正 retail_price 架构:
   - 删除 batch-pricing 接口的 pricing_target 字段和 retail_price 分支
     (上级只能改下级成本价,不能改零售价)
   - 新增 PATCH /api/admin/packages/:id/retail-price 接口
     (代理自己改自己的零售价,校验 retail_price >= cost_price)

2. 清理旧微信 YAML 配置(已全部迁移到数据库 tb_wechat_config):
   - 删除 config.yaml 中 wechat.official_account 配置节
   - 删除 NewOfficialAccountApp() 旧工厂函数
   - 清理 personal_customer service 中的死代码(旧登录/绑定微信方法)
   - 清理 docker-compose.prod.yml 中旧微信环境变量和证书挂载注释

3. 归档四个已完成提案到 openspec/changes/archive/

4. 新增前端接口变更说明文档(docs/前端接口变更说明.md)

5. 修正归档提案和 specs 中关于 pricing_target 的错误描述
2026-03-19 17:39:43 +08:00
9bd55a1695 feat: 实现客户端核心业务接口(client-core-business-api)
新增客户端资产、钱包、订单、实名、设备管理等核心业务 Handler 与 DTO:
- 客户端资产信息查询、套餐列表、套餐历史、资产刷新
- 客户端钱包详情、流水、充值校验、充值订单、充值记录
- 客户端订单创建、列表、详情
- 客户端实名认证链接获取
- 客户端设备卡列表、重启、恢复出厂、WiFi配置、切卡
- 客户端订单服务(含微信/支付宝支付流程)
- 强充自动代购异步任务处理
- 数据库迁移 000084:充值记录增加自动代购状态字段
2026-03-19 13:28:04 +08:00
e78f5794b9 feat: 实现客户端换货系统(client-exchange-system)
新增完整换货生命周期管理:后台发起 → 客户端填收货信息 → 后台发货 → 确认完成(含可选全量迁移) → 旧资产转新再销售

后台接口(7个):
- POST /api/admin/exchanges(发起换货)
- GET /api/admin/exchanges(换货列表)
- GET /api/admin/exchanges/:id(换货详情)
- POST /api/admin/exchanges/:id/ship(发货)
- POST /api/admin/exchanges/:id/complete(确认完成+可选迁移)
- POST /api/admin/exchanges/:id/cancel(取消)
- POST /api/admin/exchanges/:id/renew(旧资产转新)

客户端接口(2个):
- GET /api/c/v1/exchange/pending(查询换货通知)
- POST /api/c/v1/exchange/:id/shipping-info(填写收货信息)

核心能力:
- ExchangeOrder 模型与状态机(1待填写→2待发货→3已发货→4已完成,1/2可取消→5)
- 全量迁移事务(11张表:钱包、套餐、标签、客户绑定等)
- 旧资产转新(generation+1、状态重置、新钱包、历史隔离)
- 旧 CardReplacementRecord 表改名为 legacy,is_replaced 过滤改为查新表
- 数据库迁移:000085 新建 tb_exchange_order,000086 旧表改名
2026-03-19 13:26:54 +08:00
df76e33105 feat: 实现 C 端完整认证系统(client-auth-system)
实现面向个人客户的 7 个认证接口(A1-A7),覆盖资产验证、
微信公众号/小程序登录、手机号绑定/换绑、退出登录完整流程。

主要变更:
- 新增 PersonalCustomerOpenID 模型,支持多 AppID 多 OpenID 管理
- 实现有状态 JWT(JWT + Redis 双重校验),支持服务端主动失效
- 扩展微信 SDK:小程序 Code2Session + 3 个 DB 动态工厂函数
- 实现 A1 资产验证 IP 限流(30/min)和 A4 三层验证码限流
- 新增 7 个错误码(1180-1186)和 6 个 Redis Key 函数
- 注册 /api/c/v1/auth/* 下 7 个端点并更新 OpenAPI 文档
- 数据库迁移 000083:新建 tb_personal_customer_openid 表
2026-03-19 11:33:41 +08:00
ec86dbf463 feat: 客户端接口数据模型基础准备
- 新增资产状态、订单来源、操作人类型、实名链接类型常量
- 8个模型新增字段(asset_status/generation/source/retail_price等)
- 数据库迁移000082:7张表15+字段,含存量retail_price回填
- BUG-1修复:代理零售价渠道隔离,cost_price分配锁定
- BUG-2修复:一次性佣金仅客户端订单触发
- BUG-4修复:充值回调Store操作纳入事务
- 新增资产手动停用接口(PATCH /iot-cards/:id/deactivate、/devices/:id/deactivate)
- Carrier管理新增实名链接配置
- 后台订单generation写时快照
- BatchUpdatePricing支持retail_price调价目标
- 清理全部H5旧接口和个人客户旧登录方法
2026-03-19 10:56:50 +08:00
817d0d6e04 更新openspec
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 46s
2026-03-17 14:22:01 +08:00
b44363b335 fix: 修复新建店铺未初始化代理钱包导致充值订单报错
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m6s
新建店铺时在 shop.Service.Create() 中自动初始化主钱包(main)和分佣钱包(commission),修复充值订单创建时「目标店铺主钱包不存在」错误

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-17 14:08:26 +08:00
3e8f613475 fix: 修复 OpenAPI 文档生成器启动 panic,路由缺少 path parameter 定义
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m2s
- 新增 UpdateWechatConfigParams/AgentOfflinePayParams 聚合结构体,嵌入 IDReq 提供 path:id 标签
- 修复 PUT /:id 和 POST /:id/offline-pay 路由的 Input 引用
- 修复 Makefile 构建路径从单文件改为包路径,解决多文件编译问题
- 标记 tasks.md 中 1.2.4 迁移任务为已完成
2026-03-17 09:45:51 +08:00
242e0b1f40 docs: 更新 AGENTS.md 和 CLAUDE.md
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 6m28s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:31:07 +08:00
060d8fd65e docs: 新增微信参数配置管理和代理预充值功能总结文档
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:30:56 +08:00
f3297f0529 docs: 归档 asset-wallet-interface OpenSpec 提案,更新卡钱包 spec
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:30:48 +08:00
63ca12393b docs: 新增 OpenSpec 提案 add-payment-config-management
包含 proposal.md、design.md、tasks.md 及各模块 spec 文件(微信配置管理、富友支付、代理充值、订单支付、资产充值适配、微信支付留桩)

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:30:39 +08:00
429edf0d19 refactor: 注册微信配置和代理充值模块到 Bootstrap 和 OpenAPI 文档生成器
- bootstrap/types.go: 新增 WechatConfigStore/WechatConfigService/WechatConfigHandler/AgentRechargeService/AgentRechargeHandler 字段
- bootstrap/stores.go: 初始化 WechatConfigStore
- bootstrap/services.go: 初始化 WechatConfigService(注入 AuditService)和 AgentRechargeService
- bootstrap/handlers.go: 初始化 WechatConfigHandler 和 AgentRechargeHandler;PaymentHandler 新增 agentRechargeService 参数
- bootstrap/worker_services.go: 补充 WechatConfigService 注入
- routes/admin.go: 注册 WechatConfig 和 AgentRecharge 路由组
- openapi/handlers.go: 注册 WechatConfigHandler 和 AgentRechargeHandler 到文档生成器

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:30:30 +08:00
7c64e433e8 feat: 改造支付回调 Handler,支持富友回调和多订单类型按前缀分发
- payment.go: WechatPayCallback 改造为按订单号前缀分发(ORD→套餐订单、CRCH→资产充值、ARCH→代理充值);新增 FuiouPayCallback(GBK→UTF-8+XML解析+验签+分发);修复 RechargeOrderPrefix 废弃引用
- order.go: 注册 POST /api/callback/fuiou-pay 路由(无需认证)

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:30:17 +08:00
269769bfe4 refactor: 改造订单和资产充值 Service,支持动态支付配置
- order/service.go: 注入 wechatConfigService,CreateH5Order/CreateAdminOrder 下单时查询 active 配置并记录 payment_config_id;无配置时拒绝第三方支付;WechatPayJSAPI/WechatPayH5/FuiouPayJSAPI/FuiouPayMiniApp 添加 TODO 留桩
- recharge/service.go: Create 方法记录 payment_config_id,HandlePaymentCallback 留桩

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:30:05 +08:00
1980c846f2 feat: 订单/资产充值/代理充值模型新增 PaymentConfigID 字段
- order.go: Order 模型新增 PaymentConfigID *uint(记录下单时使用的支付配置)
- asset_wallet.go: AssetRechargeRecord 新增 PaymentConfigID *uint
- agent_wallet.go: AgentRechargeRecord 新增 PaymentConfigID *uint
配置切换时旧订单仍按 payment_config_id 加载对应配置验签,解决竞态问题

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:29:52 +08:00
89f9875a97 feat: 新增代理预充值模块(DTO、Service、Handler、路由)
- agent_recharge_dto.go: 创建/列表/详情请求响应 DTO
- service.go: 权限验证(代理只能充自己店铺)、金额范围校验、查询 active 配置、创建订单、线下充值确认(乐观锁+审计日志)、回调幂等处理
- agent_recharge.go Handler: Create/List/Get/OfflinePay 共 4 个方法
- agent_recharge.go 路由: 注册到 /api/admin/agent-recharges/*,路由层拦截企业账号

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:29:42 +08:00
30c56e66dd feat: 新增微信参数配置管理 Handler 和路由(仅平台账号可访问)
- wechat_config.go Handler: Create/List/Get/Update/Delete/Activate/Deactivate/GetActive 共 8 个方法
- wechat_config.go 路由: 注册到 /api/admin/wechat-configs/*,路由层限制平台账号权限

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:29:31 +08:00
c86afbfa8f feat: 新增微信参数配置模块(Model、DTO、Store、Service)
- wechat_config.go: WechatConfig GORM 模型,含 ProviderTypeWechat/Fuiou 常量
- wechat_config_dto.go: Create/Update/List 请求 DTO,响应 DTO 含脱敏逻辑
- wechat_config_store.go: CRUD、GetActive、ActivateInTx(事务内唯一激活)、软删除保护查询
- service.go: 业务逻辑,按渠道校验必填字段、Redis 缓存管理(wechat:config:active)、删除保护、审计日志

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:29:11 +08:00
aa41a5ed5e feat: 新增支付配置管理相关数据库迁移(000078-000081)
- 000078: 创建 tb_wechat_config 表(支持微信直连和富友双渠道,含软删除)
- 000079: tb_order 新增 payment_config_id 字段(nullable,记录下单时使用的配置)
- 000080: tb_asset_recharge_record 新增 payment_config_id 字段
- 000081: tb_agent_recharge_record 新增 payment_config_id 字段

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:28:57 +08:00
a308ee228b feat: 新增富友支付 SDK(RSA 签名、GBK 编解码、XML 协议、回调验签)
- pkg/fuiou/types.go: WxPreCreateRequest/Response、NotifyRequest 等 XML 结构体
- pkg/fuiou/client.go: Client 结构体、NewClient、字典序+GBK+MD5+RSA 签名/验签、HTTP 请求
- pkg/fuiou/wxprecreate.go: WxPreCreate 方法,支持公众号 JSAPI(JSAPI)和小程序(LETPAY)
- pkg/fuiou/notify.go: VerifyNotify(GBK→UTF-8+XML 解析+RSA 验签)、BuildNotifyResponse

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:28:42 +08:00
b0da71bd25 refactor: 清理 YAML 支付配置遗留代码,重命名 Card* 常量为 Asset*,新增支付配置相关错误码
- 删除 PaymentConfig 结构体和 WechatConfig.Payment 字段(YAML 方案已废弃)
- 删除 wechat.payment 配置节和 NewPaymentApp() 函数
- 删除 validateWechatConfig 中所有 wechatCfg.Payment.* 校验代码
- pkg/constants/wallet.go: Card* 前缀统一重命名为 Asset*,旧名保留废弃别名
- pkg/constants/redis.go: 新增 RedisWechatConfigActiveKey()
- pkg/errors/codes.go: 新增错误码 1170-1175
- go.mod: 新增 golang.org/x/text 依赖(富友支付 GBK 编解码)

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 23:28:29 +08:00
7f18765911 fix: IoT 卡列表查询补充 virtual_no 字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m58s
standaloneListColumns 是为性能优化而手写的列选择列表,
virtual_no 字段新增时只加了 model 和 DTO,遗漏了这里,
导致四条列表查询路径均未 SELECT virtual_no,字段始终为空。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 16:48:45 +08:00
876c92095c fix: 平台账号后台创建钱包订单时,绕过代理套餐分配检查
后台钱包支付下单时,原逻辑根据卡/设备所属代理店铺触发
套餐分配上架校验,导致平台账号无法为属于代理的卡购买
未被该代理分配的套餐(如 0 元赠送套餐)。

修复:在 CreateAdminOrder wallet 分支中,按买家类型区分:
- 代理账号:保留原有校验,确保卡所属代理已分配该套餐
- 平台/超管账号:跳过代理分配检查,仅验证套餐全局状态

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 15:51:01 +08:00
e45610661e docs: 更新 admin OpenAPI 文档,新增 asset_wallet 接口定义
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m57s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:44:02 +08:00
d85d7bffd6 refactor: 更新路由和 OpenAPI 注册以接入 AssetWallet
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:43:55 +08:00
fe77d9ca72 refactor: 注册 AssetWallet 组件到 Bootstrap
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:43:49 +08:00
9b83f92fb6 feat: 新增 AssetWallet Handler,实现资产钱包 API 接口
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:43:42 +08:00
2248558bd3 refactor: 适配 asset_wallet 更名,更新订单、充值和购买验证服务
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:43:37 +08:00
2aae31ac5f feat: 新增 AssetWallet Service,实现资产钱包业务逻辑
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:43:29 +08:00
5031bf15b9 refactor: 更新 wallet 常量和队列类型以适配 asset_wallet
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:43:22 +08:00
9c768e0719 refactor: 重命名 card_wallet store 为 asset_wallet,新增 transaction store
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:43:17 +08:00
b6c379265d refactor: 重命名 CardWallet 模型为 AssetWallet,新增 DTO
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:43:11 +08:00
4156bfc9dd feat: 新增 asset_wallet 和 reference_no 数据库迁移
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 15:42:52 +08:00
0ef136f008 fix: 修复资产套餐列表时间字段返回异常时区偏移问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m54s
待生效套餐的 activated_at/expires_at 在 DB 中存储为零值(0001-01-01),
Go 序列化时因 Asia/Shanghai 历史 LMT(+08:05:36)导致输出异常时区偏移。

- AssetPackageResponse.ActivatedAt/ExpiresAt 改为 *time.Time + omitempty
- 新增 nonZeroTimePtr 辅助函数,零值时间转 nil,避免序列化问题
- 同步修复 GetPackages 和 GetCurrentPackage 两处赋值

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 11:42:39 +08:00
b1d6355a7d fix: resolve 接口 series_name 永远为空,asset service 注入套餐系列 store
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m58s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 10:59:29 +08:00
907e500ffb 修复列表没有正确返回新增字段问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m58s
2026-03-16 10:51:15 +08:00
275debdd38 fix: IoT 卡列表补充 virtual_no 字段和查询过滤,修正设备/卡导入 API 文档描述
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-16 10:44:38 +08:00
b9c3875c08 feat: 新增数据库迁移,重命名 device_no 为 virtual_no,新增 iot_card.virtual_no 和 package.virtual_ratio 字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m3s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-14 18:27:28 +08:00
b5147d1acb 设备的部分改造
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m34s
2026-03-10 10:34:08 +08:00
86f8d0b644 fix: 适配 Gateway 响应模型变更,更新轮询处理器和 Mock 服务
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m25s
- polling_handler: Status→RealStatus, UsedFlow→Used, parseRealnameStatus 参数改为 bool
- mock_gateway: 同步接口路径和响应结构与上游文档一致
2026-03-07 11:29:40 +08:00
a83dca2eb2 fix: 修复 Gateway 流量卡接口路径、响应模型和时间戳与上游文档不一致
- 时间戳从 UnixMilli (13位) 改为 Unix (10位秒级)
- 实名状态接口路径 /realname-status → /realName
- 实名链接接口路径 /realname-link → /RealNameVerification
- RealnameStatusResp: status string → realStatus bool + iccid
- FlowUsageResp: usedFlow int64 → used float64 + iccid
- RealnameLinkResp: link → url
2026-03-07 11:29:34 +08:00
51ee38bc2e 使用超级管理员权限去访问gateway
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m44s
2026-03-07 11:10:22 +08:00
9417179161 fix: 修复设备限速和切卡接口请求字段解析错误
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m15s
SetSpeedLimit 和 SwitchCard 的 Handler 直接解析 gateway 结构体(驼峰命名),
导致与 OpenAPI 文档(DTO 蛇形命名)不一致,前端按文档调用时参数被静默丢弃。

改为先解析 DTO,再手动映射到 gateway 结构体,使文档与实际行为一致。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 18:16:10 +08:00
b52cb9a078 fix: 修复梯度佣金档位字段缺失,补全授权接口响应字段及强充有效状态
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m27s
- OneTimeCommissionTierDTO 补充 operator 字段映射
- GrantCommissionTierItem 补充 dimension/stat_scope 字段(从全局配置合并)
- 系列授权列表/详情补充强充锁定状态和强充金额的有效值计算
- 同步 OpenSpec 主规范并归档变更文档
2026-03-05 11:23:28 +08:00
de9eacd273 chore: 新增 systematic-debugging 技能,更新项目开发规范
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m27s
新增 systematic-debugging Skill(四阶段根因分析流程),在 AGENTS.md 和 CLAUDE.md 中补充触发条件说明。opencode.json 配置同步更新。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:38:01 +08:00
f40abaf93c docs: 同步 OpenSpec 主规范,新增系列授权 capability 并更新强充预检规范
三个 capability 同步:
- agent-series-grant(新建):定义系列授权 CRUD,覆盖固定/梯度佣金模式和强充层级场景
- force-recharge-check(更新):新增「代理层强充层级判断」Requirement,更新钱包充值和套餐购买预检场景以反映平台/代理层级规则
- shop-series-allocation(更新):在 REMOVED 区域追加三个已废弃接口的文档说明(/shop-series-allocations、/shop-package-allocations、enable_one_time_commission 等字段)

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:37:46 +08:00
e0cb4498e6 docs: 归档 refactor-agent-series-grant 变更文档
将已完成的变更(proposal、design、tasks、delta specs)归档至 openspec/changes/archive/2026-03-04-refactor-agent-series-grant/。变更内容:合并系列分配和套餐分配为系列授权(Grant)、新增梯度佣金模式、新增代理层强充层级规则。50/50 任务全部完成。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:37:33 +08:00
c7b8ecfebf refactor: 佣金计算适配梯度阶梯 Operator 比较,套餐服务集成代理强充逻辑
commission_calculation: matchOneTimeCommissionTier() 接收 agentTiers 参数,根据 tier.Operator(>、>=、<、<=,默认 >=)执行对应比较逻辑,支持代理专属梯度阶梯计算。package/service: 套餐购买预检调用更新后的强充层级判断接口。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:37:02 +08:00
2ca33b7172 fix: 强充预检按平台/代理层级判断,代理自设强充在平台未设时生效
checkForceRechargeRequirement() 新增层级逻辑:平台(PackageSeries)的强充配置具有最高优先级;平台未设强充时,读取 order.SellerShopID 对应的 ShopSeriesAllocation 强充配置;两者均未设时返回 need_force_recharge=false(降级处理)。GetPurchaseCheck 复用同一函数,无需额外修改。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:36:49 +08:00
769f6b8709 refactor: 更新路由总线和 OpenAPI 文档注册
admin.go 删除 registerShopSeriesAllocationRoutes、registerShopPackageAllocationRoutes 两处调用,注册 registerShopSeriesGrantRoutes。OpenAPI handlers.go 同步移除旧 Handler 引用,注册 ShopSeriesGrant Handler 供文档生成器使用。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:36:39 +08:00
dd68d0a62b refactor: 更新 Bootstrap 注册,移除旧分配服务,接入系列授权
Types、Services、Handlers 三个文件同步:删除 ShopSeriesAllocation 和 ShopPackageAllocation 的 Handler/Service 字段及初始化逻辑,注册新的 ShopSeriesGrant Handler 和 Service。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:36:30 +08:00
c5018f110f feat: 新增系列授权 Handler 和路由(/shop-series-grants)
Handler 实现 POST /shop-series-grants(创建)、GET /shop-series-grants(列表)、GET /shop-series-grants/:id(详情)、PUT /shop-series-grants/:id(更新佣金和强充配置)、PUT /shop-series-grants/:id/packages(管理授权内套餐)、DELETE /shop-series-grants/:id(删除)六个接口。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:36:20 +08:00
ad3a7a770a feat: 新增系列授权 Service,支持固定/梯度佣金模式和代理自设强充
实现 /shop-series-grants 全套业务逻辑:
- 创建授权(固定/梯度模式):原子性创建 ShopSeriesAllocation + ShopPackageAllocation;校验分配者天花板和阶梯阈值匹配;平台创建无天花板限制
- 强充层级:首次充值类型由平台锁定;累计充值类型平台已设时代理配置被忽略,平台未设时代理可自设
- 查询(列表/详情):聚合套餐列表,梯度模式从 PackageSeries 读取 operator 合并响应
- 更新佣金和强充配置;套餐增删改(事务保证)
- 删除:有下级依赖时禁止删除

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:36:09 +08:00
beed9d25e0 refactor: 删除旧套餐系列分配和套餐分配 Service
业务逻辑已全部迁移至 shop_series_grant/service.go,旧 Service 层完整删除。底层 Store(shop_series_allocation_store、shop_package_allocation_store)保留,仍被佣金计算、订单服务和 Grant Service 使用。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:35:56 +08:00
163d01dae5 refactor: 删除旧套餐系列/套餐分配 Handler 和路由
/shop-series-allocations 和 /shop-package-allocations 接口已被 /shop-series-grants 完全替代,开发阶段干净删除,不保留兼容接口。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:35:46 +08:00
e7d52db270 refactor: 新增系列授权 DTO,删除旧套餐/系列分配 DTO
新增 ShopSeriesGrantDTO(含 packages 列表聚合视图)、CreateShopSeriesGrantRequest(支持固定/梯度模式及强充配置)、UpdateShopSeriesGrantRequest、ManageGrantPackagesRequest 等请求/响应结构。删除已被 Grant 接口取代的 ShopSeriesAllocationDTO 和 ShopPackageAllocationDTO。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:35:38 +08:00
672274f9fd refactor: 更新套餐系列分配和套餐模型,支持梯度佣金和代理强充
ShopSeriesAllocation 新增 commission_tiers_json(梯度模式专属阶梯 JSON)、enable_force_recharge(代理自设强充开关)、force_recharge_amount(强充金额,0 表示使用阈值)字段;移除与 PackageSeries 重复的三个字段。Package 模型补充 PackageSeriesID 字段,用于系列授权套餐归属校验。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:35:27 +08:00
b52744b149 feat: 新增数据库迁移,重构套餐系列分配佣金和强充字段
迁移编号 000071,在 tb_shop_series_allocation 中新增梯度佣金字段(commission_tiers_json)、代理自设强充字段(enable_force_recharge、force_recharge_amount),删除与 PackageSeries 语义重复的三个冗余字段(enable_one_time_commission、one_time_commission_trigger、one_time_commission_threshold)。

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-04 11:34:55 +08:00
61155952a7 feat: 新增代理分配套餐上架状态(shelf_status)功能
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m56s
- 新增数据库迁移:为 shop_package_allocation 表添加 shelf_status 字段
- 更新模型/DTO:ShopPackageAllocation 增加 ShelfStatus 字段及相关枚举
- 更新套餐分配 Service:支持上架/下架状态管理逻辑
- 更新套餐 Store/Service:根据 shelf_status 过滤可售套餐
- 更新购买验证 Service:引入上架状态校验逻辑
- 归档 OpenSpec 变更:2026-03-02-agent-allocation-shelf-status
- 同步更新主规范文档:allocation-shelf-status、package-management、purchase-validation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-02 15:38:54 +08:00
8efe79526a fix: 修复平台自营资源(未分配代理)无法线下下单的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m56s
offline 支付分支新增平台自营子场景判断:
- 资源 shopID 为空时(未分配给任何代理商),使用零售价直接创建订单
- 资源 shopID 不为空时(属于代理商),走原有平台代购逻辑

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-02 11:44:18 +08:00
a625462205 更新opencode
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 46s
2026-03-02 11:08:58 +08:00
c5429e7287 fix: 修复平台/超管用户订单列表查询为空的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m5s
Service 层无条件将空 buyer_type 和 0 buyer_id 写入查询过滤条件,
导致平台/超管用户查询时附加 WHERE buyer_type = '' AND buyer_id = 0,
与任何订单均不匹配,返回空列表。

修复方式:仅当 buyerType 非空且 buyerID 非零时才添加过滤条件,
平台/超管用户不限定买家范围,可查看全部订单。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-02 10:48:11 +08:00
e661b59bb9 feat: 实现订单超时自动取消功能,支持钱包余额解冻和 Asynq Scheduler 统一调度
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m58s
- 新增 expires_at 字段和复合索引,待支付订单 30 分钟超时自动取消
- 实现 cancelOrder/unfreezeWalletForCancel 钱包余额解冻逻辑
- 创建 Asynq 定时任务(order_expire/alert_check/data_cleanup)
- 将原有 time.Ticker 轮询迁移至 Asynq Scheduler 统一调度
- 同步 delta specs 到 main specs 并归档变更
2026-02-28 17:16:15 +08:00
5bb0ff0ddf fix: 修复代理钱包订单创建逻辑,拆分后台/H5端下单方法并归档变更
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m54s
- 拆分订单创建为 CreateAdminOrder(后台一步支付)和 CreateH5Order(H5 两步支付)
- 新增 CreateAdminOrderRequest DTO,后台仅允许 wallet/offline 支付方式
- 同步 delta specs 到主规格(order-payment 更新 + admin-order-creation 新增)
- 归档 fix-agent-wallet-order-creation 变更
- 新增 implement-order-expiration 变更提案
2026-02-28 16:31:31 +08:00
8ed3d9da93 feat: 实现代理钱包订单创建和订单角色追踪功能
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m0s
新增功能:
- 代理在后台使用 wallet 支付时,订单直接完成(扣款 + 激活套餐)
- 支持代理自购和代理代购场景
- 新增订单角色追踪字段(operator_id、operator_type、actual_paid_amount、purchase_role)
- 订单查询支持 OR 逻辑(buyer_id 或 operator_id)
- 钱包流水记录交易子类型和关联店铺
- 佣金逻辑调整:代理代购不产生佣金

数据库变更:
- 订单表新增 4 个字段和 2 个索引
- 钱包流水表新增 2 个字段
- 包含迁移脚本和回滚脚本

文档:
- 功能总结文档
- 部署指南
- OpenAPI 文档更新
- Specs 同步(新增 agent-order-role-tracking capability)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-28 14:11:42 +08:00
c5bf85c8de refactor: 移除 IoT 卡未使用的价格字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m2s
- 移除 IotCard 模型的 cost_price 和 distribute_price 字段
- 移除 StandaloneIotCardResponse DTO 中对应的字段
- 添加数据库迁移文件 000066_remove_iot_card_price_fields
- 更新 opencode.json 配置

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-27 15:38:33 +08:00
f5000f2bfc 修复超管无法回收资产的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m0s
2026-02-27 11:03:44 +08:00
4189dbe98f debug: 添加资产回收店铺查询的调试日志
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m3s
在 RecallCards 方法中添加日志,用于诊断平台账号回收资产失败的问题:
- 记录操作者店铺ID
- 记录请求查询的店铺IDs
- 记录实际查询到的店铺数量和IDs
- 记录直属下级店铺集合

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-27 09:36:48 +08:00
bc60886aea fix: 修复 GetByIDs 缺少数据权限过滤导致平台账号无法回收资产
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m2s
在 ShopStore.GetByIDs 方法中添加 ApplyShopIDFilter,确保:
- 平台用户可以查询所有店铺(用于资产回收)
- 代理用户只能查询自己和下级店铺(保持权限隔离)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-26 18:07:45 +08:00
6ecc0b5adb fix: 修复套餐系列/套餐分配权限过滤问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m19s
代理用户只能看到自己分配出去的记录,而不是被分配的记录。

- 新增 ApplyAllocatorShopFilter 过滤函数
- ShopSeriesAllocationStore: List 和 GetByID 改用 ApplyAllocatorShopFilter
- ShopPackageAllocationStore: List 和 GetByID 改用 ApplyAllocatorShopFilter
- 平台用户和超管不受限制
- 代理用户只能看到 allocator_shop_id = 自己店铺ID 的记录

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-26 17:10:20 +08:00
1d602ad1f9 fix: 修复代理用户能看到全部店铺的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m3s
在 ShopStore.List 中应用数据权限过滤,新增 ApplyShopIDFilter
函数用于对 Shop 表的 id 字段进行过滤。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-26 16:55:47 +08:00
03a0960c4d refactor: 数据权限过滤从 GORM Callback 改为 Store 层显式调用
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m2s
- 移除 RegisterDataPermissionCallback 和 SkipDataPermission 机制
- 在 Auth 中间件预计算 SubordinateShopIDs 并注入 Context
- 新增 ApplyShopFilter/ApplyEnterpriseFilter/ApplyOwnerShopFilter 等 Helper 函数
- 所有 Store 层查询方法显式调用数据权限过滤函数
- 权限检查函数 CanManageShop/CanManageEnterprise 改为从 Context 获取数据

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-26 16:38:52 +08:00
4ba1f5b99d fix: 添加角色名重复检查
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m46s
- 创建角色时检查角色名是否已存在
- 更新角色时检查角色名是否与其他角色重复

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-26 14:55:46 +08:00
1382cbbf47 fix: 修复代理用户能看到未分配套餐系列的问题
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
问题:代理用户登录后能看到所有套餐系列,即使没有分配给该店铺

原因:PackageSeries 模型没有 shop_id 字段,GORM Callback 无法自动过滤

修复:
- 在 package_series Service 的 List 方法中添加权限过滤
- 代理用户只能看到通过 shop_series_allocation 分配给自己店铺的系列
- 平台用户/超级管理员可以看到所有套餐系列

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-26 14:54:52 +08:00
c1eec5d4f1 fix: 新增店铺时为初始账号分配默认角色
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m0s
问题:创建店铺时只创建了 shop_roles 记录(店铺可用角色),
但没有创建 account_roles 记录,导致初始账号没有任何权限。

修复:在创建初始账号后,立即为其分配默认角色到 account_roles 表。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-25 16:47:36 +08:00
efe8a362aa fix: 平台账号可回收所有店铺的卡和设备
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m4s
之前平台用户回收时只能回收一级代理的资产,现在允许回收所有店铺的资产。

修改:
- iot_card/service.go: isDirectSubordinate 对平台用户返回 true
- device/service.go: RecallDevices 平台用户跳过直属下级验证

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-25 16:37:23 +08:00
6dc6afece0 fix: 修复已删除店铺名称无法显示的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m6s
店铺被软删除后,GORM 默认过滤 deleted_at IS NOT NULL 的记录,
导致查询店铺名称时找不到对应店铺,shop_name 字段被 omitempty 省略。

修复方案:在加载店铺名称的查询中添加 Unscoped(),包含已删除的店铺。

影响接口:
- GET /api/admin/devices(设备列表)
- GET /api/admin/iot-cards/standalone(独立卡列表)
- GET /api/admin/asset-allocation-records(分配记录列表)
- GET /api/admin/enterprises(企业列表)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-25 16:27:58 +08:00
037595c22e feat: 单卡回收接口优化 & 店铺禁用登录拦截
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m0s
单卡回收优化:
- 移除 from_shop_id 参数,系统自动识别卡所属店铺
- 保持直属下级限制,混合来源分别处理
- 新增 GetDistributedStandaloneByICCIDRange/GetDistributedStandaloneByFilters 方法

店铺禁用拦截:
- 登录时检查关联店铺状态,禁用店铺无法登录
- 新增 CodeShopDisabled 错误码

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-25 15:54:53 +08:00
25e9749564 feat: 新增店铺时自动设置默认角色
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m1s
- CreateShopRequest 新增必填字段 default_role_id
- 创建店铺时验证默认角色(必须存在、是客户角色、已启用)
- 创建店铺后自动设置 ShopRole,初始账号立即拥有权限

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-25 14:33:13 +08:00
18daeae65a feat: 钱包系统分离 - 代理钱包与卡钱包完全隔离
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m17s
## 变更概述
将统一钱包系统拆分为代理钱包和卡钱包两个独立系统,实现数据表和代码层面的完全隔离。

## 数据库变更
- 新增 6 张表:tb_agent_wallet、tb_agent_wallet_transaction、tb_agent_recharge_record、tb_card_wallet、tb_card_wallet_transaction、tb_card_recharge_record
- 删除 3 张旧表:tb_wallet、tb_wallet_transaction、tb_recharge_record
- 代理钱包:按 (shop_id, wallet_type) 唯一标识,支持主钱包和分佣钱包
- 卡钱包:按 (resource_type, resource_id) 唯一标识,支持物联网卡和设备

## 代码变更
- Model 层:新增 AgentWallet、AgentWalletTransaction、AgentRechargeRecord、CardWallet、CardWalletTransaction、CardRechargeRecord 模型
- Store 层:新增 6 个独立 Store,支持事务、乐观锁、Redis 缓存
- Service 层:重构 commission_calculation、commission_withdrawal、order、recharge 等 8 个服务
- Bootstrap 层:更新 Store 和 Service 依赖注入
- 常量层:按钱包类型重新组织常量和 Redis Key 生成函数

## 技术特性
- 乐观锁:使用 version 字段防止并发冲突
- 多租户:支持 shop_id_tag 和 enterprise_id_tag 过滤
- 事务管理:所有余额变动使用事务保证 ACID
- 缓存策略:Cache-Aside 模式,余额变动后删除缓存

## 业务影响
- 代理钱包和卡钱包业务完全隔离,互不影响
- 为独立监控、优化、扩展打下基础
- 提升代理钱包的稳定性和独立性

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-25 09:51:00 +08:00
f32d32cd36 perf: IoT 卡 30M 行分页查询优化(P95 17.9s → <500ms)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m6s
- 新增 is_standalone 物化列 + 触发器自动维护(迁移 056)
- 并行查询拆分:多店铺 IN 查询拆为 per-shop goroutine 并行 Index Scan
- 两阶段延迟 Join:深度分页(page≥50)走覆盖索引 Index Only Scan 取 ID 再回表
- COUNT 缓存:per-shop 并行 COUNT + Redis 30 分钟 TTL
- 索引优化:删除有害全局索引、新增 partial composite indexes(迁移 057/058)
- ICCID 模糊搜索路径隔离:trigram GIN 索引走独立查询路径
- 慢查询阈值从 100ms 调整为 500ms
- 新增 30M 测试数据种子脚本和 benchmark 工具
2026-02-24 16:23:02 +08:00
c665f32976 feat: 套餐系统升级 - Worker 重构、流量重置、文档与规范更新
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m54s
- 重构 Worker 启动流程,引入 bootstrap 模块统一管理依赖注入
- 实现套餐流量重置服务(日/月/年周期重置)
- 新增套餐激活排队、加油包绑定、囤货待实名激活逻辑
- 新增订单创建幂等性防重(Redis 业务键 + 分布式锁)
- 更新 AGENTS.md/CLAUDE.md:新增注释规范、幂等性规范,移除测试要求
- 添加套餐系统升级完整文档(API文档、使用指南、功能总结、运维指南)
- 归档 OpenSpec package-system-upgrade 变更,同步 specs 到主目录
- 新增 queue types 抽象和 Redis 常量定义
2026-02-12 14:24:15 +08:00
655c9ce7a6 1 2026-02-11 17:29:06 +08:00
353621d923 移除所有测试代码和测试要求
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m33s
**变更说明**:
- 删除所有 *_test.go 文件(单元测试、集成测试、验收测试、流程测试)
- 删除整个 tests/ 目录
- 更新 CLAUDE.md:用"测试禁令"章节替换所有测试要求
- 删除测试生成 Skill (openspec-generate-acceptance-tests)
- 删除测试生成命令 (opsx:gen-tests)
- 更新 tasks.md:删除所有测试相关任务

**新规范**:
-  禁止编写任何形式的自动化测试
-  禁止创建 *_test.go 文件
-  禁止在任务中包含测试相关工作
-  仅当用户明确要求时才编写测试

**原因**:
业务系统的正确性通过人工验证和生产环境监控保证,测试代码维护成本高于价值。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 17:13:42 +08:00
804145332b chore: 归档轮询系统实现变更 (polling-system-implementation)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 44s
已完成千万级卡规模轮询系统的完整实现和集成测试验证,将变更归档到 openspec/changes/archive/2026-02-10-polling-system-implementation/

主要成果:
- 三大轮询任务:实名检查、卡流量检查、套餐流量检查
- 快速启动(<10秒)和渐进式初始化
- 完整运营工具:配置管理、并发控制、监控面板、告警系统、数据清理、手动触发
- 任务完成度:215/216(99.5%)
- 所有 24 个新增接口已生成 OpenAPI 文档

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 10:28:47 +08:00
931e140e8e feat: 实现 IoT 卡轮询系统(支持千万级卡规模)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m35s
实现功能:
- 实名状态检查轮询(可配置间隔)
- 卡流量检查轮询(支持跨月流量追踪)
- 套餐检查与超额自动停机
- 分布式并发控制(Redis 信号量)
- 手动触发轮询(单卡/批量/条件筛选)
- 数据清理配置与执行
- 告警规则与历史记录
- 实时监控统计(队列/性能/并发)

性能优化:
- Redis 缓存卡信息,减少 DB 查询
- Pipeline 批量写入 Redis
- 异步流量记录写入
- 渐进式初始化(10万卡/批)

压测工具(scripts/benchmark/):
- Mock Gateway 模拟上游服务
- 测试卡生成器
- 配置初始化脚本
- 实时监控脚本

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 17:32:44 +08:00
b11edde720 fix: 注册佣金计算任务 Handler 到队列处理器
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m19s
佣金计算任务 (commission:calculate) 的 Handler 已实现但未在队列处理器中注册,
导致支付成功后入队的佣金计算任务永远不会被消费执行。

变更内容:
- 在 pkg/queue/handler.go 中添加 registerCommissionCalculationHandler() 方法
- 创建所有需要的 Store 和 Service 依赖
- 在 RegisterHandlers() 中调用注册方法

修复后,订单支付成功将正确触发佣金计算和发放。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 16:08:03 +08:00
8ab5ebc3af feat: 在 IoT 卡和设备列表响应中添加套餐系列名称字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m2s
主要变更:
- 在 StandaloneIotCardResponse 和 DeviceResponse 中添加 series_name 字段
- 在 iot_card 和 device service 中添加 loadSeriesNames 方法批量加载系列名称
- 更新相关方法以支持 series_name 的填充

其他变更:
- 新增 OpenSpec 测试生成和共识锁定 skill
- 新增 MCP 配置文件
- 更新 CLAUDE.md 项目规范文档

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-04 15:28:41 +08:00
dc84cef2ce fix(package-series): 将 enable_one_time_commission 字段提升到创建/更新请求顶层
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m5s
- DTO: CreatePackageSeriesRequest 和 UpdatePackageSeriesRequest 添加 EnableOneTimeCommission 字段
- Service: Create/Update 方法处理顶层字段并同步到 JSON config 的 Enable 字段
- 确保顶层字段与 JSON config 内的 enable 保持一致,避免业务逻辑判断出错
2026-02-04 14:38:10 +08:00
b18ecfeb55 refactor: 一次性佣金配置从套餐级别提升到系列级别
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m29s
主要变更:
- 新增 tb_shop_series_allocation 表,存储系列级别的一次性佣金配置
- ShopPackageAllocation 移除 one_time_commission_amount 字段
- PackageSeries 新增 enable_one_time_commission 字段控制是否启用一次性佣金
- 新增 /api/admin/shop-series-allocations CRUD 接口
- 佣金计算逻辑改为从 ShopSeriesAllocation 获取一次性佣金金额
- 删除废弃的 ShopSeriesOneTimeCommissionTier 模型
- OpenAPI Tag '系列分配' 和 '单套餐分配' 合并为 '套餐分配'

迁移脚本:
- 000042: 重构佣金套餐模型
- 000043: 简化佣金分配
- 000044: 一次性佣金分配重构
- 000045: PackageSeries 添加 enable_one_time_commission 字段

测试:
- 新增验收测试 (shop_series_allocation, commission_calculation)
- 新增流程测试 (one_time_commission_chain)
- 删除过时的单元测试(已被验收测试覆盖)
2026-02-04 14:28:44 +08:00
fba8e9e76b refactor(account): 移除卡类型字段、优化账号列表查询和权限检查
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m18s
- 移除 IoT 卡和号卡的 card_type 字段(数据库迁移)
- 优化账号列表查询,支持按店铺和企业筛选
- 账号响应增加店铺名称和企业名称字段
- 实现批量加载店铺和企业名称,避免 N+1 查询
- 更新权限检查中间件,完善权限验证逻辑
- 更新相关测试用例,确保功能正确性
2026-02-03 10:59:44 +08:00
ad6d43e0cd 移除 2026-02-03 10:19:39 +08:00
5a90caa619 feat(shop-role): 实现店铺角色继承功能和权限检查优化
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m39s
- 新增店铺角色管理 API 和数据模型
- 实现角色继承和权限检查逻辑
- 添加流程测试框架和集成测试
- 更新权限服务和账号管理逻辑
- 添加数据库迁移脚本
- 归档 OpenSpec 变更文档

Ultraworked with Sisyphus
2026-02-03 10:06:13 +08:00
bc7e5d6f6d 修复go的验证库把int的0当作无值的情况 2026-02-03 09:57:53 +08:00
0b82f30f86 修复飘红问题
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 15h48m25s
2026-02-02 17:52:14 +08:00
301eb6158e docs: 添加 add-gateway-admin-api 最终报告和完成文档 2026-02-02 17:51:38 +08:00
6c83087319 docs: 标记 add-gateway-admin-api 计划所有任务为完成 2026-02-02 17:49:40 +08:00
2ae585225b test(integration): 添加 Gateway 接口集成测试
- 添加 6 个卡 Gateway 接口测试(查询状态、流量、实名、获取链接、停机、复机)
- 添加 7 个设备 Gateway 接口测试(查询信息、卡槽、限速、WiFi、切卡、重启、恢复出厂)
- 每个接口测试包含成功场景和权限校验场景
- 更新测试环境初始化,添加 Gateway 客户端 mock 支持
- 所有 13 个接口测试通过
2026-02-02 17:44:24 +08:00
543c454f16 feat(routes): 注册 7 个设备 Gateway 路由 2026-02-02 17:33:39 +08:00
246ea6e287 修改 Bootstrap 注入 Gateway Client 依赖到 IotCardHandler 和 DeviceHandler 2026-02-02 17:27:59 +08:00
80f560df33 refactor(account): 统一账号管理API、完善权限检查和操作审计
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m17s
- 合并 customer_account 和 shop_account 路由到统一的 account 接口
- 新增统一认证接口 (auth handler)
- 实现越权防护中间件和权限检查工具函数
- 新增操作审计日志模型和服务
- 更新数据库迁移 (版本 39: account_operation_log 表)
- 补充集成测试覆盖权限检查和审计日志场景
2026-02-02 17:23:20 +08:00
5851cc6403 feat(permission): 为权限树接口添加状态查询参数和返回值
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m22s
- 新增 PermissionTreeRequest DTO 支持 status 查询参数
- PermissionTreeNode 返回值新增 status 字段
- Store 层 GetAll 方法支持状态过滤
- Handler 层使用 QueryParser 解析请求参数
2026-02-02 17:12:14 +08:00
76b539e867 chore: 归档 OpenSpec 变更 refactor-series-binding-to-series-id
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m22s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-02-02 12:21:00 +08:00
b47f7b4f46 修复: 更新集成测试以适配 series_id 字段重命名
- 将所有测试用例的 series_allocation_id 改为 series_id
- 更新测试逻辑,直接使用 series.ID 而非 allocation.ID
- 修复禁用系列测试,直接禁用 PackageSeries 而非 ShopSeriesAllocation
- 所有集成测试通过验证
2026-02-02 12:16:55 +08:00
37f43d2e2d 重构: 将卡/设备的套餐系列绑定从分配ID改为系列ID
- 数据库: 重命名 series_allocation_id → series_id
- Model: IotCard 和 Device 字段重命名
- DTO: 所有请求/响应字段统一为 series_id
- Store: 方法重命名,新增 GetByShopAndSeries 查询
- Service: 业务逻辑优化,系列验证和权限验证分离
- 测试: 更新所有测试用例,新增 shop_series_allocation_store_test.go
- 文档: 更新 API 文档说明参数变更

BREAKING CHANGE: API 参数从 series_allocation_id 改为 series_id
2026-02-02 12:09:53 +08:00
a30b3036bb feat(iot-card-import): 为导入任务接口添加平台用户权限控制
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m10s
- 在 Import/List/GetByID 接口添加用户类型校验
- 仅超级管理员和平台用户可访问
- 同步更新 OpenAPI 路由描述
- 补充集成测试覆盖权限拒绝场景
2026-02-02 10:25:03 +08:00
d81bd242a4 fix(force-recharge): 补充强充配置缺失的接口和数据库字段
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m19s
- 订单管理:增加 payment_method 字段支持,合并代购订单逻辑
- 套餐系列分配:增加强充配置字段(enable_force_recharge、force_recharge_amount、force_recharge_trigger_type)
- 数据库迁移:添加 force_recharge_trigger_type 字段
- 测试:更新订单服务测试用例
- OpenSpec:归档 fix-force-recharge-missing-interfaces 变更
2026-01-31 15:34:32 +08:00
d309951493 feat(import): 用 Excel 格式替换 CSV 导入
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m33s
- 删除 CSV 解析代码,新增 Excel 解析器 (excelize)

- 更新 IoT 卡和设备导入任务处理器

- 更新 API 路由文档和前端接入指南

- 归档变更到 openspec/changes/archive/

- 同步 delta specs 到 main specs
2026-01-31 14:13:02 +08:00
62708892ec 文档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m2s
2026-01-31 13:06:30 +08:00
b8dda7e62a chore(bootstrap): 更新依赖注入和 API 文档
- Bootstrap 注册 RechargeHandler 和 RechargeService
- Bootstrap 注册 RechargeStore 数据访问层
- 更新 PaymentCallback 依赖注入(添加 RechargeService)
- 更新 OpenAPI 文档生成器注册充值接口
- 同步 admin-openapi.yaml 文档(新增充值和代购预检接口)
2026-01-31 12:15:12 +08:00
5891e9db8d feat(routes): 注册充值和代购订单路由
- 新增 H5 充值路由(创建订单、预检、列表、详情)
- 新增 Admin 代购订单预检路由
- 更新 H5 路由组注册充值处理器
- 更新 Admin 路由组注册代购预检接口
2026-01-31 12:15:07 +08:00
902ddb3687 feat(handler): 支持代购订单预检和充值订单支付回调
- OrderHandler 新增 PurchaseCheck 接口用于代购订单预检
- PaymentCallback 支持充值订单支付回调处理
- 根据订单号前缀区分订单类型(代购订单 vs 充值订单)
- 充值订单回调自动更新订单状态和钱包余额
2026-01-31 12:15:03 +08:00
760b3db1df feat(h5): 新增充值订单处理器和 DTO
- 实现 RechargeHandler 处理充值订单创建、预检、查询等接口
- 添加充值相关 DTO(CreateRechargeRequest、RechargeCheckRequest 等)
- 支持充值预检(强充检查、金额限制等)
- 支持充值订单列表和详情查询
2026-01-31 12:14:59 +08:00
001eb81e5e chore(openspec): 清理已归档的 gateway-integration 变更 2026-01-31 12:01:47 +08:00
1ec7de4ec4 chore(bootstrap): 更新依赖注入和配置
- bootstrap/services.go
  - OrderService 初始化新增依赖注入
  - 添加 ShopSeriesAllocationStore、IotCardStore、DeviceStore
- docker-compose.prod.yml
  - 对象存储 S3 端点改为 HTTPS(安全性提升)
  - 同时更新 API 和 Worker 服务配置

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-01-31 12:01:37 +08:00
113b3edd69 feat(order): 支持代购订单和强充要求检查
- OrderService 新增代购订单支持
  - 强充要求检查(首次购买最低充值)
  - 代购订单支付限制(无需支付)
  - 强充金额验证
- 新增 OrderDTO 请求/响应结构
  - PurchaseCheckRequest/Response(购买预检)
  - CreatePurchaseOnBehalfRequest(代购订单创建)
- Order 模型新增支付方式
  - PaymentMethodOffline(线下支付,仅平台代购使用)
- OrderService 依赖注入扩展
  - 新增 SeriesAllocationStore、IotCardStore、DeviceStore
  - 支持强充要求检查逻辑
- 完整的集成测试覆盖(534 行)
  - 代购订单创建、强充验证、支付限制等场景

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-01-31 12:01:33 +08:00
22f19377a5 feat(recharge): 新增充值服务和 DTO
- 实现 RechargeService 完整充值业务逻辑
  - 创建充值订单、预检强充要求
  - 支付回调处理、幂等性检查
  - 累计充值更新、一次性佣金触发
- 新增 RechargeDTO 请求/响应结构
  - CreateRechargeRequest、RechargeResponse
  - RechargeListRequest/Response、RechargeCheckRequest/Response
- 完整的单元测试覆盖(1488 行)
  - 强充要求检查、支付回调、佣金发放等场景
  - 事务处理、幂等性验证

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-01-31 12:01:26 +08:00
c7bf43f306 fix(commission): 代购订单跳过一次性佣金和累计充值更新 2026-01-31 11:46:50 +08:00
1036b5979e feat(store): 新增 RechargeStore 充值订单数据访问层
实现充值订单的完整 CRUD 操作:
- Create: 创建充值订单
- GetByRechargeNo: 根据订单号查询(不存在返回 nil)
- GetByID: 根据 ID 查询
- List: 支持分页和多条件筛选(用户、钱包、状态、时间范围)
- UpdateStatus: 更新状态(支持乐观锁检查)
- UpdatePaymentInfo: 更新支付信息

测试覆盖率: 94.7%(7个方法全部覆盖)
- 包含正常流程、边界条件、错误处理测试
- 使用 testutils.NewTestTransaction 和 GetTestRedis
- 所有测试通过

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-01-31 11:37:47 +08:00
cb0835cd94 feat(constants): 添加充值订单状态和配置常量 2026-01-31 11:32:07 +08:00
526d9c62b7 feat(errors): 添加充值和代购相关错误码
- 充值相关: CodeRechargeAmountInvalid (1120), CodeRechargeNotFound (1121), CodeRechargeAlreadyPaid (1122)
- 代购相关: CodePurchaseOnBehalfForbidden (1130), CodePurchaseOnBehalfInvalidTarget (1131)
- 强充验证: CodeForceRechargeRequired (1140), CodeForceRechargeAmountMismatch (1141)
2026-01-31 11:31:58 +08:00
116355835a feat(model): 添加代购和强充配置字段 2026-01-31 11:31:57 +08:00
f6a0f0f39c feat(migration): 添加代购和强充配置字段迁移 2026-01-31 11:31:42 +08:00
e461791a0e 解决冲突
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m7s
2026-01-30 18:09:31 +08:00
109ae688d2 解决冲突 2026-01-30 17:37:35 +08:00
65b4127b84 Merge branch 'emdash/wechat-official-account-payment-integration-30g'
# Conflicts:
#	README.md
#	cmd/api/main.go
#	internal/bootstrap/dependencies.go
#	pkg/config/config.go
#	pkg/config/defaults/config.yaml
2026-01-30 17:32:33 +08:00
bf591095a2 微信相关能力 2026-01-30 17:25:30 +08:00
accf7cb293 Merge branch 'emdash/login-prome-47c' 2026-01-30 17:23:33 +08:00
ffeb0417c0 登录权限返回修改 2026-01-30 17:22:38 +08:00
32beac4424 chore: 更新 Gateway 集成任务清单,标记所有任务完成
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- 完成 Phase 1-5 所有任务(14 个 API 接口、45 个测试、2 个文档)
- 测试覆盖率 88.8%(接近 90% 目标)
- 编译通过,无 LSP 错误
- 依赖注入到 Service 层成功
- 符合项目代码规范(中文注释、Go 命名规范)
2026-01-30 17:12:14 +08:00
3f63fffbb1 chore: apply task changes 2026-01-30 17:05:44 +08:00
4856a88d41 docs: 新增 Gateway 集成和微信公众号支付集成的 OpenSpec 规划文档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 43s
2026-01-30 16:09:32 +08:00
1cf17e8f14 清理冗余的梯度返佣(TierCommission)配置
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m46s
- 移除 Model 层:删除 ShopSeriesCommissionTier 模型及相关字段
- 更新 DTO:删除 TierCommissionConfig、TierEntry 类型及相关请求/响应字段
- 删除 Store 层:移除 ShopSeriesCommissionTierStore 及相关查询逻辑
- 简化 Service 层:删除梯度返佣处理逻辑,统计查询移除 tier_bonus 字段
- 数据库迁移:创建 000034_remove_tier_commission 移除相关表和字段
- 更新测试:移除梯度返佣相关测试用例,更新集成测试
- OpenAPI 文档:删除梯度返佣相关 schema 和枚举值
- 归档变更:归档 remove-tier-commission-redundancy 到 archive/2026-01-30-
- 同步规范:更新 4 个主 specs,标记废弃功能并添加迁移指引

原因:梯度返佣功能与一次性梯度佣金功能重复,且从未实现实际计算逻辑
迁移:使用一次性佣金的梯度模式 (OneTimeCommissionConfig.type = "tiered") 替代
2026-01-30 14:57:24 +08:00
409a68d60b feat: OpenAPI 契约对齐与框架优化
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m45s
主要变更:
1. OpenAPI 文档契约对齐
   - 统一错误响应字段名为 msg(非 message)
   - 规范 envelope 响应结构(code, msg, data, timestamp)
   - 个人客户路由纳入文档体系(使用 Register 机制)
   - 新增 BuildDocHandlers() 统一管理 handler 构造
   - 确保文档生成的幂等性

2. Service 层错误处理统一
   - 全面替换 fmt.Errorf 为 errors.New/Wrap
   - 统一错误码使用规范
   - Handler 层参数校验不泄露底层细节
   - 新增错误码验证集成测试

3. 代码质量提升
   - 删除未使用的 Task handler 和路由
   - 新增代码规范检查脚本(check-service-errors.sh)
   - 新增注释路径一致性检查(check-comment-paths.sh)
   - 更新 API 文档生成指南

4. OpenSpec 归档
   - 归档 openapi-contract-alignment 变更(63 tasks)
   - 归档 service-error-unify-core 变更
   - 归档 service-error-unify-support 变更
   - 归档 code-cleanup-docs-update 变更
   - 归档 handler-validation-security 变更
   - 同步 delta specs 到主规范文件

影响范围:
- pkg/openapi: 新增 handlers.go,优化 generator.go
- internal/service/*: 48 个 service 文件错误处理统一
- internal/handler/admin: 优化参数校验错误提示
- internal/routes: 个人客户路由改造,删除 task 路由
- scripts: 新增 3 个代码检查脚本
- docs: 更新 OpenAPI 文档(15750+ 行)
- openspec/specs: 同步 3 个主规范文件

破坏性变更:无
向后兼容:是
2026-01-30 11:40:36 +08:00
1290160728 fix: 修复订单支付幂等性问题,防止重复激活套餐
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m22s
- 使用条件更新实现支付状态原子转换(pending -> paid)
- 重复请求返回幂等成功,不再重复激活套餐
- 新增 tb_package_usage 唯一索引(order_id, package_id)
- 新增幂等性和异常状态测试,测试覆盖率 71.7%
- 归档 OpenSpec 变更 fix-order-activation-idempotency
2026-01-29 16:33:53 +08:00
2b0f79be81 归档一次性佣金配置落库与累计触发修复,同步规范文档到主 specs
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m45s
- 归档 fix-one-time-commission-config-and-accumulation 到 archive/2026-01-29-*
- 同步 delta specs 到主规范(one-time-commission-trigger、commission-calculation)
- 新增累计触发逻辑文档和测试用例
- 修复一次性佣金配置落库和累计充值更新逻辑
2026-01-29 16:00:18 +08:00
d977000a66 feat: 归档佣金计算触发和快照变更,同步规范文档
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m40s
- 归档 OpenSpec 变更到 archive 目录
- 创建 2 个新的主规范文件:commission-trigger 和 order-commission-snapshot
- 实现订单佣金快照字段和支付自动触发
- 确保事务一致性,所有佣金操作在同一事务内完成
- 提取成本价计算为公共工具函数
2026-01-29 14:58:35 +08:00
c9fee7f2f6 fix: 修复授权记录备注修改权限问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m42s
- 实现备注权限检查逻辑(authorization_service.go)
- 添加备注权限验证存储层(authorization_store.go)
- 新增集成测试覆盖备注权限场景
- 归档 fix-authorization-remark-permission 变更
- 同步 enterprise-card-authorization spec 规范
2026-01-29 14:29:11 +08:00
b02175271a feat: 实现企业设备授权功能并归档 OpenSpec 变更
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m39s
- 新增企业设备授权模块(Model、DTO、Service、Handler、Store)
- 实现设备授权的创建、查询、更新、删除等完整业务逻辑
- 添加企业卡授权与设备授权的关联关系
- 新增 2 个数据库迁移脚本
- 同步 OpenSpec delta specs 到 main specs
- 归档 add-enterprise-device-authorization 变更
- 更新 API 文档和路由配置
- 新增完整的集成测试和单元测试覆盖
2026-01-29 13:18:49 +08:00
e87513541b feat: 实现一次性佣金功能
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m41s
- 新增佣金计算服务,支持一次性佣金和返佣计算
- 新增 ShopSeriesOneTimeCommissionTier 模型和存储层
- 新增两个数据库迁移:一次性佣金表和订单佣金字段
- 更新 Commission 模型,新增佣金来源和关联字段
- 更新 CommissionRecord 存储层,支持一次性佣金查询
- 更新 MyCommission 服务,集成一次性佣金计算逻辑
- 更新 ShopCommission 服务,支持一次性佣金统计
- 新增佣金计算异步任务处理器
- 更新 API 路由,新增一次性佣金相关端点
- 归档 OpenSpec 变更文档,同步规范到主规范库
2026-01-29 09:36:12 +08:00
dfcf16f548 feat: 实现订单支付功能模块
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m36s
- 新增订单管理、支付回调、购买验证等核心服务
- 实现订单、订单项目的数据存储层和 API 接口
- 添加订单数据库迁移和 DTO 定义
- 更新 API 文档和路由配置
- 同步 3 个新规范到主规范库(订单管理、订单支付、套餐购买验证)
- 完成 OpenSpec 变更归档

Ultraworked with Sisyphus
2026-01-28 22:12:15 +08:00
a945a4f554 feat: 实现卡和设备的套餐系列绑定功能
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m37s
- 添加 Device 和 IotCard 模型的 SeriesID 字段
- 实现 DeviceService 和 IotCardService 的套餐系列绑定逻辑
- 添加 DeviceStore 和 IotCardStore 的数据库操作方法
- 更新 API 接口和路由支持套餐系列绑定
- 创建数据库迁移脚本(000027_add_series_binding_fields)
- 添加完整的单元测试和集成测试
- 更新 OpenAPI 文档
- 归档 OpenSpec 变更文档

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-01-28 19:49:45 +08:00
1da680a790 重构: 店铺套餐分配系统从加价模式改为返佣模式
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m18s
主要变更:
- 重构分配模型:从加价模式(pricing_mode/pricing_value)改为返佣模式(base_commission + tier_commission)
- 删除独立的 my_package 接口,统一到 /api/admin/packages(通过数据权限自动过滤)
- 新增批量分配和批量调价功能,支持事务和性能优化
- 新增配置版本管理,订单创建时锁定返佣配置
- 新增成本价历史记录,支持审计和纠纷处理
- 新增统计缓存系统(Redis + 异步任务),优化梯度返佣计算性能
- 删除冗余的梯度佣金独立 CRUD 接口(合并到分配配置中)
- 归档 3 个已完成的 OpenSpec changes 并同步 8 个新 capabilities 到 main specs

技术细节:
- 数据库迁移:000026_refactor_shop_package_allocation
- 新增 Store:AllocationConfigStore, PriceHistoryStore, CommissionStatsStore
- 新增 Service:BatchAllocationService, BatchPricingService, CommissionStatsService
- 新增异步任务:统计更新、定时同步、周期归档
- 测试覆盖:批量操作集成测试、梯度佣金 CRUD 清理验证

影响:
- API 变更:删除 4 个梯度 CRUD 接口(POST/GET/PUT/DELETE /:id/tiers)
- API 新增:批量分配、批量调价接口
- 数据模型:重构 shop_series_allocation 表结构
- 性能优化:批量操作使用 CreateInBatches,统计使用 Redis 缓存

相关文档:
- openspec/changes/archive/2026-01-28-refactor-shop-package-allocation/
- openspec/specs/agent-available-packages/
- openspec/specs/allocation-config-versioning/
- 等 8 个新 capability specs
2026-01-28 17:11:55 +08:00
23eb0307bb feat: 实现门店套餐分配功能并统一测试基础设施
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m30s
新增功能:
- 门店套餐分配管理(shop_package_allocation):支持门店套餐库存管理
- 门店套餐系列分配管理(shop_series_allocation):支持套餐系列分配和佣金层级设置
- 我的套餐查询(my_package):支持门店查询自己的套餐分配情况

测试改进:
- 统一集成测试基础设施,新增 testutils.NewIntegrationTestEnv
- 重构所有集成测试使用新的测试环境设置
- 移除旧的测试辅助函数和冗余测试文件
- 新增 test_helpers_test.go 统一任务测试辅助

技术细节:
- 新增数据库迁移 000025_create_shop_allocation_tables
- 新增 3 个 Handler、Service、Store 和对应的单元测试
- 更新 OpenAPI 文档和文档生成器
- 测试覆盖率:Service 层 > 90%

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-28 10:45:16 +08:00
5fefe9d0cb 重构: 使用 testutils.NewIntegrationTestEnv 替换旧的测试环境设置
- 移除 setupAuthorizationTestEnv 和 teardown 函数
- 移除所有 DELETE 清理代码,改用事务隔离
- 每个测试函数改用 env := testutils.NewIntegrationTestEnv(t)
- 使用 env.TX 替代 env.db
- 使用 env.AsSuperAdmin().Request() 和 env.AsUser() 发送请求
- 使用 env.CreateTestShop/Enterprise/Account 创建测试数据
- 移除未使用的导入(bytes, net/http/httptest)
- 保持所有测试业务逻辑不变
2026-01-27 22:44:21 +08:00
79c061b6fa feat: 实现套餐管理模块,包含套餐系列、双状态管理、废弃模型清理
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m24s
- 新增套餐系列管理 (CRUD + 状态切换)
- 新增套餐管理 (CRUD + 启用/禁用 + 上架/下架双状态)
- 清理 8 个废弃分佣模型及对应数据库表
- Package 模型新增建议成本价、建议售价、上架状态字段
- 完整的 Store/Service/Handler 三层实现
- 包含单元测试和集成测试
- 归档 add-package-module change
- 新增多个 OpenSpec changes (订单支付、店铺套餐分配、一次性分佣、卡设备系列绑定)
2026-01-27 19:55:47 +08:00
30a0717316 补充 PackageService 的 Update 和 Delete 测试
- 添加 TestPackageService_Update:更新成功、更新不存在的套餐
- 添加 TestPackageService_Delete:删除成功、删除不存在的套餐
- 测试覆盖率从 47.2% 提升到 66.9%
2026-01-27 19:38:05 +08:00
e2e6a64ba4 创建 PackageService 单元测试(覆盖双状态逻辑)
- 创建 internal/service/package/service_test.go 文件
- 测试 Create 方法:创建成功、编码重复失败、系列不存在失败
- 测试 UpdateStatus 方法:禁用时自动强制下架、启用时保持原上架状态
- 测试 UpdateShelfStatus 方法:启用状态可上架、禁用状态不能上架、下架成功
- 测试 Get 方法:获取成功、不存在返回错误
- 测试 List 方法:列表查询、按类型过滤、按状态过滤
- 使用 testutils.NewTestTransaction 创建测试事务
- 使用 middleware.SetUserContext 设置用户上下文
- 使用唯一的 PackageCode(基于时间戳)
- 重点覆盖双状态逻辑的测试
2026-01-27 19:37:08 +08:00
d104d297ca feat: 实现运营商模块重构,添加冗余字段优化查询性能
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m16s
主要变更:
- 新增 Carrier CRUD API(创建、列表、详情、更新、删除、状态更新)
- IotCard/IotCardImportTask 添加 carrier_type/carrier_name 冗余字段
- 移除 Carrier 表的 channel_name/channel_code 字段
- 查询时直接使用冗余字段,避免 JOIN Carrier 表
- 添加数据库迁移脚本(000021-000023)
- 添加单元测试和集成测试
- 同步更新 OpenAPI 文档和 specs
2026-01-27 12:18:19 +08:00
5a179ba16b 更新openspec
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m48s
2026-01-27 10:03:49 +08:00
477a9fc98d feat: 添加设备IMEI和单卡ICCID查询接口
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
- 新增 GET /api/admin/devices/by-imei/:imei 接口,支持通过设备号查询设备详情
- 新增 GET /api/admin/iot-cards/by-iccid/:iccid 接口,支持通过ICCID查询单卡详情
- 添加对应的 Service 层方法和 Handler
- 更新 OpenAPI 文档
- 添加集成测试并修复测试环境配置(使用环境变量)
- 归档已完成的 OpenSpec 变更记录

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-27 09:59:54 +08:00
ce0783f96e feat: 实现设备管理和设备导入功能,修复测试问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m30s
主要变更:
- 实现设备管理模块(创建、查询、列表、更新状态、删除)
- 实现设备批量导入功能(CSV 解析、ICCID 绑定、异步任务处理)
- 添加设备-SIM 卡绑定约束(部分唯一索引防止并发问题)
- 修复 fee_rate 数据库字段类型(numeric -> bigint)
- 修复测试数据隔离问题(基于增量断言)
- 修复集成测试中间件顺序问题
- 清理无用测试文件(PersonalCustomer、Email 相关)
- 归档 enterprise-card-authorization 变更
2026-01-26 18:05:12 +08:00
fdcff33058 feat: 实现企业卡授权和授权记录管理功能
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m9s
主要功能:
- 添加企业卡授权/回收接口 (POST /enterprises/:id/allocate-cards, recall-cards)
- 添加授权记录管理接口 (GET/PUT /authorizations)
- 实现代理用户数据权限过滤(只能查看自己店铺下企业的授权记录)
- 添加 GORM callback 支持授权记录表的数据权限过滤

技术改进:
- 原生 SQL 查询手动添加数据权限过滤(ListWithJoin, GetByIDWithJoin)
- 移除卡授权预检接口(allocate-cards/preview),保留内部方法
- 完善单元测试和集成测试覆盖
2026-01-26 15:07:03 +08:00
45aa7deb87 feat: 添加环境变量管理工具和部署配置改版
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m33s
主要改动:
- 新增交互式环境配置脚本 (scripts/setup-env.sh)
- 新增本地启动快捷脚本 (scripts/run-local.sh)
- 新增环境变量模板文件 (.env.example)
- 部署模式改版:使用嵌入式配置 + 环境变量覆盖
- 添加对象存储功能支持
- 改进 IoT 卡片导入任务
- 优化 OpenAPI 文档生成
- 删除旧的配置文件,改用嵌入式默认配置
2026-01-26 10:28:29 +08:00
194078674a feat: 实现单卡资产分配与回收功能
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m45s
- 新增单卡分配/回收 API(支持 ICCID 列表、号段范围、筛选条件三种选卡方式)
- 新增资产分配记录查询 API(支持多条件筛选和分页)
- 新增 AssetAllocationRecord 模型、Store、Service、Handler 完整实现
- 扩展 IotCardStore 新增批量更新、号段查询、筛选查询等方法
- 修复 GORM Callback 处理 slice 类型(BatchCreate)的问题
- 新增完整的单元测试和集成测试
- 同步 OpenSpec 规范并归档 change
2026-01-24 15:46:15 +08:00
a924e63e68 feat: 实现物联网卡独立管理和批量导入功能
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m42s
新增物联网卡独立管理模块,支持单卡查询、批量导入和状态管理。主要变更包括:

功能特性:
- 新增物联网卡 CRUD 接口(查询、分页列表、删除)
- 支持 CSV/Excel 批量导入物联网卡
- 实现异步导入任务处理和进度跟踪
- 新增 ICCID 号码格式校验器(支持 Luhn 算法)
- 新增 CSV 文件解析工具(支持编码检测和错误处理)

数据库变更:
- 移除 iot_card 和 device 表的 owner_id/owner_type 字段
- 新增 iot_card_import_task 导入任务表
- 为导入任务添加运营商类型字段

测试覆盖:
- 新增 IoT 卡 Store 层单元测试
- 新增 IoT 卡导入任务单元测试
- 新增 IoT 卡集成测试(包含导入流程测试)
- 新增 CSV 工具和 ICCID 校验器测试

文档更新:
- 更新 OpenAPI 文档(新增 7 个 IoT 卡接口)
- 归档 OpenSpec 变更提案
- 更新 API 文档规范和生成器指南

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-24 11:03:43 +08:00
6821e5abcf refactor: 统一错误消息数据源,优化错误码与映射表管理
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m36s
主要改动:
- 改造 errors.New() 和 Wrap() 函数签名为可变参数,优先使用 errorMessages 映射表
- 添加 allErrorCodes 注册表和 init() 启动时校验,确保错误码与映射表一致
- 添加 TestAllCodesHaveMessages 和 TestNoOrphanMessages 测试防止映射表腐化
- 清理 109 处与映射表一致的冗余硬编码(service 层)
- 保留业务特定消息覆盖能力

新增 API 用法:
- errors.New(errors.CodeUnauthorized) // 使用映射表默认消息
- errors.New(errors.CodeNotFound, "提现申请不存在") // 覆盖为自定义消息
2026-01-22 18:27:42 +08:00
b68e7ec013 优化测试数据库连接管理
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 15s
- 创建全局单例连接池,性能提升 6-7 倍
- 实现 NewTestTransaction/GetTestRedis/CleanTestRedisKeys
- 移除旧的 SetupTestDB/TeardownTestDB API
- 迁移所有测试文件到新方案(47 个文件)
- 添加测试连接管理规范文档
- 更新 AGENTS.md 和 README.md

性能对比:
- 旧方案:~71 秒(204 测试)
- 新方案:~10.5 秒(首次初始化 + 后续复用)
- 内存占用降低约 80%
- 网络连接数从 204 降至 1
2026-01-22 14:38:43 +08:00
46e4e5f4f1 refactor: 将 DTO 文件从 internal/model 移动到 internal/model/dto 目录
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m22s
- 移动 17 个 DTO 文件到 internal/model/dto/ 目录
- 更新所有 DTO 文件的 package 声明从 model 改为 dto
- 更新所有引用文件的 import 和类型引用
  - Handler 层:admin 和 h5 所有处理器
  - Service 层:所有业务服务
  - Routes 层:所有路由定义
  - Tests 层:单元测试和集成测试
- 清理未使用的 import 语句
- 验证:项目构建成功,测试编译通过,LSP 无错误
2026-01-22 10:15:04 +08:00
23be0a7d3e fix: 修复 OpenAPI 路径参数 path 标签缺失导致启动 panic 的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m17s
- 为 enterprise_card_authorization_dto.go 中的 DTO 添加 path 标签
- 为 customer_account_dto.go 中的 DTO 添加 path 标签并重构结构
- 为 enterprise_dto.go 中的 DTO 添加 path 标签并重构结构
- 更新 handler 和 service 层使用正确的请求体类型
2026-01-21 18:42:29 +08:00
8677a54370 fix: 修复 OpenAPI 文档生成器缺少新增 Handler 的问题
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 3m41s
新增以下 Handler 到文档生成器:
- ShopCommission(代理商佣金管理)
- CommissionWithdrawal(佣金提现审批)
- CommissionWithdrawalSetting(提现配置管理)
- Enterprise(企业客户管理)
- EnterpriseCard(企业卡授权)
- CustomerAccount(客户账号管理)
- MyCommission(我的佣金)

同时修复 .gitignore 中 api 规则过宽的问题
2026-01-21 18:26:10 +08:00
91c9bbfeb8 feat: 实现账号与佣金管理模块
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m35s
新增功能:
- 店铺佣金查询:店铺佣金统计、店铺佣金记录列表、店铺提现记录
- 佣金提现审批:提现申请列表、审批通过、审批拒绝
- 提现配置管理:配置列表、新增配置、获取当前生效配置
- 企业管理:企业列表、创建、更新、删除、获取详情
- 企业卡授权:授权列表、批量授权、批量取消授权、统计
- 客户账号管理:账号列表、创建、更新状态、重置密码
- 我的佣金:佣金统计、佣金记录、提现申请、提现记录

数据库变更:
- 扩展 tb_commission_withdrawal_request 新增提现单号等字段
- 扩展 tb_account 新增 is_primary 字段
- 扩展 tb_commission_record 新增 shop_id、balance_after
- 扩展 tb_commission_withdrawal_setting 新增每日提现次数限制
- 扩展 tb_iot_card、tb_device 新增 shop_id 冗余字段
- 新建 tb_enterprise_card_authorization 企业卡授权表
- 新建 tb_asset_allocation_record 资产分配记录表
- 数据迁移:owner_type 枚举值 agent 统一为 shop

测试:
- 新增 7 个单元测试文件覆盖各服务
- 修复集成测试 Redis 依赖问题
2026-01-21 18:20:44 +08:00
1489abe668 修复上次错误的提交
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m20s
2026-01-21 14:51:08 +08:00
2258 changed files with 342882 additions and 26507 deletions

30
.agents/rules/ponytail.md Normal file
View 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.

View 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.

View 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 **35 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea.
Each hypothesis must be **falsifiable**: state the prediction it makes.
> Format: "If <X> is the cause, then <changing Y> will make the bug disappear / <changing Z> will make it worse."
If you cannot state the prediction, the hypothesis is a vibe — discard or sharpen it.
**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it — proceed with your ranking if the user is AFK.
## Phase 4 — Instrument
Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.**
Tool preference:
1. **Debugger / REPL inspection** if the env supports it. One breakpoint beats ten logs.
2. **Targeted logs** at the boundaries that distinguish hypotheses.
3. Never "log everything and grep".
**Tag every debug log** with a unique prefix, e.g. `[DEBUG-a4f2]`. Cleanup at the end becomes a single grep. Untagged logs survive; tagged logs die.
**Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second.
## Phase 5 — Fix + regression test
Write the regression test **before the fix** — but only if there is a **correct seam** for it.
A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence.
**If no correct seam exists, that itself is the finding.** Note it. The codebase architecture is preventing the bug from being locked down. Flag this for the next phase.
If a correct seam exists:
1. Turn the minimised repro into a failing test at that seam.
2. Watch it fail.
3. Apply the fix.
4. Watch it pass.
5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario.
## Phase 6 — Cleanup + post-mortem
Required before declaring done:
- [ ] Original repro no longer reproduces (re-run the Phase 1 loop)
- [ ] Regression test passes (or absence of seam is documented)
- [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix)
- [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location)
- [ ] The hypothesis that turned out correct is stated in the commit / PR message — so the next debugger learns
**Then ask: what would have prevented this bug?** If the answer involves architectural change (no good test seam, tangled callers, hidden coupling) hand off to the `/improve-codebase-architecture` skill with the specifics. Make the recommendation **after** the fix is in, not before — you have more information now than when you started.

View File

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

View File

@@ -0,0 +1,7 @@
---
name: grill-me
description: A relentless interview to sharpen a plan or design.
disable-model-invocation: true
---
Run a `/grilling` session.

View 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.

View 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.

View 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.

View 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.

View 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.

View 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.

View 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.

View 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.

View 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…_

View File

@@ -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`.

View File

@@ -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`.

View File

@@ -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.

View 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
View 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
```

View 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

View 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

View 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);
});
```

View 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 110 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.

View 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.

View 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.

View 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.

View 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.

View 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.

View 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>

View 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

View 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

View 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.

View 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

View 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.

View File

@@ -1,23 +0,0 @@
---
name: OpenSpec: Apply
description: Implement an approved OpenSpec change and keep tasks in sync.
category: OpenSpec
tags: [openspec, apply]
---
<!-- OPENSPEC:START -->
**Guardrails**
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
- Keep changes tightly scoped to the requested outcome.
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
**Steps**
Track these steps as TODOs and complete them one by one.
1. Read `changes/<id>/proposal.md`, `design.md` (if present), and `tasks.md` to confirm scope and acceptance criteria.
2. Work through tasks sequentially, keeping edits minimal and focused on the requested change.
3. Confirm completion before updating statuses—make sure every item in `tasks.md` is finished.
4. Update the checklist after all work is done so each task is marked `- [x]` and reflects reality.
5. Reference `openspec list` or `openspec show <item>` when additional context is required.
**Reference**
- Use `openspec show <id> --json --deltas-only` if you need additional context from the proposal while implementing.
<!-- OPENSPEC:END -->

View File

@@ -1,27 +0,0 @@
---
name: OpenSpec: Archive
description: Archive a deployed OpenSpec change and update specs.
category: OpenSpec
tags: [openspec, archive]
---
<!-- OPENSPEC:START -->
**Guardrails**
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
- Keep changes tightly scoped to the requested outcome.
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
**Steps**
1. Determine the change ID to archive:
- If this prompt already includes a specific change ID (for example inside a `<ChangeId>` block populated by slash-command arguments), use that value after trimming whitespace.
- If the conversation references a change loosely (for example by title or summary), run `openspec list` to surface likely IDs, share the relevant candidates, and confirm which one the user intends.
- Otherwise, review the conversation, run `openspec list`, and ask the user which change to archive; wait for a confirmed change ID before proceeding.
- If you still cannot identify a single change ID, stop and tell the user you cannot archive anything yet.
2. Validate the change ID by running `openspec list` (or `openspec show <id>`) and stop if the change is missing, already archived, or otherwise not ready to archive.
3. Run `openspec archive <id> --yes` so the CLI moves the change and applies spec updates without prompts (use `--skip-specs` only for tooling-only work).
4. Review the command output to confirm the target specs were updated and the change landed in `changes/archive/`.
5. Validate with `openspec validate --strict` and inspect with `openspec show <id>` if anything looks off.
**Reference**
- Use `openspec list` to confirm change IDs before archiving.
- Inspect refreshed specs with `openspec list --specs` and address any validation issues before handing off.
<!-- OPENSPEC:END -->

View File

@@ -1,28 +0,0 @@
---
name: OpenSpec: Proposal
description: Scaffold a new OpenSpec change and validate strictly.
category: OpenSpec
tags: [openspec, change]
---
<!-- OPENSPEC:START -->
**Guardrails**
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
- Keep changes tightly scoped to the requested outcome.
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
- Identify any vague or ambiguous details and ask the necessary follow-up questions before editing files.
- Do not write any code during the proposal stage. Only create design documents (proposal.md, tasks.md, design.md, and spec deltas). Implementation happens in the apply stage after approval.
**Steps**
1. Review `openspec/project.md`, run `openspec list` and `openspec list --specs`, and inspect related code or docs (e.g., via `rg`/`ls`) to ground the proposal in current behaviour; note any gaps that require clarification.
2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, and `design.md` (when needed) under `openspec/changes/<id>/`.
3. Map the change into concrete capabilities or requirements, breaking multi-scope efforts into distinct spec deltas with clear relationships and sequencing.
4. Capture architectural reasoning in `design.md` when the solution spans multiple systems, introduces new patterns, or demands trade-off discussion before committing to specs.
5. Draft spec deltas in `changes/<id>/specs/<capability>/spec.md` (one folder per capability) using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement and cross-reference related capabilities when relevant.
6. Draft `tasks.md` as an ordered list of small, verifiable work items that deliver user-visible progress, include validation (tests, tooling), and highlight dependencies or parallelizable work.
7. Validate with `openspec validate <id> --strict` and resolve every issue before sharing the proposal.
**Reference**
- Use `openspec show <id> --json --deltas-only` or `openspec show <spec> --type spec` to inspect details when validation fails.
- Search existing requirements with `rg -n "Requirement:|Scenario:" openspec/specs` before writing new ones.
- Explore the codebase with `rg <keyword>`, `ls`, or direct file reads so proposals align with current implementation realities.
<!-- OPENSPEC:END -->

View File

@@ -1,5 +1,5 @@
---
name: OPSX: Apply
name: "OPSX: Apply"
description: Implement tasks from an OpenSpec change (Experimental)
category: Workflow
tags: [workflow, artifacts, experimental]
@@ -7,26 +7,25 @@ tags: [workflow, artifacts, experimental]
Implement tasks from an OpenSpec change.
**Input**: Optionally specify `--change <name>` after `/opsx:apply`. If omitted, MUST prompt for available changes.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
1. **Select the change**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Show changes that are implementation-ready (have tasks artifact).
Include the schema used for each change if available.
Mark changes with incomplete tasks as "(In Progress)".
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven", "tdd")
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
@@ -51,7 +50,6 @@ Implement tasks from an OpenSpec change.
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- **tdd**: spec, tests, implementation, docs
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
@@ -113,7 +111,7 @@ Working on task 4/7: <task description>
- [x] Task 2
...
All tasks complete! Ready to archive this change.
All tasks complete! You can archive this change with `/opsx:archive`.
```
**Output On Pause (Issue Encountered)**

View File

@@ -1,5 +1,5 @@
---
name: OPSX: Archive
name: "OPSX: Archive"
description: Archive a completed change in the experimental workflow
category: Workflow
tags: [workflow, archive, experimental]
@@ -7,7 +7,7 @@ tags: [workflow, archive, experimental]
Archive a completed change in the experimental workflow.
**Input**: Optionally specify `--change <name>` after `/opsx:archive`. If omitted, MUST prompt for available changes.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
@@ -46,38 +46,20 @@ Archive a completed change in the experimental workflow.
**If no tasks file exists:** Proceed without task-related warning.
4. **Check if delta specs need syncing**
4. **Assess delta spec sync state**
Check if `specs/` directory exists in the change with spec files.
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist, perform a quick sync check:**
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
a. **For each delta spec** at `openspec/changes/<name>/specs/<capability>/spec.md`:
- Extract requirement names (lines matching `### Requirement: <name>`)
- Note which sections exist (ADDED, MODIFIED, REMOVED)
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
b. **Check corresponding main spec** at `openspec/specs/<capability>/spec.md`:
- If main spec doesn't exist → needs sync
- If main spec exists, check if ADDED requirement names appear in it
- If any ADDED requirements are missing from main spec → needs sync
c. **Report findings:**
**If sync needed:**
```
⚠️ Delta specs may not be synced:
- specs/auth/spec.md → Main spec missing requirement "Token Refresh"
- specs/api/spec.md → Main spec doesn't exist yet
Would you like to sync now before archiving?
```
- Use **AskUserQuestion tool** with options: "Sync now", "Archive without syncing"
- If user chooses sync, execute `/opsx:sync` logic
**If already synced (all requirements found):**
- Proceed without prompting (specs appear to be in sync)
**If no delta specs exist:** Proceed without sync-related checks.
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
@@ -102,7 +84,7 @@ Archive a completed change in the experimental workflow.
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / not synced / no delta specs)
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
@@ -139,12 +121,12 @@ All artifacts complete. All tasks complete.
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ⚠️ Not synced
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta specs were not synced (user chose to skip)
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
@@ -170,6 +152,6 @@ Target archive directory already exists.
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Quick sync check: look for requirement names in delta specs, verify they exist in main specs
- Show clear summary of what happened
- If sync is requested, use /opsx:sync approach (agent-driven)
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,173 @@
---
name: "OPSX: Explore"
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
category: Workflow
tags: [workflow, explore, experimental, thinking]
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,106 @@
---
name: "OPSX: Propose"
description: Propose a new change - create it and generate all artifacts in one step
category: Workflow
tags: [workflow, artifacts, experimental]
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

5
.claude/settings.json Normal file
View File

@@ -0,0 +1,5 @@
{
"enabledPlugins": {
"ralph-loop@claude-plugins-official": true
}
}

View File

@@ -1,6 +1,6 @@
---
name: api-routing
description: API 路由注册规范。注册新 API 路由时使用。包含 Register() 函数用法、RouteSpec 必填项等规范。
description: API 路由注册规范。注册新 API 路由、添加新 Handler 时使用。包含 Register() 函数用法、RouteSpec 必填项、文档生成器更新等规范。
---
# API 路由注册规范
@@ -12,7 +12,29 @@ description: API 路由注册规范。注册新 API 路由时使用。包含 Reg
在以下情况下必须遵守本规范:
- 注册新的 API 路由
- 修改现有路由配置
- 添加新的 Handler 函数
- **添加新的 Handler(必须同步更新文档生成器!)**
## 新增 Handler 检查清单(⚠️ 最容易遗漏)
新增 Handler 时,必须完成以下 **4 个步骤**,否则接口不会出现在 OpenAPI 文档中:
| 步骤 | 文件 | 操作 |
|------|------|------|
| 1⃣ | `internal/bootstrap/types.go` | 添加 Handler 字段 |
| 2⃣ | `internal/bootstrap/handlers.go` | 实例化 Handler |
| 3⃣ | `internal/routes/admin.go` | 调用路由注册函数 |
| 4⃣ | `cmd/api/docs.go` + `cmd/gendocs/main.go` | **添加到文档生成器** |
### 步骤 4 详解(最常遗漏!)
```go
// cmd/api/docs.go 和 cmd/gendocs/main.go 都要改!
handlers := &bootstrap.Handlers{
// ... 现有 Handler
IotCard: admin.NewIotCardHandler(nil), // 添加
IotCardImport: admin.NewIotCardImportHandler(nil), // 添加
}
```
## 核心规则
@@ -108,13 +130,22 @@ Register(router, doc, basePath, "GET", "/health", handler.Health, RouteSpec{
## AI 助手检查清单
注册路由后必须检查:
### 注册路由时
1. ✅ 是否使用 `Register()` 函数而非直接注册
2.`Summary` 是否使用中文简短描述
3.`Tags` 是否正确分组
4.`Input``Output` 是否指向正确的 DTO
5.`Auth` 是否根据业务需求正确设置
### 新增 Handler 时(⚠️ 必查)
1.`internal/bootstrap/types.go` 添加了 Handler 字段
2.`internal/bootstrap/handlers.go` 实例化了 Handler
3.`internal/routes/admin.go` 调用了路由注册函数
4.**`cmd/api/docs.go` 添加了 Handler**
5.**`cmd/gendocs/main.go` 添加了 Handler**
6. ✅ 运行 `go run cmd/gendocs/main.go` 验证文档生成
7. ✅ 运行 `grep "接口路径" docs/admin-openapi.yaml` 确认接口存在
**完整指南**: 参见 [`docs/api-documentation-guide.md`](docs/api-documentation-guide.md)

1
.claude/skills/caveman Symbolic link
View File

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

View 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
View File

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

View File

@@ -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
View File

@@ -0,0 +1 @@
../../.agents/skills/grill-me

View File

@@ -0,0 +1 @@
../../.agents/skills/grill-with-docs

1
.claude/skills/handoff Symbolic link
View File

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

View 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
BODYJSON / 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` 或调整路径 |

View File

@@ -0,0 +1 @@
../../.agents/skills/improve-codebase-architecture

View 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 字段手动维护

View File

@@ -1,30 +1,35 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, MUST prompt for available changes.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
1. **Select the change**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Show changes that are implementation-ready (have tasks artifact).
Include the schema used for each change if available.
Mark changes with incomplete tasks as "(In Progress)".
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven", "tdd")
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
@@ -49,7 +54,6 @@ Implement tasks from an OpenSpec change.
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- **tdd**: spec, tests, implementation, docs
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**

View File

@@ -1,11 +1,17 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, MUST prompt for available changes.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
@@ -44,38 +50,20 @@ Archive a completed change in the experimental workflow.
**If no tasks file exists:** Proceed without task-related warning.
4. **Check if delta specs need syncing**
4. **Assess delta spec sync state**
Check if `specs/` directory exists in the change with spec files.
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist, perform a quick sync check:**
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
a. **For each delta spec** at `openspec/changes/<name>/specs/<capability>/spec.md`:
- Extract requirement names (lines matching `### Requirement: <name>`)
- Note which sections exist (ADDED, MODIFIED, REMOVED)
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
b. **Check corresponding main spec** at `openspec/specs/<capability>/spec.md`:
- If main spec doesn't exist → needs sync
- If main spec exists, check if ADDED requirement names appear in it
- If any ADDED requirements are missing from main spec → needs sync
c. **Report findings:**
**If sync needed:**
```
⚠️ Delta specs may not be synced:
- specs/auth/spec.md → Main spec missing requirement "Token Refresh"
- specs/api/spec.md → Main spec doesn't exist yet
Would you like to sync now before archiving?
```
- Use **AskUserQuestion tool** with options: "Sync now", "Archive without syncing"
- If user chooses sync, execute /opsx:sync logic (use the openspec-sync-specs skill)
**If already synced (all requirements found):**
- Proceed without prompting (specs appear to be in sync)
**If no delta specs exist:** Proceed without sync-related checks.
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
@@ -111,7 +99,7 @@ Archive a completed change in the experimental workflow.
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "⚠️ Not synced")
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
@@ -123,4 +111,4 @@ All artifacts complete. All tasks complete.
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- Quick sync check: look for requirement names in delta specs, verify they exist in main specs
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -1,108 +0,0 @@
---
name: openspec-continue-change
description: Continue working on an OpenSpec change by creating the next artifact. Use when the user wants to progress their change, create the next artifact, or continue their workflow.
---
Continue working on a change by creating the next artifact.
**Input**: Optionally specify a change name. If omitted, MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes sorted by most recently modified. Then use the **AskUserQuestion tool** to let the user select which change to work on.
Present the top 3-4 most recently modified changes as options, showing:
- Change name
- Schema (from `schema` field if present, otherwise "spec-driven")
- Status (e.g., "0/5 tasks", "complete", "no tasks")
- How recently it was modified (from `lastModified` field)
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to continue.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check current status**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand current state. The response includes:
- `schemaName`: The workflow schema being used (e.g., "spec-driven", "tdd")
- `artifacts`: Array of artifacts with their status ("done", "ready", "blocked")
- `isComplete`: Boolean indicating if all artifacts are complete
3. **Act based on status**:
---
**If all artifacts are complete (`isComplete: true`)**:
- Congratulate the user
- Show final status including the schema used
- Suggest: "All artifacts created! You can now implement this change or archive it."
- STOP
---
**If artifacts are ready to create** (status shows artifacts with `status: "ready"`):
- Pick the FIRST artifact with `status: "ready"` from the status output
- Get its instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- Parse the JSON to get template, dependencies, and what it unlocks
- **Create the artifact file** using the template as a starting point:
- Read any completed dependency files for context
- Fill in the template based on context and user's goals
- Write to the output path specified in instructions
- Show what was created and what's now unlocked
- STOP after creating ONE artifact
---
**If no artifacts are ready (all blocked)**:
- This shouldn't happen with a valid schema
- Show status and suggest checking for issues
4. **After creating an artifact, show progress**
```bash
openspec status --change "<name>"
```
**Output**
After each invocation, show:
- Which artifact was created
- Schema workflow being used
- Current progress (N/M complete)
- What artifacts are now unlocked
- Prompt: "Want to continue? Just ask me to continue or tell me what to do next."
**Artifact Creation Guidelines**
The artifact types and their purpose depend on the schema. Use the `instruction` field from the instructions output to understand what to create.
Common artifact patterns:
**spec-driven schema** (proposal → specs → design → tasks):
- **proposal.md**: Ask user about the change if not clear. Fill in Why, What Changes, Capabilities, Impact.
- The Capabilities section is critical - each capability listed will need a spec file.
- **specs/*.md**: Create one spec per capability listed in the proposal.
- **design.md**: Document technical decisions, architecture, and implementation approach.
- **tasks.md**: Break down implementation into checkboxed tasks.
**tdd schema** (spec → tests → implementation → docs):
- **spec.md**: Feature specification defining what to build.
- **tests/*.test.ts**: Write tests BEFORE implementation (TDD red phase).
- **src/*.ts**: Implement to make tests pass (TDD green phase).
- **docs/*.md**: Document the implemented feature.
For other schemas, follow the `instruction` field from the CLI output.
**Guardrails**
- Create ONE artifact per invocation
- Always read dependency artifacts before creating a new one
- Never skip artifacts or create out of order
- If context is unclear, ask the user before creating
- Verify the artifact file exists after writing before marking progress
- Use the schema's artifact sequence, don't assume specific artifact names

View File

@@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
┌───────────┐
│ Session │
└─────┬─────┘
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,281 @@
---
name: openspec-lock-consensus
description: 锁定共识 - 在探索讨论后,将讨论结果锁定为正式共识文档。防止后续提案偏离讨论内容。
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: junhong
version: "1.1"
---
# 共识锁定 Skill
`/opsx:explore` 讨论后,使用此 skill 将讨论结果锁定为正式共识。共识文档是后续所有 artifact 的基础约束。
## 触发方式
```
/opsx:lock <change-name>
```
或在探索结束后AI 主动提议:
> "讨论已经比较清晰了,要锁定共识吗?"
---
## 工作流程
### Step 1: 整理讨论要点
从对话中提取以下四个维度的共识:
| 维度 | 说明 | 示例 |
|------|------|------|
| **要做什么** | 明确的功能范围 | "支持批量导入 IoT 卡" |
| **不做什么** | 明确排除的内容 | "不支持实时同步,仅定时批量" |
| **关键约束** | 技术/业务限制 | "必须使用 Asynq 异步任务" |
| **验收标准** | 如何判断完成 | "导入 1000 张卡 < 30s" |
### Step 2: 使用 Question_tool 逐维度确认
**必须使用 Question_tool 进行结构化确认**,每个维度一个问题:
```typescript
// 示例:确认"要做什么"
Question_tool({
questions: [{
header: "确认:要做什么",
question: "以下是整理的功能范围,请确认:\n\n" +
"1. 功能点 A\n" +
"2. 功能点 B\n" +
"3. 功能点 C\n\n" +
"是否准确完整?",
options: [
{ label: "确认无误", description: "以上内容准确完整" },
{ label: "需要补充", description: "有遗漏的功能点" },
{ label: "需要删减", description: "有不应该包含的内容" }
],
multiple: false
}]
})
```
**如果用户选择"需要补充"或"需要删减"**
- 用户会通过自定义输入提供修改意见
- 根据反馈更新列表,再次使用 Question_tool 确认
**确认流程**
```
┌─────────────────────────────────────────────────────────────────────┐
│ Question_tool: 确认"要做什么" │
│ ├── 用户选择"确认无误" → 进入下一维度 │
│ └── 用户选择其他/自定义 → 修改后重新确认 │
├─────────────────────────────────────────────────────────────────────┤
│ Question_tool: 确认"不做什么" │
│ ├── 用户选择"确认无误" → 进入下一维度 │
│ └── 用户选择其他/自定义 → 修改后重新确认 │
├─────────────────────────────────────────────────────────────────────┤
│ Question_tool: 确认"关键约束" │
│ ├── 用户选择"确认无误" → 进入下一维度 │
│ └── 用户选择其他/自定义 → 修改后重新确认 │
├─────────────────────────────────────────────────────────────────────┤
│ Question_tool: 确认"验收标准" │
│ ├── 用户选择"确认无误" → 生成 consensus.md │
│ └── 用户选择其他/自定义 → 修改后重新确认 │
└─────────────────────────────────────────────────────────────────────┘
```
### Step 3: 生成 consensus.md
所有维度确认后,创建文件:
```bash
# 检查 change 是否存在
openspec list --json
# 如果 change 不存在,先创建
# openspec new <change-name>
# 写入 consensus.md
```
**文件路径**: `openspec/changes/<change-name>/consensus.md`
---
## Question_tool 使用规范
### 每个维度的问题模板
**1. 要做什么**
```typescript
{
header: "确认:要做什么",
question: "以下是整理的【功能范围】:\n\n" +
items.map((item, i) => `${i+1}. ${item}`).join('\n') +
"\n\n请确认是否准确完整",
options: [
{ label: "确认无误", description: "功能范围准确完整" },
{ label: "需要补充", description: "有遗漏的功能点" },
{ label: "需要删减", description: "有不应该包含的内容" }
]
}
```
**2. 不做什么**
```typescript
{
header: "确认:不做什么",
question: "以下是明确【排除的内容】:\n\n" +
items.map((item, i) => `${i+1}. ${item}`).join('\n') +
"\n\n请确认是否正确",
options: [
{ label: "确认无误", description: "排除范围正确" },
{ label: "需要补充", description: "还有其他需要排除的" },
{ label: "需要删减", description: "有些不应该排除" }
]
}
```
**3. 关键约束**
```typescript
{
header: "确认:关键约束",
question: "以下是【关键约束】:\n\n" +
items.map((item, i) => `${i+1}. ${item}`).join('\n') +
"\n\n请确认是否正确",
options: [
{ label: "确认无误", description: "约束条件正确" },
{ label: "需要补充", description: "还有其他约束" },
{ label: "需要修改", description: "约束描述不准确" }
]
}
```
**4. 验收标准**
```typescript
{
header: "确认:验收标准",
question: "以下是【验收标准】(必须可测量):\n\n" +
items.map((item, i) => `${i+1}. ${item}`).join('\n') +
"\n\n请确认是否正确",
options: [
{ label: "确认无误", description: "验收标准清晰可测量" },
{ label: "需要补充", description: "还有其他验收标准" },
{ label: "需要修改", description: "标准不够清晰或无法测量" }
]
}
```
### 处理用户反馈
当用户选择非"确认无误"选项或提供自定义输入时:
1. 解析用户的修改意见
2. 更新对应维度的内容
3. 再次使用 Question_tool 确认更新后的内容
4. 重复直到用户选择"确认无误"
---
## consensus.md 模板
```markdown
# 共识文档
**Change**: <change-name>
**确认时间**: <timestamp>
**确认人**: 用户
---
## 1. 要做什么
- [x] 功能点 A已确认
- [x] 功能点 B已确认
- [x] 功能点 C已确认
## 2. 不做什么
- [x] 排除项 A已确认
- [x] 排除项 B已确认
## 3. 关键约束
- [x] 技术约束 A已确认
- [x] 业务约束 B已确认
## 4. 验收标准
- [x] 验收标准 A已确认
- [x] 验收标准 B已确认
---
## 讨论背景
<简要总结讨论的核心问题和解决方向>
## 关键决策记录
| 决策点 | 选择 | 原因 |
|--------|------|------|
| 决策 1 | 选项 A | 理由... |
| 决策 2 | 选项 B | 理由... |
---
**签字确认**: 用户已通过 Question_tool 逐条确认以上内容
```
---
## 后续流程绑定
### Proposal 生成时
`/opsx:continue` 生成 proposal 时,**必须**
1. 读取 `consensus.md`
2. 确保 proposal 的 Capabilities 覆盖"要做什么"中的每一项
3. 确保 proposal 不包含"不做什么"中的内容
4. 确保 proposal 遵守"关键约束"
### 验证机制
如果 proposal 与 consensus 不一致,输出警告:
```
⚠️ Proposal 验证警告:
共识中"要做什么"但 Proposal 未提及:
- 功能点 C
共识中"不做什么"但 Proposal 包含:
- 排除项 A
建议修正 Proposal 或更新共识。
```
---
## Guardrails
- **必须使用 Question_tool** - 不要用纯文本确认
- **逐维度确认** - 四个维度分开确认,不要合并
- **不要跳过确认** - 每个维度都必须让用户明确确认
- **不要自作主张** - 只整理讨论中明确提到的内容
- **避免模糊表述** - "尽量"、"可能"、"考虑"等词汇需要明确化
- **验收标准必须可测量** - 避免"性能要好"这类无法验证的标准
---
## 与其他 Skills 的关系
| Skill | 关系 |
|-------|------|
| `openspec-explore` | 探索结束后触发 lock |
| `openspec-new-change` | lock 后触发 new如果 change 不存在)|
| `openspec-continue-change` | 生成 proposal 时读取 consensus 验证 |
| `openspec-generate-acceptance-tests` | 从 consensus 的验收标准生成测试骨架 |

View File

@@ -1,68 +0,0 @@
---
name: openspec-new-change
description: Start a new OpenSpec change using the experimental artifact workflow. Use when the user wants to create a new feature, fix, or modification with a structured step-by-step approach.
---
Start a new change using the experimental artifact-driven approach.
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Select a workflow schema**
Run `openspec schemas --json` to get available schemas with descriptions.
Use the **AskUserQuestion tool** to let the user choose a workflow:
- Present each schema with its description
- Mark `spec-driven` as "(default)" if it's available
- Example options: "spec-driven - proposal → specs → design → tasks (default)", "tdd - tests → implementation → docs"
If user doesn't have a preference, default to `spec-driven`.
3. **Create the change directory**
```bash
openspec new change "<name>" --schema "<selected-schema>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with the selected schema.
4. **Show the artifact status**
```bash
openspec status --change "<name>"
```
This shows which artifacts need to be created and which are ready (dependencies satisfied).
5. **Get instructions for the first artifact**
The first artifact depends on the schema (e.g., `proposal` for spec-driven, `spec` for tdd).
Check the status output to find the first artifact with status "ready".
```bash
openspec instructions <first-artifact-id> --change "<name>"
```
This outputs the template and context for creating the first artifact.
6. **STOP and wait for user direction**
**Output**
After completing the steps, summarize:
- Change name and location
- Selected schema/workflow and its artifact sequence
- Current status (0/N artifacts complete)
- The template for the first artifact
- Prompt: "Ready to create the first artifact? Just describe what this change is about and I'll draft it, or ask me to continue."
**Guardrails**
- Do NOT create any artifacts yet - just show the instructions
- Do NOT advance beyond showing the first artifact template
- If the name is invalid (not kebab-case), ask for a valid name
- If a change with that name already exists, suggest continuing that change instead
- Always pass --schema to preserve the user's workflow choice

View File

@@ -1,9 +1,24 @@
---
name: openspec-ff-change
description: Fast-forward through OpenSpec artifact creation. Use when the user wants to quickly create all artifacts needed for implementation without stepping through each one individually.
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Fast-forward through artifact creation - generate everything needed to start implementation in one go.
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
@@ -22,7 +37,7 @@ Fast-forward through artifact creation - generate everything needed to start imp
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/`.
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
@@ -44,13 +59,16 @@ Fast-forward through artifact creation - generate everything needed to start imp
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `template`: The template content to use
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file following the schema's `instruction`
- Show brief progress: "✓ Created <artifact-id>"
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
@@ -79,11 +97,14 @@ After completing all artifacts, summarize:
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use the `template` as a starting point, filling in based on context
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, suggest continuing that change instead
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -1,132 +0,0 @@
---
name: openspec-sync-specs
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Input**: Optionally specify a change name. If omitted, MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show changes that have delta specs (under `specs/` directory).
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Find delta specs**
Look for delta spec files in `openspec/changes/<name>/specs/*/spec.md`.
Each delta spec file contains sections like:
- `## ADDED Requirements` - New requirements to add
- `## MODIFIED Requirements` - Changes to existing requirements
- `## REMOVED Requirements` - Requirements to remove
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
If no delta specs found, inform user and stop.
3. **For each delta spec, apply changes to main specs**
For each capability with a delta spec at `openspec/changes/<name>/specs/<capability>/spec.md`:
a. **Read the delta spec** to understand the intended changes
b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)
c. **Apply changes intelligently**:
**ADDED Requirements:**
- If requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in main spec
- Apply the changes - this can be:
- Adding new scenarios (don't need to copy existing ones)
- Modifying existing scenarios
- Changing the requirement description
- Preserve scenarios/content not mentioned in the delta
**REMOVED Requirements:**
- Remove the entire requirement block from main spec
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
d. **Create new main spec** if capability doesn't exist yet:
- Create `openspec/specs/<capability>/spec.md`
- Add Purpose section (can be brief, mark as TBD)
- Add Requirements section with the ADDED requirements
4. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
**Delta Spec Format Reference**
```markdown
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**Key Principle: Intelligent Merging**
Unlike programmatic merging, you can apply **partial updates**:
- To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
- The delta represents *intent*, not a wholesale replacement
- Use your judgment to merge changes sensibly
**Output On Success**
```
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result

1
.claude/skills/prototype Symbolic link
View File

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

View File

@@ -0,0 +1 @@
../../.agents/skills/setup-matt-pocock-skills

1
.claude/skills/tdd Symbolic link
View File

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

1
.claude/skills/teach Symbolic link
View File

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

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

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

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

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

1
.claude/skills/triage Symbolic link
View File

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

View File

@@ -0,0 +1 @@
../../.agents/skills/write-a-skill

1
.claude/skills/zoom-out Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/zoom-out

View File

@@ -0,0 +1,150 @@
---
description: Implement tasks from an OpenSpec change (Experimental)
argument-hint: command arguments
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,155 @@
---
description: Archive a completed change in the experimental workflow
argument-hint: command arguments
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, execute `/opsx:sync` logic. Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use /opsx:sync approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,240 @@
---
description: Archive multiple completed changes at once
argument-hint: command arguments
---
Archive multiple completed changes in a single operation.
This skill allows you to batch-archive changes, handling spec conflicts intelligently by checking the codebase to determine what's actually implemented.
**Input**: None required (prompts for selection)
**Steps**
1. **Get active changes**
Run `openspec list --json` to get all active changes.
If no active changes exist, inform user and stop.
2. **Prompt for change selection**
Use **AskUserQuestion tool** with multi-select to let user choose changes:
- Show each change with its schema
- Include an option for "All changes"
- Allow any number of selections (1+ works, 2+ is the typical use case)
**IMPORTANT**: Do NOT auto-select. Always let the user choose.
3. **Batch validation - gather status for all selected changes**
For each selected change, collect:
a. **Artifact status** - Run `openspec status --change "<name>" --json`
- Parse `schemaName` and `artifacts` list
- Note which artifacts are `done` vs other states
b. **Task completion** - Read `openspec/changes/<name>/tasks.md`
- Count `- [ ]` (incomplete) vs `- [x]` (complete)
- If no tasks file exists, note as "No tasks"
c. **Delta specs** - Check `openspec/changes/<name>/specs/` directory
- List which capability specs exist
- For each, extract requirement names (lines matching `### Requirement: <name>`)
4. **Detect spec conflicts**
Build a map of `capability -> [changes that touch it]`:
```
auth -> [change-a, change-b] <- CONFLICT (2+ changes)
api -> [change-c] <- OK (only 1 change)
```
A conflict exists when 2+ selected changes have delta specs for the same capability.
5. **Resolve conflicts agentically**
**For each conflict**, investigate the codebase:
a. **Read the delta specs** from each conflicting change to understand what each claims to add/modify
b. **Search the codebase** for implementation evidence:
- Look for code implementing requirements from each delta spec
- Check for related files, functions, or tests
c. **Determine resolution**:
- If only one change is actually implemented -> sync that one's specs
- If both implemented -> apply in chronological order (older first, newer overwrites)
- If neither implemented -> skip spec sync, warn user
d. **Record resolution** for each conflict:
- Which change's specs to apply
- In what order (if both)
- Rationale (what was found in codebase)
6. **Show consolidated status table**
Display a table summarizing all changes:
```
| Change | Artifacts | Tasks | Specs | Conflicts | Status |
|---------------------|-----------|-------|---------|-----------|--------|
| schema-management | Done | 5/5 | 2 delta | None | Ready |
| project-config | Done | 3/3 | 1 delta | None | Ready |
| add-oauth | Done | 4/4 | 1 delta | auth (!) | Ready* |
| add-verify-skill | 1 left | 2/5 | None | None | Warn |
```
For conflicts, show the resolution:
```
* Conflict resolution:
- auth spec: Will apply add-oauth then add-jwt (both implemented, chronological order)
```
For incomplete changes, show warnings:
```
Warnings:
- add-verify-skill: 1 incomplete artifact, 3 incomplete tasks
```
7. **Confirm batch operation**
Use **AskUserQuestion tool** with a single confirmation:
- "Archive N changes?" with options based on status
- Options might include:
- "Archive all N changes"
- "Archive only N ready changes (skip incomplete)"
- "Cancel"
If there are incomplete changes, make clear they'll be archived with warnings.
8. **Execute archive for each confirmed change**
Process changes in the determined order (respecting conflict resolution):
a. **Sync specs** if delta specs exist:
- Use the openspec-sync-specs approach (agent-driven intelligent merge)
- For conflicts, apply in resolved order
- Track if sync was done
b. **Perform the archive**:
```bash
mkdir -p openspec/changes/archive
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
c. **Track outcome** for each change:
- Success: archived successfully
- Failed: error during archive (record error)
- Skipped: user chose not to archive (if applicable)
9. **Display summary**
Show final results:
```
## Bulk Archive Complete
Archived 3 changes:
- schema-management-cli -> archive/2026-01-19-schema-management-cli/
- project-config -> archive/2026-01-19-project-config/
- add-oauth -> archive/2026-01-19-add-oauth/
Skipped 1 change:
- add-verify-skill (user chose not to archive incomplete)
Spec sync summary:
- 4 delta specs synced to main specs
- 1 conflict resolved (auth: applied both in chronological order)
```
If any failures:
```
Failed 1 change:
- some-change: Archive directory already exists
```
**Conflict Resolution Examples**
Example 1: Only one implemented
```
Conflict: specs/auth/spec.md touched by [add-oauth, add-jwt]
Checking add-oauth:
- Delta adds "OAuth Provider Integration" requirement
- Searching codebase... found src/auth/oauth.ts implementing OAuth flow
Checking add-jwt:
- Delta adds "JWT Token Handling" requirement
- Searching codebase... no JWT implementation found
Resolution: Only add-oauth is implemented. Will sync add-oauth specs only.
```
Example 2: Both implemented
```
Conflict: specs/api/spec.md touched by [add-rest-api, add-graphql]
Checking add-rest-api (created 2026-01-10):
- Delta adds "REST Endpoints" requirement
- Searching codebase... found src/api/rest.ts
Checking add-graphql (created 2026-01-15):
- Delta adds "GraphQL Schema" requirement
- Searching codebase... found src/api/graphql.ts
Resolution: Both implemented. Will apply add-rest-api specs first,
then add-graphql specs (chronological order, newer takes precedence).
```
**Output On Success**
```
## Bulk Archive Complete
Archived N changes:
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
- <change-2> -> archive/YYYY-MM-DD-<change-2>/
Spec sync summary:
- N delta specs synced to main specs
- No conflicts (or: M conflicts resolved)
```
**Output On Partial Success**
```
## Bulk Archive Complete (partial)
Archived N changes:
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
Skipped M changes:
- <change-2> (user chose not to archive incomplete)
Failed K changes:
- <change-3>: Archive directory already exists
```
**Output When No Changes**
```
## No Changes to Archive
No active changes found. Use `/opsx:new` to create a new change.
```
**Guardrails**
- Allow any number of changes (1+ is fine, 2+ is the typical use case)
- Always prompt for selection, never auto-select
- Detect spec conflicts early and resolve by checking codebase
- When both changes are implemented, apply specs in chronological order
- Skip spec sync only when implementation is missing (warn user)
- Show clear per-change status before confirming
- Use single confirmation for entire batch
- Track and report all outcomes (success/skip/fail)
- Preserve .openspec.yaml when moving to archive
- Archive directory target uses current date: YYYY-MM-DD-<name>
- If archive target exists, fail that change but continue with others

View File

@@ -1,13 +1,11 @@
---
name: OPSX: Continue
description: Continue working on a change - create the next artifact (Experimental)
category: Workflow
tags: [workflow, artifacts, experimental]
argument-hint: command arguments
---
Continue working on a change by creating the next artifact.
**Input**: Optionally specify `--change <name>` after `/opsx:continue`. If omitted, MUST prompt for available changes.
**Input**: Optionally specify a change name after `/opsx:continue` (e.g., `/opsx:continue add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
@@ -30,7 +28,7 @@ Continue working on a change by creating the next artifact.
openspec status --change "<name>" --json
```
Parse the JSON to understand current state. The response includes:
- `schemaName`: The workflow schema being used (e.g., "spec-driven", "tdd")
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
- `artifacts`: Array of artifacts with their status ("done", "ready", "blocked")
- `isComplete`: Boolean indicating if all artifacts are complete
@@ -52,10 +50,17 @@ Continue working on a change by creating the next artifact.
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- Parse the JSON to get template, dependencies, and what it unlocks
- **Create the artifact file** using the template as a starting point:
- Parse the JSON. The key fields are:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- **Create the artifact file**:
- Read any completed dependency files for context
- Fill in the template based on context and user's goals
- Use `template` as the structure - fill in its sections
- Apply `context` and `rules` as constraints when writing - but do NOT copy them into the file
- Write to the output path specified in instructions
- Show what was created and what's now unlocked
- STOP after creating ONE artifact
@@ -89,16 +94,10 @@ Common artifact patterns:
**spec-driven schema** (proposal → specs → design → tasks):
- **proposal.md**: Ask user about the change if not clear. Fill in Why, What Changes, Capabilities, Impact.
- The Capabilities section is critical - each capability listed will need a spec file.
- **specs/*.md**: Create one spec per capability listed in the proposal.
- **specs/<capability>/spec.md**: Create one spec per capability listed in the proposal's Capabilities section (use the capability name, not the change name).
- **design.md**: Document technical decisions, architecture, and implementation approach.
- **tasks.md**: Break down implementation into checkboxed tasks.
**tdd schema** (spec → tests → implementation → docs):
- **spec.md**: Feature specification defining what to build.
- **tests/*.test.ts**: Write tests BEFORE implementation (TDD red phase).
- **src/*.ts**: Implement to make tests pass (TDD green phase).
- **docs/*.md**: Document the implemented feature.
For other schemas, follow the `instruction` field from the CLI output.
**Guardrails**
@@ -108,3 +107,6 @@ For other schemas, follow the `instruction` field from the CLI output.
- If context is unclear, ask the user before creating
- Verify the artifact file exists after writing before marking progress
- Use the schema's artifact sequence, don't assume specific artifact names
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output

View File

@@ -0,0 +1,172 @@
---
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
argument-hint: command arguments
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first (e.g., start a change with `/opsx:new` or `/opsx:ff`). You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create one?"
→ Can transition to `/opsx:new` or `/opsx:ff`
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into action**: "Ready to start? `/opsx:new` or `/opsx:ff`"
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -1,8 +1,6 @@
---
name: OPSX: Fast Forward
description: Create a change and generate all artifacts needed for implementation in one go
category: Workflow
tags: [workflow, artifacts, experimental]
argument-hint: command arguments
---
Fast-forward through artifact creation - generate everything needed to start implementation.
@@ -46,12 +44,15 @@ Fast-forward through artifact creation - generate everything needed to start imp
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `template`: The template content to use
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file following the schema's `instruction`
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "✓ Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**

View File

@@ -1,8 +1,6 @@
---
name: OPSX: New
description: Start a new change using the experimental artifact workflow (OPSX)
category: Workflow
tags: [workflow, artifacts, experimental]
argument-hint: command arguments
---
Start a new change using the experimental artifact-driven approach.
@@ -20,21 +18,21 @@ Start a new change using the experimental artifact-driven approach.
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Select a workflow schema**
2. **Determine the workflow schema**
Run `openspec schemas --json` to get available schemas with descriptions.
Use the default schema (omit `--schema`) unless the user explicitly requests a different workflow.
Use the **AskUserQuestion tool** to let the user choose a workflow:
- Present each schema with its description
- Mark `spec-driven` as "(default)" if it's available
- Example options: "spec-driven - proposal → specs → design → tasks (default)", "tdd - tests → implementation → docs"
**Use a different schema only if the user mentions:**
- A specific schema name → use `--schema <name>`
- "show workflows" or "what workflows" → run `openspec schemas --json` and let them choose
If user doesn't have a preference, default to `spec-driven`.
**Otherwise**: Omit `--schema` to use the default.
3. **Create the change directory**
```bash
openspec new change "<name>" --schema "<selected-schema>"
openspec new change "<name>"
```
Add `--schema <name>` only if the user requested a specific workflow.
This creates a scaffolded change at `openspec/changes/<name>/` with the selected schema.
4. **Show the artifact status**
@@ -56,7 +54,7 @@ Start a new change using the experimental artifact-driven approach.
After completing the steps, summarize:
- Change name and location
- Selected schema/workflow and its artifact sequence
- Schema/workflow being used and its artifact sequence
- Current status (0/N artifacts complete)
- The template for the first artifact
- Prompt: "Ready to create the first artifact? Run `/opsx:continue` or just describe what this change is about and I'll draft it."
@@ -66,4 +64,4 @@ After completing the steps, summarize:
- Do NOT advance beyond showing the first artifact template
- If the name is invalid (not kebab-case), ask for a valid name
- If a change with that name already exists, suggest using `/opsx:continue` instead
- Always pass --schema to preserve the user's workflow choice
- Pass --schema if using a non-default workflow

View File

@@ -0,0 +1,523 @@
---
description: Guided onboarding - walk through a complete OpenSpec workflow cycle with narration
argument-hint: command arguments
---
Guide the user through their first complete OpenSpec workflow cycle. This is a teaching experience—you'll do real work in their codebase while explaining each step.
---
## Preflight
Before starting, check if OpenSpec is initialized:
```bash
openspec status --json 2>&1 || echo "NOT_INITIALIZED"
```
**If not initialized:**
> OpenSpec isn't set up in this project yet. Run `openspec init` first, then come back to `/opsx:onboard`.
Stop here if not initialized.
---
## Phase 1: Welcome
Display:
```
## Welcome to OpenSpec!
I'll walk you through a complete change cycle—from idea to implementation—using a real task in your codebase. Along the way, you'll learn the workflow by doing it.
**What we'll do:**
1. Pick a small, real task in your codebase
2. Explore the problem briefly
3. Create a change (the container for our work)
4. Build the artifacts: proposal → specs → design → tasks
5. Implement the tasks
6. Archive the completed change
**Time:** ~15-20 minutes
Let's start by finding something to work on.
```
---
## Phase 2: Task Selection
### Codebase Analysis
Scan the codebase for small improvement opportunities. Look for:
1. **TODO/FIXME comments** - Search for `TODO`, `FIXME`, `HACK`, `XXX` in code files
2. **Missing error handling** - `catch` blocks that swallow errors, risky operations without try-catch
3. **Functions without tests** - Cross-reference `src/` with test directories
4. **Type issues** - `any` types in TypeScript files (`: any`, `as any`)
5. **Debug artifacts** - `console.log`, `console.debug`, `debugger` statements in non-debug code
6. **Missing validation** - User input handlers without validation
Also check recent git activity:
```bash
git log --oneline -10 2>/dev/null || echo "No git history"
```
### Present Suggestions
From your analysis, present 3-4 specific suggestions:
```
## Task Suggestions
Based on scanning your codebase, here are some good starter tasks:
**1. [Most promising task]**
Location: `src/path/to/file.ts:42`
Scope: ~1-2 files, ~20-30 lines
Why it's good: [brief reason]
**2. [Second task]**
Location: `src/another/file.ts`
Scope: ~1 file, ~15 lines
Why it's good: [brief reason]
**3. [Third task]**
Location: [location]
Scope: [estimate]
Why it's good: [brief reason]
**4. Something else?**
Tell me what you'd like to work on.
Which task interests you? (Pick a number or describe your own)
```
**If nothing found:** Fall back to asking what the user wants to build:
> I didn't find obvious quick wins in your codebase. What's something small you've been meaning to add or fix?
### Scope Guardrail
If the user picks or describes something too large (major feature, multi-day work):
```
That's a valuable task, but it's probably larger than ideal for your first OpenSpec run-through.
For learning the workflow, smaller is better—it lets you see the full cycle without getting stuck in implementation details.
**Options:**
1. **Slice it smaller** - What's the smallest useful piece of [their task]? Maybe just [specific slice]?
2. **Pick something else** - One of the other suggestions, or a different small task?
3. **Do it anyway** - If you really want to tackle this, we can. Just know it'll take longer.
What would you prefer?
```
Let the user override if they insist—this is a soft guardrail.
---
## Phase 3: Explore Demo
Once a task is selected, briefly demonstrate explore mode:
```
Before we create a change, let me quickly show you **explore mode**—it's how you think through problems before committing to a direction.
```
Spend 1-2 minutes investigating the relevant code:
- Read the file(s) involved
- Draw a quick ASCII diagram if it helps
- Note any considerations
```
## Quick Exploration
[Your brief analysis—what you found, any considerations]
┌─────────────────────────────────────────┐
│ [Optional: ASCII diagram if helpful] │
└─────────────────────────────────────────┘
Explore mode (`/opsx:explore`) is for this kind of thinking—investigating before implementing. You can use it anytime you need to think through a problem.
Now let's create a change to hold our work.
```
**PAUSE** - Wait for user acknowledgment before proceeding.
---
## Phase 4: Create the Change
**EXPLAIN:**
```
## Creating a Change
A "change" in OpenSpec is a container for all the thinking and planning around a piece of work. It lives in `openspec/changes/<name>/` and holds your artifacts—proposal, specs, design, tasks.
Let me create one for our task.
```
**DO:** Create the change with a derived kebab-case name:
```bash
openspec new change "<derived-name>"
```
**SHOW:**
```
Created: `openspec/changes/<name>/`
The folder structure:
```
openspec/changes/<name>/
├── proposal.md ← Why we're doing this (empty, we'll fill it)
├── design.md ← How we'll build it (empty)
├── specs/ ← Detailed requirements (empty)
└── tasks.md ← Implementation checklist (empty)
```
Now let's fill in the first artifact—the proposal.
```
---
## Phase 5: Proposal
**EXPLAIN:**
```
## The Proposal
The proposal captures **why** we're making this change and **what** it involves at a high level. It's the "elevator pitch" for the work.
I'll draft one based on our task.
```
**DO:** Draft the proposal content (don't save yet):
```
Here's a draft proposal:
---
## Why
[1-2 sentences explaining the problem/opportunity]
## What Changes
[Bullet points of what will be different]
## Capabilities
### New Capabilities
- `<capability-name>`: [brief description]
### Modified Capabilities
<!-- If modifying existing behavior -->
## Impact
- `src/path/to/file.ts`: [what changes]
- [other files if applicable]
---
Does this capture the intent? I can adjust before we save it.
```
**PAUSE** - Wait for user approval/feedback.
After approval, save the proposal:
```bash
openspec instructions proposal --change "<name>" --json
```
Then write the content to `openspec/changes/<name>/proposal.md`.
```
Proposal saved. This is your "why" document—you can always come back and refine it as understanding evolves.
Next up: specs.
```
---
## Phase 6: Specs
**EXPLAIN:**
```
## Specs
Specs define **what** we're building in precise, testable terms. They use a requirement/scenario format that makes expected behavior crystal clear.
For a small task like this, we might only need one spec file.
```
**DO:** Create the spec file:
```bash
mkdir -p openspec/changes/<name>/specs/<capability-name>
```
Draft the spec content:
```
Here's the spec:
---
## ADDED Requirements
### Requirement: <Name>
<Description of what the system should do>
#### Scenario: <Scenario name>
- **WHEN** <trigger condition>
- **THEN** <expected outcome>
- **AND** <additional outcome if needed>
---
This format—WHEN/THEN/AND—makes requirements testable. You can literally read them as test cases.
```
Save to `openspec/changes/<name>/specs/<capability>/spec.md`.
---
## Phase 7: Design
**EXPLAIN:**
```
## Design
The design captures **how** we'll build it—technical decisions, tradeoffs, approach.
For small changes, this might be brief. That's fine—not every change needs deep design discussion.
```
**DO:** Draft design.md:
```
Here's the design:
---
## Context
[Brief context about the current state]
## Goals / Non-Goals
**Goals:**
- [What we're trying to achieve]
**Non-Goals:**
- [What's explicitly out of scope]
## Decisions
### Decision 1: [Key decision]
[Explanation of approach and rationale]
---
For a small task, this captures the key decisions without over-engineering.
```
Save to `openspec/changes/<name>/design.md`.
---
## Phase 8: Tasks
**EXPLAIN:**
```
## Tasks
Finally, we break the work into implementation tasks—checkboxes that drive the apply phase.
These should be small, clear, and in logical order.
```
**DO:** Generate tasks based on specs and design:
```
Here are the implementation tasks:
---
## 1. [Category or file]
- [ ] 1.1 [Specific task]
- [ ] 1.2 [Specific task]
## 2. Verify
- [ ] 2.1 [Verification step]
---
Each checkbox becomes a unit of work in the apply phase. Ready to implement?
```
**PAUSE** - Wait for user to confirm they're ready to implement.
Save to `openspec/changes/<name>/tasks.md`.
---
## Phase 9: Apply (Implementation)
**EXPLAIN:**
```
## Implementation
Now we implement each task, checking them off as we go. I'll announce each one and occasionally note how the specs/design informed the approach.
```
**DO:** For each task:
1. Announce: "Working on task N: [description]"
2. Implement the change in the codebase
3. Reference specs/design naturally: "The spec says X, so I'm doing Y"
4. Mark complete in tasks.md: `- [ ]``- [x]`
5. Brief status: "✓ Task N complete"
Keep narration light—don't over-explain every line of code.
After all tasks:
```
## Implementation Complete
All tasks done:
- [x] Task 1
- [x] Task 2
- [x] ...
The change is implemented! One more step—let's archive it.
```
---
## Phase 10: Archive
**EXPLAIN:**
```
## Archiving
When a change is complete, we archive it. This moves it from `openspec/changes/` to `openspec/changes/archive/YYYY-MM-DD-<name>/`.
Archived changes become your project's decision history—you can always find them later to understand why something was built a certain way.
```
**DO:**
```bash
openspec archive "<name>"
```
**SHOW:**
```
Archived to: `openspec/changes/archive/YYYY-MM-DD-<name>/`
The change is now part of your project's history. The code is in your codebase, the decision record is preserved.
```
---
## Phase 11: Recap & Next Steps
```
## Congratulations!
You just completed a full OpenSpec cycle:
1. **Explore** - Thought through the problem
2. **New** - Created a change container
3. **Proposal** - Captured WHY
4. **Specs** - Defined WHAT in detail
5. **Design** - Decided HOW
6. **Tasks** - Broke it into steps
7. **Apply** - Implemented the work
8. **Archive** - Preserved the record
This same rhythm works for any size change—a small fix or a major feature.
---
## Command Reference
| Command | What it does |
|---------|--------------|
| `/opsx:explore` | Think through problems before/during work |
| `/opsx:new` | Start a new change, step through artifacts |
| `/opsx:ff` | Fast-forward: create all artifacts at once |
| `/opsx:continue` | Continue working on an existing change |
| `/opsx:apply` | Implement tasks from a change |
| `/opsx:verify` | Verify implementation matches artifacts |
| `/opsx:archive` | Archive a completed change |
---
## What's Next?
Try `/opsx:new` or `/opsx:ff` on something you actually want to build. You've got the rhythm now!
```
---
## Graceful Exit Handling
### User wants to stop mid-way
If the user says they need to stop, want to pause, or seem disengaged:
```
No problem! Your change is saved at `openspec/changes/<name>/`.
To pick up where we left off later:
- `/opsx:continue <name>` - Resume artifact creation
- `/opsx:apply <name>` - Jump to implementation (if tasks exist)
The work won't be lost. Come back whenever you're ready.
```
Exit gracefully without pressure.
### User just wants command reference
If the user says they just want to see the commands or skip the tutorial:
```
## OpenSpec Quick Reference
| Command | What it does |
|---------|--------------|
| `/opsx:explore` | Think through problems (no code changes) |
| `/opsx:new <name>` | Start a new change, step by step |
| `/opsx:ff <name>` | Fast-forward: all artifacts at once |
| `/opsx:continue <name>` | Continue an existing change |
| `/opsx:apply <name>` | Implement tasks |
| `/opsx:verify <name>` | Verify implementation |
| `/opsx:archive <name>` | Archive when done |
Try `/opsx:new` to start your first change, or `/opsx:ff` if you want to move fast.
```
Exit gracefully.
---
## Guardrails
- **Follow the EXPLAIN → DO → SHOW → PAUSE pattern** at key transitions (after explore, after proposal draft, after tasks, after archive)
- **Keep narration light** during implementation—teach without lecturing
- **Don't skip phases** even if the change is small—the goal is teaching the workflow
- **Pause for acknowledgment** at marked points, but don't over-pause
- **Handle exits gracefully**—never pressure the user to continue
- **Use real codebase tasks**—don't simulate or use fake examples
- **Adjust scope gently**—guide toward smaller tasks but respect user choice

View File

@@ -1,15 +1,13 @@
---
name: OPSX: Sync
description: Sync delta specs from a change to main specs
category: Workflow
tags: [workflow, specs, experimental]
argument-hint: command arguments
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Input**: Optionally specify `--change <name>` after `/opsx:sync`. If omitted, MUST prompt for available changes.
**Input**: Optionally specify a change name after `/opsx:sync` (e.g., `/opsx:sync add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**

View File

@@ -0,0 +1,162 @@
---
description: Verify implementation matches change artifacts before archiving
argument-hint: command arguments
---
Verify that an implementation matches the change artifacts (specs, tasks, design).
**Input**: Optionally specify a change name after `/opsx:verify` (e.g., `/opsx:verify add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show changes that have implementation tasks (tasks artifact exists).
Include the schema used for each change if available.
Mark changes with incomplete tasks as "(In Progress)".
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifacts exist for this change
3. **Get the change directory and load artifacts**
```bash
openspec instructions apply --change "<name>" --json
```
This returns the change directory and context files. Read all available artifacts from `contextFiles`.
4. **Initialize verification report structure**
Create a report structure with three dimensions:
- **Completeness**: Track tasks and spec coverage
- **Correctness**: Track requirement implementation and scenario coverage
- **Coherence**: Track design adherence and pattern consistency
Each dimension can have CRITICAL, WARNING, or SUGGESTION issues.
5. **Verify Completeness**
**Task Completion**:
- If tasks.md exists in contextFiles, read it
- Parse checkboxes: `- [ ]` (incomplete) vs `- [x]` (complete)
- Count complete vs total tasks
- If incomplete tasks exist:
- Add CRITICAL issue for each incomplete task
- Recommendation: "Complete task: <description>" or "Mark as done if already implemented"
**Spec Coverage**:
- If delta specs exist in `openspec/changes/<name>/specs/`:
- Extract all requirements (marked with "### Requirement:")
- For each requirement:
- Search codebase for keywords related to the requirement
- Assess if implementation likely exists
- If requirements appear unimplemented:
- Add CRITICAL issue: "Requirement not found: <requirement name>"
- Recommendation: "Implement requirement X: <description>"
6. **Verify Correctness**
**Requirement Implementation Mapping**:
- For each requirement from delta specs:
- Search codebase for implementation evidence
- If found, note file paths and line ranges
- Assess if implementation matches requirement intent
- If divergence detected:
- Add WARNING: "Implementation may diverge from spec: <details>"
- Recommendation: "Review <file>:<lines> against requirement X"
**Scenario Coverage**:
- For each scenario in delta specs (marked with "#### Scenario:"):
- Check if conditions are handled in code
- Check if tests exist covering the scenario
- If scenario appears uncovered:
- Add WARNING: "Scenario not covered: <scenario name>"
- Recommendation: "Add test or implementation for scenario: <description>"
7. **Verify Coherence**
**Design Adherence**:
- If design.md exists in contextFiles:
- Extract key decisions (look for sections like "Decision:", "Approach:", "Architecture:")
- Verify implementation follows those decisions
- If contradiction detected:
- Add WARNING: "Design decision not followed: <decision>"
- Recommendation: "Update implementation or revise design.md to match reality"
- If no design.md: Skip design adherence check, note "No design.md to verify against"
**Code Pattern Consistency**:
- Review new code for consistency with project patterns
- Check file naming, directory structure, coding style
- If significant deviations found:
- Add SUGGESTION: "Code pattern deviation: <details>"
- Recommendation: "Consider following project pattern: <example>"
8. **Generate Verification Report**
**Summary Scorecard**:
```
## Verification Report: <change-name>
### Summary
| Dimension | Status |
|--------------|------------------|
| Completeness | X/Y tasks, N reqs|
| Correctness | M/N reqs covered |
| Coherence | Followed/Issues |
```
**Issues by Priority**:
1. **CRITICAL** (Must fix before archive):
- Incomplete tasks
- Missing requirement implementations
- Each with specific, actionable recommendation
2. **WARNING** (Should fix):
- Spec/design divergences
- Missing scenario coverage
- Each with specific recommendation
3. **SUGGESTION** (Nice to fix):
- Pattern inconsistencies
- Minor improvements
- Each with specific recommendation
**Final Assessment**:
- If CRITICAL issues: "X critical issue(s) found. Fix before archiving."
- If only warnings: "No critical issues. Y warning(s) to consider. Ready for archive (with noted improvements)."
- If all clear: "All checks passed. Ready for archive."
**Verification Heuristics**
- **Completeness**: Focus on objective checklist items (checkboxes, requirements list)
- **Correctness**: Use keyword search, file path analysis, reasonable inference - don't require perfect certainty
- **Coherence**: Look for glaring inconsistencies, don't nitpick style
- **False Positives**: When uncertain, prefer SUGGESTION over WARNING, WARNING over CRITICAL
- **Actionability**: Every issue must have a specific recommendation with file/line references where applicable
**Graceful Degradation**
- If only tasks.md exists: verify task completion only, skip spec/design checks
- If tasks + specs exist: verify completeness and correctness, skip design
- If full artifacts: verify all three dimensions
- Always note which checks were skipped and why
**Output Format**
Use clear markdown with:
- Table for summary scorecard
- Grouped lists for issues (CRITICAL/WARNING/SUGGESTION)
- Code references in format: `file.ts:123`
- Specific, actionable recommendations
- No vague suggestions like "consider reviewing"

View 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.

View File

@@ -0,0 +1,4 @@
interface:
display_name: "导出数据源开发"
short_description: "指导新增和维护项目导出数据源场景"
default_prompt: "Use $export-datasource to add a new export scene for this project."

View File

@@ -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;
```

View File

@@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
┌───────────┐
│ Session │
└─────┬─────┘
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

36
.config/dbhub.toml Normal file
View File

@@ -0,0 +1,36 @@
[[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"
[[tools]]
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
View 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
View 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
View 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

View File

@@ -64,26 +64,13 @@ jobs:
- name: 部署到本地(仅 main 分支)
if: github.ref == 'refs/heads/main'
run: |
# 确保部署目录存在
mkdir -p ${{ env.DEPLOY_DIR }}/{configs,logs}
# 调试:显示当前目录和文件
echo "📍 当前工作目录: $(pwd)"
echo "📁 当前目录内容:"
ls -la
# 确保部署目录存在(仅需日志目录,配置已嵌入二进制文件)
mkdir -p ${{ env.DEPLOY_DIR }}/logs
# 强制更新 docker-compose.prod.yml确保使用最新配置
echo "📋 更新部署配置文件..."
cp -v docker-compose.prod.yml ${{ env.DEPLOY_DIR }}/
# configs 目录只在不存在时初始化(避免覆盖运行时配置)
if [ ! -d ${{ env.DEPLOY_DIR }}/configs ] || [ -z "$(ls -A ${{ env.DEPLOY_DIR }}/configs 2>/dev/null)" ]; then
echo "📋 初始化配置目录..."
cp -rv configs/* ${{ env.DEPLOY_DIR }}/configs/
else
echo "✅ 配置目录已存在,保留现有配置"
fi
cd ${{ env.DEPLOY_DIR }}
echo "📥 拉取最新镜像..."

40
.gitignore vendored
View File

@@ -26,8 +26,6 @@ vendor/
.cache/
# Environment variables
.env
.env.*
!.env.example
# Log files
@@ -73,3 +71,41 @@ cmd/api/api
ai-gateway.conf
__debug_bin1621385388
docs/admin-openapi.yaml
/api
/gendocs
/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

15
.mcp.json Normal file
View File

@@ -0,0 +1,15 @@
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@bytebase/dbhub@latest",
"--transport",
"stdio",
"--config",
".config/dbhub.toml"
]
}
}
}

View File

@@ -0,0 +1,149 @@
---
description: Implement tasks from an OpenSpec change (Experimental)
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx-apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx-continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx-archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,154 @@
---
description: Archive a completed change in the experimental workflow
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx-archive` (e.g., `/opsx-archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,170 @@
---
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx-explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,103 @@
---
description: Propose a new change - create it and generate all artifacts in one step
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx-apply
---
**Input**: The argument after `/opsx-propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx-apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

115
.opencode/package-lock.json generated Normal file
View 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"
}
}
}
}

View 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
```

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