Compare commits

...

339 Commits

Author SHA1 Message Date
6212e0d92f test: add unit test framework and calculation service tests 2026-06-21 05:31:03 +08:00
83671834ca refactor: split IChargeBillServiceImpl into focused services 2026-06-21 05:19:38 +08:00
4460ceae66 chore: clean up expired TODOs and create tracking document
- Remove expired TODO from TenantOptionUtil.java (7 months overdue, was: '最晚2025年11月底删除')
- Remove commented-out dead code
- Create docs/TODO_TRACKING.md with categorized inventory of 37 remaining TODOs
2026-06-21 05:08:31 +08:00
785c8dac64 refactor(test): extract BaseApiTest to eliminate login duplication 2026-06-21 05:02:04 +08:00
c37f30b989 fix: 全量clean编译修复残留class文件问题 2026-06-21 04:58:37 +08:00
94ba3022c8 fix(test): replace fragile assertions with meaningful validations 2026-06-21 04:56:02 +08:00
0cad9be0eb fix: remove duplicate files to prevent classpath conflicts 2026-06-21 04:53:10 +08:00
29fc989554 fix(report): 修复InfectiousCardMapper.xml DTO引用路径 2026-06-21 04:51:47 +08:00
38346f47cf fix(pharmacy): 修复所有药房模块XML DTO引用路径 2026-06-21 04:48:08 +08:00
8be86da14d fix(pharmacy): 修复CommonAppMapper.xml DTO引用路径 2026-06-21 04:40:57 +08:00
11f92ebc42 feat(pharmacy): 添加药房配药模块核心功能
- 新增租户配置工具类TenantOptionUtil,支持租户配置项获取及临时兼容方案
- 实现药房共通服务PharmacyDispensaryCommonService,提供初始化、药品查询、分页等功能
- 开发药房发药单服务PharmacyDispensaryDispensingOrderService,支持发药单详情及编辑操作
- 创建药房损益单服务PharmacyDispensaryProfitLossOrderService,处理损益单业务逻辑
- 构建药房请领单服务PharmacyDispensaryRequisitionOrderService,请领流程管理
- 设计药房退库单服务PharmacyDispensaryReturnToWarehouseOrderService,退库业务处理
2026-06-21 04:35:27 +08:00
fbafd661c2 refactor(util): 迁移TenantOptionUtil并重构相关依赖
- 将TenantOptionUtil从web包移动到common.utils包
- 更新所有相关控制器和服务中的导入路径
- 将YbManager实现类替换为IYbManager接口
- 统一yb枚举类导入路径从common.enums.ybenums到his.yb.enums
- 移除已废弃的TenantOptionUtil类文件
- 更新手术排班相关枚举导入路径
- 调整药房管理相关DTO导入路径到pharmacy.dispense包
- 统一文档模块枚举类导入路径到document.enums包
- 在护士站应用服务中添加事件发布器和相关业务事件处理
- 更新库存管理和支付相关的医保枚举引用路径
2026-06-21 04:34:29 +08:00
e4f7b30442 fix(yb): 修复医保模块编译错误
- IYbHttpUtils: 新增 queryYbCatalogue, upload9101, threePartSearch, yb5205SpecialDiseaseDrugRecordSearch, ybToReverse 方法声明
- IYbDao: 新增 reconcileGeneralLedgerDetail, getFinancialSettlement3209AParam, paymentCompareYbSettle(List), getFinancial3203APage 方法声明
- IYbManager: 新增 getPreSettleInfo(4参数) 重载方法声明
- YbController: 修复 Sign 导入冲突(domain.Sign vs dto.Sign)
- domain pom: 新增 spring-web provided 依赖(支持 MultipartFile/ResponseEntity 类型)
2026-06-20 23:44:25 +08:00
d9a61e3cfa feat(dataflow): 添加WebSocket端点+事件发布点
- WebSocketConfig: 新增 /ws/critical-value 和 /ws/dashboard 端点
- SurgeryAppServiceImpl: addSurgery 保存后发布 SurgeryCompletedEvent (Chain 8)
- RadiologyImageAppServiceImpl: submitReport 发布后发布 ExamReportPublishedEvent (Chain 9)
- NursingAppServiceImpl: createAssessment 完成后发布 AdmissionAssessmentCompletedEvent (Chain 10)
2026-06-20 23:01:11 +08:00
537fc749a7 feat(ui): 护理质量图表展示优化 - 趋势图+科室对比+类别分布+预警表格 2026-06-20 22:31:39 +08:00
715209d099 feat(ui): 仪表盘实时数据推送优化 - WebSocket连接+预警卡片+趋势展示 2026-06-20 22:23:43 +08:00
109abc122a feat(ui): 危急值实时通知优化 - WebSocket推送+声音提醒+快捷处理 2026-06-20 22:15:04 +08:00
da6f03961c feat(dataflow): 新增Chain11 手术→病理送检链路 2026-06-20 22:03:20 +08:00
da3b466087 feat(dataflow): 数据流优化完成 - 10条链路+重试机制+链路联动 2026-06-20 21:54:55 +08:00
33f67cecae feat(dataflow): 添加链路联动 危急值→医嘱停止
- 创建 OrderStopRequestEvent 事件类
- CriticalValueHandler 添加联动逻辑:危急值确认后发布停嘱事件
- findRelatedOrders 为 stub,待接入医嘱服务
2026-06-20 21:42:26 +08:00
1c2bf43d42 feat(dataflow): 为所有Handler添加重试机制 2026-06-20 21:36:47 +08:00
f6680122eb feat(dataflow): 新增Chain10 入院评估→护理计划自动生成 2026-06-20 21:32:00 +08:00
dd73bcda87 feat(dataflow): 新增Chain9 检查→报告→医嘱联动 2026-06-20 21:29:16 +08:00
5cfe484015 feat(dataflow): 新增Chain8 手术→术后恢复链路 2026-06-20 21:25:27 +08:00
d53448fcfb feat(dataflow): 补全Chain6 护理质控规则检查 2026-06-20 21:21:56 +08:00
b6512597a5 feat(dataflow): 补全Chain5 DRG入组引擎调用 2026-06-20 21:17:47 +08:00
74aa24f36e fix(security): 修复EmpiController @PreAuthorize格式错误 2026-06-20 16:30:54 +08:00
8fd2a10950 fix(mobile): 修复患者详情数据提取 - 兼容多种API返回格式 2026-06-20 16:02:21 +08:00
7907415fb5 fix(mobile): 修复评估API路径对齐后端nursing-assessment-enhanced接口 2026-06-20 15:54:23 +08:00
7e852e2be6 fix(mobile): 修复业务逻辑联动 - encounterId正确传递+患者详情数据展示 2026-06-20 15:40:44 +08:00
37a0c1885e fix(mobile): 修复患者详情页 - 完整展示姓名/床位/医嘱/体征/评估数据 2026-06-20 15:28:03 +08:00
5050366f50 fix(db): 修复所有Flyway版本冲突(V84-V90) 2026-06-20 15:18:40 +08:00
591ad2b549 fix(db): 修复Flyway V83版本冲突 - 重命名为V85 2026-06-20 15:13:26 +08:00
c2cd74e479 Merge remote-tracking branch 'origin/develop' into develop 2026-06-20 15:10:42 +08:00
6b8a05c250 fix(db): 修复Flyway V82版本冲突 - 重命名为V83/V84 2026-06-20 15:09:55 +08:00
c671f5aa89 fix(ui): 修复路由文件语法错误(移除残留的移动端路由括号) 2026-06-20 14:57:28 +08:00
9e428cbd0f fix(mobile): 优化患者列表 - 分页加载+搜索+数据格式适配 2026-06-20 14:41:38 +08:00
f5ae4f3c64 fix: 修复SysTenantController编译错误 - LambdaQueryWrapper导入+字段名修正 2026-06-20 14:16:28 +08:00
6843418a88 fix(security): 添加移动端API到安全白名单 2026-06-20 14:13:34 +08:00
11aac8b135 fix(ui): 移除主UI中的移动端路由(已移至独立项目) 2026-06-20 14:13:11 +08:00
1045706e5e fix(mobile): 补全后端移动端接口+修复API路径 2026-06-20 12:43:53 +08:00
8b081ca8e4 fix(mobile): 修复所有API路径对齐后端实际接口 2026-06-20 12:36:15 +08:00
58993d51e3 fix(mobile): 修复患者列表API使用正确的patient-home-manage/init接口 2026-06-20 12:18:58 +08:00
2d58b05fdc fix(mobile): 登录页医院选择始终显示+加载提示 2026-06-20 11:58:02 +08:00
70c46fc990 fix(#769): zhaoyun (文件合入) 2026-06-20 03:34:28 +08:00
aec3bf3e34 fix(#786): zhaoyun (文件合入) 2026-06-20 00:11:17 +08:00
618c069aaa fix(mobile): 患者列表默认显示所有患者 2026-06-19 23:48:10 +08:00
39c68a3361 fix(mobile): 修复患者列表API路径 2026-06-19 23:44:15 +08:00
df61879a06 fix(mobile): 添加API错误处理和超时提示 2026-06-19 23:43:25 +08:00
1bf3bbd432 fix(mobile): 移除首页无效链接(需要患者上下文的功能) 2026-06-19 23:42:32 +08:00
895abb972e fix(mobile): 登录页医院选择移至密码下方 2026-06-19 23:41:22 +08:00
67370bd1cf fix(mobile): 登录页匹配PC端逻辑 - 输入用户名后加载租户列表 2026-06-19 23:38:09 +08:00
cab9537c7e fix(security): 将租户列表接口加入安全白名单 2026-06-19 23:34:06 +08:00
2437366093 fix(mobile): 添加租户列表接口+修复医院选择为空 2026-06-19 23:30:41 +08:00
bffef625cb fix(mobile): 登录页记住上次选择的医院 2026-06-19 23:27:34 +08:00
5c1502a180 fix(mobile): 修复登录页死循环 - 401拦截器排除登录页+使用匿名租户接口 2026-06-19 23:24:26 +08:00
7adf298ce7 Merge remote-tracking branch 'origin/develop' into develop 2026-06-19 23:24:01 +08:00
fdf56a33ce fix: 修复关键BUG - SQL注入+移动端修复 2026-06-19 23:11:13 +08:00
8914dca1df fix(mobile): 修复医院选择 - 使用租户列表接口加载所有医院 2026-06-19 22:55:33 +08:00
6f288f99de fix(mobile): 登录页面医院选择移至第一位 2026-06-19 22:40:45 +08:00
7d9da53cc4 fix(mobile): 修复移动端API对接 - 使用现有护士站接口+登录获取用户信息 2026-06-19 22:37:35 +08:00
6dc9aaba6c feat(mobile): 重构移动端护士工作站 - 完整功能版本 2026-06-19 22:04:41 +08:00
3bc8a85426 fix(mobile): 修复登录页面始终显示医院选择 2026-06-19 21:59:26 +08:00
5b90a61484 fix(mobile): 修复登录逻辑对齐现有系统 2026-06-19 21:57:43 +08:00
86f12b425a fix(#782): guanyu (文件合入) 2026-06-19 19:57:57 +08:00
829fca8869 fix(#769): zhaoyun (文件合入) 2026-06-19 19:34:42 +08:00
32bbda6dd4 fix(#770): zhaoyun (文件合入) 2026-06-19 18:23:25 +08:00
471eacaf52 fix(#769): zhaoyun (文件合入) 2026-06-19 18:10:34 +08:00
f1ac7cc1fb fix(#768): guanyu (文件合入) 2026-06-19 18:02:16 +08:00
b67725d08c fix(#770): zhaoyun (文件合入) 2026-06-19 17:54:54 +08:00
c2ed6e04b0 fix(#782): guanyu (文件合入) 2026-06-19 16:53:53 +08:00
8fafa12337 fix(#767): zhaoyun (文件合入) 2026-06-19 16:14:29 +08:00
1801fc27ae fix(#786): zhaoyun (文件合入) 2026-06-19 15:49:26 +08:00
b6b8f8be71 fix(#782): guanyu (文件合入) 2026-06-19 14:32:06 +08:00
a9daab268b fix(#770): zhaoyun (文件合入) 2026-06-19 14:28:45 +08:00
9d486c3742 feat(mobile): 添加登录页面+租户选择+路由守卫 2026-06-19 12:48:57 +08:00
38bc99ee14 fix(mobile): 修复移动端核心功能问题
- 新增 getPatientList API 调用正确的患者列表接口
- PatientDetail: Promise.all 并发加载患者信息/医嘱/体征/评估
- 所有页面添加 loading 状态和 ElMessage 错误提示
- 任务完成添加 ElMessageBox 确认对话框
- TaskList 添加刷新按钮
- Mine 退出登录添加确认对话框
2026-06-19 12:44:43 +08:00
05332ce2d9 fix(mobile): 修复后端端口为18080 2026-06-19 12:26:05 +08:00
686fcb5692 fix(mobile): 修复移动端API路径与后端对接 2026-06-19 12:25:47 +08:00
99812e1bf0 feat(mobile-h5): 创建独立移动端H5护理工作站项目 2026-06-19 12:16:58 +08:00
5ab3865e04 refactor: 移除UI项目中的mobile代码,准备独立移动端项目 2026-06-19 12:15:18 +08:00
0b183dacf8 fix(#772): guanyu (文件合入) 2026-06-19 12:05:37 +08:00
0e055fdadc fix(#776): zhaoyun (文件合入) 2026-06-19 11:43:50 +08:00
7b4cfeb6d5 feat(mobile-h5): 移动H5护理工作站 2026-06-19 10:44:32 +08:00
844eb8b7ab feat(kg): 数据导入+规则库 2026-06-19 10:36:06 +08:00
179d8c9c97 feat(kg): 推理引擎+CDSS集成 2026-06-19 10:34:43 +08:00
ed1dd56ad4 feat(kg): 推理引擎+数据导入 2026-06-19 10:33:41 +08:00
523a64daf0 feat(miniprogram): 移动护理小程序后端API
- 新增 MpNursingTask 实体 + Mapper + Service
- 新增 MpVitalSignRecord 实体 + Mapper + Service
- 新增 MpAssessmentRecord 实体 + Mapper + Service
- 新增 IMpNursingAppService 7个API接口
- 新增 MpNursingController 7个REST端点
- 新增 V90 Flyway迁移(3张表)
- 所有接口加 @PreAuthorize 权限控制
2026-06-19 10:29:47 +08:00
d9a1b188b5 feat(kg): 医疗知识图谱全栈实现 - 补充缺失字段 2026-06-19 10:18:32 +08:00
469e705d47 fix(#722): zhaoyun (文件合入) 2026-06-19 08:28:25 +08:00
a5a44cd215 fix(#722): zhaoyun (文件合入) 2026-06-19 08:19:08 +08:00
be90a13cd6 feat(kg): 关系管理+知识图谱可视化 2026-06-19 08:06:38 +08:00
deafee0621 feat(kg): 医疗知识图谱全栈实现 2026-06-19 07:41:03 +08:00
554c1fe97b feat(data-platform): implement P2.2 data collection, BI report engine, and data dashboard
- DataCollection module: clinical/operational data collection APIs
- BiReport engine: generate reports (revenue/department/drg) + dashboard
- DataDashboard: realtime and historical data screen with ECharts-style cards
- All endpoints secured with @PreAuthorize
- Frontend: BiDashboard.vue + DataDashboard.vue + API files
2026-06-19 07:17:15 +08:00
91236c5499 feat(aidiagnosis): add AI-assisted diagnosis suggestion module 2026-06-19 07:17:13 +08:00
8bc80efe2c feat(data): 数据中台+BI报表+AI辅助诊疗 2026-06-19 07:02:44 +08:00
8b2b47b71c feat(cdss): upgrade rule engine with priority, category, execution history and stats 2026-06-19 06:55:48 +08:00
18e3c06b1a feat(mobile): 添加护理评估+输液管理路由 2026-06-19 06:44:09 +08:00
e117022bb6 feat(mobile+telehealth): 移动护理评估+输液管理+互联网医院 2026-06-19 06:38:07 +08:00
50cabbeb32 docs(architecture): 添加 HealthLink-HIS 深度优化升级设计方案
- 定义总体升级目标包括移动化、智能化、平台化、云化和生态化五个维度
- 设计微服务拆分方案涵盖19个核心服务及对应技术选型
- 制定云原生部署方案支持容器化和多租户架构
- 规划移动化方案包含移动护理APP和互联网医院功能
- 设计AI智能化方案含CDSS临床决策支持和NLP病历处理
- 构建数据平台方案实现数据中台和BI决策支持
- 制定安全加固方案确保系统认证授权和数据安全
- 制定四阶段实施路线图覆盖12个月的完整交付计划
- 明确团队扩展需求和年度预算估算
- 识别关键风险并制定相应应对措施
2026-06-19 06:28:22 +08:00
0adf56eee6 fix(#772): guanyu (文件合入) 2026-06-19 06:04:46 +08:00
4c384a03fd fix(#782): guanyu (文件合入) 2026-06-19 05:38:56 +08:00
1d55523d69 fix(#768): guanyu (文件合入) 2026-06-19 05:27:34 +08:00
ef07eadbf9 fix(#786): zhaoyun (文件合入) 2026-06-19 05:24:37 +08:00
0eeb655492 fix(#785): zhaoyun (文件合入) 2026-06-19 05:17:30 +08:00
2eca6a7f31 fix(#785): zhaoyun (文件合入) 2026-06-19 05:08:47 +08:00
be495e2fe5 fix(#770): zhaoyun (文件合入) 2026-06-19 04:29:53 +08:00
1385faa962 fix(#770): zhaoyun (文件合入) 2026-06-19 04:20:39 +08:00
f878f4e3ce fix(#746): zhaoyun (文件合入) 2026-06-19 03:42:03 +08:00
5361749ff9 fix(#783): zhaoyun (文件合入) 2026-06-19 02:10:45 +08:00
ff949a8644 fix(#786): zhaoyun (文件合入) 2026-06-19 00:19:30 +08:00
d055f3b67a fix(#776): guanyu (文件合入) 2026-06-19 00:08:01 +08:00
3198eef403 fix(#770): zhaoyun (文件合入) 2026-06-18 23:50:02 +08:00
8b97b44e3f fix(#768): guanyu (文件合入) 2026-06-18 23:48:55 +08:00
f78cebdebd feat(security): 审计日志增强前端页面
- auditlog-enhanced/api.js: 审计日志增强API接口
- auditlog-enhanced/index.vue: 审计日志管理页面(支持风险级别/业务类型筛选/统计面板)
2026-06-18 22:49:45 +08:00
69425325f8 feat(security): 安全加固认证授权+审计日志
- TokenService: 添加token黑名单和刷新机制
- SysLoginService: 集成登录失败锁定
- LoginFailLockService: 新增登录失败锁定服务
- SysAuditLog: 扩展审计日志字段(风险级别/业务类型/客户端IP等)
- V84__audit_enhancement.sql: 数据库迁移脚本
- IAuditEnhanceAppService: 审计日志增强服务接口
- AuditEnhanceAppServiceImpl: 审计日志增强服务实现
- AuditEnhanceController: 审计日志增强Controller(/audit/enhanced/logs, /audit/enhanced/stats)
- auditlog-enhanced: 前端审计日志管理页面
2026-06-18 22:49:45 +08:00
cb9968ee76 feat(mobile): 移动护理APP医嘱执行+生命体征 2026-06-18 22:49:45 +08:00
aa4a582981 fix(#732): zhaoyun (文件合入) 2026-06-18 22:49:02 +08:00
e9a3fe95a1 fix(#732): zhaoyun (文件合入) 2026-06-18 22:40:55 +08:00
29c0fcda9f fix: 修复剩余MEDIUM/LOW问题 2026-06-18 21:34:03 +08:00
ea0c3b80c3 fix(security): 修复XSS+硬编码IP+资源泄露 2026-06-18 21:31:14 +08:00
8afeb2e4d9 fix(security): 添加VITE_PAYMENT_URL环境变量配置 2026-06-18 21:29:41 +08:00
3d977d0a2d fix(notice): 修复通知内容显示安全问题并更新支付接口URL配置
- 移除DetailView.vue中的v-html指令,改用安全的内容显示方式
- 添加safeContent计算属性过滤HTML标签防止XSS攻击
- 在HeaderNotice/index.vue中移除v-html避免潜在安全风险
- 将硬编码的支付接口URL替换为环境变量VITE_PAYMENT_URL
- 统一多个页面中的医保插件调用地址配置为动态环境变量
- 确保所有通知内容展示都经过安全处理避免恶意脚本注入
2026-06-18 21:25:15 +08:00
d4eae894b2 Merge remote-tracking branch 'origin/develop' into develop 2026-06-18 21:24:28 +08:00
3ffb6c8a47 fix(#732): zhaoyun (文件合入) 2026-06-18 21:14:44 +08:00
be2a2f90cb fix(#732): zhaoyun (文件合入) 2026-06-18 20:57:12 +08:00
4a8902f1c9 fix(security): 修复XSS v-html安全问题 2026-06-18 20:31:27 +08:00
81bbc5c280 fix: 修复NPE+日期比较+权限注解+事务注解 2026-06-18 20:15:50 +08:00
87f8840d57 fix(security): 修复SQL注入+字段引用错误 2026-06-18 20:08:49 +08:00
7cf7d42a31 fix(db): 修复21表delete_flag命名错误 2026-06-18 20:06:27 +08:00
0c7df661f9 fix: 修复V59迁移+重复表定义+缺失导入 2026-06-18 20:03:31 +08:00
b1e7d45416 fix: 解决Git冲突+修复菜单权限 2026-06-18 19:39:54 +08:00
46053a3c73 merge: resolve conflicts 2026-06-18 19:38:34 +08:00
568b10829c feat(quality): 添加业务分析控制器实现数据统计功能
- 新增 QualityBusinessAnalyticsController 控制器类
- 实现分页查询业务分析数据接口 /page
- 实现新增业务分析记录接口 /add
- 实现业务统计数据汇总接口 /summary
- 集成分页查询和条件筛选功能
- 添加事务管理确保数据一致性
2026-06-18 19:30:17 +08:00
4b54b04bc1 remove(infection): 删除CDSS相关实体和服务类
- 删除CdssAlert实体类及其对应的映射器和实现类
- 删除CdssRule实体类及其对应的映射器和实现类
- 移除ICdssAlertService和ICdssRuleService接口定义
- 清理infection模块中的临床决策支持系统相关代码结构
2026-06-18 19:29:55 +08:00
6a2a579fec refactor(infection): 移除CDSS临床决策支持相关功能
- 删除CdssAppServiceImpl实现类及其接口ICdssAppService
- 移除CdssController控制器及相关的API端点
- 删除BusinessAnalyticsController业务分析控制器
- 移除V71__cdss.sql数据库迁移脚本
- 清理所有与CDSS规则和告警相关的代码
2026-06-18 19:29:39 +08:00
09dbd5e9f0 fix: 修复Flyway V68/V69/V75版本冲突,重命名为V78/V79/V80 2026-06-18 19:23:12 +08:00
3fd259b3ea fix(#776): guanyu (文件合入) 2026-06-18 19:21:55 +08:00
690f680866 fix: 修复Flyway V66版本冲突 2026-06-18 19:20:58 +08:00
0bb113557c fix: 修复EmrQualityScore别名冲突 2026-06-18 19:06:24 +08:00
359afba793 fix(ui): 修复EMR数据仓库页面缺失API函数导出 2026-06-18 19:03:38 +08:00
424a99f412 fix(quality): 修复EmrQualityScoreMapper bean冲突
将quality包下的EmrQualityScoreMapper重命名为QualityScoreMapper,
避免与emr包下的EmrQualityScoreMapper产生Spring bean名冲突。
同步更新EmrQualityAppServiceImpl和TerminalQualityAppServiceImpl的引用。
2026-06-18 18:50:42 +08:00
9cfb7fcf78 fix: 修复DrgAnalysisController bean冲突+添加缺失菜单 2026-06-18 18:41:06 +08:00
10cca41375 fix(#779): zhaoyun (文件合入) 2026-06-18 18:10:01 +08:00
Ranyunqiao
b82d9774f2 bug 775 778 779 785 2026-06-18 18:00:27 +08:00
1a7092d2d8 feat(cdss): CDSS临床决策支持系统 — 修复API路径+新增规则管理页面 2026-06-18 17:52:28 +08:00
9122ef4847 feat(cdss): CDSS临床决策支持 2026-06-18 17:47:36 +08:00
5dda5fe217 feat(reportmanage): 报表维度扩展 — 多维度报表查询
- 新增 IReportDimensionAppService + ReportDimensionAppServiceImpl
- 新增 ReportDimensionController (GET /query)
- 支持按状态/DRG/诊断维度统计
- 前端 ReportDimension.vue 维度切换+明细表格
2026-06-18 17:37:34 +08:00
0994550f2f Revert "feat(cdss): CDSS临床决策支持系统"
This reverts commit cba192401e.
2026-06-18 17:34:34 +08:00
ea0821ee3d feat(mrhomepage): 病案统计细化 — 科室统计+医生统计
- 新增 IMrStatsDetailAppService + MrStatsDetailAppServiceImpl
- 新增 MrStatsDetailController (GET /by-dept, GET /by-doctor)
- 新增 V75 迁移脚本: mr_homepage 加 department_id, doctor_id
- 前端 MrStatsDetail.vue 统计面板+DRG/诊断分布
2026-06-18 17:30:17 +08:00
f0e189ca8e feat(regional): 区域医疗信息共享 2026-06-18 17:29:50 +08:00
cba192401e feat(cdss): CDSS临床决策支持系统 2026-06-18 17:29:20 +08:00
0752f53966 feat(infection): 院感监测细化 — 科室感染率+感染趋势
- 新增 IInfectionDetailAppService + InfectionDetailAppServiceImpl
- 新增 InfectionDetailController (GET /rate-by-dept, GET /trend)
- 新增 V74 迁移脚本: hir_infection_case 加 department_id
- 前端 InfectionDetailStats.vue 统计面板+趋势表格
2026-06-18 17:24:56 +08:00
2702258e34 Merge remote-tracking branch 'origin/develop' into develop 2026-06-18 17:23:45 +08:00
0b0e25e1a0 feat(emr): 实现电子病历结构化数据仓库和质量评分功能
- 添加EMR结构化数据提取、存储和查询功能
- 实现病历质量评分计算,包括完整性、及时性和准确性指标
- 新增CDSS临床决策支持服务和告警管理功能
- 实现区域医疗信息共享数据交换功能
- 添加院感监测统计分析功能
- 更新数据库迁移脚本,创建相关数据表结构
- 修正菜单图标大小写问题
2026-06-18 17:23:32 +08:00
067758497e feat(emr): 实现电子病历结构化数据仓库和质量评分功能
- 添加EMR结构化数据提取、存储和查询功能
- 实现病历质量评分计算,包括完整性、及时性和准确性指标
- 新增CDSS临床决策支持服务和告警管理功能
- 实现区域医疗信息共享数据交换功能
- 添加院感监测统计分析功能
- 更新数据库迁移脚本,创建相关数据表结构
- 修正菜单图标大小写问题
2026-06-18 17:22:11 +08:00
66bff74140 fix(#775): zhaoyun (文件合入) 2026-06-18 17:14:04 +08:00
04a8fbb751 feat(security): add @PreAuthorize to nurse station and doctor station controllers
- ProgressNoteController: added PreAuthorize for all endpoints
- NursingExecutionController: added PreAuthorize for scan, handoff, and infusion endpoints
- NursingRecordController: added PreAuthorize for all nursing record endpoints
- OutpatientEnhancedController: added PreAuthorize for discharge summary endpoints
2026-06-18 17:11:41 +08:00
1e4838076e feat(lis-pacs): 确认LIS+PACS能力完整,补齐@PreAuthorize 2026-06-18 17:05:37 +08:00
8dde2b2fed feat(anesthesia): add preop visit, intraop events, Aldrete scoring, enhance safety check
- AnesthesiaPreopVisit: pre-anesthesia assessment (术前访视)
- AnesthesiaIntraopEvent: intraoperative events (插管/拔管/体位)
- AnesthesiaAldreteScore: PACU Aldrete recovery scoring
- SurgerySafetyCheckController: added @PreAuthorize and phase status/stats endpoints
- Flyway V70 migration for new tables
2026-06-18 17:03:51 +08:00
e60b5217fc feat(anesthesia): 添加麻醉管理相关实体类、数据访问层和服务层
- 创建 AnesthesiaAldreteScore 实体类及对应的映射器、服务接口和实现类
- 创建 AnesthesiaIntraopEvent 实体类及对应的映射器、服务接口和实现类
- 创建 AnesthesiaPreopVisit 实体类及对应的映射器、服务接口和实现类
- 添加 V66 数据库迁移脚本,更新所有菜单项的图标
- 为麻醉评分、术中事件和术前访视功能提供完整的数据持久化支持
- 优化菜单图标配置以提高系统界面的用户体验
2026-06-18 16:55:56 +08:00
278d7d39a4 feat(security): 添加控制器方法权限验证
- 在放射科增强控制器中添加安全注解导入
- 为实验室历史记录比较接口添加感染科室列表权限验证
- 为实验室结果添加接口添加感染科室编辑权限验证
- 为实验室趋势查询接口添加感染科室列表权限验证
- 为门诊增强控制器添加安全注解导入
- 为出院小结分页接口添加门诊出院列表权限验证
- 为出院小结添加接口添加门诊出院添加权限验证
- 为出院完成接口添加门诊出院编辑权限验证
2026-06-18 16:55:35 +08:00
b682bde47f feat(ybmanage): add DRG/DIP deep analysis module (T13.5) 2026-06-18 16:03:09 +08:00
46ae0f39ab feat(einvoice): add electronic invoice module (T13.4) 2026-06-18 15:59:45 +08:00
5ee15b348b feat(epidemic): add autoScreen/saveReport/getReportStats endpoints, enhance EpidemicReport entity with screen fields, and create EpidemicReport.vue 2026-06-18 15:57:16 +08:00
f3aac08c4e feat(ehcard): add electronic health card module (T13.3) 2026-06-18 15:56:12 +08:00
5aaa4ee883 feat(tcm): add TCM diagnosis entity, saveDiagnosis/saveConstitution endpoints, and unified TcmDiagnosis.vue 2026-06-18 15:54:02 +08:00
4a45c9cdd4 docs: Phase 3里程碑评审报告 2026-06-18 15:39:42 +08:00
cb8a67cb3b test: Phase 3集成测试报告 2026-06-18 15:35:12 +08:00
7f315175a8 test: Phase 3集成测试报告 + 修复quality API导入缺失 2026-06-18 15:35:12 +08:00
ba0c37ccbb feat(rationaldrug): 添加肝肾功能调量API接口 2026-06-18 15:35:11 +08:00
ed0d05327d feat(reportmanage): 可视化仪表盘前端页面 2026-06-18 15:35:11 +08:00
7d196f83fc feat(reportmanage): 经营分析+数据导出前端页面 2026-06-18 15:35:10 +08:00
wangjian963
0887dd5c29 Merge remote-tracking branch 'origin/develop' into develop 2026-06-18 15:22:38 +08:00
wangjian963
32514ebd7b 792 【住院管理-护士工作站】在入出转管理的床位10号床位和11号床位有2个重复的 2026-06-18 15:21:53 +08:00
632d0828b4 feat(reportmanage): T11.3 可视化仪表盘 - AppService + Controller + Frontend 2026-06-18 15:11:30 +08:00
c004badf30 feat(rationaldrug): T11.4 肝肾功能自动调量
- 新增 DosageAdjustmentRequestDto 请求DTO
- IRationalDrugAppService 新增 adjustDosageByOrganFunction 方法
- RationalDrugAppServiceImpl 实现肝肾功能评估 + 剂量匹配逻辑
- RationalDrugController 新增 POST /adjust-dosage 端点
- rationaldrug.js 新增前端 API 函数
- 新建 DosageAdjustment.vue 肝肾功能输入 + 调量建议展示
2026-06-18 15:10:26 +08:00
abafd4b2a9 feat(reportmanage): T11.2 经营分析+数据导出 - AppService + Controller + Frontend 2026-06-18 15:07:09 +08:00
965418dc45 feat(reportmanage): T11.1 DRG/DIP分析模块 - AppService + Controller + Frontend 2026-06-18 15:02:48 +08:00
dfd4faa00b Merge remote-tracking branch 'origin/develop' into develop 2026-06-18 14:55:52 +08:00
4c3f7e406b feat(empi): T9.2 重复检测+跨系统同步 — detectDuplicates/syncCrossSystem接口+前端重复检测tab 2026-06-18 14:20:37 +08:00
0e27b9f8df feat(followup): T9.4 随访管理 — AppService(generatePlan/assignTasks/recordFollowup) + 新端点 2026-06-18 14:19:33 +08:00
d863e54ff0 feat(quality): T9.3 质控指标自动采集 — AppService+Controller+前端页面 2026-06-18 14:16:51 +08:00
0c0fd33155 feat(empi): T9.1 患者身份合并/拆分 — 后端splitPatients接口+前端拆分管理tab 2026-06-18 14:16:19 +08:00
wangjian963
b002818935 Bug #722 — 住院病历页面打不开(前端) 2026-06-18 13:55:36 +08:00
wangjian963
8ed2df212d 待办事项 "Candidate group list is empty"(后端) 2026-06-18 13:52:35 +08:00
20934572d2 feat(esb): T8.3 编码映射+监控+可靠性 - AppService/Controller/Frontend 2026-06-18 12:58:36 +08:00
2d67395228 feat(esb): T8.2 CDA临床文档 - AppService/Controller/Frontend 2026-06-18 12:56:18 +08:00
b6a521db29 feat(esb): T8.1 HL7 FHIR R4消息转换 - AppService/Controller/Frontend 2026-06-18 12:53:46 +08:00
f1c583d9b7 feat(lab): T7.1 室内质控Westgard规则 - AppService/Controller/前端质控图 2026-06-18 12:44:20 +08:00
e1e424b0d4 feat(check): T7.3 DICOM image capture + structured report - add AppService layer, align routes to /check/image/* and /check/report/*, add @PreAuthorize infection:check:edit/list 2026-06-18 12:38:20 +08:00
3fcc4c1ee7 feat(lab): T7.2 室间质评+报告打印 - AppService/Controller/前端报告单 2026-06-18 12:36:34 +08:00
ec8238ab26 feat(lab): T7.1 室内质控Westgard规则 - AppService/Controller/前端质控图 2026-06-18 12:34:39 +08:00
98385e6553 docs(project): 添加三甲达标实施计划并更新图标资源
- 添加 HealthLink-HIS 三甲达标完整实施计划文档 (2026-06-17)
- 移除旧版 drug.svg 图标文件
- 新增 analysis.svg 统计分析图标
- 新增 bell.svg 通知提醒图标
- 新增 connection.svg 连接配置图标
- 计划涵盖 4 个阶段 17 个 Sprint 的详细实施方案
- 包含 142 项必备能力现状分析及完成度统计
- 提供代码审计关键发现及修复策略指导
2026-06-18 12:30:54 +08:00
f990726def feat(nursing): 护理文书+质量指标+交接班增强
- 护理文书: 已有完整实现(NursingRecordController+前端),无需新增
- 护理质量指标: 新增 /nursing-quality/collect 采集指标, /nursing-quality/indicators 查询指标
- 交接班: 新增 /nursing-execution/handoff/key-patients 重点患者列表
- 前端: nursingquality 新增采集按钮, nursingexecution 交接班tab增加重点患者提示
2026-06-18 12:26:08 +08:00
0a865dd0d5 feat(nursing): T6.3 疼痛评估NRS/VAS功能 2026-06-18 12:16:17 +08:00
90ee407d5a feat(nursing): T6.2 营养风险筛查NRS2002功能 2026-06-18 12:14:48 +08:00
7c3c22d029 feat(nursing): T6.1 管道滑脱风险评估功能 2026-06-18 12:13:16 +08:00
53823ea845 Merge remote-tracking branch 'origin/develop' into develop 2026-06-18 12:08:28 +08:00
75f024267b fix(#768): guanyu (文件合入) 2026-06-18 12:03:30 +08:00
wangjian963
12516a55fa 774 【门诊医生工作站】在门诊医生站的医嘱下的【个人】【科室】【全院】下的医嘱套件都没有数据回显但是可以点击 2026-06-18 11:25:11 +08:00
c5a252f41d feat(infection): 手卫生+环境+耐药菌监测 2026-06-18 11:08:42 +08:00
4d37f44b04 feat(infection): 目标性监测 2026-06-18 11:05:44 +08:00
89ccad59ed feat(infection): 暴发预警 2026-06-18 11:03:20 +08:00
fe8020cd1e feat(infection): 暴发预警
- 创建 IOutbreakWarningAppService + OutbreakWarningAppServiceImpl
- 实现 checkOutbreak() 同科室短时间多例感染检测
- 实现 getWarnings() 预警记录查询
- 创建 OutbreakWarningController: POST /infection/outbreak/check, GET /infection/outbreak/list
- 创建前端 OutbreakWarning.vue 预警规则配置 + 预警结果列表
- 修复 TargetedSurveillanceAppServiceImpl parseDate JDK25兼容问题
2026-06-18 11:02:07 +08:00
wangjian963
a0b12d1229 修复关键警告 — emit 未声明 2026-06-18 10:45:16 +08:00
wangjian963
67f1baf04a 759 【门诊医生工作站】电子处方点击新增处方,报卡在100%卡出屏幕且诊断等下拉框无数据回显 2026-06-18 10:42:52 +08:00
7ef676fa75 feat(infection): 院感病例自动筛查 2026-06-18 10:41:56 +08:00
e40695224c fix(#770): zhaoyun (文件合入) 2026-06-18 10:07:44 +08:00
wangjian963
5ea218d9bf 682 【住院医生工作站】历史医嘱的报卡的布局有些字段被覆盖 2026-06-18 10:04:24 +08:00
Ranyunqiao
745ca570b7 bug 698 2026-06-18 09:42:01 +08:00
wangjian963
85ef4cb1c5 将V66__update_menu_icons的版本号修改为V67. 2026-06-18 09:38:55 +08:00
50857cb440 fix(#767): zhaoyun (文件合入) 2026-06-18 09:17:50 +08:00
81cf607dec Merge remote-tracking branch 'origin/develop' into develop 2026-06-18 06:21:17 +08:00
7fd05a0b42 fix(#787): zhaoyun (文件合入) 2026-06-18 06:10:10 +08:00
7c375f5af8 fix(#723): zhaoyun (文件合入) 2026-06-18 01:05:57 +08:00
3f164d4585 fix(#783): zhaoyun (文件合入) 2026-06-17 23:53:27 +08:00
fe2a60f379 fix(#783): zhaoyun (文件合入) 2026-06-17 23:49:11 +08:00
d21a2f49c1 fix(#786): zhaoyun (文件合入) 2026-06-17 23:35:11 +08:00
767619e308 fix(#783): zhaoyun (文件合入) 2026-06-17 22:53:07 +08:00
1911278570 fix(#783): zhaoyun (文件合入) 2026-06-17 22:33:57 +08:00
f0f4a95fe9 fix(#774): zhaoyun (文件合入) 2026-06-17 21:39:36 +08:00
3a454189b0 fix(#791): zhaoyun (文件合入) 2026-06-17 19:53:53 +08:00
51acc3f91c fix(#783): zhaoyun (文件合入) 2026-06-17 19:39:28 +08:00
5ec3c8425a fix(#791): zhaoyun (文件合入) 2026-06-17 18:52:09 +08:00
dbb4504be9 fix(#783): zhaoyun (文件合入) 2026-06-17 18:03:51 +08:00
wangjian963
a380ad93d9 fix: 修复 vxe-table 列宽 px 单位导致宽度失效
vxe-table 的 min-width/width 仅接受纯数字,带 px/% 单位的设置会被
  静默忽略。统一去掉 vxe-column/vxe-table 上的 px 后缀,将百分比
  min-width 改为 width(vxe 的 width 支持百分比字符串)。
2026-06-17 18:03:29 +08:00
wangjian963
ad90af44a2 783 【住院医生工作站-诊断录入】新增诊断时,可以不保存一直新增诊断,不符合逻辑 2026-06-17 16:47:29 +08:00
86cb6be013 fix(#786): zhaoyun (文件合入) 2026-06-17 16:35:11 +08:00
06111ef284 fix(#784): guanyu (文件合入) 2026-06-17 16:28:55 +08:00
wangjian963
f56aa2ad2e 780 【护士工作站-已出院】列表上的【特级】【一级】【二级】【三级】的筛选查询无响应 2026-06-17 16:18:34 +08:00
84cc974597 在 mrhomepage.js 中补了缺失的三个 API 函数导出:saveDeathDiscussion、listDeathDiscussions、getPendingDeadline 2026-06-17 16:00:26 +08:00
36acf6c513 补充"vxe-pc-ui"依赖 2026-06-17 15:43:20 +08:00
bbd86abbe7 feat(menu): 更新菜单图标配置
- 为系统管理模块的所有菜单项添加相应的图标
- 为门诊管理、住院管理、收费工作站等核心功能配置图标
- 为药房管理、库房管理、财务管理等业务模块设置图标
- 为医生工作站、护士站、检查检验等医疗专业功能分配图标
- 为医保管理、报表管理、接口管理等系统功能配置图标
- 为麻醉管理、合理用药、急诊管理等专科模块添加图标
- 为护理管理、病理管理、影像管理等医技科室设置图标
-
2026-06-17 15:27:26 +08:00
8e9308faf6 fix(consultation): 修复会诊意见列表接口参数验证问题
- 将consultationId参数设置为非必需,解决空值传递导致的验证异常
- 保持原有的会诊意见查询功能逻辑不变
- 提升接口的容错性和用户体验
2026-06-17 15:27:09 +08:00
5eb9b62d32 fix(medicine): 移除未使用的响应式变量并修复会诊确认逻辑
- 移除了 medicineDialog.vue 中未使用的 supplierListOptions、statusRestrictedOptions、
partAttributeEnumOptions 和 tempOrderSplitPropertyOptions 响应式变量
- 修复了 consultationconfirmation/index.vue 中加载会诊意见时缺少
consultationId 验证的问题
- 防止在会诊 ID 不存在时尝试加载会诊意见导致的潜在错误
2026-06-17 15:23:22 +08:00
808c0305c9 Merge remote-tracking branch 'origin/develop' into develop 2026-06-17 15:19:58 +08:00
d5f177ae56 refactor(diagnosistreatment): 优化诊断治疗对话框组件结构
- 移除未使用的 title 响应式变量
- 移除未使用的下拉选项响应式变量(diagnosisCategoryOptions、statusFlagOptions、exeOrganizations、typeEnumOptions)
- 简化组件初始化逻辑,直接使用 props 数据
- 清理多余的赋值操作,提高代码可读性
- 优化图标SVG路径定义,调整矩形绘制方式
2026-06-17 15:19:33 +08:00
wangjian963
d7d76c922e 712 【收费工作站-预交金管理】“预交金管理”页面缺失展示“支付方式”列及患者“床号”、“费用类型” 2026-06-17 15:18:48 +08:00
wangjian963
b6eec300a9 696 [收费工作站-住院登记] 优化姓名搜索框,增设“身份证号”与“申请时间段”检索条件,及列表字段补充显示 2026-06-17 15:01:38 +08:00
52b94b9df4 refactor(icons): 优化SVG图标路径结构
- 移除多余的垂直线条路径定义
- 简化为三个水平条形路径,减少重复代码
- 保持图标的视觉表现一致性

fix(device): 修复设备对话框标题和选项初始化问题

- 移除冗余的标题赋值操作
- 删除未使用的分类、状态和供应商选项属性
- 保留必要的表单重置和树形结构加载逻辑
2026-06-17 15:00:54 +08:00
c49c9229a8 refactor(device): 优化设备对话框组件并添加SVG图标
- 移除未使用的title、deviceCategories、statusFlagOptions和supplierListOptions变量
- 保留必要的deptOptions、locationOptions和unitCode相关变量
- 添加analyze.svg、approve-check.svg、assess.svg等多个SVG图标文件
- 新增图标包括审核、评估、认证等相关功能图标
- 优化组件代码结构,减少不必要的响应式数据声明
- 添加包装单位选项和加载状态管理功能
2026-06-17 14:54:21 +08:00
eccc0ec7cf refactor(device): 优化设备对话框组件并添加SVG图标
- 移除未使用的title、deviceCategories、statusFlagOptions和supplierListOptions变量
- 保留必要的deptOptions、locationOptions和unitCode相关变量
- 添加analyze.svg、approve-check.svg、assess.svg等多个SVG图标文件
- 新增图标包括审核、评估、认证等相关功能图标
- 优化组件代码结构,减少不必要的响应式数据声明
- 添加包装单位选项和加载状态管理功能
2026-06-17 14:54:14 +08:00
84c0f6a43d feat(mrhomepage): 死亡病例讨论记录 2026-06-17 14:50:25 +08:00
f1a8fafb72 feat(mrhomepage): 病案示踪管理 2026-06-17 14:46:17 +08:00
786fc14147 Merge remote-tracking branch 'origin/develop' into develop 2026-06-17 14:43:53 +08:00
5cd42a3253 feat(mrhomepage): 添加病历主页跟踪和借阅归还功能
- 新增trackStatus函数用于获取病历主页跟踪状态
- 新增borrowRecord函数用于记录病历借阅操作
- 新增returnRecord函数用于记录病历归还操作
2026-06-17 14:43:34 +08:00
b5f83b96e6 feat(icons): 添加多种SVG图标资源
- 新增amethyst.svg图标文件
- 新增ash.svg图标文件
- 新增aurora.svg图标文件
- 新增basalt.svg图标文件
- 新增beryl.svg图标文件
- 新增chalk.svg图标文件
- 新增citrine.svg图标文件
- 新增clay.svg图标文件
- 新增condensation.svg图标文件
- 新增coral.svg图标文件
- 新增crystal.svg图标文件
- 新增current.svg图标文件
- 新增dew.svg图标文件
- 新增diamond.svg图标文件
- 新增drop.svg图标文件
- 新增dust.svg图标文件
- 新增emerald.svg图标文件
- 新增fog.svg图标文件
- 新增frost.svg图标文件
- 新增garnet.svg图标文件
- 新增gem.svg图标文件
- 新增glint.svg图标文件
- 新增glow.svg图标文件
- 新增granite.svg图标文件
- 新增gravel.svg图标文件
- 新增halo.svg图标文件
- 新增haze.svg图标文件
2026-06-17 14:43:23 +08:00
9694184748 feat(icons): 添加天气和自然灾害相关的SVG图标
- 添加cloud-rain.svg云雨图标
- 添加cloud-sun.svg晴云图标
- 添加compost.svg堆肥图标
- 添加cyclone.svg气旋图标
- 添加drought.svg干旱图标
- 添加earthquake.svg地震图标
- 添加fertilizer.svg肥料图标
- 添加fire.svg火灾图标
- 添加flood.svg洪水图标
- 添加hurricane.svg飓风图标
- 添加land.svg土地图标
- 添加landslide.svg滑坡图标
- 添加lightning.svg闪电图标
- 添加mud.svg泥浆图标
- 添加plant.svg植物图标
- 添加rain.svg降雨图标
- 添加seed.svg种子图标
- 添加snow.svg降雪图标
- 添加soil.svg土壤图标
- 添加storm.svg风暴图标
- 添加sun.svg太阳图标
- 添加thunder.svg雷声图标
- 添加tornado.svg龙卷风图标
- 添加tsunami.svg海啸图标
- 添加typhoon.svg台风图标
- 添加vol
2026-06-17 14:37:26 +08:00
e7bdf4e5ac fix(#790): zhaoyun (文件合入) 2026-06-17 14:36:23 +08:00
0156884099 Merge remote-tracking branch 'origin/develop' into develop 2026-06-17 14:35:19 +08:00
d6e64e5019 feat(icons): 添加奖励和荣誉相关SVG图标
- 添加 accolade.svg 图标用于表彰功能
- 添加 achievement.svg 图标用于成就展示
- 添加 allowance.svg 图标用于津贴相关界面
- 添加 appreciate.svg 图标用于感谢和赞赏功能
- 添加 bloom.svg 图标用于成长和绽放主题
- 添加 blossom.svg 图标用于花朵绽放效果
- 添加 bounty.svg 图标用于奖励和赏金功能
- 添加 bouquet.svg 图标用于花束相关界面
- 添加 bud.svg 图标用于花蕾和新芽概念
- 添加 cape.svg 图标用于披风和特殊权限标识
- 添加 certificate-award.svg 图标用于证书和奖项
- 添加 champion.svg 图标用于冠军和优胜者标识
- 添加 commend.svg 图标用于表扬和推荐功能
- 添加 commendation.svg 图标用于嘉奖和赞扬
- 添加 crown.svg 图标用于皇冠和等级象征
- 添加 cultivate.svg 图标用于培育和种植功能
- 添加 distinction.svg 图标用于区分和卓越标识
- 添加 excellence.svg 图标用于优秀和杰出展示
- 添加 first-place.svg 图标用于第一名和获胜标识
- 添加 flourish.svg 图标用于繁荣和发展展示
- 添加 flower.svg 图标用于花朵和装饰元素
- 添加 gown.svg 图标用于礼服和正式场合
- 添加 grant.svg 图标用于资助和授予功能
- 添加 gratitude.svg 图标用于感恩和感谢展示
- 添加 growth.svg 图标用于成长和发育过程
- 添加 honor.svg 图标用于荣誉和尊敬标识
- 添加 laurel.svg 图标用于月桂叶和胜利象征
2026-06-17 14:34:51 +08:00
9ea5830095 feat(icons): 添加奖励和荣誉相关SVG图标
- 添加 accolade.svg 图标用于表彰功能
- 添加 achievement.svg 图标用于成就展示
- 添加 allowance.svg 图标用于津贴相关界面
- 添加 appreciate.svg 图标用于感谢和赞赏功能
- 添加 bloom.svg 图标用于成长和绽放主题
- 添加 blossom.svg 图标用于花朵绽放效果
- 添加 bounty.svg 图标用于奖励和赏金功能
- 添加 bouquet.svg 图标用于花束相关界面
- 添加 bud.svg 图标用于花蕾和新芽概念
- 添加 cape.svg 图标用于披风和特殊权限标识
- 添加 certificate-award.svg 图标用于证书和奖项
- 添加 champion.svg 图标用于冠军和优胜者标识
- 添加 commend.svg 图标用于表扬和推荐功能
- 添加 commendation.svg 图标用于嘉奖和赞扬
- 添加 crown.svg 图标用于皇冠和等级象征
- 添加 cultivate.svg 图标用于培育和种植功能
- 添加 distinction.svg 图标用于区分和卓越标识
- 添加 excellence.svg 图标用于优秀和杰出展示
- 添加 first-place.svg 图标用于第一名和获胜标识
- 添加 flourish.svg 图标用于繁荣和发展展示
- 添加 flower.svg 图标用于花朵和装饰元素
- 添加 gown.svg 图标用于礼服和正式场合
- 添加 grant.svg 图标用于资助和授予功能
- 添加 gratitude.svg 图标用于感恩和感谢展示
- 添加 growth.svg 图标用于成长和发育过程
- 添加 honor.svg 图标用于荣誉和尊敬标识
- 添加 laurel.svg 图标用于月桂叶和胜利象征
2026-06-17 14:34:45 +08:00
7b912ee96c fix(#784): guanyu (文件合入) 2026-06-17 14:31:26 +08:00
9d4c0b6b2a feat(quality): 病案终末质控 2026-06-17 14:29:42 +08:00
52377d7529 feat(icons): 添加医疗信息系统所需SVG图标
- 添加accelerate.svg加速功能图标
- 添加access-control.svg访问控制图标
- 添加accounting.svg会计功能图标
- 添加adjustment.svg调整功能图标
- 添加admission.svg入院功能图标
- 添加advise.svg咨询功能图标
- 添加affiliation.svg关联功能图标
- 添加agreement.svg协议功能图标
- 添加agreement-vote.svg协议投票图标
- 添加alert.svg警告功能图标
- 添加allergy.svg过敏功能图标
- 添加alliance.svg联盟功能图标
- 添加analytics.svg分析功能图标
- 添加anesthesia.svg麻醉功能图标
- 添加approval.svg审批功能图标
- 添加arbitration.svg仲裁功能图标
- 添加archive.svg归档功能图标
- 添加asset.svg资产功能图标
- 添加attendance.svg考勤功能图标
- 添加audit.svg审计功能图标
- 添加audit-log.svg审计日志图标
- 添加audit-report.svg审计报告图标
- 添加audit-trail.svg审计轨迹图标
- 添加backup.svg备份功能图标
- 添加band.svg标签
2026-06-17 14:27:45 +08:00
5100237faf fix(database): 修复数据库字典重复和表结构缺失问题
- 删除手术状态下拉框的重复字典数据,保留每组中dict_code最小的记录
- 修复HisBaseEntity列缺失问题,为多个表添加create_by、update_by、update_time等基础字段
- 为adm_patient表添加邮政编码、户籍地址、监护人信息、患者来源等缺失字段
- 添加文化程度字典类型和相关字典数据,补充3919到3914等10个学历级别选项
- 为adm_patient_identifier表创建tenant_id和patient_id的联合索引以提升查询性能
- 修复prescription_intercept_log和clinical_pathway_execution表的基础实体字段缺失
- 为wor_device_request表增加医嘱退回相关的back_reason、performer_check_id等字段
- 创建EMPI核心表empi_person和empi_person_id_mapping用于全局患者主
2026-06-17 14:27:36 +08:00
e344091a41 fix(database): 修复数据库字典重复和表结构缺失问题
- 删除手术状态下拉框的重复字典数据,保留每组中dict_code最小的记录
- 修复HisBaseEntity列缺失问题,为多个表添加create_by、update_by、update_time等基础字段
- 为adm_patient表添加邮政编码、户籍地址、监护人信息、患者来源等缺失字段
- 添加文化程度字典类型和相关字典数据,补充3919到3914等10个学历级别选项
- 为adm_patient_identifier表创建tenant_id和patient_id的联合索引以提升查询性能
- 修复prescription_intercept_log和clinical_pathway_execution表的基础实体字段缺失
- 为wor_device_request表增加医嘱退回相关的back_reason、performer_check_id等字段
- 创建EMPI核心表empi_person和empi_person_id_mapping用于全局患者主
2026-06-17 14:25:50 +08:00
73aa812544 fix(database): 修复数据库字典重复和表结构缺失问题
- 删除手术状态下拉框的重复字典数据,保留每组中dict_code最小的记录
- 修复HisBaseEntity列缺失问题,为多个表添加create_by、update_by、update_time等基础字段
- 为adm_patient表添加邮政编码、户籍地址、监护人信息、患者来源等缺失字段
- 添加文化程度字典类型和相关字典数据,补充3919到3914等10个学历级别选项
- 为adm_patient_identifier表创建tenant_id和patient_id的联合索引以提升查询性能
- 修复prescription_intercept_log和clinical_pathway_execution表的基础实体字段缺失
- 为wor_device_request表增加医嘱退回相关的back_reason、performer_check_id等字段
- 创建EMPI核心表empi_person和empi_person_id_mapping用于全局患者主
2026-06-17 14:25:32 +08:00
de6d6a2b51 fix(mrhomepage): 修复HQMS Mapper XML缺失 2026-06-17 14:19:47 +08:00
wangjian963
57d14603ee 669 [门诊医生站-中医处方] 中医处方头信息(费用性质、频次、天数、付数等)在保存并重新进入后回显为空 2026-06-17 14:16:07 +08:00
1df1f0d1ad feat(mrhomepage): HQMS首页上报 2026-06-17 14:14:45 +08:00
00604b2d01 feat(mrhomepage): 病案首页质量校验
- 新增 IMrHomepageQualityAppService + impl,实现 checkQuality/getQualityResults
- 新增 MrHomepageQualityController (POST /quality/check, GET /quality/results/{id})
- 增强 MrHomepageQualityCheckServiceImpl:必填项+逻辑校验+ICD编码+费用一致性
- 新增 MrHomepageQualityCheck.vue 校验结果展示页面
- 更新前端 API 文件添加 checkQuality/getQualityResults 接口
2026-06-17 14:02:42 +08:00
wangjian963
a58168c6de Merge remote-tracking branch 'origin/develop' into develop 2026-06-17 13:52:42 +08:00
wangjian963
7f1f3e1a3b 617 [住院登记] “费用性质”字段保存逻辑错误(登记选择医保保存后变为全自费 2026-06-17 13:52:20 +08:00
09e43e4b8c feat(emr): 病历时效监控 2026-06-17 13:47:02 +08:00
9673c0ed80 feat(emr): 病历完整性检查
- 创建 IEmrCompletenessAppService + impl,实现 checkCompleteness() 和 getCheckResults()
- 创建 EmrCompletenessController,POST /emr/completeness/check 和 GET /emr/completeness/results/{emrId}
- 新建 EmrCompletenessCheck.vue 检查结果展示 + 不合格项提醒
- 添加前端 API 函数 checkCompleteness / getCompletenessResults
2026-06-17 13:37:53 +08:00
f3a24a9129 feat(emr): 病历版本管理
- V64 Flyway迁移: emr_version表(不可删除, 三甲评审)
- EmrVersion实体: 版本号递增, 内容快照, 差异记录
- EmrVersionMapper + XML: selectByEmrId/selectLatest
- IEmrVersionService + impl: 基础CRUD
- IEmrVersionAppService + impl: saveVersion/getVersions/compareVersions
- EmrVersionController: POST /emr/version/save, GET /emr/version/list/{emrId}, GET /emr/version/compare
- 前端API: saveEmrVersion/getEmrVersionList/compareEmrVersions
- EmrVersionCompare.vue: 版本列表+对比视图
2026-06-17 13:28:34 +08:00
6184ed262f feat(emr): 病历修改留痕 — AppService/Controller/前端组件 2026-06-17 13:22:02 +08:00
f0d20a8d79 Merge remote-tracking branch 'origin/develop' into develop 2026-06-17 13:14:43 +08:00
694935b648 feat(anesthesia): 术后随访记录 2026-06-17 13:00:50 +08:00
Ranyunqiao
5801fec21c bug 789 2026-06-17 12:53:47 +08:00
b3800b7ae0 feat(anesthesia): 麻醉小结功能
- V63 Flyway migration: anes_summary table
- Entity, Mapper, Service, AppService, Controller
- POST /anesthesia/summary, GET /anesthesia/summary/{recordId}
- Frontend AnesthesiaSummary.vue with form and display
2026-06-17 12:53:11 +08:00
557263875b feat(anesthesia): 术中生命体征5min间隔监测 2026-06-17 12:48:18 +08:00
8adee630fb fix(anesthesia): 修复Mapper XML缺失+recordId硬编码 2026-06-17 12:40:11 +08:00
f444584908 feat(anesthesia): ASA麻醉评估 2026-06-17 12:35:45 +08:00
0ec77ab89c Merge remote-tracking branch 'origin/develop' into develop 2026-06-17 12:32:16 +08:00
e8356f5f83 fix(critical-value): 修复handler_id约束+补全update_time/update_by列 2026-06-17 12:30:07 +08:00
fc892e96dc feat(critical-value): 危急值处理记录闭环 2026-06-17 12:25:27 +08:00
58238e6b25 fix(#788): zhaoyun (文件合入) 2026-06-17 12:20:32 +08:00
f79c5a2c26 fix(clinical-pathway): 修复P0问题 - delete_flag/权限控制/缺失端点/tenant_id类型 2026-06-17 12:20:11 +08:00
815b80437e feat(clinical-pathway): 临床路径执行管理 2026-06-17 12:12:41 +08:00
4385472f26 fix(#778): zhaoyun (文件合入) 2026-06-17 12:07:15 +08:00
5ef05b9b55 fix(blood-transfusion): 修复P0/P1问题 - 字段映射/参数清理/tenant_id/Flyway版本 2026-06-17 12:02:38 +08:00
d7455684db feat(blood-transfusion): 输血管理全流程 2026-06-17 11:51:35 +08:00
d8e9da965b Merge remote-tracking branch 'origin/develop' into develop 2026-06-17 11:48:46 +08:00
575f5d6c32 fix(database): 修复数据库字典重复和表结构缺失问题
- 删除手术状态下拉框的重复字典数据,保留每组中dict_code最小的记录
- 修复HisBaseEntity列缺失问题,为多个表添加create_by、update_by、update_time等基础字段
- 为adm_patient表添加邮政编码、户籍地址、监护人信息、患者来源等缺失字段
- 添加文化程度字典类型和相关字典数据,补充3919到3914等10个学历级别选项
- 为adm_patient_identifier表创建tenant_id和patient_id的联合索引以提升查询性能
- 修复prescription_intercept_log和clinical_pathway_execution表的基础实体字段缺失
- 为wor_device_request表增加医嘱退回相关的back_reason、performer_check_id等字段
- 创建EMPI核心表empi_person和empi_person_id_mapping用于全局患者主索引管理
- 为empi_merge_log表添加create_time字段以完善审计信息
- 更新院感管理和评审保障模块的设计文档,明确各模块实现状态和缺失功能
2026-06-17 11:46:56 +08:00
3fd7862a85 fix(#778): zhaoyun (文件合入) 2026-06-17 11:45:45 +08:00
892890b59f fix(order-closed-loop): 修复P0问题 - deptId过滤/权限控制/死代码 2026-06-17 11:44:49 +08:00
621bc27267 Merge remote-tracking branch 'origin/develop' into develop 2026-06-17 11:43:18 +08:00
Ranyunqiao
62c1b4278b Merge remote-tracking branch 'origin/develop' into develop 2026-06-17 11:39:11 +08:00
Ranyunqiao
690486084e 112 【住院护士站-护理记录】功能重构升级(参考开源系统信创版本) 2026-06-17 11:38:41 +08:00
wangjian963
d792f03bbd fix(ui): 已登记入院表格事件修复与布局优化
- handleRadioChange({newValue}→{row}): 修复 vxe-table radio-change
    事件参数错误,selectedRow 始终为 undefined,打印住院证功能失效
  - queryParams 初始定义与 resetQuery 对齐,补全缺失字段
  - 表格布局重构:
    · 移除 height="100%"(解除横向滚动条位置漂移)
    · table min-width="1600px" + 容器 overflow-x:auto
    · 固定列 width / 信息列 min-width 差异化约束
2026-06-17 11:37:14 +08:00
6a4545c240 feat(order-closed-loop): 医嘱执行闭环追踪
- AppService: 添加 getTrace(adviceId) 查询医嘱全生命周期时间轴
- AppService: 添加 getStatisticsWithParams(deptId, startDate, endDate) 执行统计
- Controller: 添加 GET /trace/{adviceId} 和 GET /statistics/summary 端点
- 前端: 新建 OrderExecuteTrace.vue 时间轴视图 + 执行统计面板
- API: 添加 getOrderExecuteTrace 和 getExecuteStatistics 接口
2026-06-17 11:34:24 +08:00
a2e607caf4 chore(db): 移除多个数据库迁移脚本
- 移除患者管理字段缺失修复脚本 V2026_0608_1
- 移除文化程度字典类型添加脚本 V2026_0608_2
- 移除HisBaseEntity列缺失修复脚本 V2026_0608
- 移除处方拦截日志表修复脚本 V2026_0611
- 移除临床路径执行表修复脚本 V2026_0612
- 移除EMPI核心表创建脚本 V2026_0616_1
- 移除EMPI合并日志时间字段修复脚本 V2026_0616_2
- 移除手术状态字典重复数据修复脚本 V2026_0617
- 移除医嘱退回流程设备请求字段添加脚本 V20260615
2026-06-17 11:24:16 +08:00
wangjian963
cfc7ca9b4e 676 [住院医生站-临床医嘱] 勾选“待签发”临时医嘱后,点击【签发】按钮无响应 2026-06-17 11:13:11 +08:00
wangjian963
bdb7d978fb fix(ui): 修复住院医生站与护士站临床医嘱若干稳定性问题
医生站:
    - 修复类型切换后编辑表单残留、blur/click竞态致选中无效、批量保存缺patientId
    - 修复filterPrescriptionList.find过滤下展开失败、popover溢出、表格塌陷
    - 提取resolveCategoryCode/getAdviceTableRef消除重复, 优化adviceTableRef类型
    - 修复adviceBaseList keyField、选中残留、TS类型声明

  护士站:
    - 校对: 新增已执行状态判定+退回拦截, 修复状态标签颜色不一致
    - 执行: 修复长期医嘱dayTimes为空被静默丢弃
    - 双模块: 新增keep-alive重激活刷新+患者列表自动加载

  配置:
    - eslint.config.js 新增 @typescript-eslint/parser 支持Vue TS解析
2026-06-17 11:06:45 +08:00
5a227014fe fix(surgery): #684 手术状态下拉框重复 - 清理字典重复数据 2026-06-17 11:02:18 +08:00
1c68860541 ```
feat(patient): 移除门诊记录组件

- 删除了 OutpatientRecord.vue 组件文件
- 移除了门诊记录表格显示功能
- 清理了相关的数据获取和状态管理逻辑
- 移除了查看门诊详情的路由跳转功能
```
2026-06-17 10:40:34 +08:00
2a0303d0e6 fix(regdoctorstation): RegPrescriptionUtils groupingBy null key保护
Bug #674: 住院签发长期医嘱时 conditionDefinitionId/pharmacologyCategoryCode/therapyEnum 为 null
导致 Collectors.groupingBy 抛出 NPE 'element cannot be mapped to a null key'

修复:对齐门诊版 PrescriptionUtils 的 null 处理逻辑
- getConditionDefinitionId null -> 默认 0L
- getPharmacologyCategoryCode null -> 默认 '0'
- getTherapyEnum null -> 默认 0
- generatePrescriptionNo null/空 -> 走普通处方号
2026-06-17 09:32:46 +08:00
81d5c99a35 fix(#769): zhaoyun (文件合入) 2026-06-17 09:08:16 +08:00
8258d3e2da fix(#774): zhaoyun (文件合入) 2026-06-17 08:54:39 +08:00
3812561ede fix(#766): zhaoyun (文件合入) 2026-06-16 20:42:43 +08:00
wangjian963
48189a075f fix(智能分诊排队管理): 修复表格事件参数Bug及清理硬编码假数据和死代码
- 修复 cell-click 事件参数Bug:vxe-table 的 cell-click 回调为 { row, ... } 对象,
    未解构导致 selectedQueueRow 被赋值为事件对象,row.id 始终为 undefined,
    造成移出队列、选呼、上移/下移等所有操作报"缺少ID"
  - 修复 checkbox-change 事件参数Bug:同样需解构 { records } 才能获取选中数组,
    否则 selectedCandidates 为事件对象,"加入队列"按钮永久禁用
  - 移除候选池/队列硬编码假数据,ref 初始化为空数组,消除页面加载时的数据闪
  - 移除死代码:formatMinutesToMmSs、mapStatusToFrontend、
    getNextQueueOrder、recalculateQueueOrders
  - 修复 getRowClassName/canMoveUp/canMoveDown 使用 id 替代 queueOrder 匹配,
    避免不同诊室同序号误高亮/误判
  - 修复 filterTodayData:registerTime 缺失时保留数据而非全部丢弃
  - 移除候选池表格无用的 :row-config
2026-06-16 16:35:20 +08:00
wangjian963
c26b458298 Merge remote-tracking branch 'origin/develop' into develop 2026-06-16 16:21:58 +08:00
e38c5993a0 fix(#770): zhaoyun (文件合入) 2026-06-16 16:21:49 +08:00
Ranyunqiao
cb82f8d5bf bug 673 761 719 754 728 727 763 2026-06-16 16:16:09 +08:00
wangjian963
ea8dca058a fix(智能分诊排队管理): 移除候选池和队列的硬编码假数据,消除页面加载时的数据闪现问题
- 删除 getInitialCandidatePoolList() 和 getInitialQueueList() 两个硬编码函数(共8条虚构患者/队列记录)
  - 候选池和队列 ref 初始值由硬编码假数据改为空数组 []
  - currentDate 初始值由固定日期改为空字符串,由 loadDataFromApi 动态计算
  - currentCall 初始值由假数据(郑华/4号诊室)改为占位符(-/-/-),由 syncCurrentCallFromQueue 动态同步
  - loadDataFromApi 异常回退不再注入假数据,统一清空为 []
2026-06-16 16:15:13 +08:00
deb5683ca6 Merge remote-tracking branch 'origin/develop' into develop 2026-06-16 16:12:16 +08:00
c4ca097bf6 feat(menu): 添加用户可访问菜单树接口并优化界面展示
- 新增 /userMenus 接口供普通用户获取自身权限范围内的菜单树
- 修复菜单ID路径参数正则表达式匹配问题
- 优化门诊挂号患者列表表格列宽和滚动显示
- 更新患者主索引界面搜索表单和表格展示逻辑
- 调整挂号记录表格高度计算和列固定布局
- 更新未闭环医嘱统计界面提示信息和分页功能
- 修复用户医院名称获取逻辑优先级问题
- 添加EMPI合并日志创建时间字段迁移脚本
2026-06-16 16:08:40 +08:00
wangjian963
8b6265801d fix(门诊医生站): 修复中医tab页药品医嘱搜索选中后不填充及展开行不渲染的问题
vxe-table v4 中 expandRowKeys 仅在初始化时生效,后续变更必须通过实例方法
  setRowExpand/clearRowExpand 控制展开行。同时 vxe-table 浅监听 data prop,
  替换行对象引用会导致 slot scope 响应链路断裂。
2026-06-16 16:05:36 +08:00
wangjian963
bf5a9674df fix(门诊医生站): 修复中医诊断弹窗选择后诊断详情不显示的问题
- addDiagnosisDialog: 修复 vxe-table v4 cell-click 事件未解构 row 导致
    conditionName/syndromeName 为 undefined,右侧详情始终为空
  - diagnosislist: 新增 medTypeCode prop 按诊断类型过滤列表,避免中/西医错选
  - diagnosis: 保存时排除中医诊断(已通过独立接口保存),防止重复提交
2026-06-16 14:30:39 +08:00
954462272e feat(empi): 添加EMPI合并日志记录功能
- 引入EmpiMergeLog实体类和IEmpiMergeLogService服务接口
- 在EmpiAppServiceImpl中注入mergeLogService依赖
- 实现合并操作时自动创建合并日志记录
- 记录合并的源患者ID、目标患者ID和合并类型
- 添加合并原因、操作人和合并时间等关键信息
- 确保每次患者合并操作都有完整的审计日志
2026-06-16 14:10:37 +08:00
9a5d772c72 Merge remote-tracking branch 'origin/develop' into develop 2026-06-16 13:38:18 +08:00
d861c20d5e feat(empi): 实现EMPI患者主索引系统核心功能
- 新增EMPI核心数据表:empi_person和empi_person_id_mapping
- 实现EMPI服务层接口,支持患者注册、合并、查询等功能
- 集成EMPI与院内患者系统的双向关联查询
- 添加患者保存事件监听器,实现EMPI数据自动同步
- 开发EMPI管理界面,支持患者合并操作和数据展示
- 优化EMPI统计功能,增加重复率和待合并患者统计
- 完善EMPI ID映射机制,支持多系统患者标识关联
2026-06-16 13:38:05 +08:00
488573a51b fix(#663): guanyu (文件合入) 2026-06-16 13:37:38 +08:00
wangjian963
259a5946c2 667 [门诊收费-业务流程] 医嘱未挂钩【完诊】状态,医生未终结门诊即可提前在收费端结算,存在漏开/错开费用风险
- @select → @checkbox-change,适配新事件签名
  - 新增 collapseAllExpanded() 使用 setRowExpand/clearRowExpand 兼容 v4 expand
  - setNewRow/setValue 保持行引用不变,原地更新数据
  - 所有医嘱类型编辑模板新增"取消"按钮
  - 内联布局样式抽取为 .edit-form-row 类,四种医嘱类型布局统一
  - 列宽、间距、备注框宽度等样式微调
  - requiredProps 空安全检查、handleBlur 修复、ref 名称修复
2026-06-16 13:33:42 +08:00
d0d6cf3533 fix(#770): zhaoyun (文件合入) 2026-06-16 13:30:49 +08:00
Ranyunqiao
fef1ca6637 Merge remote-tracking branch 'origin/develop' into develop 2026-06-16 13:06:40 +08:00
Ranyunqiao
fca3d0ca86 style: add el-tag styling to order status in transfer out list to match doctor station 2026-06-16 12:34:30 +08:00
193a08acbd fix(#776): guanyu (文件合入) 2026-06-16 12:01:52 +08:00
Ranyunqiao
41d05a1629 fix(ui): use dict text from frontend for accurate display of frequency, usage, amount, dose and ordering doctor 2026-06-16 11:55:41 +08:00
wangjian963
8cfa6fe05e fix(门诊医生站-医嘱列表): vxe-table v4适配及编辑区UI优化
- @select → @checkbox-change,适配新事件签名
  - 新增 collapseAllExpanded() 使用 setRowExpand/clearRowExpand 兼容 v4 expand
  - setNewRow/setValue 保持行引用不变,原地更新数据
  - 所有医嘱类型编辑模板新增"取消"按钮
  - 内联布局样式抽取为 .edit-form-row 类,四种医嘱类型布局统一
  - 列宽、间距、备注框宽度等样式微调
  - requiredProps 空安全检查、handleBlur 修复、ref 名称修复
2026-06-16 11:52:11 +08:00
wangjian963
8eb6feb70d 修复门诊医生站,医嘱tab表格布局错误问题。 2026-06-16 10:35:09 +08:00
Ranyunqiao
f93bec967a Merge remote-tracking branch 'origin/develop' into develop 2026-06-16 10:21:42 +08:00
Ranyunqiao
020d1be4be bug 716 718 2026-06-16 10:21:26 +08:00
wangjian963
f7f037aee9 656 [门诊医生站-检查申请] 单击已保存记录回显异常:自动跳转页签错误且“检查方法”数据未回显 2026-06-16 10:14:56 +08:00
6c77ee8f84 fix(#776): guanyu (文件合入) 2026-06-16 09:38:40 +08:00
0855d1153b fix(#776): guanyu (文件合入) 2026-06-16 08:50:32 +08:00
wangjian963
168961e656 654
[住院医生站-手术申请] 申请单保存成功后弹窗未自动关闭
2026-06-15 17:14:46 +08:00
wangjian963
9dc4a12339 Merge remote-tracking branch 'origin/develop' into develop 2026-06-15 16:55:47 +08:00
wangjian963
9bbf7c6c08 651 [住院医生站-手术申请] 无法检索出已启用的手术项目(如:“血管闭合切割刀”) 2026-06-15 16:55:17 +08:00
05088a1d1a fix(#734): guanyu (文件合入) 2026-06-15 16:53:01 +08:00
Ranyunqiao
5e9dbb2f1b Merge remote-tracking branch 'origin/develop' into develop 2026-06-15 16:48:48 +08:00
Ranyunqiao
b25d2fbaa9 bug 588 628 642 700 714 715 2026-06-15 16:48:27 +08:00
690e7ca22c fix(charge): 门诊日结 groupingBy null key 修复
Collectors.groupingBy 遇到 contractNo/busNo 为 null 的元素会抛
NullPointerException: Element cannot be mapped to a null key

修复: 在 groupingBy 前增加 .filter(e -> key != null && !key.isEmpty())
2026-06-15 16:47:44 +08:00
43ab5b4498 fix(flyway): 解除 V42 版本号冲突
merge PR #11 时带入 guanyu commit 01e8cc459 错误恢复的已废弃 V42__bug745
文件(该文件内容本已迁移到 V45,原 V42 应删除)。两个 V42 并存导致 Flyway
启动阻塞:"Found more than one migration with version 42"。

修复:删除冗余的 V42__bug745_fix_mr_sealing_medical_record_id.sql(空 deprecated
文件,实际逻辑在 V45)。保留 V42__add_delete_flag_columns.sql(原始文件,2026-06-11)。

验证:
- mvn clean package 通过
- 后端启动成功(HTTP 404 根路径,Flyway 无冲突)
- 登录 API + 门诊收费列表 API 正常响应
- Jackson 3 Long→String 序列化仍生效
2026-06-15 16:18:00 +08:00
219ac30dc5 fix(#763): guanyu (文件合入) 2026-06-15 15:46:59 +08:00
20f71ec5d9 Merge PR #11: refactor(jackson): Jackson 2 → 3 全项目迁移 2026-06-15 15:43:23 +08:00
2814 changed files with 316960 additions and 15531 deletions

View File

@@ -0,0 +1,47 @@
---
title: Fix vue/no-dupe-keys ESLint errors
status: in-progress
files_total: 26
errors_total: 65
---
# Fix vue/no-dupe-keys ESLint Errors
## Strategy by category
### Category A: Dialog components (props used by parent, refs are shadow copies)
- Delete the ref declarations that duplicate prop keys
- Delete the `xxx.value = props.xxx` assignment lines in show()/edit()
- Template will resolve to props keys automatically
Files:
1. deviceDialog.vue: title, deviceCategories, statusFlagOptions, supplierListOptions
2. diagnosisTreatmentDialog.vue: title, diagnosisCategoryOptions, statusFlagOptions, exeOrganizations, typeEnumOptions
3. medicineDialog.vue: supplierListOptions, statusRestrictedOptions, partAttributeEnumOptions, tempOrderSplitPropertyOptions
4. observationDialog.vue: title, observationTypeEnum, statusFlagOptions, instrumentIdOption
5. instrumentDialog.vue: title, instrumentTypeEnum, statusFlagOptions
6. specimenDialog.vue: title, specimenTypeEnum, statusFlagOptions
### Category B: Page components (refs are mutated locally, props are dead code)
- Remove the prop entries from defineProps (they're never passed by parent)
- Keep the ref declarations
Files:
7. returningInventory/index.vue: purposeTypeListOptions, sourceTypeListOptions, categoryListOptions
8. lossReporting/index.vue: purposeTypeListOptions, sourceTypeListOptions, categoryListOptions
9. inventoryReceiptDialog.vue: itemTypeOptions, practitionerListOptions, supplierListOptions
10. chkstockBatch/index.vue: purposeTypeListOptions, categoryListOptions
### Category C: Components where refs are locally mutated AND used via props
- Both the prop and ref are actively used
- Rename the ref to localXxx and update all references
Files:
11. Crontab/index.vue: hideComponent → localHideComponent, expression → localExpression
12. AdmissionDiagnosis.vue: tableData → localTableData, multiple → localMultiple
13. DischargeDiagnosis.vue: tableData → localTableData, multiple → localMultiple
14. prescription.vue: prescriptionNo → localPrescriptionNo, typeDetail → localTypeDetail
15. details.vue: prescriptionNo → localPrescriptionNo, typeDetail → localTypeDetail
### Category D: Extra files not in original list (found in ESLint output)
Files 16-26 also need fixes - will assess each.

35
.idea/dataSources.local.xml generated Normal file
View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="dataSourceStorageLocal" created-in="IU-253.33514.17">
<data-source name="postgresql@192.168.110.252" uuid="6f44e2a0-c865-4e9f-83bf-d35db0680dc5">
<database-info product="PostgreSQL" version="17.6" jdbc-version="4.2" driver-name="PostgreSQL JDBC Driver" driver-version="42.7.3" dbms="POSTGRES" exact-version="17.6" exact-driver-version="42.7">
<identifier-quote-string>&quot;</identifier-quote-string>
</database-info>
<case-sensitivity plain-identifiers="lower" quoted-identifiers="exact" />
<secret-storage>master_key</secret-storage>
<user-name>postgresql</user-name>
<schema-mapping>
<introspection-scope>
<node kind="database" qname="@">
<node kind="schema" qname="@" />
</node>
</introspection-scope>
</schema-mapping>
</data-source>
<data-source name="postgresql@47.116.196.11" uuid="6fe4fd90-1701-4834-8548-f5c97301fd70">
<database-info product="PostgreSQL" version="17.6" jdbc-version="4.2" driver-name="PostgreSQL JDBC Driver" driver-version="42.7.3" dbms="POSTGRES" exact-version="17.6" exact-driver-version="42.7">
<identifier-quote-string>&quot;</identifier-quote-string>
</database-info>
<case-sensitivity plain-identifiers="lower" quoted-identifiers="exact" />
<secret-storage>master_key</secret-storage>
<user-name>postgresql</user-name>
<schema-mapping>
<introspection-scope>
<node kind="database" qname="@">
<node kind="schema" qname="@" />
</node>
</introspection-scope>
</schema-mapping>
</data-source>
</component>
</project>

29
.idea/dataSources.xml generated Normal file
View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="postgresql@192.168.110.252" uuid="6f44e2a0-c865-4e9f-83bf-d35db0680dc5">
<driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql://192.168.110.252:15432/postgresql?currentSchema=healthlink_his&amp;characterEncoding=UTF-8&amp;client_encoding=UTF-8</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
<data-source source="LOCAL" name="postgresql@47.116.196.11" uuid="6fe4fd90-1701-4834-8548-f5c97301fd70">
<driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql://47.116.196.11:15432/postgresql?currentSchema=healthlink_his&amp;characterEncoding=UTF-8&amp;client_encoding=UTF-8</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
#n:healthlink_his
!<md> [786566, 0, null, null, -2147483648, -2147483648]

View File

@@ -0,0 +1,2 @@
#n:information_schema
!<md> [null, 0, null, null, -2147483648, -2147483648]

View File

@@ -0,0 +1,2 @@
#n:pg_catalog
!<md> [null, 0, null, null, -2147483648, -2147483648]

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
#n:healthlink_his
!<md> [786700, 0, null, null, -2147483648, -2147483648]

View File

@@ -0,0 +1,2 @@
#n:information_schema
!<md> [null, 0, null, null, -2147483648, -2147483648]

View File

@@ -0,0 +1,2 @@
#n:pg_catalog
!<md> [null, 0, null, null, -2147483648, -2147483648]

6
.idea/db-forest-config.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="db-tree-configuration">
<option name="data" value="----------------------------------------&#10;1:0:6f44e2a0-c865-4e9f-83bf-d35db0680dc5&#10;2:0:6fe4fd90-1701-4834-8548-f5c97301fd70&#10;" />
</component>
</project>

8
.idea/shelf/_2026_6_16_09_56____.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<changelist name="在进行更新之前于_2026_6_16_09_56_取消提交了更改_[更改]" date="1781574986508" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_09_56_取消提交了更改_[更改]/shelved.patch" />
<option name="DESCRIPTION" value="在进行更新之前于 2026/6/16 09:56 取消提交了更改 [更改]" />
<binary>
<option name="AFTER_PATH" value="MD/HEALTHLINK_HIS_PRICING_v0.1.docx" />
<option name="SHELVED_PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_09_56_取消提交了更改_[更改]/HEALTHLINK_HIS_PRICING_v0.1.docx" />
</binary>
</changelist>

8
.idea/shelf/_2026_6_16_10_44____.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<changelist name="在进行更新之前于_2026_6_16_10_44_取消提交了更改_[更改]" date="1781577901658" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_10_44_取消提交了更改_[更改]/shelved.patch" />
<option name="DESCRIPTION" value="在进行更新之前于 2026/6/16 10:44 取消提交了更改 [更改]" />
<binary>
<option name="AFTER_PATH" value="MD/HEALTHLINK_HIS_PRICING_v0.1.docx" />
<option name="SHELVED_PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_10_44_取消提交了更改_[更改]/HEALTHLINK_HIS_PRICING_v0.1.docx" />
</binary>
</changelist>

8
.idea/shelf/_2026_6_16_13_36____.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<changelist name="在进行更新之前于_2026_6_16_13_36_取消提交了更改_[更改]" date="1781588195703" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_13_36_取消提交了更改_[更改]/shelved.patch" />
<option name="DESCRIPTION" value="在进行更新之前于 2026/6/16 13:36 取消提交了更改 [更改]" />
<binary>
<option name="AFTER_PATH" value="MD/HEALTHLINK_HIS_PRICING_v0.1.docx" />
<option name="SHELVED_PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_13_36_取消提交了更改_[更改]/HEALTHLINK_HIS_PRICING_v0.1.docx" />
</binary>
</changelist>

8
.idea/shelf/_2026_6_16_13_38____.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<changelist name="在进行更新之前于_2026_6_16_13_38_取消提交了更改_[更改]" date="1781588299786" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_13_38_取消提交了更改_[更改]/shelved.patch" />
<option name="DESCRIPTION" value="在进行更新之前于 2026/6/16 13:38 取消提交了更改 [更改]" />
<binary>
<option name="AFTER_PATH" value="MD/HEALTHLINK_HIS_PRICING_v0.1.docx" />
<option name="SHELVED_PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_13_38_取消提交了更改_[更改]/HEALTHLINK_HIS_PRICING_v0.1.docx" />
</binary>
</changelist>

8
.idea/shelf/_2026_6_16_15_24____.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<changelist name="在进行更新之前于_2026_6_16_15_24_取消提交了更改_[更改]" date="1781594661495" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_15_24_取消提交了更改_[更改]/shelved.patch" />
<option name="DESCRIPTION" value="在进行更新之前于 2026/6/16 15:24 取消提交了更改 [更改]" />
<binary>
<option name="AFTER_PATH" value="MD/HEALTHLINK_HIS_PRICING_v0.1.docx" />
<option name="SHELVED_PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_15_24_取消提交了更改_[更改]/HEALTHLINK_HIS_PRICING_v0.1.docx" />
</binary>
</changelist>

8
.idea/shelf/_2026_6_16_16_12____.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<changelist name="在进行更新之前于_2026_6_16_16_12_取消提交了更改_[更改]" date="1781597537348" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_16_12_取消提交了更改_[更改]/shelved.patch" />
<option name="DESCRIPTION" value="在进行更新之前于 2026/6/16 16:12 取消提交了更改 [更改]" />
<binary>
<option name="AFTER_PATH" value="MD/HEALTHLINK_HIS_PRICING_v0.1.docx" />
<option name="SHELVED_PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_16_16_12_取消提交了更改_[更改]/HEALTHLINK_HIS_PRICING_v0.1.docx" />
</binary>
</changelist>

8
.idea/shelf/_2026_6_17_08_41____.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<changelist name="在进行更新之前于_2026_6_17_08_41_取消提交了更改_[更改]" date="1781656871923" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_17_08_41_取消提交了更改_[更改]/shelved.patch" />
<option name="DESCRIPTION" value="在进行更新之前于 2026/6/17 08:41 取消提交了更改 [更改]" />
<binary>
<option name="AFTER_PATH" value="MD/HEALTHLINK_HIS_PRICING_v0.1.docx" />
<option name="SHELVED_PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_17_08_41_取消提交了更改_[更改]/HEALTHLINK_HIS_PRICING_v0.1.docx" />
</binary>
</changelist>

4
.idea/shelf/_2026_6_17_11_43____.xml generated Normal file
View File

@@ -0,0 +1,4 @@
<changelist name="在进行更新之前于_2026_6_17_11_43_取消提交了更改_[更改]" date="1781667802685" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/在进行更新之前于_2026_6_17_11_43_取消提交了更改_[更改]/shelved.patch" />
<option name="DESCRIPTION" value="在进行更新之前于 2026/6/17 11:43 取消提交了更改 [更改]" />
</changelist>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,60 @@
# 修复 ohmyagent (ultrawork) 命令无法使用的问题
## 问题分析
用户反馈 `/ulw``/ultrawork` 命令无法使用,报错 "Unknown skill: ulw" 或 "Unknown skill: ultrawork"。
### 根因
1. **技能与命令冲突**`ultrawork` 既是一个 skill (`C:\Users\Administrator\.claude\skills\ultrawork\SKILL.md`),又有一个 command (`C:\Users\Administrator\.claude\commands\ulw.md`)
2. **命令注册问题**`/ulw` 作为 command 存在,但 Claude Code 的 skill 系统在查找 "ulw" 这个 skill 时找不到
3. **多版本冲突**:存在两个版本的 ultrawork 配置:
- `C:\Users\Administrator\.claude\ultrawork-sanguo.json` (根目录配置)
- `C:\Users\Administrator\.claude\plugins\ultrawork-sanguo\config\ultrawork-sanguo.json` (插件配置)
## 修复方案已确认Skill优先
统一使用 Skill 系统,将 `/ulw` 命令改为触发 `ultrawork` skill。
**修改文件:**
- `C:\Users\Administrator\.claude\commands\ulw.md` - 改为调用 ultrawork skill
## 具体修复步骤
### Step 1: 修复 ulw.md command
`C:\Users\Administrator\.claude\commands\ulw.md` 修改为触发 ultrawork skill 的 command
```markdown
---
name: ulw
description: 激活 UltraWork 三国军团调度系统
---
# /ulw - UltraWork 三国军团
当用户输入 /ulw 时,加载 ultrawork skill 并执行任务。
## 触发方式
使用 skill 工具加载 ultrawork skill然后根据 skill 流程执行任务。
```
### Step 2: 验证 ultrawork skill 配置
检查 `C:\Users\Administrator\.claude\skills\ultrawork\SKILL.md` 确保:
- name 字段为 "ultrawork"
- description 包含触发关键词(/ulw, /ultrawork, ultrawork
## 验证方法
1. 输入 `/ulw 测试任务` 应该能触发 ultrawork skill
2. 输入 `/ultrawork` 应该能触发 ultrawork skill
3. 直接说 "ultrawork 测试任务" 也应该能触发
## 关键文件
- `C:\Users\Administrator\.claude\commands\ulw.md`
- `C:\Users\Administrator\.claude\skills\ultrawork\SKILL.md`
- `C:\Users\Administrator\.claude\ultrawork-sanguo.json`
- `C:\Users\Administrator\.claude\plugins\ultrawork-sanguo\config\ultrawork-sanguo.json`

6
.mimocode/settings.json Normal file
View File

@@ -0,0 +1,6 @@
{
"provider": "openai-compatible",
"apiKey": "tp-c5g4lq98ufrnmb8tgde32pf1jodrqs2bfkyz19shto080000",
"baseUrl": "https://token-plan-cn.xiaomimimo.com/v1",
"model": "mimo-v2.5-pro"
}

27
.qoder/agents/chenlin.md Normal file
View File

@@ -0,0 +1,27 @@
---
name: chenlin
description: 归档师 — 生成报告、Git归档、禅道备注
tools: Bash, Read, Write, Grep, Glob
model: inherit
maxTurns: 3
memory: project
effort: medium
color: orange
skills:
- archive
---
# 陈琳 (chenlin) — 归档师
## 角色
- 生成完整修复报告Markdown
- 写入 Git docs/bug-fixes/
- 写入 SQLite bug_reports 表
- 写入 Redis 缓存
- 禅道添加归档备注
## 铁律
1. 报告必须包含:基本信息、根因分析、修复文件、流程时间线
2. Git 归档路径his-repo/docs/bug-fixes/bug-{id}.md
3. SQLite 归档必须使用完整的 INSERT 列(含 test_output、pipeline_json
4. 禅道备注格式:[📝 陈琳归档] Bug #xxx 修复报告已归档

27
.qoder/agents/guanyu.md Normal file
View File

@@ -0,0 +1,27 @@
---
name: guanyu
description: 后端修复师 — Java/Spring/Mapper/数据库 修复
tools: Bash, Read, Write, Edit, Grep, Glob
model: inherit
maxTurns: 8
memory: project
effort: xhigh
color: red
skills:
- fix
---
# 关羽 (guanyu) — 后端修复师
## 角色
- 修复 Java/Spring Boot 后端 Bug
- 处理 API 接口、Service 逻辑、Mapper/SQL
- 数据库相关修复INSERT/UPDATE/DELETE
## 铁律
1. 修复前必须先读 AGENTS.md 了解项目规范
2. 修复后必须运行 `mvn compile` 验证编译
3. 涉及 SQL 必须先查真实数据库表结构
4. 一次只修一个 Bug不扩大范围
5. 修复后必须有 git commitcommit message 包含 Bug 编号
6. 数据库铁律:必须用 db-query 工具验证 SQL 语法正确性

25
.qoder/agents/huatuo.md Normal file
View File

@@ -0,0 +1,25 @@
---
name: huatuo
description: 验收师 — 最终验收、确认修复完整性
tools: Bash, Read, Grep, Glob
model: inherit
maxTurns: 3
memory: project
effort: medium
color: yellow
skills:
- verify
---
# 华佗 (huatuo) — 验收师
## 角色
- 最终验收修复结果
- 确认测试通过、代码提交、文档完整
- 人类 Bug 只加备注不改状态
## 铁律
1. 必须检查 git commit 是否存在
2. 必须检查测试报告是否通过
3. 人类提的 Bug 不改状态不改分配,只加备注
4. 智能体提的 Bug 可以改分配和加备注

26
.qoder/agents/liubei.md Normal file
View File

@@ -0,0 +1,26 @@
---
name: liubei
description: 总协调者 — 扫描禅道Bug、调度智能体、生成进度报告
tools: Bash, Read, Grep, Glob
model: inherit
maxTurns: 5
memory: project
effort: high
color: gold
skills:
- analyze
---
# 刘备 (liubei) — 总协调者
## 角色
- 扫描禅道所有未关闭 Bug
- 根据 Bug 标题关键词路由到对应修复智能体
- 监控管线进度,生成报告
- 不直接修复 Bug
## 铁律
1. 只调度,不修改代码
2. 每 5 分钟自动扫描一次
3. 路由规则:数据库→荀彧,后端→关羽,前端→赵云
4. 已关闭/已解决的 Bug 不再调度

25
.qoder/agents/xunyu.md Normal file
View File

@@ -0,0 +1,25 @@
---
name: xunyu
description: DB审查师 — 数据库变更审查、SQL验证
tools: Bash, Read, Grep, Glob
model: inherit
maxTurns: 3
memory: project
effort: high
color: cyan
skills:
- db-review
---
# 荀彧 (xunyu) — DB审查师
## 角色
- 审查修复中的数据库变更
- 验证 SQL 语法、表结构、约束
- 检查迁移脚本完整性
## 铁律
1. 必须用 db-query 工具查询真实数据库
2. 检查 NOT NULL 约束、外键约束
3. 验证 INSERT/UPDATE 字段与表结构匹配
4. 审查结果必须包含:通过/不通过、原因、建议

25
.qoder/agents/zhangfei.md Normal file
View File

@@ -0,0 +1,25 @@
---
name: zhangfei
description: 测试师 — Playwright回归测试、质量验证
tools: Bash, Read, Grep, Glob
model: inherit
maxTurns: 5
memory: project
effort: high
color: green
skills:
- test
---
# 张飞 (zhangfei) — 测试师
## 角色
- 运行 Playwright 回归测试
- 验证修复是否生效
- 测试失败时退回修复智能体
## 铁律
1. 必须用 `--workers=1` 避免压垮 dev server
2. 测试超时 120 秒
3. 最多重试 3 次,超过则通知人工介入
4. 测试结果必须写入禅道备注

25
.qoder/agents/zhaoyun.md Normal file
View File

@@ -0,0 +1,25 @@
---
name: zhaoyun
description: 前端修复师 — Vue/TypeScript/CSS 修复
tools: Bash, Read, Write, Edit, Grep, Glob
model: inherit
maxTurns: 8
memory: project
effort: xhigh
color: blue
skills:
- fix
---
# 赵云 (zhaoyun) — 前端修复师
## 角色
- 修复 Vue3/TypeScript 前端 Bug
- 处理界面显示、组件交互、样式问题
- API 调用对接
## 铁律
1. 修复前必须先读 AGENTS.md 了解项目规范
2. 修复后必须运行 `vue-tsc --noEmit` 验证类型
3. 一次只修一个 Bug不扩大范围
4. 修复后必须有 git commitcommit message 包含 Bug 编号

View File

@@ -0,0 +1,26 @@
---
name: zhugeliang
description: 分析师 — 分析Bug根因、拆解修复步骤、路由到正确智能体
tools: Bash, Read, Grep, Glob, WebFetch
model: inherit
maxTurns: 3
memory: project
effort: xhigh
color: purple
skills:
- analyze
---
# 诸葛亮 (zhugeliang) — 分析师
## 角色
- 接收刘备分派的 Bug深度分析根因
- 读取禅道完整信息(含图片附件 OCR
- 拆解修复步骤,确定修复策略
- 路由到正确的修复智能体
## 铁律
1. 必须读取 AGENTS.md 了解项目规范
2. 必须分析完整 6 环链路前端→Controller→Service→Mapper→DB→关联模块
3. 涉及数据库字段的 Bug 必须先查真实表结构
4. 分析报告必须包含:根因、影响范围、修复方案、测试要点

377
.qoder/rules/IRON_LAWS.md Normal file
View File

@@ -0,0 +1,377 @@
# 🔴 AgentForge 铁律(不可违反)
> 所有智能体在处理任何任务时必须遵守。违反任何一条 = 阻断提交。
> 唯一源头文件:修改此文件后所有智能体自动生效。
---
## 一、Bug 状态管理
- **已关闭/已解决的 Bug 禁止处理** — 处理前检查禅道 statusresolved/closed 直接跳过
- **人类提的 Bug 只加备注不改状态** — reporter 是人类账号时,不改 status、不改 assignedTo
- **智能体提的 Bug 可改分配和加备注** — 状态变更等测试通过后由华佗确认
- **每个修复必须有 git commit** — 格式: `fix(#bug_id): 简要描述`
- **🔴 修复完成必须提交** — `git add --all && git commit && git push`,未提交=没修
- **🔴 修复必须合并到 develop** — 工作树 commit ≠ 生效,必须 cherry-pick/merge 到 develop
- **🔴 未合并到 develop 的修复等于没修** — 验收时检查 develop 上是否有该 commit
- **🔴 修复必须编译部署后才算完成** — `mvn package``systemctl restart` → 验证启动时间
---
## 二、修复流程
- **一次只修一个 Bug**,不扩大范围
- **修前必须完整获取 Bug 全部信息** — 描述、复现步骤、所有截图/附件、所有备注历史。禁止只看标题就写代码
- **修复前必须读 AGENTS.md**
- **修复后必须验证编译** — `mvn compile` / `vue-tsc --noEmit` 0 error
- **commit 前必须验证** — 编译通过 + 无新增 lint 警告
---
## 三、全链路 6 环分析
涉及数据库字段的 Bug 必须走完整链路:
```
前端/页面 → Controller → Service → Mapper → DB/SQL → 关联模块
①录入 ②验证 ③业务 ④持久化 ⑤存储 ⑥联动
```
---
## 四、状态值一致性(来自 Bug #574 教训)
修改任何状态值前,**必须**列出完整链路并逐项检查:
1. 枚举定义(如 `SlotStatus`)的值
2. Service 层设置的状态值是否与枚举一致
3. 查询/列表接口的状态映射是否覆盖所有枚举值
4. 前端 `STATUS_CLASS_MAP` 是否包含新状态
5. 前端过滤条件(`v-if``v-for`)是否兼容新状态
6. 池/统计表的聚合 SQL 是否包含新状态值
**禁止**:只改一端不检查其他端。
---
## 五、状态变更影响面分析(来自 Bug #574→575 教训)
改任何状态枚举值前,**必须**执行影响面分析:
1. `rg "原状态枚举名" --type java` 列出所有引用文件
2. 逐个检查:设置值?查询过滤?显示映射?统计聚合?
3. 检查逆向流程:退号、取消、停诊是否兼容新状态
4. 检查 XML mapper 中所有查询过滤条件
5. 检查前端所有 v-if/v-for/disabled 条件
**禁止**:只改正向流程不验逆向流程。
---
## 六、逆向流程验证(来自 Bug #575 教训)
涉及状态流转的 Bug验证时**必须**覆盖:
- 正向:预约→签到→就诊→完成
- 逆向:退号、取消预约、停诊、退费
- 边界:并发操作、重复操作、异常中断
**禁止**:只测正向流程就标记"修复完成"。
---
## 七、全链路验证(状态流转 Bug 必做)
修复后按以下顺序验证,**编译通过不等于修复完成**
```
① 数据库SELECT status FROM table WHERE id = ? → 确认写入正确
② 后端接口:检查所有 if/switch 分支 → 确认映射正确
③ 前端显示:检查 STATUS_CLASS_MAP → 确认文本正确
④ 前端交互:检查 v-if/v-for/disabled → 确认按钮状态正确
⑤ 统计数据:检查聚合 SQL → 确认统计包含新状态
```
---
## 八、池/统计表同步(来自 Bug #574 反复修复教训)
- **任何状态变更必须同步更新关联统计表**
- 检查清单:
1. 状态变更后,哪些统计字段需要更新?
2. 是原子递增/递减,还是全量重算?
3. 并发安全:用 `SET field = field + 1` 还是先查后改?
4. 逆向操作(退号/取消)是否正确回滚统计?
- **禁止**:只改状态不改统计,或只改统计不改状态
---
## 九、统计变更必须验证实际值(来自 Bug #575 教训)
- 修改统计逻辑后,**必须查数据库验证实际值**
- `SELECT booked_num, locked_num FROM adm_schedule_pool WHERE id = ?`
- 对比操作前后的值,确认统计正确
- **禁止**:改了统计逻辑不查数据库验证
---
## 十、禁止删除源文件
- **绝对禁止**删除项目中已有的 Java/Vue/SQL 源文件
- 编译错误 → 修复错误,不删除文件
- 重复文件 → 重构合并,不删除文件
- AI 幻觉文件 → 检查 `git ls-tree baseline -- <file>` 确认后再删除
- **唯一例外**:人类明确确认删除
---
## 十一、禁止修改已有公开方法签名
- 不能删除或重命名已有的 public 方法
- 不能修改已有方法的参数列表
- 需要新功能 → 添加重载方法
- 需要改行为 → 修改方法内部实现
---
## 十二、搜索所有相关代码路径
修复前必须用 `rg` 搜索:
```
rg "状态枚举名|相关方法名|相关字段名" --type java --type vue
```
确保不遗漏任何引用路径。
---
## 十三、数据库铁律
- **修前必须查询真实数据库** — 确认表结构、字段约束、索引
- **禁止凭猜测写 SQL** — 先 `\d table_name` 查看表结构
- **修改 SQL 后必须验证** — `EXPLAIN` 或实际查询验证语法
- **NOT NULL 约束必须检查** — INSERT/UPDATE 前先查 `is_nullable`
- **关联表必须查完整** — 涉及 JOIN 查所有关联表结构和外键
- **涉及 SQL 必须先查真实数据库**
---
## 十四、测试铁律
- Playwright 必须 `--workers=1`
- 超时 120 秒,最多重试 3 次
- 测试失败自动重试,超过 3 次通知人工介入
- 测试结果写入禅道备注
- **DB审查失败自动回退** — 路由回原修复智能体
---
## 十五、归档铁律
- **三重写入** — Git + SQLite + Redis
- SQLite 必须使用完整字段
- 禅道备注格式:`[📝 陈琳归档] Bug #xxx`
- 归档报告必须包含:基本信息 + 根因分析 + 修复文件 + 流程时间线
---
## 十六、禅道交互
- 备注使用 resolve+activate workaround
- 不直接调用 comment API会 404
- 图片附件必须 OCR 读取
---
## 十七、质量门禁
- L1: 编译通过
- L2: 测试通过
- L3: DB审查通过
- L4: 验收通过
- L5: 归档完成
---
## 过往教训
| Bug | 教训 | 根因 |
|---|---|---|
| #574 | 状态值 BOOKED(1)→应为 CHECKED_IN(3),前端映射缺失 | 没走完整状态链路 |
| #574 | AI 看到编译错误直接删文件 | 没检查 git baseline |
| #574 | 多次 fallback 修错文件OrderServiceImpl | 没用 rg 搜索所有引用 |
| #574 | 签到后 booked_num 未累加 | 只改状态没改统计 |
| #575 | 改了签到状态没检查退号流程 | 只验正向不验逆向 |
| #575 | booked_num 应在预约时累加而非签到时 | 统计变更未验证实际值 |
| — | 修复完成未提交到 develop | 框架未强制验证提交 |
| — | 退号流程只检查 BOOKED(1) 不兼容 CHECKED_IN(3) | 状态变更影响面分析缺失 |
---
## 十八、禁止硬编码业务默认值(来自 Bug #617 教训)
- **禁止**在提交参数中硬编码业务默认值(如 `contractNo: '0000'`
- 必须使用用户在表单中选择的值,硬编码值仅作为 fallback
- 检查清单:
1. 表单字段是否有 `v-model` 绑定?
2. 构建提交参数时是否使用了绑定值?
3. 提交后是否覆盖了用户选择?
- **禁止**:用户选了医保,提交时却写死为自费
---
## 过往教训(补充)
| Bug | 教训 | 根因 |
|---|---|---|
| #617 | 费用性质硬编码为 '0000'(自费),用户选医保无效 | 构建参数时写死默认值 |
---
## 十九、前端验证铁律
- **提交前必须编译前端** — `npm run build``npx vite build` 通过才算完成
- **禁止只改 .vue 文件不验证编译** — 改完必须跑一次编译确认无报错
- **SCSS 括号闭合必须检查** — `<style lang="scss" scoped>` 内的所有 `{}` 必须成对闭合
- **SCSS 嵌套层级不超过 4 层** — 过深嵌套说明结构需要重构
- **编译报错必须当场修复** — 看到 error 立即修,不要留到下一步
### SCSS 检查清单
```bash
# 编译验证
cd openhis-ui-vue3 && npm run build
# 如果编译报错,检查 SCSS
grep -n "{" src/views/xxx/index.vue | wc -l # 开括号数
grep -n "}" src/views/xxx/index.vue | wc -l # 闭括号数
# 两者必须相等
```
---
## 二十、提交前验证铁律
- **后端**: `mvn compile` 通过 + 无新增 warning
- **前端**: `npm run build` 通过 + 无 SCSS 错误
- **禁止跳过编译直接提交** — 编译失败的代码不允许进仓库
- **提交信息格式**: `type(scope): description`(如 `fix(charge): 修复退费金额计算`
### 提交前检查流程
```bash
# 1. 后端编译
cd openhis-server-new && mvn compile -pl openhis-application -am
# 2. 前端编译
cd openhis-ui-vue3 && npm run build
# 3. 两个都通过才提交
git add --all && git commit -m "type(scope): description"
```
---
## 二十六、resolve 前必须验证 develop commit来自 v0.5.1 修复)
- **禁止**仅凭 worktree 未提交变更就 resolve Bug
- resolve 前必须检查 `git log origin/develop --grep="Bug#{id}"` 是否有 commit
- `comment_bug` 用 resolve+activate workaroundactivate 失败会导致 bug 卡在 resolved
- `ok_to_commit` 必须要求 `has_fix_commit = true`develop 上有实际 commit
- **验证方式**: `git log origin/develop --grep="Bug#{id}" --oneline -1` 有输出才允许 resolve
---
## 二十七、comment_bug 禁止改状态铁律(来自 v0.5.2 修复)
- **禁止**使用 resolve+activate workaround 添加备注 — activate 失败会导致 bug 卡在 resolved
- 添加备注必须使用不改状态的方式CLI `zentao bug update --comment` 或 API `PUT /bugs/{id}`
- `comment_bug` 函数必须只写 comment不触发任何状态变更
- **教训**: 36 个 bug 因 activate 失败被误标为 resolved无代码提交
### 正确做法
```rust
// ✅ 正确:只加备注,不改状态
zentao bug update --id <BUG_ID> --comment "备注内容"
// ❌ 错误resolve+activate 会改状态
POST /bugs/{id}/resolve // 改为 resolved
POST /bugs/{id}/activate // 如果失败bug 卡在 resolved
```
---
## 二十八、文件快照禁用覆盖判定铁律(来自 v0.5.2 修复)
- **禁止**用主仓库文件快照 diff 覆盖 success 判定
- success 判定必须基于 agent worktree 的实际变更(`count_changed_files` + `has_fix_commit`
- 主仓库快照仅用于日志记录,不能影响判定结果
- **教训**: 主仓库快照检测到其他 agent 的变更,误判当前 agent 修复成功
### 根因
```
Agent A cherry-pick 到 develop → 主仓库有变更
Agent B 运行 → 主仓库快照检测到 A 的变更 → 误判 B 修复成功
```
### 正确做法
```rust
// ✅ 正确:基于 worktree 判定
let changes = count_worktree_changes(agent_name); // 检查 worktree
let has_fix = has_recent_fix_commit(agent_name, bug_id); // 检查 develop commit
// ❌ 错误:基于主仓库判定
let file_diff = snapshot_and_diff(main_repo_dir, &before); // 检查主仓库
if has_real_changes { r.success = true; } // 误判
```
---
## 二十九、Worktree 必须存在且为 Git 仓库铁律
- 每个 agent 的 worktree 目录必须存在且包含 `.git` 文件
- 启动 executor 前必须验证 worktree 存在:`test -d /tmp/agentforge-worktrees/{agent}`
- worktree 不存在时必须创建:`git worktree add /tmp/agentforge-worktrees/{agent} -b {agent}`
- **教训**: 4 个 agentzhangfei, chenlin, huatuo, liubei无 worktreecodex 运行失败但仍标记成功
### 验证命令
```bash
# 检查所有 agent worktree
for agent in zhaoyun guanyu xunyu zhangfei huatuo chenlin zhugeliang liubei; do
if [ -d "/tmp/agentforge-worktrees/$agent/.git" ]; then
echo "✅ $agent: worktree OK"
else
echo "❌ $agent: worktree MISSING"
cd /root/.openclaw/workspace/his-repo
git worktree add /tmp/agentforge-worktrees/$agent -b $agent
fi
done
```
---
## 三十、Bug 状态变更必须双重确认铁律
- resolve Bug 前必须检查当前状态:`zentao bug get --id {id} | grep status`
- 只有 `status: active` 的 Bug 才允许 resolve
- resolve 后必须验证状态:`zentao bug get --id {id} | grep status` 确认为 `resolved`
- activate 后必须验证状态:确认恢复为 `active`
- **教训**: 批量操作 36 个 bug 时1 个因状态不对失败,需要逐个检查
### 批量操作模板
```bash
source /root/.config/zentao/.env
for id in 711 710 709; do
# 1. 检查当前状态
status=$(zentao bug get --id "$id" 2>&1 | grep "status:" | awk '{print $2}')
if [ "$status" != "active" ]; then
echo "⚠️ Bug #$id: 当前状态=$status,跳过"
continue
fi
# 2. 执行操作
zentao bug activate --id "$id" --data '{"openedBuild":"6"}'
# 3. 验证结果
new_status=$(zentao bug get --id "$id" 2>&1 | grep "status:" | awk '{print $2}')
echo "Bug #$id: $status$new_status"
done
```

46
.qoder/rules/backend.md Normal file
View File

@@ -0,0 +1,46 @@
---
description: Backend development rules for HealthLink-HIS Java/Spring Boot code
paths:
- "healthlink-his-server/**/*.java"
- "healthlink-his-server/**/pom.xml"
---
# Backend Development Rules
## Architecture
- Layered: `Controller → AppService → Service → Mapper → Entity`
- Package: `com.healthlink.his.web.{module}.{layer}`
- All queries use `LambdaQueryWrapper`, no string SQL concatenation
- All endpoints require `@PreAuthorize` permission control
- Use `@Transactional(rollbackFor = Exception.class)` for transaction management
## Naming conventions
- Controller: `XxxController`
- AppService: `IXxxAppService` / `XxxAppServiceImpl`
- Service: `IXxxService` / `XxxServiceImpl`
- Mapper: `XxxMapper`
- Entity: `Xxx`
- DTO: `XxxDto` / `XxxQueryDto`
## Iron Laws (Backend)
- **Iron Law 7**: Never modify existing public method signatures (no delete/rename, no parameter changes)
- **Iron Law 18**: Never break existing functionality when adding new features
- **Iron Law 19**: Compile errors are your responsibility to fix, regardless of origin
- **Iron Law 6**: Never delete existing Java source files
## DTO Field Type Defense
- Frontend Boolean fields → use String + business layer conversion (Jackson strict Boolean validation)
- All DTOs accepting frontend input: add `@JsonIgnoreProperties(ignoreUnknown = true)`
## Verification commands
```bash
cd healthlink-his-server
mvn clean compile -DskipTests # Compile check
mvn install -DskipTests # Build and install
mvn test # Run all tests
```
## Common patterns
- Patient sensitive information must be desensitized in logs
- Use Hutool utility classes for common operations
- Flowable for workflow, LiteFlow for rule engine

48
.qoder/rules/database.md Normal file
View File

@@ -0,0 +1,48 @@
---
description: Database and Flyway migration rules for HealthLink-HIS
paths:
- "**/*.sql"
- "**/mapper/*.xml"
- "healthlink-his-server/**/resources/db/migration/**"
---
# Database and Migration Rules
## Iron Law 2: Flyway database migration
- All new tables or new fields require a Flyway migration script
- Path: `healthlink-his-application/src/main/resources/db/migration/`
- Naming: `V{version}__{description}.sql` (double underscore)
## Iron Law 17: Database iron laws
- **Query real database before modification** — confirm table structure, field constraints, indexes
- **No guessing SQL** — check table structure first
- **Verify after SQL modification** — use `EXPLAIN` or actual query to verify syntax
- **Check NOT NULL constraints** — verify `is_nullable` before INSERT/UPDATE
- **Check all related tables** — for JOIN queries, check all related table structures and foreign keys
## Iron Law 18: SQL migration restrictions
- Only `ALTER TABLE ADD COLUMN` allowed
- No `DROP COLUMN` or `RENAME COLUMN`
- New fields can only be appended, not deleted or renamed
## Database connection
- PostgreSQL 15+ at `192.168.110.252:15432`
- Database: `healthlink_his`
- Flyway is enabled in dev and runs on startup
- Migration conflicts will block server startup
## Full chain 6-ring analysis
For bugs/requirements involving database fields, follow the complete chain:
```
Frontend/Page → Controller → Service → Mapper → DB/SQL → Related modules
①Input ②Validate ③Business ④Persist ⑤Storage ⑥Linkage
```
| Ring | Check |
|------|-------|
| ① Input | Frontend has input entry (dialog, table row edit, form) |
| ② Validate | Controller parameter validation, @Valid, permission control |
| ③ Business | Service business logic, transaction boundaries, multiple Service implementation entries |
| ④ Persist | Mapper XML, DTO field mapping, type conversion |
| ⑤ Storage | Database table structure, indexes, NOT NULL constraints |
| ⑥ Linkage | Upstream (orders→nurse station), downstream (printing, billing, reports) synchronization |

46
.qoder/rules/debugging.md Normal file
View File

@@ -0,0 +1,46 @@
---
description: Systematic debugging process for HealthLink-HIS
paths:
- "**/*.java"
- "**/*.{vue,js,ts}"
- "**/*.sql"
---
# Systematic Debugging Process
> **Iron Law: No root cause investigation, no fix proposal.**
## Four-stage process
### Stage 1: Root cause investigation (must complete before fixing)
1. Carefully read error message (stack trace, line numbers, error codes)
2. Stabilize reproduction (can it be reliably triggered? steps? every time?)
3. Check recent changes (`git diff`, new dependencies, config changes)
4. Multi-component system: add diagnostic logs at each component boundary, locate which layer is broken
5. Trace data flow: where does the bad value come from? who calls it? trace back to the source
### Stage 2: Pattern analysis
- Find similar working code in the same codebase
- Compare differences item by item
- Understand dependency relationships
### Stage 3: Hypothesis and test
- Form single hypothesis: "I believe X is the root cause because Y"
- Make minimal change to test
- Effective → Stage 4; Invalid → new hypothesis
### Stage 4: Implement
- Create failing test case
- Fix root cause (not symptoms)
- Verify fix
## Use /fix-compile skill
When `mvn compile` or `npm run build:dev` fails, use the `/fix-compile` skill for systematic diagnosis and repair.
## Common error patterns
- **Duplicate method**: Check all Service implementations for the same method
- **Missing import**: Verify package structure matches `com.healthlink.his.web.{module}`
- **Type mismatch**: Check DTO field types (Iron Law: DTO field type defense)
- **SCSS bracket**: Count `{` and `}` in `<style lang="scss" scoped>` blocks
- **Flyway conflict**: Check migration version numbers in `healthlink-his-application/src/main/resources/db/migration/`
- **State chain break**: Bug#574 lesson — check complete state flow (enum → Service → query → frontend mapping → statistics)

53
.qoder/rules/frontend.md Normal file
View File

@@ -0,0 +1,53 @@
---
description: Frontend development rules for HealthLink-HIS Vue 3/Element Plus code
paths:
- "healthlink-his-ui/src/**/*.{vue,js,ts,jsx,tsx}"
- "healthlink-his-ui/package.json"
- "healthlink-his-ui/vite.config.js"
---
# Frontend Development Rules
## Tech stack
- Vue 3.5 + Vite 6.4 + Element Plus 2.14 + Pinia 2.2 + TypeScript 5.9
- Based on RuoYi-Vue3 framework
## Directory structure
```
src/api/{module}/ # API interfaces
src/views/{module}/ # Page components
src/store/modules/ # Pinia state management
src/components/ # Shared components
```
## Key constraints
- API prefix: `/healthlink-his/api/v1/`
- Route lazy loading: `() => import('@/views/xxx/index.vue')`
- Use `<script setup>` syntax for all pages
- Button permissions: `v-hasPermi` directive
- Cleanup: events registered in `onMounted` must be removed in `onUnmounted`
## Iron Laws (Frontend)
- **Iron Law 4**: API paths must align with backend (`/healthlink-his/api/v1/`)
- **Iron Law 18**: Never break existing page component structure when adding new pages
- **Iron Law 23**: Always use UTF-8 encoding when reading/writing files (PowerShell trap)
- **Iron Law 30**: Frontend compilation is mandatory — `npm run build:dev` must pass
## SCSS rules
- Check bracket closure in `<style lang="scss" scoped>` blocks
- All `{}` must be paired
- Compilation errors must be fixed immediately
## Verification commands
```bash
cd healthlink-his-ui
npm run build:dev # Build verification
npm run lint # ESLint check
npm run test:run # Vitest unit tests
```
## Common patterns
- Use Element Plus components (ElTable, ElForm, ElDialog)
- Use vxe-table for complex data grids
- Use ECharts for charts and visualizations
- Use vue-plugin-hiprint for printing

49
.qoder/rules/testing.md Normal file
View File

@@ -0,0 +1,49 @@
---
description: Testing and verification rules for HealthLink-HIS
paths:
- "**/*.java"
- "**/*.{vue,js,ts}"
- "**/*.sql"
---
# Testing and Verification Rules
## Iron Law 1: Test after modification
- Backend: `mvn clean compile -DskipTests``mvn install -DskipTests``mvn test`
- Frontend: `npm run build:dev``npm run lint``npm run test:run`
- White box: Compilation passes, no ERROR
- Black box: Key interfaces return `{code:200, data:...}`, verify business logic
- Smoke: Application starts normally, core flow works
## Iron Law 3: Commit only after tests pass
- Compilation + all tests must pass before `git commit`
- Do not commit incomplete features, debug code, or temporary files
## Iron Law 8: Verification before completion
- **Cannot claim "done", "passed", "no problem" without running verification commands**
- Forbidden: "should work", "probably fine", "looks correct"
- Required: Run command → Read output → Confirm result → Then claim
- This is an honesty principle, not an efficiency issue
## Iron Law 19: Compile errors are not distinguished by source
- `mvn compile`, `vite build`, `vue-tsc` errors = not acceptable, **regardless of origin**
- Forbidden: "this is a pre-existing issue", "not my change", "original bug"
- Correct approach: Locate error → Fix → Rebuild to confirm → Then continue
## Full verification pipeline
Use `/verify` skill to run the complete verification suite:
- Backend: compile + build + test
- Frontend: build + lint + test
## Test frameworks
- Backend: JUnit + Spring Boot Test
- Frontend: Vitest (unit), Playwright (E2E)
## Running specific tests
```bash
# Backend single test class
mvn test -pl healthlink-his-application -Dtest="XxxTest" -Dsurefire.failIfNoSpecifiedTests=false
# Frontend single test file
npm run test:run -- path/to/test.spec.ts
```

20
.qoder/settings.json Normal file
View File

@@ -0,0 +1,20 @@
{
"provider": "openai-compatible",
"apiKey": "tp-c5g4lq98ufrnmb8tgde32pf1jodrqs2bfkyz19shto080000",
"baseUrl": "https://token-plan-cn.xiaomimimo.com/v1",
"model": "mimo-v2.5-pro",
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "node -e \"const d=require('fs').readFileSync(0,'utf-8');const j=JSON.parse(d);const f=j.tool_input?.file_path||j.tool_response?.filePath;if(f&&f.match(/\\.(vue|js|ts|jsx|tsx|scss|css)$/)&&f.startsWith('healthlink-his-ui/')){const p=f.replace('healthlink-his-ui/','');const{execSync}=require('child_process');try{execSync('npx prettier --write '+p,{cwd:'healthlink-his-ui',stdio:'pipe',timeout:15000})}catch(e){}}\" 2>/dev/null || true",
"timeout": 20
}
]
}
]
}
}

View File

@@ -0,0 +1,13 @@
{
"permissions": {
"allow": [
"Bash(cd healthlink-his-ui && npx eslint --version)",
"Bash(echo '{\"tool_name\":\"Edit\",\"tool_input\":{\"file_path\":\"healthlink-his-ui/src/App.vue\"}}' | jq -r '.tool_input.file_path // .tool_response.filePath' | { read -r f; cd healthlink-his-ui && npx eslint --fix \"$f\" 2>&1 || true; })",
"Bash(node:*)",
"Bash(echo '{\"tool_name\":\"Edit\",\"tool_input\":{\"file_path\":\"healthlink-his-ui/src/App.vue\"}}' | node -e \"const data = require\\('fs'\\).readFileSync\\(0, 'utf-8'\\); const json = JSON.parse\\(data\\); const f = json.tool_input?.file_path || json.tool_response?.filePath; console.log\\(f\\);\")",
"Bash(echo '{\"tool_name\":\"Edit\",\"tool_input\":{\"file_path\":\"healthlink-his-ui/src/App.vue\"}}' | node -e \"\nconst d=require\\('fs'\\).readFileSync\\(0,'utf-8'\\);\nconst j=JSON.parse\\(d\\);\nconst f=j.tool_input?.file_path||j.tool_response?.filePath;\nif\\(f && f.match\\(/\\\\.\\(vue|js|ts|jsx|tsx\\)\\\\$/\\) && f.startsWith\\('healthlink-his-ui/'\\)\\) {\n const relPath = f.replace\\('healthlink-his-ui/', ''\\);\n const {execSync} = require\\('child_process'\\);\n try { execSync\\('npx eslint --fix ' + relPath, {cwd: 'healthlink-his-ui', stdio: 'pipe', timeout: 10000}\\); console.log\\('formatted: ' + f\\); }\n catch\\(e\\) { console.log\\('lint skipped: ' + f\\); }\n}\n\" 2>/dev/null || true)",
"Bash(ls -la .qoder/settings.json 2>/dev/null || echo \"File does not exist\")",
"Bash(ls -la D:/his/RULES.md 2>/dev/null && wc -l D:/his/RULES.md || echo \"RULES.md not found\")"
]
}
}

View File

@@ -0,0 +1,27 @@
---
name: bug-analyze
description: Bug分析技能 — 根因分析和修复方案设计
when_to_use: 分析Bug时自动激活
---
# Bug 分析技能
## 分析流程
### 1. 信息收集
- 读取禅道 Bug 完整信息
- OCR 读取附件图片中的错误信息
- 查询数据库相关表结构
### 2. 6 环分析
```
前端/页面 → Controller → Service → Mapper → DB/SQL → 关联模块
①录入 ②验证 ③业务 ④持久化 ⑤存储 ⑥联动
```
### 3. 输出
- 根因描述
- 影响范围
- 修复方案
- 测试要点
- 路由建议(数据库→荀彧,后端→关羽,前端→赵云)

View File

@@ -0,0 +1,31 @@
---
name: chenlin-archive
description: 归档技能 — 生成报告、多层归档
when_to_use: 验收通过后自动激活
---
# 归档技能
## 归档流程
### 🔴 前置检查(必须通过才能归档)
- **修复必须在 develop 分支上** — `git log origin/develop --grep="#{id}"` 有结果
- 未合并到 develop 的修复禁止归档
### 1. 收集数据
- 从 traces 表收集全流程事件
- 从 git 收集 commit 信息(必须在 develop 分支上)
- 从测试结果收集通过/失败状态
### 2. 生成报告
- Markdown 格式
- 包含:基本信息、根因分析、修复文件、流程时间线
### 3. 三重归档
- **Git**: his-repo/docs/bug-fixes/bug-{id}.md
- **SQLite**: bug_reports 表(完整字段)
- **Redis**: fix_doc:{id}30天 TTL
### 4. 禅道备注
- 格式:[📝 陈琳归档] Bug #xxx 修复报告已归档
- 使用 resolve+activate workaround

View File

@@ -0,0 +1,29 @@
---
name: db-review
description: DB审查技能 — 数据库变更验证
when_to_use: 修复涉及SQL/数据库时自动激活
paths:
- "*.sql"
- "*mapper*"
- "*Mapper*"
---
# DB 审查技能
## 审查流程
### 1. 检查变更范围
- 使用 `git diff --name-only` 查看变更文件
- 识别 SQL DDL 变更(.sql、migration
- 区分 DDL 变更和代码引用mapper XML
### 2. 验证 SQL
- 用 db-query 查询真实表结构
- 检查 NOT NULL 约束
- 检查外键约束
- 用 EXPLAIN 验证查询计划
### 3. 审查结论
- 无 DDL 变更 → 直接通过
- 有 DDL 变更 → 检查迁移脚本
- 审查失败 → 退回修复智能体并附原因

View File

@@ -0,0 +1,50 @@
---
name: bug-fix
description: Bug修复技能 — 全链路修复流程
when_to_use: 修复Bug时自动激活
paths:
- "*.java"
- "*.vue"
- "*.ts"
---
# Bug 修复技能
## 修复流程
### 1. 分析阶段
- 读取禅道 Bug 完整信息(标题、描述、附件图片)
- 使用 OCR 读取图片中的错误信息
- 分析 6 环链路前端→Controller→Service→Mapper→DB→关联模块
- **状态值一致性检查**(涉及状态流转的 Bug 必做):
1. 列出所有相关枚举定义及其数值
2. 搜索所有引用该枚举的代码路径(`rg "SlotStatus\|OrderStatus\|Status"` )
3. 确认 Service 层设置值、查询映射、前端显示三者一致
4. 确认统计/聚合 SQL 包含所有相关状态值
### 2. 定位阶段
- 使用 `rg` 搜索相关代码
- 使用 `git blame` 追溯历史
- 确认根因
### 3. 修复阶段
- 一次只修一个 Bug
- 修改最小范围代码
- 遵守项目编码规范
### 4. 验证阶段
- 后端:`mvn compile`
- 前端:`vue-tsc --noEmit`
- 数据库:`db-query` 验证 SQL
- **全链路验证**(状态流转 Bug 必做):
1. 数据库:确认状态值已正确写入(`SELECT status FROM table WHERE id = ?`
2. 后端接口:确认返回的状态映射正确(检查所有 `if/switch` 分支)
3. 前端显示:确认页面显示正确状态文本(检查 `STATUS_CLASS_MAP`
4. 前端交互:确认按钮/操作基于正确状态启用/禁用
5. 统计数据:确认池/报表统计包含新状态值
- **禁止**:只验证编译通过就认为修复完成
### 5. 提交阶段
- `git add` + `git commit`
- commit message 格式:`fix(#bug_id): 简要描述`
- 推送到 develop 分支

View File

@@ -0,0 +1,28 @@
---
name: playwright-test
description: Playwright回归测试技能
when_to_use: 测试Bug修复时自动激活
---
# Playwright 回归测试技能
## 测试流程
### 1. 环境准备
- 确保前端 dev server 运行在 81 端口
- 使用 `--workers=1` 单线程运行
### 2. 执行测试
```bash
cd /root/.openclaw/workspace/his-repo/openhis-ui-vue3
npx playwright test --grep @bug{ID} --reporter=line --workers=1
```
### 3. 结果判定
- 测试通过 → 通知华佗验收
- 测试失败 → 增加重试计数,退回修复智能体
- 超过 3 次 → 通知人工介入
### 4. 结果记录
- 写入禅道备注
- 保存测试文档到 Redis

View File

@@ -0,0 +1,30 @@
---
name: acceptance
description: 验收技能 — 最终确认修复完整性
when_to_use: 测试通过后自动激活
---
# 验收技能
## 验收清单(必须全部通过)
### 🔴 强制检查(任一失败=拒绝验收)
- [ ] **修复已合并到 develop 分支**`git log origin/develop --grep="#bug_id"` 必须有结果
- [ ] 工作树 commit ≠ 生产生效,必须 merge 到 develop 并 push
- [ ] git commit message 包含 Bug 编号
- [ ] 测试报告通过
### 人类 Bug 处理
- 只加备注,不改状态
- 不改分配
### 智能体 Bug 处理
- 可以改分配
- 可以加备注
## 合并验证命令
```bash
cd /root/.openclaw/workspace/his-repo
git log origin/develop --oneline --grep="#{bug_id}"
# 必须有输出,否则拒绝验收
```

View File

@@ -0,0 +1,164 @@
---
name: brainstorming
description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation."
---
# Brainstorming Ideas Into Designs
Help turn ideas into fully formed designs and specs through natural collaborative dialogue.
Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design and get user approval.
<HARD-GATE>
Do NOT invoke any implementation skill, write any code, scaffold any project, or take any implementation action until you have presented a design and the user has approved it. This applies to EVERY project regardless of perceived simplicity.
</HARD-GATE>
## Anti-Pattern: "This Is Too Simple To Need A Design"
Every project goes through this process. A todo list, a single-function utility, a config change — all of them. "Simple" projects are where unexamined assumptions cause the most wasted work. The design can be short (a few sentences for truly simple projects), but you MUST present it and get approval.
## Checklist
You MUST create a task for each of these items and complete them in order:
1. **Explore project context** — check files, docs, recent commits
2. **Offer visual companion** (if topic will involve visual questions) — this is its own message, not combined with a clarifying question. See the Visual Companion section below.
3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria
4. **Propose 2-3 approaches** — with trade-offs and your recommendation
5. **Present design** — in sections scaled to their complexity, get user approval after each section
6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` and commit
7. **Spec self-review** — quick inline check for placeholders, contradictions, ambiguity, scope (see below)
8. **User reviews written spec** — ask user to review the spec file before proceeding
9. **Transition to implementation** — invoke writing-plans skill to create implementation plan
## Process Flow
```dot
digraph brainstorming {
"Explore project context" [shape=box];
"Visual questions ahead?" [shape=diamond];
"Offer Visual Companion\n(own message, no other content)" [shape=box];
"Ask clarifying questions" [shape=box];
"Propose 2-3 approaches" [shape=box];
"Present design sections" [shape=box];
"User approves design?" [shape=diamond];
"Write design doc" [shape=box];
"Spec self-review\n(fix inline)" [shape=box];
"User reviews spec?" [shape=diamond];
"Invoke writing-plans skill" [shape=doublecircle];
"Explore project context" -> "Visual questions ahead?";
"Visual questions ahead?" -> "Offer Visual Companion\n(own message, no other content)" [label="yes"];
"Visual questions ahead?" -> "Ask clarifying questions" [label="no"];
"Offer Visual Companion\n(own message, no other content)" -> "Ask clarifying questions";
"Ask clarifying questions" -> "Propose 2-3 approaches";
"Propose 2-3 approaches" -> "Present design sections";
"Present design sections" -> "User approves design?";
"User approves design?" -> "Present design sections" [label="no, revise"];
"User approves design?" -> "Write design doc" [label="yes"];
"Write design doc" -> "Spec self-review\n(fix inline)";
"Spec self-review\n(fix inline)" -> "User reviews spec?";
"User reviews spec?" -> "Write design doc" [label="changes requested"];
"User reviews spec?" -> "Invoke writing-plans skill" [label="approved"];
}
```
**The terminal state is invoking writing-plans.** Do NOT invoke frontend-design, mcp-builder, or any other implementation skill. The ONLY skill you invoke after brainstorming is writing-plans.
## The Process
**Understanding the idea:**
- Check out the current project state first (files, docs, recent commits)
- Before asking detailed questions, assess scope: if the request describes multiple independent subsystems (e.g., "build a platform with chat, file storage, billing, and analytics"), flag this immediately. Don't spend questions refining details of a project that needs to be decomposed first.
- If the project is too large for a single spec, help the user decompose into sub-projects: what are the independent pieces, how do they relate, what order should they be built? Then brainstorm the first sub-project through the normal design flow. Each sub-project gets its own spec → plan → implementation cycle.
- For appropriately-scoped projects, ask questions one at a time to refine the idea
- Prefer multiple choice questions when possible, but open-ended is fine too
- Only one question per message - if a topic needs more exploration, break it into multiple questions
- Focus on understanding: purpose, constraints, success criteria
**Exploring approaches:**
- Propose 2-3 different approaches with trade-offs
- Present options conversationally with your recommendation and reasoning
- Lead with your recommended option and explain why
**Presenting the design:**
- Once you believe you understand what you're building, present the design
- Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced
- Ask after each section whether it looks right so far
- Cover: architecture, components, data flow, error handling, testing
- Be ready to go back and clarify if something doesn't make sense
**Design for isolation and clarity:**
- Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently
- For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on?
- Can someone understand what a unit does without reading its internals? Can you change the internals without breaking consumers? If not, the boundaries need work.
- Smaller, well-bounded units are also easier for you to work with - you reason better about code you can hold in context at once, and your edits are more reliable when files are focused. When a file grows large, that's often a signal that it's doing too much.
**Working in existing codebases:**
- Explore the current structure before proposing changes. Follow existing patterns.
- Where existing code has problems that affect the work (e.g., a file that's grown too large, unclear boundaries, tangled responsibilities), include targeted improvements as part of the design - the way a good developer improves code they're working in.
- Don't propose unrelated refactoring. Stay focused on what serves the current goal.
## After the Design
**Documentation:**
- Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`
- (User preferences for spec location override this default)
- Use elements-of-style:writing-clearly-and-concisely skill if available
- Commit the design document to git
**Spec Self-Review:**
After writing the spec document, look at it with fresh eyes:
1. **Placeholder scan:** Any "TBD", "TODO", incomplete sections, or vague requirements? Fix them.
2. **Internal consistency:** Do any sections contradict each other? Does the architecture match the feature descriptions?
3. **Scope check:** Is this focused enough for a single implementation plan, or does it need decomposition?
4. **Ambiguity check:** Could any requirement be interpreted two different ways? If so, pick one and make it explicit.
Fix any issues inline. No need to re-review — just fix and move on.
**User Review Gate:**
After the spec review loop passes, ask the user to review the written spec before proceeding:
> "Spec written and committed to `<path>`. Please review it and let me know if you want to make any changes before we start writing out the implementation plan."
Wait for the user's response. If they request changes, make them and re-run the spec review loop. Only proceed once the user approves.
**Implementation:**
- Invoke the writing-plans skill to create a detailed implementation plan
- Do NOT invoke any other skill. writing-plans is the next step.
## Key Principles
- **One question at a time** - Don't overwhelm with multiple questions
- **Multiple choice preferred** - Easier to answer than open-ended when possible
- **YAGNI ruthlessly** - Remove unnecessary features from all designs
- **Explore alternatives** - Always propose 2-3 approaches before settling
- **Incremental validation** - Present design, get approval before moving on
- **Be flexible** - Go back and clarify when something doesn't make sense
## Visual Companion
A browser-based companion for showing mockups, diagrams, and visual options during brainstorming. Available as a tool — not a mode. Accepting the companion means it's available for questions that benefit from visual treatment; it does NOT mean every question goes through the browser.
**Offering the companion:** When you anticipate that upcoming questions will involve visual content (mockups, layouts, diagrams), offer it once for consent:
> "Some of what we're working on might be easier to explain if I can show it to you in a web browser. I can put together mockups, diagrams, comparisons, and other visuals as we go. This feature is still new and can be token-intensive. Want to try it? (Requires opening a local URL)"
**This offer MUST be its own message.** Do not combine it with clarifying questions, context summaries, or any other content. The message should contain ONLY the offer above and nothing else. Wait for the user's response before continuing. If they decline, proceed with text-only brainstorming.
**Per-question decision:** Even after the user accepts, decide FOR EACH QUESTION whether to use the browser or the terminal. The test: **would the user understand this better by seeing it than reading it?**
- **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs
- **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions
A question about a UI topic is not automatically a visual question. "What does personality mean in this context?" is a conceptual question — use the terminal. "Which wizard layout works better?" is a visual question — use the browser.
If they agree to the companion, read the detailed guide before proceeding:
`skills/brainstorming/visual-companion.md`

View File

@@ -0,0 +1,214 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Superpowers Brainstorming</title>
<style>
/*
* BRAINSTORM COMPANION FRAME TEMPLATE
*
* This template provides a consistent frame with:
* - OS-aware light/dark theming
* - Fixed header and selection indicator bar
* - Scrollable main content area
* - CSS helpers for common UI patterns
*
* Content is injected via placeholder comment in #claude-content.
*/
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; overflow: hidden; }
/* ===== THEME VARIABLES ===== */
:root {
--bg-primary: #f5f5f7;
--bg-secondary: #ffffff;
--bg-tertiary: #e5e5e7;
--border: #d1d1d6;
--text-primary: #1d1d1f;
--text-secondary: #86868b;
--text-tertiary: #aeaeb2;
--accent: #0071e3;
--accent-hover: #0077ed;
--success: #34c759;
--warning: #ff9f0a;
--error: #ff3b30;
--selected-bg: #e8f4fd;
--selected-border: #0071e3;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-primary: #1d1d1f;
--bg-secondary: #2d2d2f;
--bg-tertiary: #3d3d3f;
--border: #424245;
--text-primary: #f5f5f7;
--text-secondary: #86868b;
--text-tertiary: #636366;
--accent: #0a84ff;
--accent-hover: #409cff;
--selected-bg: rgba(10, 132, 255, 0.15);
--selected-border: #0a84ff;
}
}
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
display: flex;
flex-direction: column;
line-height: 1.5;
}
/* ===== FRAME STRUCTURE ===== */
.header {
background: var(--bg-secondary);
padding: 0.5rem 1.5rem;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.header h1 { font-size: 0.85rem; font-weight: 500; color: var(--text-secondary); }
.header .status { font-size: 0.7rem; color: var(--success); display: flex; align-items: center; gap: 0.4rem; }
.header .status::before { content: ''; width: 6px; height: 6px; background: var(--success); border-radius: 50%; }
.main { flex: 1; overflow-y: auto; }
#claude-content { padding: 2rem; min-height: 100%; }
.indicator-bar {
background: var(--bg-secondary);
border-top: 1px solid var(--border);
padding: 0.5rem 1.5rem;
flex-shrink: 0;
text-align: center;
}
.indicator-bar span {
font-size: 0.75rem;
color: var(--text-secondary);
}
.indicator-bar .selected-text {
color: var(--accent);
font-weight: 500;
}
/* ===== TYPOGRAPHY ===== */
h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }
h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
.subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }
.section { margin-bottom: 2rem; }
.label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }
/* ===== OPTIONS (for A/B/C choices) ===== */
.options { display: flex; flex-direction: column; gap: 0.75rem; }
.option {
background: var(--bg-secondary);
border: 2px solid var(--border);
border-radius: 12px;
padding: 1rem 1.25rem;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
align-items: flex-start;
gap: 1rem;
}
.option:hover { border-color: var(--accent); }
.option.selected { background: var(--selected-bg); border-color: var(--selected-border); }
.option .letter {
background: var(--bg-tertiary);
color: var(--text-secondary);
width: 1.75rem; height: 1.75rem;
border-radius: 6px;
display: flex; align-items: center; justify-content: center;
font-weight: 600; font-size: 0.85rem; flex-shrink: 0;
}
.option.selected .letter { background: var(--accent); color: white; }
.option .content { flex: 1; }
.option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }
.option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }
/* ===== CARDS (for showing designs/mockups) ===== */
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }
.card {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
overflow: hidden;
cursor: pointer;
transition: all 0.15s ease;
}
.card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.card.selected { border-color: var(--selected-border); border-width: 2px; }
.card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }
.card-body { padding: 1rem; }
.card-body h3 { margin-bottom: 0.25rem; }
.card-body p { color: var(--text-secondary); font-size: 0.85rem; }
/* ===== MOCKUP CONTAINER ===== */
.mockup {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
overflow: hidden;
margin-bottom: 1.5rem;
}
.mockup-header {
background: var(--bg-tertiary);
padding: 0.5rem 1rem;
font-size: 0.75rem;
color: var(--text-secondary);
border-bottom: 1px solid var(--border);
}
.mockup-body { padding: 1.5rem; }
/* ===== SPLIT VIEW (side-by-side comparison) ===== */
.split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
@media (max-width: 700px) { .split { grid-template-columns: 1fr; } }
/* ===== PROS/CONS ===== */
.pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
.pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }
.pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }
.cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }
.pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }
.pros li, .cons li { margin-bottom: 0.25rem; }
/* ===== PLACEHOLDER (for mockup areas) ===== */
.placeholder {
background: var(--bg-tertiary);
border: 2px dashed var(--border);
border-radius: 8px;
padding: 2rem;
text-align: center;
color: var(--text-tertiary);
}
/* ===== INLINE MOCKUP ELEMENTS ===== */
.mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }
.mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }
.mock-content { padding: 1.5rem; flex: 1; }
.mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }
.mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }
</style>
</head>
<body>
<div class="header">
<h1><a href="https://github.com/obra/superpowers" style="color: inherit; text-decoration: none;">Superpowers Brainstorming</a></h1>
<div class="status">Connected</div>
</div>
<div class="main">
<div id="claude-content">
<!-- CONTENT -->
</div>
</div>
<div class="indicator-bar">
<span id="indicator-text">Click an option above, then return to the terminal</span>
</div>
</body>
</html>

View File

@@ -0,0 +1,88 @@
(function() {
const WS_URL = 'ws://' + window.location.host;
let ws = null;
let eventQueue = [];
function connect() {
ws = new WebSocket(WS_URL);
ws.onopen = () => {
eventQueue.forEach(e => ws.send(JSON.stringify(e)));
eventQueue = [];
};
ws.onmessage = (msg) => {
const data = JSON.parse(msg.data);
if (data.type === 'reload') {
window.location.reload();
}
};
ws.onclose = () => {
setTimeout(connect, 1000);
};
}
function sendEvent(event) {
event.timestamp = Date.now();
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(event));
} else {
eventQueue.push(event);
}
}
// Capture clicks on choice elements
document.addEventListener('click', (e) => {
const target = e.target.closest('[data-choice]');
if (!target) return;
sendEvent({
type: 'click',
text: target.textContent.trim(),
choice: target.dataset.choice,
id: target.id || null
});
// Update indicator bar (defer so toggleSelect runs first)
setTimeout(() => {
const indicator = document.getElementById('indicator-text');
if (!indicator) return;
const container = target.closest('.options') || target.closest('.cards');
const selected = container ? container.querySelectorAll('.selected') : [];
if (selected.length === 0) {
indicator.textContent = 'Click an option above, then return to the terminal';
} else if (selected.length === 1) {
const label = selected[0].querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || selected[0].dataset.choice;
indicator.innerHTML = '<span class="selected-text">' + label + ' selected</span> — return to terminal to continue';
} else {
indicator.innerHTML = '<span class="selected-text">' + selected.length + ' selected</span> — return to terminal to continue';
}
}, 0);
});
// Frame UI: selection tracking
window.selectedChoice = null;
window.toggleSelect = function(el) {
const container = el.closest('.options') || el.closest('.cards');
const multi = container && container.dataset.multiselect !== undefined;
if (container && !multi) {
container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected'));
}
if (multi) {
el.classList.toggle('selected');
} else {
el.classList.add('selected');
}
window.selectedChoice = el.dataset.choice;
};
// Expose API for explicit use
window.brainstorm = {
send: sendEvent,
choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })
};
connect();
})();

View File

@@ -0,0 +1,354 @@
const crypto = require('crypto');
const http = require('http');
const fs = require('fs');
const path = require('path');
// ========== WebSocket Protocol (RFC 6455) ==========
const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
function computeAcceptKey(clientKey) {
return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
}
function encodeFrame(opcode, payload) {
const fin = 0x80;
const len = payload.length;
let header;
if (len < 126) {
header = Buffer.alloc(2);
header[0] = fin | opcode;
header[1] = len;
} else if (len < 65536) {
header = Buffer.alloc(4);
header[0] = fin | opcode;
header[1] = 126;
header.writeUInt16BE(len, 2);
} else {
header = Buffer.alloc(10);
header[0] = fin | opcode;
header[1] = 127;
header.writeBigUInt64BE(BigInt(len), 2);
}
return Buffer.concat([header, payload]);
}
function decodeFrame(buffer) {
if (buffer.length < 2) return null;
const secondByte = buffer[1];
const opcode = buffer[0] & 0x0F;
const masked = (secondByte & 0x80) !== 0;
let payloadLen = secondByte & 0x7F;
let offset = 2;
if (!masked) throw new Error('Client frames must be masked');
if (payloadLen === 126) {
if (buffer.length < 4) return null;
payloadLen = buffer.readUInt16BE(2);
offset = 4;
} else if (payloadLen === 127) {
if (buffer.length < 10) return null;
payloadLen = Number(buffer.readBigUInt64BE(2));
offset = 10;
}
const maskOffset = offset;
const dataOffset = offset + 4;
const totalLen = dataOffset + payloadLen;
if (buffer.length < totalLen) return null;
const mask = buffer.slice(maskOffset, dataOffset);
const data = Buffer.alloc(payloadLen);
for (let i = 0; i < payloadLen; i++) {
data[i] = buffer[dataOffset + i] ^ mask[i % 4];
}
return { opcode, payload: data, bytesConsumed: totalLen };
}
// ========== Configuration ==========
const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));
const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
const CONTENT_DIR = path.join(SESSION_DIR, 'content');
const STATE_DIR = path.join(SESSION_DIR, 'state');
let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
const MIME_TYPES = {
'.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
'.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
};
// ========== Templates and Constants ==========
const WAITING_PAGE = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Brainstorm Companion</title>
<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
h1 { color: #333; } p { color: #666; }</style>
</head>
<body><h1>Brainstorm Companion</h1>
<p>Waiting for the agent to push a screen...</p></body></html>`;
const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
const helperInjection = '<script>\n' + helperScript + '\n</script>';
// ========== Helper Functions ==========
function isFullDocument(html) {
const trimmed = html.trimStart().toLowerCase();
return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
}
function wrapInFrame(content) {
return frameTemplate.replace('<!-- CONTENT -->', content);
}
function getNewestScreen() {
const files = fs.readdirSync(CONTENT_DIR)
.filter(f => f.endsWith('.html'))
.map(f => {
const fp = path.join(CONTENT_DIR, f);
return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
})
.sort((a, b) => b.mtime - a.mtime);
return files.length > 0 ? files[0].path : null;
}
// ========== HTTP Request Handler ==========
function handleRequest(req, res) {
touchActivity();
if (req.method === 'GET' && req.url === '/') {
const screenFile = getNewestScreen();
let html = screenFile
? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
: WAITING_PAGE;
if (html.includes('</body>')) {
html = html.replace('</body>', helperInjection + '\n</body>');
} else {
html += helperInjection;
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html);
} else if (req.method === 'GET' && req.url.startsWith('/files/')) {
const fileName = req.url.slice(7);
const filePath = path.join(CONTENT_DIR, path.basename(fileName));
if (!fs.existsSync(filePath)) {
res.writeHead(404);
res.end('Not found');
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': contentType });
res.end(fs.readFileSync(filePath));
} else {
res.writeHead(404);
res.end('Not found');
}
}
// ========== WebSocket Connection Handling ==========
const clients = new Set();
function handleUpgrade(req, socket) {
const key = req.headers['sec-websocket-key'];
if (!key) { socket.destroy(); return; }
const accept = computeAcceptKey(key);
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
);
let buffer = Buffer.alloc(0);
clients.add(socket);
socket.on('data', (chunk) => {
buffer = Buffer.concat([buffer, chunk]);
while (buffer.length > 0) {
let result;
try {
result = decodeFrame(buffer);
} catch (e) {
socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
clients.delete(socket);
return;
}
if (!result) break;
buffer = buffer.slice(result.bytesConsumed);
switch (result.opcode) {
case OPCODES.TEXT:
handleMessage(result.payload.toString());
break;
case OPCODES.CLOSE:
socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
clients.delete(socket);
return;
case OPCODES.PING:
socket.write(encodeFrame(OPCODES.PONG, result.payload));
break;
case OPCODES.PONG:
break;
default: {
const closeBuf = Buffer.alloc(2);
closeBuf.writeUInt16BE(1003);
socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
clients.delete(socket);
return;
}
}
}
});
socket.on('close', () => clients.delete(socket));
socket.on('error', () => clients.delete(socket));
}
function handleMessage(text) {
let event;
try {
event = JSON.parse(text);
} catch (e) {
console.error('Failed to parse WebSocket message:', e.message);
return;
}
touchActivity();
console.log(JSON.stringify({ source: 'user-event', ...event }));
if (event.choice) {
const eventsFile = path.join(STATE_DIR, 'events');
fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
}
}
function broadcast(msg) {
const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
for (const socket of clients) {
try { socket.write(frame); } catch (e) { clients.delete(socket); }
}
}
// ========== Activity Tracking ==========
const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
let lastActivity = Date.now();
function touchActivity() {
lastActivity = Date.now();
}
// ========== File Watching ==========
const debounceTimers = new Map();
// ========== Server Startup ==========
function startServer() {
if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
// Track known files to distinguish new screens from updates.
// macOS fs.watch reports 'rename' for both new files and overwrites,
// so we can't rely on eventType alone.
const knownFiles = new Set(
fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html'))
);
const server = http.createServer(handleRequest);
server.on('upgrade', handleUpgrade);
const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
if (!filename || !filename.endsWith('.html')) return;
if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
debounceTimers.set(filename, setTimeout(() => {
debounceTimers.delete(filename);
const filePath = path.join(CONTENT_DIR, filename);
if (!fs.existsSync(filePath)) return; // file was deleted
touchActivity();
if (!knownFiles.has(filename)) {
knownFiles.add(filename);
const eventsFile = path.join(STATE_DIR, 'events');
if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
} else {
console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
}
broadcast({ type: 'reload' });
}, 100));
});
watcher.on('error', (err) => console.error('fs.watch error:', err.message));
function shutdown(reason) {
console.log(JSON.stringify({ type: 'server-stopped', reason }));
const infoFile = path.join(STATE_DIR, 'server-info');
if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
fs.writeFileSync(
path.join(STATE_DIR, 'server-stopped'),
JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
);
watcher.close();
clearInterval(lifecycleCheck);
server.close(() => process.exit(0));
}
function ownerAlive() {
if (!ownerPid) return true;
try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
}
// Check every 60s: exit if owner process died or idle for 30 minutes
const lifecycleCheck = setInterval(() => {
if (!ownerAlive()) shutdown('owner process exited');
else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
}, 60 * 1000);
lifecycleCheck.unref();
// Validate owner PID at startup. If it's already dead, the PID resolution
// was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
// Disable monitoring and rely on the idle timeout instead.
if (ownerPid) {
try { process.kill(ownerPid, 0); }
catch (e) {
if (e.code !== 'EPERM') {
console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
ownerPid = null;
}
}
}
server.listen(PORT, HOST, () => {
const info = JSON.stringify({
type: 'server-started', port: Number(PORT), host: HOST,
url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
screen_dir: CONTENT_DIR, state_dir: STATE_DIR
});
console.log(info);
fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n');
});
}
if (require.main === module) {
startServer();
}
module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };

View File

@@ -0,0 +1,148 @@
#!/usr/bin/env bash
# Start the brainstorm server and output connection info
# Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--foreground] [--background]
#
# Starts server on a random high port, outputs JSON with URL.
# Each session gets its own directory to avoid conflicts.
#
# Options:
# --project-dir <path> Store session files under <path>/.superpowers/brainstorm/
# instead of /tmp. Files persist after server stops.
# --host <bind-host> Host/interface to bind (default: 127.0.0.1).
# Use 0.0.0.0 in remote/containerized environments.
# --url-host <host> Hostname shown in returned URL JSON.
# --foreground Run server in the current terminal (no backgrounding).
# --background Force background mode (overrides Codex auto-foreground).
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Parse arguments
PROJECT_DIR=""
FOREGROUND="false"
FORCE_BACKGROUND="false"
BIND_HOST="127.0.0.1"
URL_HOST=""
while [[ $# -gt 0 ]]; do
case "$1" in
--project-dir)
PROJECT_DIR="$2"
shift 2
;;
--host)
BIND_HOST="$2"
shift 2
;;
--url-host)
URL_HOST="$2"
shift 2
;;
--foreground|--no-daemon)
FOREGROUND="true"
shift
;;
--background|--daemon)
FORCE_BACKGROUND="true"
shift
;;
*)
echo "{\"error\": \"Unknown argument: $1\"}"
exit 1
;;
esac
done
if [[ -z "$URL_HOST" ]]; then
if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then
URL_HOST="localhost"
else
URL_HOST="$BIND_HOST"
fi
fi
# Some environments reap detached/background processes. Auto-foreground when detected.
if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
FOREGROUND="true"
fi
# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected.
if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
case "${OSTYPE:-}" in
msys*|cygwin*|mingw*) FOREGROUND="true" ;;
esac
if [[ -n "${MSYSTEM:-}" ]]; then
FOREGROUND="true"
fi
fi
# Generate unique session directory
SESSION_ID="$$-$(date +%s)"
if [[ -n "$PROJECT_DIR" ]]; then
SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}"
else
SESSION_DIR="/tmp/brainstorm-${SESSION_ID}"
fi
STATE_DIR="${SESSION_DIR}/state"
PID_FILE="${STATE_DIR}/server.pid"
LOG_FILE="${STATE_DIR}/server.log"
# Create fresh session directory with content and state peers
mkdir -p "${SESSION_DIR}/content" "$STATE_DIR"
# Kill any existing server
if [[ -f "$PID_FILE" ]]; then
old_pid=$(cat "$PID_FILE")
kill "$old_pid" 2>/dev/null
rm -f "$PID_FILE"
fi
cd "$SCRIPT_DIR"
# Resolve the harness PID (grandparent of this script).
# $PPID is the ephemeral shell the harness spawned to run us — it dies
# when this script exits. The harness itself is $PPID's parent.
OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')"
if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then
OWNER_PID="$PPID"
fi
# Foreground mode for environments that reap detached/background processes.
if [[ "$FOREGROUND" == "true" ]]; then
echo "$$" > "$PID_FILE"
env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs
exit $?
fi
# Start server, capturing output to log file
# Use nohup to survive shell exit; disown to remove from job table
nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs > "$LOG_FILE" 2>&1 &
SERVER_PID=$!
disown "$SERVER_PID" 2>/dev/null
echo "$SERVER_PID" > "$PID_FILE"
# Wait for server-started message (check log file)
for i in {1..50}; do
if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then
# Verify server is still alive after a short window (catches process reapers)
alive="true"
for _ in {1..20}; do
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
alive="false"
break
fi
sleep 0.1
done
if [[ "$alive" != "true" ]]; then
echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $SCRIPT_DIR/start-server.sh${PROJECT_DIR:+ --project-dir $PROJECT_DIR} --host $BIND_HOST --url-host $URL_HOST --foreground\"}"
exit 1
fi
grep "server-started" "$LOG_FILE" | head -1
exit 0
fi
sleep 0.1
done
# Timeout - server didn't start
echo '{"error": "Server failed to start within 5 seconds"}'
exit 1

View File

@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Stop the brainstorm server and clean up
# Usage: stop-server.sh <session_dir>
#
# Kills the server process. Only deletes session directory if it's
# under /tmp (ephemeral). Persistent directories (.superpowers/) are
# kept so mockups can be reviewed later.
SESSION_DIR="$1"
if [[ -z "$SESSION_DIR" ]]; then
echo '{"error": "Usage: stop-server.sh <session_dir>"}'
exit 1
fi
STATE_DIR="${SESSION_DIR}/state"
PID_FILE="${STATE_DIR}/server.pid"
if [[ -f "$PID_FILE" ]]; then
pid=$(cat "$PID_FILE")
# Try to stop gracefully, fallback to force if still alive
kill "$pid" 2>/dev/null || true
# Wait for graceful shutdown (up to ~2s)
for i in {1..20}; do
if ! kill -0 "$pid" 2>/dev/null; then
break
fi
sleep 0.1
done
# If still running, escalate to SIGKILL
if kill -0 "$pid" 2>/dev/null; then
kill -9 "$pid" 2>/dev/null || true
# Give SIGKILL a moment to take effect
sleep 0.1
fi
if kill -0 "$pid" 2>/dev/null; then
echo '{"status": "failed", "error": "process still running"}'
exit 1
fi
rm -f "$PID_FILE" "${STATE_DIR}/server.log"
# Only delete ephemeral /tmp directories
if [[ "$SESSION_DIR" == /tmp/* ]]; then
rm -rf "$SESSION_DIR"
fi
echo '{"status": "stopped"}'
else
echo '{"status": "not_running"}'
fi

View File

@@ -0,0 +1,49 @@
# Spec Document Reviewer Prompt Template
Use this template when dispatching a spec document reviewer subagent.
**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.
**Dispatch after:** Spec document is written to docs/superpowers/specs/
```
Task tool (general-purpose):
description: "Review spec document"
prompt: |
You are a spec document reviewer. Verify this spec is complete and ready for planning.
**Spec to review:** [SPEC_FILE_PATH]
## What to Check
| Category | What to Look For |
|----------|------------------|
| Completeness | TODOs, placeholders, "TBD", incomplete sections |
| Consistency | Internal contradictions, conflicting requirements |
| Clarity | Requirements ambiguous enough to cause someone to build the wrong thing |
| Scope | Focused enough for a single plan — not covering multiple independent subsystems |
| YAGNI | Unrequested features, over-engineering |
## Calibration
**Only flag issues that would cause real problems during implementation planning.**
A missing section, a contradiction, or a requirement so ambiguous it could be
interpreted two different ways — those are issues. Minor wording improvements,
stylistic preferences, and "sections less detailed than others" are not.
Approve unless there are serious gaps that would lead to a flawed plan.
## Output Format
## Spec Review
**Status:** Approved | Issues Found
**Issues (if any):**
- [Section X]: [specific issue] - [why it matters for planning]
**Recommendations (advisory, do not block approval):**
- [suggestions for improvement]
```
**Reviewer returns:** Status, Issues (if any), Recommendations

View File

@@ -0,0 +1,287 @@
# Visual Companion Guide
Browser-based visual brainstorming companion for showing mockups, diagrams, and options.
## When to Use
Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?**
**Use the browser** when the content itself is visual:
- **UI mockups** — wireframes, layouts, navigation structures, component designs
- **Architecture diagrams** — system components, data flow, relationship maps
- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions
- **Design polish** — when the question is about look and feel, spacing, visual hierarchy
- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams
**Use the terminal** when the content is text or tabular:
- **Requirements and scope questions** — "what does X mean?", "which features are in scope?"
- **Conceptual A/B/C choices** — picking between approaches described in words
- **Tradeoff lists** — pros/cons, comparison tables
- **Technical decisions** — API design, data modeling, architectural approach selection
- **Clarifying questions** — anything where the answer is words, not a visual preference
A question *about* a UI topic is not automatically a visual question. "What kind of wizard do you want?" is conceptual — use the terminal. "Which of these wizard layouts feels right?" is visual — use the browser.
## How It Works
The server watches a directory for HTML files and serves the newest one to the browser. You write HTML content to `screen_dir`, the user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` that you read on your next turn.
**Content fragments vs full documents:** If your HTML file starts with `<!DOCTYPE` or `<html`, the server serves it as-is (just injects the helper script). Otherwise, the server automatically wraps your content in the frame template — adding the header, CSS theme, selection indicator, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.
## Starting a Session
```bash
# Start server with persistence (mockups saved to project)
scripts/start-server.sh --project-dir /path/to/project
# Returns: {"type":"server-started","port":52341,"url":"http://localhost:52341",
# "screen_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/content",
# "state_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/state"}
```
Save `screen_dir` and `state_dir` from the response. Tell user to open the URL.
**Finding connection info:** The server writes its startup JSON to `$STATE_DIR/server-info`. If you launched the server in the background and didn't capture stdout, read that file to get the URL and port. When using `--project-dir`, check `<project>/.superpowers/brainstorm/` for the session directory.
**Note:** Pass the project root as `--project-dir` so mockups persist in `.superpowers/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.superpowers/` to `.gitignore` if it's not already there.
**Launching the server by platform:**
**Claude Code (macOS / Linux):**
```bash
# Default mode works — the script backgrounds the server itself
scripts/start-server.sh --project-dir /path/to/project
```
**Claude Code (Windows):**
```bash
# Windows auto-detects and uses foreground mode, which blocks the tool call.
# Use run_in_background: true on the Bash tool call so the server survives
# across conversation turns.
scripts/start-server.sh --project-dir /path/to/project
```
When calling this via the Bash tool, set `run_in_background: true`. Then read `$STATE_DIR/server-info` on the next turn to get the URL and port.
**Codex:**
```bash
# Codex reaps background processes. The script auto-detects CODEX_CI and
# switches to foreground mode. Run it normally — no extra flags needed.
scripts/start-server.sh --project-dir /path/to/project
```
**Gemini CLI:**
```bash
# Use --foreground and set is_background: true on your shell tool call
# so the process survives across turns
scripts/start-server.sh --project-dir /path/to/project --foreground
```
**Other environments:** The server must keep running in the background across conversation turns. If your environment reaps detached processes, use `--foreground` and launch the command with your platform's background execution mechanism.
If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host:
```bash
scripts/start-server.sh \
--project-dir /path/to/project \
--host 0.0.0.0 \
--url-host localhost
```
Use `--url-host` to control what hostname is printed in the returned URL JSON.
## The Loop
1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`:
- Before each write, check that `$STATE_DIR/server-info` exists. If it doesn't (or `$STATE_DIR/server-stopped` exists), the server has shut down — restart it with `start-server.sh` before continuing. The server auto-exits after 30 minutes of inactivity.
- Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`
- **Never reuse filenames** — each screen gets a fresh file
- Use Write tool — **never use cat/heredoc** (dumps noise into terminal)
- Server automatically serves the newest file
2. **Tell user what to expect and end your turn:**
- Remind them of the URL (every step, not just first)
- Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage")
- Ask them to respond in the terminal: "Take a look and let me know what you think. Click to select an option if you'd like."
3. **On your next turn** — after the user responds in the terminal:
- Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines
- Merge with the user's terminal text to get the full picture
- The terminal message is the primary feedback; `state_dir/events` provides structured interaction data
4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated.
5. **Unload when returning to terminal** — when the next step doesn't need the browser (e.g., a clarifying question, a tradeoff discussion), push a waiting screen to clear the stale content:
```html
<!-- filename: waiting.html (or waiting-2.html, etc.) -->
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
<p class="subtitle">Continuing in terminal...</p>
</div>
```
This prevents the user from staring at a resolved choice while the conversation has moved on. When the next visual question comes up, push a new content file as usual.
6. Repeat until done.
## Writing Content Fragments
Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, selection indicator, and all interactive infrastructure).
**Minimal example:**
```html
<h2>Which layout works better?</h2>
<p class="subtitle">Consider readability and visual hierarchy</p>
<div class="options">
<div class="option" data-choice="a" onclick="toggleSelect(this)">
<div class="letter">A</div>
<div class="content">
<h3>Single Column</h3>
<p>Clean, focused reading experience</p>
</div>
</div>
<div class="option" data-choice="b" onclick="toggleSelect(this)">
<div class="letter">B</div>
<div class="content">
<h3>Two Column</h3>
<p>Sidebar navigation with main content</p>
</div>
</div>
</div>
```
That's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that.
## CSS Classes Available
The frame template provides these CSS classes for your content:
### Options (A/B/C choices)
```html
<div class="options">
<div class="option" data-choice="a" onclick="toggleSelect(this)">
<div class="letter">A</div>
<div class="content">
<h3>Title</h3>
<p>Description</p>
</div>
</div>
</div>
```
**Multi-select:** Add `data-multiselect` to the container to let users select multiple options. Each click toggles the item. The indicator bar shows the count.
```html
<div class="options" data-multiselect>
<!-- same option markup — users can select/deselect multiple -->
</div>
```
### Cards (visual designs)
```html
<div class="cards">
<div class="card" data-choice="design1" onclick="toggleSelect(this)">
<div class="card-image"><!-- mockup content --></div>
<div class="card-body">
<h3>Name</h3>
<p>Description</p>
</div>
</div>
</div>
```
### Mockup container
```html
<div class="mockup">
<div class="mockup-header">Preview: Dashboard Layout</div>
<div class="mockup-body"><!-- your mockup HTML --></div>
</div>
```
### Split view (side-by-side)
```html
<div class="split">
<div class="mockup"><!-- left --></div>
<div class="mockup"><!-- right --></div>
</div>
```
### Pros/Cons
```html
<div class="pros-cons">
<div class="pros"><h4>Pros</h4><ul><li>Benefit</li></ul></div>
<div class="cons"><h4>Cons</h4><ul><li>Drawback</li></ul></div>
</div>
```
### Mock elements (wireframe building blocks)
```html
<div class="mock-nav">Logo | Home | About | Contact</div>
<div style="display: flex;">
<div class="mock-sidebar">Navigation</div>
<div class="mock-content">Main content area</div>
</div>
<button class="mock-button">Action Button</button>
<input class="mock-input" placeholder="Input field">
<div class="placeholder">Placeholder area</div>
```
### Typography and sections
- `h2` — page title
- `h3` — section heading
- `.subtitle` — secondary text below title
- `.section` — content block with bottom margin
- `.label` — small uppercase label text
## Browser Events Format
When the user clicks options in the browser, their interactions are recorded to `$STATE_DIR/events` (one JSON object per line). The file is cleared automatically when you push a new screen.
```jsonl
{"type":"click","choice":"a","text":"Option A - Simple Layout","timestamp":1706000101}
{"type":"click","choice":"c","text":"Option C - Complex Grid","timestamp":1706000108}
{"type":"click","choice":"b","text":"Option B - Hybrid","timestamp":1706000115}
```
The full event stream shows the user's exploration path — they may click multiple options before settling. The last `choice` event is typically the final selection, but the pattern of clicks can reveal hesitation or preferences worth asking about.
If `$STATE_DIR/events` doesn't exist, the user didn't interact with the browser — use only their terminal text.
## Design Tips
- **Scale fidelity to the question** — wireframes for layout, polish for polish questions
- **Explain the question on each page** — "Which layout feels more professional?" not just "Pick one"
- **Iterate before advancing** — if feedback changes current screen, write a new version
- **2-4 options max** per screen
- **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues.
- **Keep mockups simple** — focus on layout and structure, not pixel-perfect design
## File Naming
- Use semantic names: `platform.html`, `visual-style.html`, `layout.html`
- Never reuse filenames — each screen must be a new file
- For iterations: append version suffix like `layout-v2.html`, `layout-v3.html`
- Server serves newest file by modification time
## Cleaning Up
```bash
scripts/stop-server.sh $SESSION_DIR
```
If the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.
## Reference
- Frame template (CSS reference): `scripts/frame-template.html`
- Helper script (client-side): `scripts/helper.js`

View File

@@ -0,0 +1,210 @@
---
name: bug-driven-testing
description: Write tests before fixing bugs. Each bug fix must have corresponding Playwright/E2E test cases that verify the fix and prevent regression. Use when fixing bugs, verifying fixes, or setting up regression test suites.
---
# Bug-Driven Testing (BDT) 方法论
> **核心原则:先写测试,再修 Bug。测试是修复的契约不是修复的附庸。**
## 一、为什么需要 BDT
传统 AI 修 Bug 的问题:
1. 修完不测 → 不知道修没修好
2. 测了但用例不对 → 测了等于没测
3. 修了 A 坏了 B → 没有回归保护
4. 测试和修复脱节 → 无法追溯
BDT 解决:**每个 Bug 有专属测试用例,修复前生成,修复后验证,形成闭环。**
## 二、BDT 工作流6 步)
```
Step 1: Bug 分析 → 提取测试场景
Step 2: 测试设计 → 生成 Playwright 用例
Step 3: 基线测试 → 确认 Bug 存在(应失败)
Step 4: 修复代码 → 解决根因
Step 5: 回归测试 → 确认修复有效(应通过)
Step 6: 扩展测试 → 检查是否引入新问题
```
### Step 1: Bug 分析 — 提取测试场景
从禅道 Bug 信息中提取 **5 要素**
| 要素 | 来源 | 用途 |
|------|------|------|
| **模块** | 标题 + module | 确定测试页面和路由 |
| **操作路径** | 复现步骤 | 生成操作序列 |
| **期望结果** | 期望结果字段 | 生成断言 |
| **实际结果** | 实际结果字段 | 确认 Bug 存在 |
| **关联页面** | 标题关键词 | 定位测试目标元素 |
**关键词 → 模块映射表:**
```
门诊医生/诊前/挂号 → /doctorstation
住院医生/医嘱/医嘱录入 → /inpatientDoctor
住院护士/补费/发退药 → /inpatientNurse
分诊/排队/候诊 → /triageandqueuemanage
挂号/预约/签到 → /registration
手术/计费 → /operatingroom
诊断/中医 → /inpatientDoctor
病历/EMR → /doctorstation
目录/诊疗 → /catalog
药房/发药/库存 → /pharmacy
```
**操作路径 → Playwright 动作映射:**
```
"点击 XXX 按钮" → page.click('button:has-text("XXX")')
"选择 XXX" → page.selectOption / page.click('.el-option')
"输入 XXX" → page.fill('input', 'XXX')
"查看列表" → page.waitForLoadState('networkidle')
"弹窗确认" → page.click('.el-message-box button:has-text("确定")')
"检查报错" → expect(page.locator('.el-message--error')).toBeVisible()
"检查显示" → expect(page.locator('目标元素')).toBeVisible()
```
### Step 2: 测试设计 — 生成 Playwright 用例
**每个 Bug 测试用例的结构:**
```typescript
test.describe('🐛 Bug#N 模块名', () => {
// beforeEach: 登录 + 导航到目标页面
test('#N 标题 @bugN @regression', async ({ page }) => {
// 1. 导航到目标页面
// 2. 执行复现步骤(操作路径)
// 3. 断言期望结果
// 4. 检查无 JS 错误
// 5. 截图记录
});
});
```
**测试用例的 7 种检查模式:**
| # | 模式 | 适用场景 | Playwright 写法 |
|---|------|---------|----------------|
| 1 | **页面加载** | 所有 Bug | `expect(page).not.toHaveURL(/.*login.*/)` |
| 2 | **元素可见** | 显示/缺失类 | `expect(locator).toBeVisible()` |
| 3 | **元素可交互** | 按钮/弹窗类 | `await locator.click()` + 等待响应 |
| 4 | **数据正确** | 列表/回显类 | `expect(locator).toHaveText()` |
| 5 | **无报错** | 所有 Bug | `page.on('pageerror')` + `expect(jsErrors).toEqual([])` |
| 6 | **流程完整** | 交互流程类 | 多步骤操作链 + 每步断言 |
| 7 | **状态变更** | 退回/审核类 | 操作前状态 vs 操作后状态对比 |
### Step 3: 基线测试 — 确认 Bug 存在
修复前运行测试,**预期应该失败**,证明 Bug 确实存在:
```bash
npx playwright test --grep @bugN --reporter=line
# 预期: FAIL (证明 Bug 存在)
```
如果基线测试通过了:
- 可能 Bug 已被之前的修复解决 → 检查 develop 分支
- 可能测试用例设计不正确 → 重新分析 Bug
- 可能环境问题 → 检查 dev server / 数据库
### Step 4: 修复代码
按照 Harness Engineering 方法论修复:
1. 全链路 6 环分析
2. 一次只修一个 Bug
3. 只动必要文件
### Step 5: 回归测试 — 确认修复有效
修复后运行测试,**预期应该通过**
```bash
npx playwright test --grep @bugN --reporter=line
# 预期: PASS (证明修复有效)
```
### Step 6: 扩展测试 — 检查回归
运行相邻模块的测试,检查是否引入新问题:
```bash
npx playwright test --grep @regression --reporter=line
# 预期: 全部 PASS
```
## 三、测试用例生成规则
### 从 Bug 标题推断检查项
| 标题关键词 | 生成的检查项 |
|-----------|-------------|
| 报错/错误/异常 | 检查页面无 JS 错误 + 控制台无报错 |
| 显示/缺失/不规范 | 检查元素正确显示 + 数据完整性 |
| 弹窗/弹框 | 检查弹窗正常弹出 + 内容正确 |
| 保存/提交/写入 | 检查保存操作成功 + 数据持久化 |
| 列表/查询 | 检查列表数据加载 + 分页功能 |
| 按钮/操作 | 检查按钮可点击 + 操作响应 |
| 下拉/选择/字典 | 检查下拉选项加载 + 选项值正确 |
| 退回/撤回/取消 | 检查退回流程 + 状态变更 |
### 从复现步骤生成操作序列
```
复现步骤: "1. 登录 → 2. 进入住院医生站 → 3. 点击医嘱录入 → 4. 保存"
生成代码:
await page.goto('/inpatientDoctor');
await page.click('button:has-text("医嘱录入")');
await page.click('button:has-text("保存")');
```
## 四、质量标准
**好的 Bug 测试用例:**
- ✅ 有 `@bug{N}` 标签(可单独运行)
- ✅ 有 `@regression` 标签(回归测试套件)
- ✅ 操作路径来自禅道复现步骤
- ✅ 断言覆盖期望结果
- ✅ 检查无 JS 错误
- ✅ 有截图记录
- ✅ 独立运行(不依赖其他测试)
**坏的 Bug 测试用例:**
- ❌ 只检查页面加载(太弱)
- ❌ 没有断言(只操作不断言)
- ❌ 依赖特定数据(硬编码)
- ❌ 超时设置过短
## 五、与 Agent 工作流集成
```
Agent 收到 Bug
├→ Step 1: 读取禅道 Bug 详情(标题/步骤/截图)
├→ Step 2: 生成 Playwright 测试用例(自动生成 spec 文件)
├→ Step 3: 运行基线测试(应失败)
│ └→ 如果通过 → 检查 develop 是否已修复
├→ Step 4: 修复代码(全链路 6 环)
├→ Step 5: 运行回归测试(应通过)
│ └→ 如果失败 → 分析失败原因 → 返回 Step 4
└→ Step 6: 提交代码 + 推远程 + 更新禅道
```
## 六、CLI 命令速查
```bash
# 生成测试用例
bash tests/e2e/utils/generate-bug-test.sh <bug_id> "<bug_title>"
# 运行单个 Bug 测试
npx playwright test --grep @bug630
# 运行全部回归测试
npx playwright test --grep @regression
# 查看测试报告
npx playwright show-report tests/e2e/report
```

View File

@@ -0,0 +1,73 @@
---
name: check-status
description: Show current code status including uncommitted changes, test health, and build state. Use to get a quick overview before starting work or before committing.
---
Show a comprehensive status report of the HealthLink-HIS codebase:
## 1. Git status
```bash
git status
git log --oneline -5
```
## 2. Uncommitted changes
```bash
git diff --stat
git diff --name-only
```
## 3. Backend health (quick check)
```bash
cd healthlink-his-server
mvn clean compile -DskipTests -q
echo "Backend compile: $?"
```
## 4. Frontend health (quick check)
```bash
cd healthlink-his-ui
npm run build:dev --silent 2>&1 | tail -5
npm run lint --silent 2>&1 | tail -10
```
## 5. Test status
```bash
# Backend: check if tests exist for modified files
git diff --name-only | grep -E "\.java$" | while read f; do
test_file=$(echo "$f" | sed 's/src\/main/src\/test/' | sed 's/\.java$/Test\.java/')
if [ -f "$test_file" ]; then
echo "✓ Test exists: $test_file"
else
echo "⚠ No test: $f"
fi
done
# Frontend: check test coverage
cd healthlink-his-ui
npm run test:run -- --reporter=basic 2>&1 | grep -E "(PASS|FAIL|Tests|Coverage)"
```
## Report format:
```
=== Git Status ===
Branch: develop
Uncommitted: X files
Last commit: abc1234 (message)
=== Backend ===
Compile: ✓/✗
Modified files: X
Tests missing: Y
=== Frontend ===
Build: ✓/✗
Lint: ✓/✗ (X warnings, Y errors)
Tests: X passed, Y failed
=== Ready to commit? ===
✓/✗ (list blockers if any)
```
## Iron Law 3 reminder:
"编译 + 测试全部通过后才能 git commit"

View File

@@ -0,0 +1,84 @@
---
name: closed-loop-testing
description: Quality gates, test automation, and feedback loops for AI-generated code. Use when generating tests, running validation pipelines, setting up quality gates, or implementing auto-fix loops for test failures. Covers L1-L5 quality gates, mutation testing, coverage strategies, and failure analysis.
---
# 闭环测试 — 质量门禁与反馈循环
> 没有门禁的 Agent 是不受控的。每层门禁捕获特定类型的问题。
## 🚪 五层质量门禁
| 门禁 | 时间 | 范围 | 失败处理 |
|---|---|---|---|
| **L1 编译检查** | <30 | 语法类型导入 | Agent 自行修复 |
| **L2 静态分析** | <2 分钟 | 代码风格复杂度安全 | Agent 修复 |
| **L3 单元测试** | <5 分钟 | 功能正确性边界条件 | 自动修复或上报 |
| **L4 集成测试** | <15 分钟 | 模块间交互数据流 | 上报人工 |
| **L5 生产验证** | 持续 | 监控告警性能 | 自动回滚 |
## 🔄 反馈循环机制
```
测试失败
→ 分析失败原因(编译/逻辑/边界/依赖)
→ 提取可行动的反馈(文件:行号:错误类型:修复方向)
→ Agent 修复
→ 重测
→ 若持续失败3次→ 上报人类
```
### 反馈格式规范
```
文件路径:行号 错误类型 错误描述 | 修复建议
示例:
src/payment/applepay_processor.py:42 TypeError amount must be int | 添加类型转换 str → int
```
## 🧪 测试生成策略
### 策略优先级
1. **边界值分析** 测试空值越界特殊值
2. **等价类划分** 覆盖每个分支路径
3. **错误猜测** 基于经验预测常见错误
4. **组合测试** 参数组合爆炸场景
### 覆盖率目标
```yaml
unit_test_coverage: 90% # 行覆盖率
mutation_score: 80% # 变异测试通过率
branch_coverage: 85% # 分支覆盖率
```
## 📊 失败原因分析(基于项目数据)
| 类型 | 占比 | 典型表现 | 捕获门禁 |
|---|---|---|---|
| 架构错误 | 35% | 接口不匹配依赖错乱 | L1 编译 |
| 业务逻辑 | 25% | 条件判断错误数据流断裂 | L3 单元测试 |
| 创造性偏差 | 20% | 过度设计不必要的抽象 | L3 + L5 |
| Debug 残留 | 15% | print临时变量未清理 | L2 静态分析 |
| 其他 | 5% | 环境工具问题 | L5 |
## ⚙️ 本项目测试命令
```bash
# L1 编译检查Java
cd /root/.openclaw/workspace/his-repo/openhis-server-new
mvn compile -pl openhis-application -am
# L1 语法检查Python
python3 -c "import py_compile; py_compile.compile('strategy.py', doraise=True)"
# L2 全链路验证
# 检查 AGENTS.md 中的铁律清单:录入 → 保存 → 查询 → 修改 → 删除 → 关联
```
## ⚠️ 常见陷阱
| 陷阱 | 表现 | 解决 |
|---|---|---|
| 测试滞后 | Agent 写完代码再补测试 | 测试先行或并行生成 |
| 覆盖幻觉 | 覆盖率数字达标但逻辑没测 | 引入变异测试 |
| 反馈过载 | 同时报太多错误 | 按优先级逐层暴露 |
| Mock 泛滥 | 过度 Mock 导致测试失真 | 优先写集成测试 |

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Closed Loop Testing"
short_description: "Part of Harness Engineering plugin — closed-loop-testing"

View File

@@ -0,0 +1,113 @@
---
name: constraint-design
description: Design patterns for writing effective Agent constraints. Use when defining rules, policies, or guardrails for AI code generation. Covers constraint types (architectural/code quality/security/business), DSL patterns, conflict resolution, and progressive trust scaling.
---
# 约束设计 — 让 Agent 在边界内发挥
> 好的约束不是束缚,是护栏。它让 Agent 在安全区域内自由发挥。
## 📐 四类约束
### 1. 架构约束
定义系统结构和组件关系:
```yaml
architecture:
required_interface: "PaymentProcessor" # 必须实现
file_location: "src/payment/" # 文件位置
naming_convention: "{name}_processor.py"
forbidden_patterns:
- "god_class" # 禁止上帝类
- "circular_dep" # 禁止循环依赖
```
### 2. 代码质量约束
定义代码质量和风格标准:
```yaml
code_quality:
max_complexity: 10 # 圈复杂度上限
max_line_length: 120 # Java / 100Vue
type_hints: "required" # 必须类型提示
docstrings: "public_only" # 公共方法需要文档
test_coverage: 90 # 覆盖率目标
```
### 3. 安全约束
防止 Agent 引入安全隐患:
```yaml
security:
no_hardcoded_secrets: true
use_vault_for_credentials: true
input_sanitization: "strict"
forbidden_functions:
- "eval()"
- "exec()"
```
### 4. 业务规则
领域特定的约束:
```yaml
business:
data_flow: "full_chain" # 必须走通全链路
soft_delete: true # 软删除机制
audit_log: true # 操作审计
```
## 🎯 约束设计原则
### 原则 1可验证
每条约束必须能被自动化检查:
```
✅ "代码覆盖率 > 90%" — 可用 pytest-cov 验证
❌ "代码质量要高" — 无法验证
```
### 原则 2无歧义
约束必须精确,不留解读空间:
```
✅ "每函数不超过 50 行"
❌ "函数不要太长"
```
### 原则 3优先级排序
约束冲突时按优先级裁决:
```
安全(1) > 架构(2) > 业务(3) > 质量(4) > 性能(5)
```
### 原则 4渐进增强
从最少的约束开始,按需增加:
```
L1: 编译通过
L2: + 类型提示 + 命名规范
L3: + 测试覆盖 + 复杂度限制
L4: + 安全扫描 + 架构合规
```
## 🔧 约束 DSL 模式
### 声明式(推荐)
```yaml
constraint:
type: "must" | "must_not" | "should" | "may"
scope: "file" | "class" | "method" | "project"
rule: "具体规则"
verification: "如何验证"
```
### 命令式(脚本)
```python
# validate_constraints.py
def check_naming(file_path):
if not file_path.endswith("_processor.py"):
raise Violation("命名不规范")
```
## ⚠️ 常见陷阱
| 陷阱 | 表现 | 解决 |
|---|---|---|
| 过度约束 | Agent 无法完成任务 | 从最小约束集开始 |
| 约束冲突 | 约束 A 要求 X约束 B 禁止 X | 建立优先级链 |
| 无法验证 | 约束定义模糊,无法自动化检查 | 每条约束都必须可验证 |
| 静态不变 | 项目演进后约束过时 | 定期复审约束集 |

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Constraint Design"
short_description: "Part of Harness Engineering plugin — constraint-design"

View File

@@ -0,0 +1,182 @@
---
name: dispatching-parallel-agents
description: Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies
---
# Dispatching Parallel Agents
## Overview
You delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.
When you have multiple unrelated failures (different test files, different subsystems, different bugs), investigating them sequentially wastes time. Each investigation is independent and can happen in parallel.
**Core principle:** Dispatch one agent per independent problem domain. Let them work concurrently.
## When to Use
```dot
digraph when_to_use {
"Multiple failures?" [shape=diamond];
"Are they independent?" [shape=diamond];
"Single agent investigates all" [shape=box];
"One agent per problem domain" [shape=box];
"Can they work in parallel?" [shape=diamond];
"Sequential agents" [shape=box];
"Parallel dispatch" [shape=box];
"Multiple failures?" -> "Are they independent?" [label="yes"];
"Are they independent?" -> "Single agent investigates all" [label="no - related"];
"Are they independent?" -> "Can they work in parallel?" [label="yes"];
"Can they work in parallel?" -> "Parallel dispatch" [label="yes"];
"Can they work in parallel?" -> "Sequential agents" [label="no - shared state"];
}
```
**Use when:**
- 3+ test files failing with different root causes
- Multiple subsystems broken independently
- Each problem can be understood without context from others
- No shared state between investigations
**Don't use when:**
- Failures are related (fix one might fix others)
- Need to understand full system state
- Agents would interfere with each other
## The Pattern
### 1. Identify Independent Domains
Group failures by what's broken:
- File A tests: Tool approval flow
- File B tests: Batch completion behavior
- File C tests: Abort functionality
Each domain is independent - fixing tool approval doesn't affect abort tests.
### 2. Create Focused Agent Tasks
Each agent gets:
- **Specific scope:** One test file or subsystem
- **Clear goal:** Make these tests pass
- **Constraints:** Don't change other code
- **Expected output:** Summary of what you found and fixed
### 3. Dispatch in Parallel
```typescript
// In Claude Code / AI environment
Task("Fix agent-tool-abort.test.ts failures")
Task("Fix batch-completion-behavior.test.ts failures")
Task("Fix tool-approval-race-conditions.test.ts failures")
// All three run concurrently
```
### 4. Review and Integrate
When agents return:
- Read each summary
- Verify fixes don't conflict
- Run full test suite
- Integrate all changes
## Agent Prompt Structure
Good agent prompts are:
1. **Focused** - One clear problem domain
2. **Self-contained** - All context needed to understand the problem
3. **Specific about output** - What should the agent return?
```markdown
Fix the 3 failing tests in src/agents/agent-tool-abort.test.ts:
1. "should abort tool with partial output capture" - expects 'interrupted at' in message
2. "should handle mixed completed and aborted tools" - fast tool aborted instead of completed
3. "should properly track pendingToolCount" - expects 3 results but gets 0
These are timing/race condition issues. Your task:
1. Read the test file and understand what each test verifies
2. Identify root cause - timing issues or actual bugs?
3. Fix by:
- Replacing arbitrary timeouts with event-based waiting
- Fixing bugs in abort implementation if found
- Adjusting test expectations if testing changed behavior
Do NOT just increase timeouts - find the real issue.
Return: Summary of what you found and what you fixed.
```
## Common Mistakes
**❌ Too broad:** "Fix all the tests" - agent gets lost
**✅ Specific:** "Fix agent-tool-abort.test.ts" - focused scope
**❌ No context:** "Fix the race condition" - agent doesn't know where
**✅ Context:** Paste the error messages and test names
**❌ No constraints:** Agent might refactor everything
**✅ Constraints:** "Do NOT change production code" or "Fix tests only"
**❌ Vague output:** "Fix it" - you don't know what changed
**✅ Specific:** "Return summary of root cause and changes"
## When NOT to Use
**Related failures:** Fixing one might fix others - investigate together first
**Need full context:** Understanding requires seeing entire system
**Exploratory debugging:** You don't know what's broken yet
**Shared state:** Agents would interfere (editing same files, using same resources)
## Real Example from Session
**Scenario:** 6 test failures across 3 files after major refactoring
**Failures:**
- agent-tool-abort.test.ts: 3 failures (timing issues)
- batch-completion-behavior.test.ts: 2 failures (tools not executing)
- tool-approval-race-conditions.test.ts: 1 failure (execution count = 0)
**Decision:** Independent domains - abort logic separate from batch completion separate from race conditions
**Dispatch:**
```
Agent 1 → Fix agent-tool-abort.test.ts
Agent 2 → Fix batch-completion-behavior.test.ts
Agent 3 → Fix tool-approval-race-conditions.test.ts
```
**Results:**
- Agent 1: Replaced timeouts with event-based waiting
- Agent 2: Fixed event structure bug (threadId in wrong place)
- Agent 3: Added wait for async tool execution to complete
**Integration:** All fixes independent, no conflicts, full suite green
**Time saved:** 3 problems solved in parallel vs sequentially
## Key Benefits
1. **Parallelization** - Multiple investigations happen simultaneously
2. **Focus** - Each agent has narrow scope, less context to track
3. **Independence** - Agents don't interfere with each other
4. **Speed** - 3 problems solved in time of 1
## Verification
After agents return:
1. **Review each summary** - Understand what changed
2. **Check for conflicts** - Did agents edit same code?
3. **Run full suite** - Verify all fixes work together
4. **Spot check** - Agents can make systematic errors
## Real-World Impact
From debugging session (2025-10-03):
- 6 failures across 3 files
- 3 agents dispatched in parallel
- All investigations completed concurrently
- All fixes integrated successfully
- Zero conflicts between agent changes

View File

@@ -0,0 +1,119 @@
---
name: durable-execution
description: Checkpoint management and state persistence for long-running agents. Use when executing tasks that span multiple steps, need failure recovery, or require idempotent operations. Covers checkpoint strategy, state management layers, event sourcing, and recovery patterns.
---
# 持久化执行 — 检查点与状态管理
> 可靠是规模化的前提。每个长时任务都必须有可恢复的检查点。
## 🎯 何时使用
- 任务预计超过 5 个步骤
- 任务涉及文件修改(需要回滚能力)
- 任务依赖外部服务/API
- 任务需要在中断后恢复
## 📦 三层状态管理
| 层级 | 内容 | 本项目的实现 |
|---|---|---|
| **系统层** | 工作流 ID、超时、重试配置 | update_plan 记录任务 ID 和进度 |
| **执行层** | 当前活动、执行进度、等待事件 | checklist_write 分步骤记录 |
| **业务层** | 已完成工作、中间产物 | git diff + 编译结果作为验证 |
## 🔄 检查点策略
### 触发时机
```
时间触发:每完成 1 个关键步骤
事件触发:编译通过 / 失败后
状态变化每次代码修改后git diff 可见)
```
### 检查点内容
```yaml
checkpoint:
step_id: "string"
status: "pending | in_progress | completed | failed"
inputs: { } # 该步骤的输入参数
outputs: { } # 该步骤的产出
error_message: "" # 失败原因
timestamp: "ISO8601" # 时间戳
```
### 恢复流程
```
失败检测
→ 定位最新检查点update_plan / checklist
→ 分析失败原因(编译错误 / 测试失败 / 逻辑错误)
→ git restore 撤销本次修改
→ 从失败点修复(不从头开始)
→ 继续执行
→ 恢复验证(确认状态一致性)
```
## ♻️ 幂等性模式
### 模式 1唯一标识
每个操作生成唯一 ID已执行则跳过
```
generate_code(task_id="abc123")
if executed(task_id="abc123"):
return cached_result # 已执行,跳过
```
### 模式 2状态检查
执行前检查目标是否已达成:
```
if file_exists("src/utils/helper.js"):
return # 已生成,跳过
```
### 模式 3补偿操作
不可逆操作提供回滚机制:
```
try:
modify_file(path)
except:
restore_from_git(path) # 补偿操作
```
## 📝 事件溯源(简化版)
每次操作产生不可变事件记录:
```
事件流(按时间顺序):
① 人类提交任务 → ② Agent 制定计划
→ ③ 修改文件 → ④ 编译检查
→ ⑤ 数据流验证 → ⑥ 人类审查
→ ⑦ 提交代码
```
每次事件可通过 `git log` + `update_plan` 追溯。
## ⚡ 本项目的检查点命令速查
```bash
# 查看当前进度
grep -n "^[0-9]\+\." <(cat AGENTS.md | grep -A 100 "工作流程")
# 回滚最近的修改
git checkout -- <file>
# 查看修改历史
git log --oneline -10
# 查看未提交的变更
git diff --stat HEAD
```
## ⚠️ 常见陷阱
| 陷阱 | 表现 | 解决 |
|---|---|---|
| 不设检查点 | 失败后全部重来 | 步骤间自动 save_checkpoint |
| 幂等性缺失 | 重复执行导致错误 | 唯一 ID / 状态检查 |
| 状态不一致 | 检查点与实际不符 | git diff 验证后再恢复 |
| 检查点过大 | 保存和恢复慢 | 只保存增量状态 |

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Durable Execution"
short_description: "Part of Harness Engineering plugin — durable-execution"

View File

@@ -0,0 +1,70 @@
---
name: executing-plans
description: Use when you have a written implementation plan to execute in a separate session with review checkpoints
---
# Executing Plans
## Overview
Load plan, review critically, execute all tasks, report when complete.
**Announce at start:** "I'm using the executing-plans skill to implement this plan."
**Note:** Tell your human partner that Superpowers works much better with access to subagents. The quality of its work will be significantly higher if run on a platform with subagent support (such as Claude Code or Codex). If subagents are available, use superpowers:subagent-driven-development instead of this skill.
## The Process
### Step 1: Load and Review Plan
1. Read plan file
2. Review critically - identify any questions or concerns about the plan
3. If concerns: Raise them with your human partner before starting
4. If no concerns: Create TodoWrite and proceed
### Step 2: Execute Tasks
For each task:
1. Mark as in_progress
2. Follow each step exactly (plan has bite-sized steps)
3. Run verifications as specified
4. Mark as completed
### Step 3: Complete Development
After all tasks complete and verified:
- Announce: "I'm using the finishing-a-development-branch skill to complete this work."
- **REQUIRED SUB-SKILL:** Use superpowers:finishing-a-development-branch
- Follow that skill to verify tests, present options, execute choice
## When to Stop and Ask for Help
**STOP executing immediately when:**
- Hit a blocker (missing dependency, test fails, instruction unclear)
- Plan has critical gaps preventing starting
- You don't understand an instruction
- Verification fails repeatedly
**Ask for clarification rather than guessing.**
## When to Revisit Earlier Steps
**Return to Review (Step 1) when:**
- Partner updates the plan based on your feedback
- Fundamental approach needs rethinking
**Don't force through blockers** - stop and ask.
## Remember
- Review plan critically first
- Follow plan steps exactly
- Don't skip verifications
- Reference skills when plan says to
- Stop when blocked, don't guess
- Never start implementation on main/master branch without explicit user consent
## Integration
**Required workflow skills:**
- **superpowers:using-git-worktrees** - Ensures isolated workspace (creates one or verifies existing)
- **superpowers:writing-plans** - Creates the plan this skill executes
- **superpowers:finishing-a-development-branch** - Complete development after all tasks

View File

@@ -0,0 +1,251 @@
---
name: finishing-a-development-branch
description: Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup
---
# Finishing a Development Branch
## Overview
Guide completion of development work by presenting clear options and handling chosen workflow.
**Core principle:** Verify tests → Detect environment → Present options → Execute choice → Clean up.
**Announce at start:** "I'm using the finishing-a-development-branch skill to complete this work."
## The Process
### Step 1: Verify Tests
**Before presenting options, verify tests pass:**
```bash
# Run project's test suite
npm test / cargo test / pytest / go test ./...
```
**If tests fail:**
```
Tests failing (<N> failures). Must fix before completing:
[Show failures]
Cannot proceed with merge/PR until tests pass.
```
Stop. Don't proceed to Step 2.
**If tests pass:** Continue to Step 2.
### Step 2: Detect Environment
**Determine workspace state before presenting options:**
```bash
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
```
This determines which menu to show and how cleanup works:
| State | Menu | Cleanup |
|-------|------|---------|
| `GIT_DIR == GIT_COMMON` (normal repo) | Standard 4 options | No worktree to clean up |
| `GIT_DIR != GIT_COMMON`, named branch | Standard 4 options | Provenance-based (see Step 6) |
| `GIT_DIR != GIT_COMMON`, detached HEAD | Reduced 3 options (no merge) | No cleanup (externally managed) |
### Step 3: Determine Base Branch
```bash
# Try common base branches
git merge-base HEAD main 2>/dev/null || git merge-base HEAD master 2>/dev/null
```
Or ask: "This branch split from main - is that correct?"
### Step 4: Present Options
**Normal repo and named-branch worktree — present exactly these 4 options:**
```
Implementation complete. What would you like to do?
1. Merge back to <base-branch> locally
2. Push and create a Pull Request
3. Keep the branch as-is (I'll handle it later)
4. Discard this work
Which option?
```
**Detached HEAD — present exactly these 3 options:**
```
Implementation complete. You're on a detached HEAD (externally managed workspace).
1. Push as new branch and create a Pull Request
2. Keep as-is (I'll handle it later)
3. Discard this work
Which option?
```
**Don't add explanation** - keep options concise.
### Step 5: Execute Choice
#### Option 1: Merge Locally
```bash
# Get main repo root for CWD safety
MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
cd "$MAIN_ROOT"
# Merge first — verify success before removing anything
git checkout <base-branch>
git pull
git merge <feature-branch>
# Verify tests on merged result
<test command>
# Only after merge succeeds: cleanup worktree (Step 6), then delete branch
```
Then: Cleanup worktree (Step 6), then delete branch:
```bash
git branch -d <feature-branch>
```
#### Option 2: Push and Create PR
```bash
# Push branch
git push -u origin <feature-branch>
# Create PR
gh pr create --title "<title>" --body "$(cat <<'EOF'
## Summary
<2-3 bullets of what changed>
## Test Plan
- [ ] <verification steps>
EOF
)"
```
**Do NOT clean up worktree** — user needs it alive to iterate on PR feedback.
#### Option 3: Keep As-Is
Report: "Keeping branch <name>. Worktree preserved at <path>."
**Don't cleanup worktree.**
#### Option 4: Discard
**Confirm first:**
```
This will permanently delete:
- Branch <name>
- All commits: <commit-list>
- Worktree at <path>
Type 'discard' to confirm.
```
Wait for exact confirmation.
If confirmed:
```bash
MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
cd "$MAIN_ROOT"
```
Then: Cleanup worktree (Step 6), then force-delete branch:
```bash
git branch -D <feature-branch>
```
### Step 6: Cleanup Workspace
**Only runs for Options 1 and 4.** Options 2 and 3 always preserve the worktree.
```bash
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
WORKTREE_PATH=$(git rev-parse --show-toplevel)
```
**If `GIT_DIR == GIT_COMMON`:** Normal repo, no worktree to clean up. Done.
**If worktree path is under `.worktrees/`, `worktrees/`, or `~/.config/superpowers/worktrees/`:** Superpowers created this worktree — we own cleanup.
```bash
MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
cd "$MAIN_ROOT"
git worktree remove "$WORKTREE_PATH"
git worktree prune # Self-healing: clean up any stale registrations
```
**Otherwise:** The host environment (harness) owns this workspace. Do NOT remove it. If your platform provides a workspace-exit tool, use it. Otherwise, leave the workspace in place.
## Quick Reference
| Option | Merge | Push | Keep Worktree | Cleanup Branch |
|--------|-------|------|---------------|----------------|
| 1. Merge locally | yes | - | - | yes |
| 2. Create PR | - | yes | yes | - |
| 3. Keep as-is | - | - | yes | - |
| 4. Discard | - | - | - | yes (force) |
## Common Mistakes
**Skipping test verification**
- **Problem:** Merge broken code, create failing PR
- **Fix:** Always verify tests before offering options
**Open-ended questions**
- **Problem:** "What should I do next?" is ambiguous
- **Fix:** Present exactly 4 structured options (or 3 for detached HEAD)
**Cleaning up worktree for Option 2**
- **Problem:** Remove worktree user needs for PR iteration
- **Fix:** Only cleanup for Options 1 and 4
**Deleting branch before removing worktree**
- **Problem:** `git branch -d` fails because worktree still references the branch
- **Fix:** Merge first, remove worktree, then delete branch
**Running git worktree remove from inside the worktree**
- **Problem:** Command fails silently when CWD is inside the worktree being removed
- **Fix:** Always `cd` to main repo root before `git worktree remove`
**Cleaning up harness-owned worktrees**
- **Problem:** Removing a worktree the harness created causes phantom state
- **Fix:** Only clean up worktrees under `.worktrees/`, `worktrees/`, or `~/.config/superpowers/worktrees/`
**No confirmation for discard**
- **Problem:** Accidentally delete work
- **Fix:** Require typed "discard" confirmation
## Red Flags
**Never:**
- Proceed with failing tests
- Merge without verifying tests on result
- Delete work without confirmation
- Force-push without explicit request
- Remove a worktree before confirming merge success
- Clean up worktrees you didn't create (provenance check)
- Run `git worktree remove` from inside the worktree
**Always:**
- Verify tests before offering options
- Detect environment before presenting menu
- Present exactly 4 options (or 3 for detached HEAD)
- Get typed confirmation for Option 4
- Clean up worktree for Options 1 & 4 only
- `cd` to main repo root before worktree removal
- Run `git worktree prune` after removal

View File

@@ -0,0 +1,43 @@
---
name: fix-compile
description: Diagnose and fix compilation errors systematically. Use when `mvn compile` or `npm run build:dev` fails.
---
Systematically diagnose and fix compilation errors following the 4-stage debugging process:
## Stage 1: Root cause investigation
1. Read the FULL error message (stack trace, line numbers, error codes)
2. Identify the error type:
- Java: syntax, type mismatch, missing import, duplicate method, signature conflict
- Vue/JS: syntax, import error, TypeScript type, SCSS bracket mismatch
3. Check recent changes: `git diff HEAD~5` to see what changed
4. For Java errors: check if the method/class already exists elsewhere (Iron Law 9)
5. For Vue errors: check SCSS bracket closure (Iron Law 30)
## Stage 2: Pattern analysis
- Search for similar working code: `rg "similar_pattern" --type java --type vue`
- Compare with working examples in the same codebase
- Check if dependencies are correctly imported
## Stage 3: Hypothesis and test
- Form ONE hypothesis: "I believe X is the root cause because Y"
- Make the MINIMAL change to test it
- If it works → Stage 4
- If not → new hypothesis (max 3 attempts before asking user)
## Stage 4: Implement fix
- Apply the fix
- Run the verification command again:
- Backend: `mvn clean compile -DskipTests`
- Frontend: `npm run build:dev`
- Confirm zero errors before declaring success
## Common error patterns in this codebase:
- **Duplicate method**: Check all Service implementations for the same method
- **Missing import**: Verify package structure matches `com.healthlink.his.web.{module}`
- **Type mismatch**: Check DTO field types (Iron Law: DTO field type defense)
- **SCSS bracket**: Count `{` and `}` in `<style lang="scss" scoped>` blocks
- **Flyway conflict**: Check migration version numbers in `healthlink-his-application/src/main/resources/db/migration/`
## After fixing:
Run `/verify` to ensure the fix didn't break anything else.

View File

@@ -0,0 +1,30 @@
---
name: full-chain-fix
description: Full-chain verification methodology for bugfixes and feature development. When fixing a bug or implementing a requirement, trace the complete data flow (input → save → query → edit → delete → related modules) instead of fixing locally.
metadata:
short-description: Full-chain data flow verification for bugfixes
---
# 全链路修复原则 ⚠️
> 修 Bug / 做需求时,**不得"就事论事"**,必须走通完整的**数据流全链路**。
## 检查清单(每一环都确认)
1. **录入** → 前端有无输入入口?(弹窗、表格行编辑、表单…)
2. **保存** → 前端 → API → 后端 Controller → Service → Entity → DB**每一个保存入口**都传了该字段吗?(注意多个 Service 实现类可能走不同入口)
3. **查询** → DB → Mapper XML注意 UNION ALL 子查询要统一加)→ DTO → 前端展示,列和数据绑定都完整吗?
4. **修改** → 已有数据编辑回显 → 修改再保存 → 数据能正确更新吗?
5. **删除/停止/撤回** → 相关状态变更会丢失该字段数据吗?
6. **关联模块** → 上游(如医嘱录入后护士站要看到备注)和下游(如打印、计费、报表)是否也需要同步修改?
## 常见陷阱
- ❌ 只修了「主入口」的保存逻辑,忘了「批量保存」「签发保存」等其他入口
- ❌ 前端加了输入框,后端 Service 没传字段(不同模块可能走不同 Service 实现类)
- ❌ Mapper XML 是 UNION ALL 查询,只改了其中一个子查询,导致列数不匹配或漏加
- ❌ DTO 层级继承关系没检查(如 `RegAdviceSaveDto extends AdviceSaveDto`,父类改了对不对)
- ❌ 只测了新增,没测编辑已有数据的回显和修改再保存
## 执行细则
- 每个字段的新增/修改,先在脑中画出完整的数据流向图再动手
- 提交前逐个环节检查一遍,确保没有断链
- 编译通过不等同于功能正确,必要时做端到端验证

View File

@@ -0,0 +1,175 @@
---
name: harness-engineering
description: "Master methodology for designing AI Agent work environments. Use when designing constraints, feedback loops, control planes, quality gates, or durable execution for Codex agents. Encodes the full Harness Engineering paradigm."
---
# Harness Engineering — 核心方法论
> Harness = 约束 + 反馈 + 控制平面 + 持久执行
## 🔧 四大核心组件
### 1. 约束系统 (Constraints)
定义 Agent 行为边界和输出质量。四层金字塔:
| 层级 | 内容 | 本项目落地 |
|---|---|---|
| **L1 架构约束** | 接口合约、包结构、命名规范、禁止模式 | AGENTS.md 铁律、全链路清单 |
| **L2 代码质量** | 圈复杂度、代码风格、类型提示、文档要求 | 编译门禁 + 语法检查 |
| **L3 安全约束** | 敏感信息检测、权限检查、输入验证 | 配置文件不可硬编码 |
| **L4 业务规则** | 领域逻辑、数据一致性、事务边界 | 全链路数据流验证 |
**关键原则:**
- 约束越底层越自动(编译检查),越上层越需要人工裁决
- 约束冲突时:安全 > 架构 > 质量 > 业务
- 约束应随信任度动态调整(信任度模型见下文)
### 2. 反馈系统 (Feedback Loop)
测试 → 失败 → Agent 修复 → 重测。分三层:
| 层级 | 速度 | 覆盖范围 | 失败处理 |
|---|---|---|---|
| **L1 编译检查** | <30 | 语法类型签名 | 立即阻断Agent 自行修复 |
| **L2 数据流验证** | <5 分钟 | 全链路字段Mapper XMLDTO | Agent 修复必要时上报 |
| **L3 人工审查** | 10-30 分钟 | 架构设计业务正确性 | 驳回 / 指导 / 批准 |
**反馈设计铁律:**
- 反馈必须可行动指出文件 + 行号 + 错误类型 + 修复方向
- 反馈越及时越好L1 即时 L2 分钟 L3 小时
- 失败后先回滚到最近检查点再重试
### 3. 控制平面 (Control Plane)
任务调度和 Agent 协调的核心机制
```
┌─────────────────────────────────────────────┐
│ 控制平面三层架构 │
│ │
│ 战略层(人类主导) │
│ ├── 设定目标、审批关键决策 │
│ └── 异常升级处理 │
│ │
│ 战术层Control Plane 主导) │
│ ├── 任务分解 + 规划 │
│ ├── update_plan / checklist_write │
│ └── 依赖协调 + 资源分配 │
│ │
│ 执行层Agent 自主) │
│ ├── 代码生成、测试执行 │
│ ├── apply_patch / exec_command │
│ └── 错误恢复 + 检查点保存 │
└─────────────────────────────────────────────┘
```
### 4. 持久执行 (Durable Execution)
长时任务的检查点恢复机制详见 `$durable-execution` 技能
- 每个关键步骤保存检查点`update_plan` 进度
- 失败后从最新检查点恢复不从头开始
- 幂等设计同一操作重复执行结果一致
## 📋 工作流程
### 标准工作流Plan → Generate → Validate → Review
```
收到任务
├→ 1. 计划Plan
│ ├── 分解步骤checklist_write + update_plan
│ ├── 评估复杂度 / 风险
│ └── 设定检查点里程碑
├→ 2. 生成Generate
│ ├── 并行探索spawn_agent × N
│ ├── 约束优先:先加载 AGENTS.md 和相关规则
│ └── 增量修改:只动必要文件
├→ 3. 验证Validate
│ ├── L1 编译检查mvn compile / python3 -c py_compile
│ ├── L2 数据流验证(全链路检查清单)
│ └── L3 人工审查(提交 diff 给人类)
└→ 4. 审查Review
├── 提交前 self-review对照约束逐条检查
├── 生成变更摘要
└── 提交 / 推送
```
### 异常流程
```
编译失败 → 分析错误 → 撤销本次修改 → 从检查点恢复 → 重试
持续失败3次 → 上报人类 → 等待指导
```
## 🎯 质量门禁Quality Gates
| 门禁 | 触发时机 | 通过条件 | 失败动作 |
|---|---|---|---|
| L1 编译 | 每次修改后 | 编译通过 | 立即修复 |
| L2 全链路 | 提交前 | 数据流完整 | Agent 修复 |
| L3 审查 | PR 提交 | 人类批准 | 驳回/指导 |
| L4 回归 | 合并后 | 无回归 | 紧急修复 |
## 🔐 分层信任模型
| 信任等级 | 特征 | 自动化程度 |
|---|---|---|
| L1 怀疑 | Agent 错误率高人工逐行审查 | <20% 自动 |
| L2 试探 | Agent 稳定抽样审查 | 40-60% 自动 |
| L3 信任 | Agent 可靠关注结果 | 70-85% 自动 |
| L4 委托 | Agent 成为伙伴人类管战略 | 90%+ 自动 |
**当前项目状态:** L2 试探级编译门禁自动 + 全链路验证 + 人工终审
## 📐 约束设计模式
### 1. 肯定模式 — 必须遵守的规则
```
必须实现 XXX 接口
代码覆盖率必须 > 90%
每个公共方法必须有类型提示
```
### 2. 否定模式 — 禁止的行为
```
禁止直接操作数据库(必须通过 Repository
禁止硬编码密码/密钥
禁止使用 eval()
```
### 3. 边界模式 — 限制范围
```
圈复杂度 <= 10
每函数行数 <= 50
单文件修改 <= 5 个
```
### 4. 优先级模式 — 冲突处理
```
安全 > 架构 > 质量 > 性能 > 便利
```
## ⚠️ 常见陷阱
| 陷阱 | 表现 | 解决 |
|---|---|---|
| 过度约束 | Agent 被束缚效率低 | 从最少约束开始按需增加 |
| 约束冲突 | 多个规则互相矛盾 | 确定优先级顺序 |
| 反馈延迟 | 编译太慢Agent 等待 | 分层测试快速失败 |
| 控制不足 | Agent 自由度过高 | 增加检查点和门禁 |
| 跳过验证 | 直接提交未验证代码 | 门禁自动化阻塞提交 |
## 📚 相关技能
- `$durable-execution` 检查点幂等性事件溯源
- `$closed-loop-testing` 质量门禁测试策略反馈循环
- `$constraint-design` DSL 设计策略模式约束编排
- `$review-audit` 审查工作流审计追踪合规检查
- `$full-chain-fix` 全链路数据流修复已安装
- `$karpathy-guidelines` 减少 LLM 编码错误已安装

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Harness Engineering"
short_description: "Part of Harness Engineering plugin — harness-engineering"

View File

@@ -0,0 +1,67 @@
---
name: karpathy-guidelines
description: Behavioral guidelines to reduce common LLM coding mistakes. Use when writing, reviewing, or refactoring code to avoid overcomplication, make surgical changes, surface assumptions, and define verifiable success criteria.
license: MIT
---
# Karpathy Guidelines
Behavioral guidelines to reduce common LLM coding mistakes, derived from [Andrej Karpathy's observations](https://x.com/karpathy/status/2015883857489522876) on LLM coding pitfalls.
**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
## 1. Think Before Coding
**Don't assume. Don't hide confusion. Surface tradeoffs.**
Before implementing:
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
- If something is unclear, stop. Name what's confusing. Ask.
## 2. Simplicity First
**Minimum code that solves the problem. Nothing speculative.**
- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
- No error handling for impossible scenarios.
- If you write 200 lines and it could be 50, rewrite it.
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
## 3. Surgical Changes
**Touch only what you must. Clean up only your own mess.**
When editing existing code:
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.
When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.
The test: Every changed line should trace directly to the user's request.
## 4. Goal-Driven Execution
**Define success criteria. Loop until verified.**
Transform tasks into verifiable goals:
- "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after"
For multi-step tasks, state a brief plan:
```
1. [Step] → verify: [check]
2. [Step] → verify: [check]
3. [Step] → verify: [check]
```
Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.

View File

@@ -0,0 +1,213 @@
---
name: receiving-code-review
description: Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation
---
# Code Review Reception
## Overview
Code review requires technical evaluation, not emotional performance.
**Core principle:** Verify before implementing. Ask before assuming. Technical correctness over social comfort.
## The Response Pattern
```
WHEN receiving code review feedback:
1. READ: Complete feedback without reacting
2. UNDERSTAND: Restate requirement in own words (or ask)
3. VERIFY: Check against codebase reality
4. EVALUATE: Technically sound for THIS codebase?
5. RESPOND: Technical acknowledgment or reasoned pushback
6. IMPLEMENT: One item at a time, test each
```
## Forbidden Responses
**NEVER:**
- "You're absolutely right!" (explicit CLAUDE.md violation)
- "Great point!" / "Excellent feedback!" (performative)
- "Let me implement that now" (before verification)
**INSTEAD:**
- Restate the technical requirement
- Ask clarifying questions
- Push back with technical reasoning if wrong
- Just start working (actions > words)
## Handling Unclear Feedback
```
IF any item is unclear:
STOP - do not implement anything yet
ASK for clarification on unclear items
WHY: Items may be related. Partial understanding = wrong implementation.
```
**Example:**
```
your human partner: "Fix 1-6"
You understand 1,2,3,6. Unclear on 4,5.
❌ WRONG: Implement 1,2,3,6 now, ask about 4,5 later
✅ RIGHT: "I understand items 1,2,3,6. Need clarification on 4 and 5 before proceeding."
```
## Source-Specific Handling
### From your human partner
- **Trusted** - implement after understanding
- **Still ask** if scope unclear
- **No performative agreement**
- **Skip to action** or technical acknowledgment
### From External Reviewers
```
BEFORE implementing:
1. Check: Technically correct for THIS codebase?
2. Check: Breaks existing functionality?
3. Check: Reason for current implementation?
4. Check: Works on all platforms/versions?
5. Check: Does reviewer understand full context?
IF suggestion seems wrong:
Push back with technical reasoning
IF can't easily verify:
Say so: "I can't verify this without [X]. Should I [investigate/ask/proceed]?"
IF conflicts with your human partner's prior decisions:
Stop and discuss with your human partner first
```
**your human partner's rule:** "External feedback - be skeptical, but check carefully"
## YAGNI Check for "Professional" Features
```
IF reviewer suggests "implementing properly":
grep codebase for actual usage
IF unused: "This endpoint isn't called. Remove it (YAGNI)?"
IF used: Then implement properly
```
**your human partner's rule:** "You and reviewer both report to me. If we don't need this feature, don't add it."
## Implementation Order
```
FOR multi-item feedback:
1. Clarify anything unclear FIRST
2. Then implement in this order:
- Blocking issues (breaks, security)
- Simple fixes (typos, imports)
- Complex fixes (refactoring, logic)
3. Test each fix individually
4. Verify no regressions
```
## When To Push Back
Push back when:
- Suggestion breaks existing functionality
- Reviewer lacks full context
- Violates YAGNI (unused feature)
- Technically incorrect for this stack
- Legacy/compatibility reasons exist
- Conflicts with your human partner's architectural decisions
**How to push back:**
- Use technical reasoning, not defensiveness
- Ask specific questions
- Reference working tests/code
- Involve your human partner if architectural
**Signal if uncomfortable pushing back out loud:** "Strange things are afoot at the Circle K"
## Acknowledging Correct Feedback
When feedback IS correct:
```
✅ "Fixed. [Brief description of what changed]"
✅ "Good catch - [specific issue]. Fixed in [location]."
✅ [Just fix it and show in the code]
❌ "You're absolutely right!"
❌ "Great point!"
❌ "Thanks for catching that!"
❌ "Thanks for [anything]"
❌ ANY gratitude expression
```
**Why no thanks:** Actions speak. Just fix it. The code itself shows you heard the feedback.
**If you catch yourself about to write "Thanks":** DELETE IT. State the fix instead.
## Gracefully Correcting Your Pushback
If you pushed back and were wrong:
```
✅ "You were right - I checked [X] and it does [Y]. Implementing now."
✅ "Verified this and you're correct. My initial understanding was wrong because [reason]. Fixing."
❌ Long apology
❌ Defending why you pushed back
❌ Over-explaining
```
State the correction factually and move on.
## Common Mistakes
| Mistake | Fix |
|---------|-----|
| Performative agreement | State requirement or just act |
| Blind implementation | Verify against codebase first |
| Batch without testing | One at a time, test each |
| Assuming reviewer is right | Check if breaks things |
| Avoiding pushback | Technical correctness > comfort |
| Partial implementation | Clarify all items first |
| Can't verify, proceed anyway | State limitation, ask for direction |
## Real Examples
**Performative Agreement (Bad):**
```
Reviewer: "Remove legacy code"
❌ "You're absolutely right! Let me remove that..."
```
**Technical Verification (Good):**
```
Reviewer: "Remove legacy code"
✅ "Checking... build target is 10.15+, this API needs 13+. Need legacy for backward compat. Current impl has wrong bundle ID - fix it or drop pre-13 support?"
```
**YAGNI (Good):**
```
Reviewer: "Implement proper metrics tracking with database, date filters, CSV export"
✅ "Grepped codebase - nothing calls this endpoint. Remove it (YAGNI)? Or is there usage I'm missing?"
```
**Unclear Item (Good):**
```
your human partner: "Fix items 1-6"
You understand 1,2,3,6. Unclear on 4,5.
✅ "Understand 1,2,3,6. Need clarification on 4 and 5 before implementing."
```
## GitHub Thread Replies
When replying to inline review comments on GitHub, reply in the comment thread (`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`), not as a top-level PR comment.
## The Bottom Line
**External feedback = suggestions to evaluate, not orders to follow.**
Verify. Question. Then implement.
No performative agreement. Technical rigor always.

View File

@@ -0,0 +1,103 @@
---
name: requesting-code-review
description: Use when completing tasks, implementing major features, or before merging to verify work meets requirements
---
# Requesting Code Review
Dispatch a code reviewer subagent to catch issues before they cascade. The reviewer gets precisely crafted context for evaluation — never your session's history. This keeps the reviewer focused on the work product, not your thought process, and preserves your own context for continued work.
**Core principle:** Review early, review often.
## When to Request Review
**Mandatory:**
- After each task in subagent-driven development
- After completing major feature
- Before merge to main
**Optional but valuable:**
- When stuck (fresh perspective)
- Before refactoring (baseline check)
- After fixing complex bug
## How to Request
**1. Get git SHAs:**
```bash
BASE_SHA=$(git rev-parse HEAD~1) # or origin/main
HEAD_SHA=$(git rev-parse HEAD)
```
**2. Dispatch code reviewer subagent:**
Use Task tool with `general-purpose` type, fill template at `code-reviewer.md`
**Placeholders:**
- `{DESCRIPTION}` - Brief summary of what you built
- `{PLAN_OR_REQUIREMENTS}` - What it should do
- `{BASE_SHA}` - Starting commit
- `{HEAD_SHA}` - Ending commit
**3. Act on feedback:**
- Fix Critical issues immediately
- Fix Important issues before proceeding
- Note Minor issues for later
- Push back if reviewer is wrong (with reasoning)
## Example
```
[Just completed Task 2: Add verification function]
You: Let me request code review before proceeding.
BASE_SHA=$(git log --oneline | grep "Task 1" | head -1 | awk '{print $1}')
HEAD_SHA=$(git rev-parse HEAD)
[Dispatch code reviewer subagent]
DESCRIPTION: Added verifyIndex() and repairIndex() with 4 issue types
PLAN_OR_REQUIREMENTS: Task 2 from docs/superpowers/plans/deployment-plan.md
BASE_SHA: a7981ec
HEAD_SHA: 3df7661
[Subagent returns]:
Strengths: Clean architecture, real tests
Issues:
Important: Missing progress indicators
Minor: Magic number (100) for reporting interval
Assessment: Ready to proceed
You: [Fix progress indicators]
[Continue to Task 3]
```
## Integration with Workflows
**Subagent-Driven Development:**
- Review after EACH task
- Catch issues before they compound
- Fix before moving to next task
**Executing Plans:**
- Review after each task or at natural checkpoints
- Get feedback, apply, continue
**Ad-Hoc Development:**
- Review before merge
- Review when stuck
## Red Flags
**Never:**
- Skip review because "it's simple"
- Ignore Critical issues
- Proceed with unfixed Important issues
- Argue with valid technical feedback
**If reviewer wrong:**
- Push back with technical reasoning
- Show code/tests that prove it works
- Request clarification
See template at: requesting-code-review/code-reviewer.md

View File

@@ -0,0 +1,168 @@
# Code Reviewer Prompt Template
Use this template when dispatching a code reviewer subagent.
**Purpose:** Review completed work against requirements and code quality standards before it cascades into more work.
```
Task tool (general-purpose):
description: "Review code changes"
prompt: |
You are a Senior Code Reviewer with expertise in software architecture,
design patterns, and best practices. Your job is to review completed work
against its plan or requirements and identify issues before they cascade.
## What Was Implemented
{DESCRIPTION}
## Requirements / Plan
{PLAN_OR_REQUIREMENTS}
## Git Range to Review
**Base:** {BASE_SHA}
**Head:** {HEAD_SHA}
```bash
git diff --stat {BASE_SHA}..{HEAD_SHA}
git diff {BASE_SHA}..{HEAD_SHA}
```
## What to Check
**Plan alignment:**
- Does the implementation match the plan / requirements?
- Are deviations justified improvements, or problematic departures?
- Is all planned functionality present?
**Code quality:**
- Clean separation of concerns?
- Proper error handling?
- Type safety where applicable?
- DRY without premature abstraction?
- Edge cases handled?
**Architecture:**
- Sound design decisions?
- Reasonable scalability and performance?
- Security concerns?
- Integrates cleanly with surrounding code?
**Testing:**
- Tests verify real behavior, not mocks?
- Edge cases covered?
- Integration tests where they matter?
- All tests passing?
**Production readiness:**
- Migration strategy if schema changed?
- Backward compatibility considered?
- Documentation complete?
- No obvious bugs?
## Calibration
Categorize issues by actual severity. Not everything is Critical.
Acknowledge what was done well before listing issues — accurate praise
helps the implementer trust the rest of the feedback.
If you find significant deviations from the plan, flag them specifically
so the implementer can confirm whether the deviation was intentional.
If you find issues with the plan itself rather than the implementation,
say so.
## Output Format
### Strengths
[What's well done? Be specific.]
### Issues
#### Critical (Must Fix)
[Bugs, security issues, data loss risks, broken functionality]
#### Important (Should Fix)
[Architecture problems, missing features, poor error handling, test gaps]
#### Minor (Nice to Have)
[Code style, optimization opportunities, documentation polish]
For each issue:
- File:line reference
- What's wrong
- Why it matters
- How to fix (if not obvious)
### Recommendations
[Improvements for code quality, architecture, or process]
### Assessment
**Ready to merge?** [Yes | No | With fixes]
**Reasoning:** [1-2 sentence technical assessment]
## Critical Rules
**DO:**
- Categorize by actual severity
- Be specific (file:line, not vague)
- Explain WHY each issue matters
- Acknowledge strengths
- Give a clear verdict
**DON'T:**
- Say "looks good" without checking
- Mark nitpicks as Critical
- Give feedback on code you didn't actually read
- Be vague ("improve error handling")
- Avoid giving a clear verdict
```
**Placeholders:**
- `{DESCRIPTION}` — brief summary of what was built
- `{PLAN_OR_REQUIREMENTS}` — what it should do (plan file path, task text, or requirements)
- `{BASE_SHA}` — starting commit
- `{HEAD_SHA}` — ending commit
**Reviewer returns:** Strengths, Issues (Critical / Important / Minor), Recommendations, Assessment
## Example Output
```
### Strengths
- Clean database schema with proper migrations (db.ts:15-42)
- Comprehensive test coverage (18 tests, all edge cases)
- Good error handling with fallbacks (summarizer.ts:85-92)
### Issues
#### Important
1. **Missing help text in CLI wrapper**
- File: index-conversations:1-31
- Issue: No --help flag, users won't discover --concurrency
- Fix: Add --help case with usage examples
2. **Date validation missing**
- File: search.ts:25-27
- Issue: Invalid dates silently return no results
- Fix: Validate ISO format, throw error with example
#### Minor
1. **Progress indicators**
- File: indexer.ts:130
- Issue: No "X of Y" counter for long operations
- Impact: Users don't know how long to wait
### Recommendations
- Add progress reporting for user experience
- Consider config file for excluded projects (portability)
### Assessment
**Ready to merge: With fixes**
**Reasoning:** Core implementation is solid with good architecture and tests. Important issues (help text, date validation) are easily fixed and don't affect core functionality.
```

View File

@@ -0,0 +1,109 @@
---
name: review-audit
description: Review workflows, audit trails, and compliance checks for AI-generated code. Use when conducting code review, setting up approval workflows, maintaining audit logs, or ensuring compliance. Covers human-in-loop review, trust-scaled approval, compliance checks, and escalation paths.
---
# 审查与审计 — 人类在环的质量守门人
> AI 生成代码的速度再快,也需要人类在关键节点把关。
## 👁️ 三层审查体系
### L1自审Agent 自查)
提交前 Agent 对照约束逐条检查:
```yaml
self_review_checklist:
- "所有修改是否能通过编译?"
- "是否遵守了命名规范?"
- "是否添加了类型提示?"
- "测试覆盖是否达标?"
- "有没有遗漏的 TODO / DEBUG"
- "变更范围是否超出任务边界?"
```
### L2配对审查Agent + 人类)
Agent 生成变更摘要,人类做终审:
```yaml
review_summary:
files_changed: 3
lines_added: 45
lines_removed: 12
coverage_delta: "+5%"
risk_level: "low"
key_decisions:
- "选择了方案 B性能优先于可读性"
```
### L3合规审查审计追踪
记录所有 AI 操作,满足合规要求:
```yaml
audit_record:
agent_id: "codex-v4"
task_id: "bug-597"
timestamp: "2026-05-28T14:30:00Z"
actions:
- type: "file_modify"
path: "AdviceManageAppMapper.xml"
diff: "+7 lines, -2 lines"
approvals:
- reviewer: "human"
decision: "approved"
timestamp: "2026-05-28T14:35:00Z"
```
## 🔐 信任度比例审查
| 信任等级 | 自审 | 配对审查 | 合规审查 | 说明 |
|---|---|---|---|---|
| L1 怀疑 | 强制 | 逐行 | 强制 | 新 Agent / 新项目 |
| L2 试探 | 强制 | 抽样 30% | 强制 | 当前项目状态 |
| L3 信任 | 强制 | 抽样 10% | 按需 | Agent 可靠性已验证 |
| L4 委托 | 自动 | 仅异常 | 按需 | 高度信任环境 |
## 📋 审查工作流
```
Agent 完成工作
→ 执行自审(对照约束清单)
→ 生成变更摘要files_changed / coverage / risk
→ 提交 PR / 变更请求
├→ L1 通过 → 自动合并(低风险 + 高信任)
├→ L1 失败 → Agent 修复
├→ L3 需要 → 生成审计记录
└→ 人类审查
├→ 批准 → 合并 / 部署
├→ 驳回 → 反馈具体问题 → Agent 修复 → 重审
└→ 指导 → 提供修改方向 → Agent 调整
```
## 🚨 升级路径
```
问题类型 首次 第2次 第3次
─────────────────────────────────────────────────────────────────
编译失败 Agent 修复 Agent 修复 上报人类
测试失败 Agent 修复 上报人类 等待指导
逻辑错误 上报人类 等待指导 暂停任务
安全违规 立即暂停 安全团队介入 永久标记
```
## 📊 审查效率指标
| 指标 | 目标 | 说明 |
|---|---|---|
| 审查通过率 | > 80% | 一次提交即通过 |
| 审查时间 | < 30 分钟 | 人类每次审查耗时 |
| 缺陷逃逸率 | < 5% | 生产环境发现的问题 |
| 审计覆盖率 | 100% | 所有 AI 操作均记录 |
## ⚠️ 常见陷阱
| 陷阱 | 表现 | 解决 |
|---|---|---|
| 审查疲劳 | 人类草率批准 | 限制每日审查量轮换审查人 |
| 过度信任 | 跳过审查直接合并 | 设置强制门禁 |
| 审计缺失 | 无法追溯问题来源 | 每次操作都记录审计事件 |
| 反馈模糊 | "这里不对" 缺少具体位置 | 文件:行号:错误描述 |

View File

@@ -0,0 +1,3 @@
interface:
display_name: "Review Audit"
short_description: "Part of Harness Engineering plugin — review-audit"

View File

@@ -0,0 +1,279 @@
---
name: subagent-driven-development
description: Use when executing implementation plans with independent tasks in the current session
---
# Subagent-Driven Development
Execute plan by dispatching fresh subagent per task, with two-stage review after each: spec compliance review first, then code quality review.
**Why subagents:** You delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.
**Core principle:** Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration
**Continuous execution:** Do not pause to check in with your human partner between tasks. Execute all tasks from the plan without stopping. The only reasons to stop are: BLOCKED status you cannot resolve, ambiguity that genuinely prevents progress, or all tasks complete. "Should I continue?" prompts and progress summaries waste their time — they asked you to execute the plan, so execute it.
## When to Use
```dot
digraph when_to_use {
"Have implementation plan?" [shape=diamond];
"Tasks mostly independent?" [shape=diamond];
"Stay in this session?" [shape=diamond];
"subagent-driven-development" [shape=box];
"executing-plans" [shape=box];
"Manual execution or brainstorm first" [shape=box];
"Have implementation plan?" -> "Tasks mostly independent?" [label="yes"];
"Have implementation plan?" -> "Manual execution or brainstorm first" [label="no"];
"Tasks mostly independent?" -> "Stay in this session?" [label="yes"];
"Tasks mostly independent?" -> "Manual execution or brainstorm first" [label="no - tightly coupled"];
"Stay in this session?" -> "subagent-driven-development" [label="yes"];
"Stay in this session?" -> "executing-plans" [label="no - parallel session"];
}
```
**vs. Executing Plans (parallel session):**
- Same session (no context switch)
- Fresh subagent per task (no context pollution)
- Two-stage review after each task: spec compliance first, then code quality
- Faster iteration (no human-in-loop between tasks)
## The Process
```dot
digraph process {
rankdir=TB;
subgraph cluster_per_task {
label="Per Task";
"Dispatch implementer subagent (./implementer-prompt.md)" [shape=box];
"Implementer subagent asks questions?" [shape=diamond];
"Answer questions, provide context" [shape=box];
"Implementer subagent implements, tests, commits, self-reviews" [shape=box];
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [shape=box];
"Spec reviewer subagent confirms code matches spec?" [shape=diamond];
"Implementer subagent fixes spec gaps" [shape=box];
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [shape=box];
"Code quality reviewer subagent approves?" [shape=diamond];
"Implementer subagent fixes quality issues" [shape=box];
"Mark task complete in TodoWrite" [shape=box];
}
"Read plan, extract all tasks with full text, note context, create TodoWrite" [shape=box];
"More tasks remain?" [shape=diamond];
"Dispatch final code reviewer subagent for entire implementation" [shape=box];
"Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen];
"Read plan, extract all tasks with full text, note context, create TodoWrite" -> "Dispatch implementer subagent (./implementer-prompt.md)";
"Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer subagent asks questions?";
"Implementer subagent asks questions?" -> "Answer questions, provide context" [label="yes"];
"Answer questions, provide context" -> "Dispatch implementer subagent (./implementer-prompt.md)";
"Implementer subagent asks questions?" -> "Implementer subagent implements, tests, commits, self-reviews" [label="no"];
"Implementer subagent implements, tests, commits, self-reviews" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)";
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" -> "Spec reviewer subagent confirms code matches spec?";
"Spec reviewer subagent confirms code matches spec?" -> "Implementer subagent fixes spec gaps" [label="no"];
"Implementer subagent fixes spec gaps" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [label="re-review"];
"Spec reviewer subagent confirms code matches spec?" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="yes"];
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" -> "Code quality reviewer subagent approves?";
"Code quality reviewer subagent approves?" -> "Implementer subagent fixes quality issues" [label="no"];
"Implementer subagent fixes quality issues" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="re-review"];
"Code quality reviewer subagent approves?" -> "Mark task complete in TodoWrite" [label="yes"];
"Mark task complete in TodoWrite" -> "More tasks remain?";
"More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"];
"More tasks remain?" -> "Dispatch final code reviewer subagent for entire implementation" [label="no"];
"Dispatch final code reviewer subagent for entire implementation" -> "Use superpowers:finishing-a-development-branch";
}
```
## Model Selection
Use the least powerful model that can handle each role to conserve cost and increase speed.
**Mechanical implementation tasks** (isolated functions, clear specs, 1-2 files): use a fast, cheap model. Most implementation tasks are mechanical when the plan is well-specified.
**Integration and judgment tasks** (multi-file coordination, pattern matching, debugging): use a standard model.
**Architecture, design, and review tasks**: use the most capable available model.
**Task complexity signals:**
- Touches 1-2 files with a complete spec → cheap model
- Touches multiple files with integration concerns → standard model
- Requires design judgment or broad codebase understanding → most capable model
## Handling Implementer Status
Implementer subagents report one of four statuses. Handle each appropriately:
**DONE:** Proceed to spec compliance review.
**DONE_WITH_CONCERNS:** The implementer completed the work but flagged doubts. Read the concerns before proceeding. If the concerns are about correctness or scope, address them before review. If they're observations (e.g., "this file is getting large"), note them and proceed to review.
**NEEDS_CONTEXT:** The implementer needs information that wasn't provided. Provide the missing context and re-dispatch.
**BLOCKED:** The implementer cannot complete the task. Assess the blocker:
1. If it's a context problem, provide more context and re-dispatch with the same model
2. If the task requires more reasoning, re-dispatch with a more capable model
3. If the task is too large, break it into smaller pieces
4. If the plan itself is wrong, escalate to the human
**Never** ignore an escalation or force the same model to retry without changes. If the implementer said it's stuck, something needs to change.
## Prompt Templates
- `./implementer-prompt.md` - Dispatch implementer subagent
- `./spec-reviewer-prompt.md` - Dispatch spec compliance reviewer subagent
- `./code-quality-reviewer-prompt.md` - Dispatch code quality reviewer subagent
## Example Workflow
```
You: I'm using Subagent-Driven Development to execute this plan.
[Read plan file once: docs/superpowers/plans/feature-plan.md]
[Extract all 5 tasks with full text and context]
[Create TodoWrite with all tasks]
Task 1: Hook installation script
[Get Task 1 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]
Implementer: "Before I begin - should the hook be installed at user or system level?"
You: "User level (~/.config/superpowers/hooks/)"
Implementer: "Got it. Implementing now..."
[Later] Implementer:
- Implemented install-hook command
- Added tests, 5/5 passing
- Self-review: Found I missed --force flag, added it
- Committed
[Dispatch spec compliance reviewer]
Spec reviewer: ✅ Spec compliant - all requirements met, nothing extra
[Get git SHAs, dispatch code quality reviewer]
Code reviewer: Strengths: Good test coverage, clean. Issues: None. Approved.
[Mark Task 1 complete]
Task 2: Recovery modes
[Get Task 2 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]
Implementer: [No questions, proceeds]
Implementer:
- Added verify/repair modes
- 8/8 tests passing
- Self-review: All good
- Committed
[Dispatch spec compliance reviewer]
Spec reviewer: ❌ Issues:
- Missing: Progress reporting (spec says "report every 100 items")
- Extra: Added --json flag (not requested)
[Implementer fixes issues]
Implementer: Removed --json flag, added progress reporting
[Spec reviewer reviews again]
Spec reviewer: ✅ Spec compliant now
[Dispatch code quality reviewer]
Code reviewer: Strengths: Solid. Issues (Important): Magic number (100)
[Implementer fixes]
Implementer: Extracted PROGRESS_INTERVAL constant
[Code reviewer reviews again]
Code reviewer: ✅ Approved
[Mark Task 2 complete]
...
[After all tasks]
[Dispatch final code-reviewer]
Final reviewer: All requirements met, ready to merge
Done!
```
## Advantages
**vs. Manual execution:**
- Subagents follow TDD naturally
- Fresh context per task (no confusion)
- Parallel-safe (subagents don't interfere)
- Subagent can ask questions (before AND during work)
**vs. Executing Plans:**
- Same session (no handoff)
- Continuous progress (no waiting)
- Review checkpoints automatic
**Efficiency gains:**
- No file reading overhead (controller provides full text)
- Controller curates exactly what context is needed
- Subagent gets complete information upfront
- Questions surfaced before work begins (not after)
**Quality gates:**
- Self-review catches issues before handoff
- Two-stage review: spec compliance, then code quality
- Review loops ensure fixes actually work
- Spec compliance prevents over/under-building
- Code quality ensures implementation is well-built
**Cost:**
- More subagent invocations (implementer + 2 reviewers per task)
- Controller does more prep work (extracting all tasks upfront)
- Review loops add iterations
- But catches issues early (cheaper than debugging later)
## Red Flags
**Never:**
- Start implementation on main/master branch without explicit user consent
- Skip reviews (spec compliance OR code quality)
- Proceed with unfixed issues
- Dispatch multiple implementation subagents in parallel (conflicts)
- Make subagent read plan file (provide full text instead)
- Skip scene-setting context (subagent needs to understand where task fits)
- Ignore subagent questions (answer before letting them proceed)
- Accept "close enough" on spec compliance (spec reviewer found issues = not done)
- Skip review loops (reviewer found issues = implementer fixes = review again)
- Let implementer self-review replace actual review (both are needed)
- **Start code quality review before spec compliance is ✅** (wrong order)
- Move to next task while either review has open issues
**If subagent asks questions:**
- Answer clearly and completely
- Provide additional context if needed
- Don't rush them into implementation
**If reviewer finds issues:**
- Implementer (same subagent) fixes them
- Reviewer reviews again
- Repeat until approved
- Don't skip the re-review
**If subagent fails task:**
- Dispatch fix subagent with specific instructions
- Don't try to fix manually (context pollution)
## Integration
**Required workflow skills:**
- **superpowers:using-git-worktrees** - Ensures isolated workspace (creates one or verifies existing)
- **superpowers:writing-plans** - Creates the plan this skill executes
- **superpowers:requesting-code-review** - Code review template for reviewer subagents
- **superpowers:finishing-a-development-branch** - Complete development after all tasks
**Subagents should use:**
- **superpowers:test-driven-development** - Subagents follow TDD for each task
**Alternative workflow:**
- **superpowers:executing-plans** - Use for parallel session instead of same-session execution

View File

@@ -0,0 +1,25 @@
# Code Quality Reviewer Prompt Template
Use this template when dispatching a code quality reviewer subagent.
**Purpose:** Verify implementation is well-built (clean, tested, maintainable)
**Only dispatch after spec compliance review passes.**
```
Task tool (general-purpose):
Use template at requesting-code-review/code-reviewer.md
DESCRIPTION: [task summary, from implementer's report]
PLAN_OR_REQUIREMENTS: Task N from [plan-file]
BASE_SHA: [commit before task]
HEAD_SHA: [current commit]
```
**In addition to standard code quality concerns, the reviewer should check:**
- Does each file have one clear responsibility with a well-defined interface?
- Are units decomposed so they can be understood and tested independently?
- Is the implementation following the file structure from the plan?
- Did this implementation create new files that are already large, or significantly grow existing files? (Don't flag pre-existing file sizes — focus on what this change contributed.)
**Code reviewer returns:** Strengths, Issues (Critical/Important/Minor), Assessment

View File

@@ -0,0 +1,113 @@
# Implementer Subagent Prompt Template
Use this template when dispatching an implementer subagent.
```
Task tool (general-purpose):
description: "Implement Task N: [task name]"
prompt: |
You are implementing Task N: [task name]
## Task Description
[FULL TEXT of task from plan - paste it here, don't make subagent read file]
## Context
[Scene-setting: where this fits, dependencies, architectural context]
## Before You Begin
If you have questions about:
- The requirements or acceptance criteria
- The approach or implementation strategy
- Dependencies or assumptions
- Anything unclear in the task description
**Ask them now.** Raise any concerns before starting work.
## Your Job
Once you're clear on requirements:
1. Implement exactly what the task specifies
2. Write tests (following TDD if task says to)
3. Verify implementation works
4. Commit your work
5. Self-review (see below)
6. Report back
Work from: [directory]
**While you work:** If you encounter something unexpected or unclear, **ask questions**.
It's always OK to pause and clarify. Don't guess or make assumptions.
## Code Organization
You reason best about code you can hold in context at once, and your edits are more
reliable when files are focused. Keep this in mind:
- Follow the file structure defined in the plan
- Each file should have one clear responsibility with a well-defined interface
- If a file you're creating is growing beyond the plan's intent, stop and report
it as DONE_WITH_CONCERNS — don't split files on your own without plan guidance
- If an existing file you're modifying is already large or tangled, work carefully
and note it as a concern in your report
- In existing codebases, follow established patterns. Improve code you're touching
the way a good developer would, but don't restructure things outside your task.
## When You're in Over Your Head
It is always OK to stop and say "this is too hard for me." Bad work is worse than
no work. You will not be penalized for escalating.
**STOP and escalate when:**
- The task requires architectural decisions with multiple valid approaches
- You need to understand code beyond what was provided and can't find clarity
- You feel uncertain about whether your approach is correct
- The task involves restructuring existing code in ways the plan didn't anticipate
- You've been reading file after file trying to understand the system without progress
**How to escalate:** Report back with status BLOCKED or NEEDS_CONTEXT. Describe
specifically what you're stuck on, what you've tried, and what kind of help you need.
The controller can provide more context, re-dispatch with a more capable model,
or break the task into smaller pieces.
## Before Reporting Back: Self-Review
Review your work with fresh eyes. Ask yourself:
**Completeness:**
- Did I fully implement everything in the spec?
- Did I miss any requirements?
- Are there edge cases I didn't handle?
**Quality:**
- Is this my best work?
- Are names clear and accurate (match what things do, not how they work)?
- Is the code clean and maintainable?
**Discipline:**
- Did I avoid overbuilding (YAGNI)?
- Did I only build what was requested?
- Did I follow existing patterns in the codebase?
**Testing:**
- Do tests actually verify behavior (not just mock behavior)?
- Did I follow TDD if required?
- Are tests comprehensive?
If you find issues during self-review, fix them now before reporting.
## Report Format
When done, report:
- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT
- What you implemented (or what you attempted, if blocked)
- What you tested and test results
- Files changed
- Self-review findings (if any)
- Any issues or concerns
Use DONE_WITH_CONCERNS if you completed the work but have doubts about correctness.
Use BLOCKED if you cannot complete the task. Use NEEDS_CONTEXT if you need
information that wasn't provided. Never silently produce work you're unsure about.
```

View File

@@ -0,0 +1,61 @@
# Spec Compliance Reviewer Prompt Template
Use this template when dispatching a spec compliance reviewer subagent.
**Purpose:** Verify implementer built what was requested (nothing more, nothing less)
```
Task tool (general-purpose):
description: "Review spec compliance for Task N"
prompt: |
You are reviewing whether an implementation matches its specification.
## What Was Requested
[FULL TEXT of task requirements]
## What Implementer Claims They Built
[From implementer's report]
## CRITICAL: Do Not Trust the Report
The implementer finished suspiciously quickly. Their report may be incomplete,
inaccurate, or optimistic. You MUST verify everything independently.
**DO NOT:**
- Take their word for what they implemented
- Trust their claims about completeness
- Accept their interpretation of requirements
**DO:**
- Read the actual code they wrote
- Compare actual implementation to requirements line by line
- Check for missing pieces they claimed to implement
- Look for extra features they didn't mention
## Your Job
Read the implementation code and verify:
**Missing requirements:**
- Did they implement everything that was requested?
- Are there requirements they skipped or missed?
- Did they claim something works but didn't actually implement it?
**Extra/unneeded work:**
- Did they build things that weren't requested?
- Did they over-engineer or add unnecessary features?
- Did they add "nice to haves" that weren't in spec?
**Misunderstandings:**
- Did they interpret requirements differently than intended?
- Did they solve the wrong problem?
- Did they implement the right feature but wrong way?
**Verify by reading code, not by trusting report.**
Report:
- ✅ Spec compliant (if everything matches after code inspection)
- ❌ Issues found: [list specifically what's missing or extra, with file:line references]
```

View File

@@ -0,0 +1,119 @@
# Creation Log: Systematic Debugging Skill
Reference example of extracting, structuring, and bulletproofing a critical skill.
## Source Material
Extracted debugging framework from `~/.claude/CLAUDE.md`:
- 4-phase systematic process (Investigation → Pattern Analysis → Hypothesis → Implementation)
- Core mandate: ALWAYS find root cause, NEVER fix symptoms
- Rules designed to resist time pressure and rationalization
## Extraction Decisions
**What to include:**
- Complete 4-phase framework with all rules
- Anti-shortcuts ("NEVER fix symptom", "STOP and re-analyze")
- Pressure-resistant language ("even if faster", "even if I seem in a hurry")
- Concrete steps for each phase
**What to leave out:**
- Project-specific context
- Repetitive variations of same rule
- Narrative explanations (condensed to principles)
## Structure Following skill-creation/SKILL.md
1. **Rich when_to_use** - Included symptoms and anti-patterns
2. **Type: technique** - Concrete process with steps
3. **Keywords** - "root cause", "symptom", "workaround", "debugging", "investigation"
4. **Flowchart** - Decision point for "fix failed" → re-analyze vs add more fixes
5. **Phase-by-phase breakdown** - Scannable checklist format
6. **Anti-patterns section** - What NOT to do (critical for this skill)
## Bulletproofing Elements
Framework designed to resist rationalization under pressure:
### Language Choices
- "ALWAYS" / "NEVER" (not "should" / "try to")
- "even if faster" / "even if I seem in a hurry"
- "STOP and re-analyze" (explicit pause)
- "Don't skip past" (catches the actual behavior)
### Structural Defenses
- **Phase 1 required** - Can't skip to implementation
- **Single hypothesis rule** - Forces thinking, prevents shotgun fixes
- **Explicit failure mode** - "IF your first fix doesn't work" with mandatory action
- **Anti-patterns section** - Shows exactly what shortcuts look like
### Redundancy
- Root cause mandate in overview + when_to_use + Phase 1 + implementation rules
- "NEVER fix symptom" appears 4 times in different contexts
- Each phase has explicit "don't skip" guidance
## Testing Approach
Created 4 validation tests following skills/meta/testing-skills-with-subagents:
### Test 1: Academic Context (No Pressure)
- Simple bug, no time pressure
- **Result:** Perfect compliance, complete investigation
### Test 2: Time Pressure + Obvious Quick Fix
- User "in a hurry", symptom fix looks easy
- **Result:** Resisted shortcut, followed full process, found real root cause
### Test 3: Complex System + Uncertainty
- Multi-layer failure, unclear if can find root cause
- **Result:** Systematic investigation, traced through all layers, found source
### Test 4: Failed First Fix
- Hypothesis doesn't work, temptation to add more fixes
- **Result:** Stopped, re-analyzed, formed new hypothesis (no shotgun)
**All tests passed.** No rationalizations found.
## Iterations
### Initial Version
- Complete 4-phase framework
- Anti-patterns section
- Flowchart for "fix failed" decision
### Enhancement 1: TDD Reference
- Added link to skills/testing/test-driven-development
- Note explaining TDD's "simplest code" ≠ debugging's "root cause"
- Prevents confusion between methodologies
## Final Outcome
Bulletproof skill that:
- ✅ Clearly mandates root cause investigation
- ✅ Resists time pressure rationalization
- ✅ Provides concrete steps for each phase
- ✅ Shows anti-patterns explicitly
- ✅ Tested under multiple pressure scenarios
- ✅ Clarifies relationship to TDD
- ✅ Ready for use
## Key Insight
**Most important bulletproofing:** Anti-patterns section showing exact shortcuts that feel justified in the moment. When Claude thinks "I'll just add this one quick fix", seeing that exact pattern listed as wrong creates cognitive friction.
## Usage Example
When encountering a bug:
1. Load skill: skills/debugging/systematic-debugging
2. Read overview (10 sec) - reminded of mandate
3. Follow Phase 1 checklist - forced investigation
4. If tempted to skip - see anti-pattern, stop
5. Complete all phases - root cause found
**Time investment:** 5-10 minutes
**Time saved:** Hours of symptom-whack-a-mole
---
*Created: 2025-10-03*
*Purpose: Reference example for skill extraction and bulletproofing*

View File

@@ -0,0 +1,296 @@
---
name: systematic-debugging
description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
---
# Systematic Debugging
## Overview
Random fixes waste time and create new bugs. Quick patches mask underlying issues.
**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.
**Violating the letter of this process is violating the spirit of debugging.**
## The Iron Law
```
NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST
```
If you haven't completed Phase 1, you cannot propose fixes.
## When to Use
Use for ANY technical issue:
- Test failures
- Bugs in production
- Unexpected behavior
- Performance problems
- Build failures
- Integration issues
**Use this ESPECIALLY when:**
- Under time pressure (emergencies make guessing tempting)
- "Just one quick fix" seems obvious
- You've already tried multiple fixes
- Previous fix didn't work
- You don't fully understand the issue
**Don't skip when:**
- Issue seems simple (simple bugs have root causes too)
- You're in a hurry (rushing guarantees rework)
- Manager wants it fixed NOW (systematic is faster than thrashing)
## The Four Phases
You MUST complete each phase before proceeding to the next.
### Phase 1: Root Cause Investigation
**BEFORE attempting ANY fix:**
1. **Read Error Messages Carefully**
- Don't skip past errors or warnings
- They often contain the exact solution
- Read stack traces completely
- Note line numbers, file paths, error codes
2. **Reproduce Consistently**
- Can you trigger it reliably?
- What are the exact steps?
- Does it happen every time?
- If not reproducible → gather more data, don't guess
3. **Check Recent Changes**
- What changed that could cause this?
- Git diff, recent commits
- New dependencies, config changes
- Environmental differences
4. **Gather Evidence in Multi-Component Systems**
**WHEN system has multiple components (CI → build → signing, API → service → database):**
**BEFORE proposing fixes, add diagnostic instrumentation:**
```
For EACH component boundary:
- Log what data enters component
- Log what data exits component
- Verify environment/config propagation
- Check state at each layer
Run once to gather evidence showing WHERE it breaks
THEN analyze evidence to identify failing component
THEN investigate that specific component
```
**Example (multi-layer system):**
```bash
# Layer 1: Workflow
echo "=== Secrets available in workflow: ==="
echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}"
# Layer 2: Build script
echo "=== Env vars in build script: ==="
env | grep IDENTITY || echo "IDENTITY not in environment"
# Layer 3: Signing script
echo "=== Keychain state: ==="
security list-keychains
security find-identity -v
# Layer 4: Actual signing
codesign --sign "$IDENTITY" --verbose=4 "$APP"
```
**This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗)
5. **Trace Data Flow**
**WHEN error is deep in call stack:**
See `root-cause-tracing.md` in this directory for the complete backward tracing technique.
**Quick version:**
- Where does bad value originate?
- What called this with bad value?
- Keep tracing up until you find the source
- Fix at source, not at symptom
### Phase 2: Pattern Analysis
**Find the pattern before fixing:**
1. **Find Working Examples**
- Locate similar working code in same codebase
- What works that's similar to what's broken?
2. **Compare Against References**
- If implementing pattern, read reference implementation COMPLETELY
- Don't skim - read every line
- Understand the pattern fully before applying
3. **Identify Differences**
- What's different between working and broken?
- List every difference, however small
- Don't assume "that can't matter"
4. **Understand Dependencies**
- What other components does this need?
- What settings, config, environment?
- What assumptions does it make?
### Phase 3: Hypothesis and Testing
**Scientific method:**
1. **Form Single Hypothesis**
- State clearly: "I think X is the root cause because Y"
- Write it down
- Be specific, not vague
2. **Test Minimally**
- Make the SMALLEST possible change to test hypothesis
- One variable at a time
- Don't fix multiple things at once
3. **Verify Before Continuing**
- Did it work? Yes → Phase 4
- Didn't work? Form NEW hypothesis
- DON'T add more fixes on top
4. **When You Don't Know**
- Say "I don't understand X"
- Don't pretend to know
- Ask for help
- Research more
### Phase 4: Implementation
**Fix the root cause, not the symptom:**
1. **Create Failing Test Case**
- Simplest possible reproduction
- Automated test if possible
- One-off test script if no framework
- MUST have before fixing
- Use the `superpowers:test-driven-development` skill for writing proper failing tests
2. **Implement Single Fix**
- Address the root cause identified
- ONE change at a time
- No "while I'm here" improvements
- No bundled refactoring
3. **Verify Fix**
- Test passes now?
- No other tests broken?
- Issue actually resolved?
4. **If Fix Doesn't Work**
- STOP
- Count: How many fixes have you tried?
- If < 3: Return to Phase 1, re-analyze with new information
- **If ≥ 3: STOP and question the architecture (step 5 below)**
- DON'T attempt Fix #4 without architectural discussion
5. **If 3+ Fixes Failed: Question Architecture**
**Pattern indicating architectural problem:**
- Each fix reveals new shared state/coupling/problem in different place
- Fixes require "massive refactoring" to implement
- Each fix creates new symptoms elsewhere
**STOP and question fundamentals:**
- Is this pattern fundamentally sound?
- Are we "sticking with it through sheer inertia"?
- Should we refactor architecture vs. continue fixing symptoms?
**Discuss with your human partner before attempting more fixes**
This is NOT a failed hypothesis - this is a wrong architecture.
## Red Flags - STOP and Follow Process
If you catch yourself thinking:
- "Quick fix for now, investigate later"
- "Just try changing X and see if it works"
- "Add multiple changes, run tests"
- "Skip the test, I'll manually verify"
- "It's probably X, let me fix that"
- "I don't fully understand but this might work"
- "Pattern says X but I'll adapt it differently"
- "Here are the main problems: [lists fixes without investigation]"
- Proposing solutions before tracing data flow
- **"One more fix attempt" (when already tried 2+)**
- **Each fix reveals new problem in different place**
**ALL of these mean: STOP. Return to Phase 1.**
**If 3+ fixes failed:** Question the architecture (see Phase 4.5)
## your human partner's Signals You're Doing It Wrong
**Watch for these redirections:**
- "Is that not happening?" - You assumed without verifying
- "Will it show us...?" - You should have added evidence gathering
- "Stop guessing" - You're proposing fixes without understanding
- "Ultrathink this" - Question fundamentals, not just symptoms
- "We're stuck?" (frustrated) - Your approach isn't working
**When you see these:** STOP. Return to Phase 1.
## Common Rationalizations
| Excuse | Reality |
|--------|---------|
| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. |
| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. |
| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. |
| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. |
| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. |
| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. |
| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. |
| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |
## Quick Reference
| Phase | Key Activities | Success Criteria |
|-------|---------------|------------------|
| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |
| **2. Pattern** | Find working examples, compare | Identify differences |
| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |
| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |
## When Process Reveals "No Root Cause"
If systematic investigation reveals issue is truly environmental, timing-dependent, or external:
1. You've completed the process
2. Document what you investigated
3. Implement appropriate handling (retry, timeout, error message)
4. Add monitoring/logging for future investigation
**But:** 95% of "no root cause" cases are incomplete investigation.
## Supporting Techniques
These techniques are part of systematic debugging and available in this directory:
- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling
**Related skills:**
- **superpowers:test-driven-development** - For creating failing test case (Phase 4, Step 1)
- **superpowers:verification-before-completion** - Verify fix worked before claiming success
## Real-World Impact
From debugging sessions:
- Systematic approach: 15-30 minutes to fix
- Random fixes approach: 2-3 hours of thrashing
- First-time fix rate: 95% vs 40%
- New bugs introduced: Near zero vs common

View File

@@ -0,0 +1,158 @@
// Complete implementation of condition-based waiting utilities
// From: Lace test infrastructure improvements (2025-10-03)
// Context: Fixed 15 flaky tests by replacing arbitrary timeouts
import type { ThreadManager } from '~/threads/thread-manager';
import type { LaceEvent, LaceEventType } from '~/threads/types';
/**
* Wait for a specific event type to appear in thread
*
* @param threadManager - The thread manager to query
* @param threadId - Thread to check for events
* @param eventType - Type of event to wait for
* @param timeoutMs - Maximum time to wait (default 5000ms)
* @returns Promise resolving to the first matching event
*
* Example:
* await waitForEvent(threadManager, agentThreadId, 'TOOL_RESULT');
*/
export function waitForEvent(
threadManager: ThreadManager,
threadId: string,
eventType: LaceEventType,
timeoutMs = 5000
): Promise<LaceEvent> {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const check = () => {
const events = threadManager.getEvents(threadId);
const event = events.find((e) => e.type === eventType);
if (event) {
resolve(event);
} else if (Date.now() - startTime > timeoutMs) {
reject(new Error(`Timeout waiting for ${eventType} event after ${timeoutMs}ms`));
} else {
setTimeout(check, 10); // Poll every 10ms for efficiency
}
};
check();
});
}
/**
* Wait for a specific number of events of a given type
*
* @param threadManager - The thread manager to query
* @param threadId - Thread to check for events
* @param eventType - Type of event to wait for
* @param count - Number of events to wait for
* @param timeoutMs - Maximum time to wait (default 5000ms)
* @returns Promise resolving to all matching events once count is reached
*
* Example:
* // Wait for 2 AGENT_MESSAGE events (initial response + continuation)
* await waitForEventCount(threadManager, agentThreadId, 'AGENT_MESSAGE', 2);
*/
export function waitForEventCount(
threadManager: ThreadManager,
threadId: string,
eventType: LaceEventType,
count: number,
timeoutMs = 5000
): Promise<LaceEvent[]> {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const check = () => {
const events = threadManager.getEvents(threadId);
const matchingEvents = events.filter((e) => e.type === eventType);
if (matchingEvents.length >= count) {
resolve(matchingEvents);
} else if (Date.now() - startTime > timeoutMs) {
reject(
new Error(
`Timeout waiting for ${count} ${eventType} events after ${timeoutMs}ms (got ${matchingEvents.length})`
)
);
} else {
setTimeout(check, 10);
}
};
check();
});
}
/**
* Wait for an event matching a custom predicate
* Useful when you need to check event data, not just type
*
* @param threadManager - The thread manager to query
* @param threadId - Thread to check for events
* @param predicate - Function that returns true when event matches
* @param description - Human-readable description for error messages
* @param timeoutMs - Maximum time to wait (default 5000ms)
* @returns Promise resolving to the first matching event
*
* Example:
* // Wait for TOOL_RESULT with specific ID
* await waitForEventMatch(
* threadManager,
* agentThreadId,
* (e) => e.type === 'TOOL_RESULT' && e.data.id === 'call_123',
* 'TOOL_RESULT with id=call_123'
* );
*/
export function waitForEventMatch(
threadManager: ThreadManager,
threadId: string,
predicate: (event: LaceEvent) => boolean,
description: string,
timeoutMs = 5000
): Promise<LaceEvent> {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const check = () => {
const events = threadManager.getEvents(threadId);
const event = events.find(predicate);
if (event) {
resolve(event);
} else if (Date.now() - startTime > timeoutMs) {
reject(new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`));
} else {
setTimeout(check, 10);
}
};
check();
});
}
// Usage example from actual debugging session:
//
// BEFORE (flaky):
// ---------------
// const messagePromise = agent.sendMessage('Execute tools');
// await new Promise(r => setTimeout(r, 300)); // Hope tools start in 300ms
// agent.abort();
// await messagePromise;
// await new Promise(r => setTimeout(r, 50)); // Hope results arrive in 50ms
// expect(toolResults.length).toBe(2); // Fails randomly
//
// AFTER (reliable):
// ----------------
// const messagePromise = agent.sendMessage('Execute tools');
// await waitForEventCount(threadManager, threadId, 'TOOL_CALL', 2); // Wait for tools to start
// agent.abort();
// await messagePromise;
// await waitForEventCount(threadManager, threadId, 'TOOL_RESULT', 2); // Wait for results
// expect(toolResults.length).toBe(2); // Always succeeds
//
// Result: 60% pass rate → 100%, 40% faster execution

View File

@@ -0,0 +1,115 @@
# Condition-Based Waiting
## Overview
Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI.
**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes.
## When to Use
```dot
digraph when_to_use {
"Test uses setTimeout/sleep?" [shape=diamond];
"Testing timing behavior?" [shape=diamond];
"Document WHY timeout needed" [shape=box];
"Use condition-based waiting" [shape=box];
"Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"];
"Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"];
"Testing timing behavior?" -> "Use condition-based waiting" [label="no"];
}
```
**Use when:**
- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`)
- Tests are flaky (pass sometimes, fail under load)
- Tests timeout when run in parallel
- Waiting for async operations to complete
**Don't use when:**
- Testing actual timing behavior (debounce, throttle intervals)
- Always document WHY if using arbitrary timeout
## Core Pattern
```typescript
// ❌ BEFORE: Guessing at timing
await new Promise(r => setTimeout(r, 50));
const result = getResult();
expect(result).toBeDefined();
// ✅ AFTER: Waiting for condition
await waitFor(() => getResult() !== undefined);
const result = getResult();
expect(result).toBeDefined();
```
## Quick Patterns
| Scenario | Pattern |
|----------|---------|
| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` |
| Wait for state | `waitFor(() => machine.state === 'ready')` |
| Wait for count | `waitFor(() => items.length >= 5)` |
| Wait for file | `waitFor(() => fs.existsSync(path))` |
| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` |
## Implementation
Generic polling function:
```typescript
async function waitFor<T>(
condition: () => T | undefined | null | false,
description: string,
timeoutMs = 5000
): Promise<T> {
const startTime = Date.now();
while (true) {
const result = condition();
if (result) return result;
if (Date.now() - startTime > timeoutMs) {
throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`);
}
await new Promise(r => setTimeout(r, 10)); // Poll every 10ms
}
}
```
See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.
## Common Mistakes
**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU
**✅ Fix:** Poll every 10ms
**❌ No timeout:** Loop forever if condition never met
**✅ Fix:** Always include timeout with clear error
**❌ Stale data:** Cache state before loop
**✅ Fix:** Call getter inside loop for fresh data
## When Arbitrary Timeout IS Correct
```typescript
// Tool ticks every 100ms - need 2 ticks to verify partial output
await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition
await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior
// 200ms = 2 ticks at 100ms intervals - documented and justified
```
**Requirements:**
1. First wait for triggering condition
2. Based on known timing (not guessing)
3. Comment explaining WHY
## Real-World Impact
From debugging session (2025-10-03):
- Fixed 15 flaky tests across 3 files
- Pass rate: 60% → 100%
- Execution time: 40% faster
- No more race conditions

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